Skip to content

Commit

Permalink
src/pack_ints.rs: pack & unpack without thread_local
Browse files Browse the repository at this point in the history
  • Loading branch information
poshcoe committed Apr 19, 2024
1 parent 7e58be5 commit 6c4fa2d
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/pack_ints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@ macro_rules! impl_smaller {

// Scratch space to bridge gap between pack_ints and pack_bytes.
// In theory, we could avoid this intermediate step, but it would result in a lot of generated code.
#[cfg(feature = "std")]
fn with_scratch<T>(f: impl FnOnce(&mut Vec<u8>) -> T) -> T {
thread_local! {
static SCRATCH: core::cell::RefCell<Vec<u8>> = const { core::cell::RefCell::new(Vec::new()) }
Expand All @@ -245,6 +246,7 @@ fn with_scratch<T>(f: impl FnOnce(&mut Vec<u8>) -> T) -> T {
f(s)
})
}
#[cfg(feature = "std")]
macro_rules! impl_u8 {
() => {
fn pack8(v: &mut [Self], out: &mut Vec<u8>) {
Expand All @@ -268,6 +270,27 @@ macro_rules! impl_u8 {
}
};
}
#[cfg(not(feature = "std"))]
macro_rules! impl_u8 {
() => {
fn pack8(v: &mut [Self], out: &mut Vec<u8>) {
// resort to allocation
let mut bytes: Vec<_> = v.iter().map(|&v| v as u8).collect();
pack_bytes(&mut bytes, out);
}
fn unpack8(input: &mut &[u8], length: usize, out: &mut CowSlice<Self::Une>) -> Result<()> {
// resort to allocation
let allocation: Vec<u8> = Vec::with_capacity(length);
let mut bytes = CowSlice::with_allocation(allocation);
unpack_bytes(input, length, &mut bytes)?;
// Safety: unpack_bytes ensures bytes has length of `length`.
let slice = unsafe { bytes.as_slice(length) };
out.set_owned()
.extend(slice.iter().map(|&v| (v as Self).to_ne_bytes()));
Ok(())
}
};
}

impl SizedUInt for u128 {
impl_simple!();
Expand Down

0 comments on commit 6c4fa2d

Please sign in to comment.