Skip to content

Commit

Permalink
fix the readme example and run it as a doctest (#47)
Browse files Browse the repository at this point in the history
fixes #46 

thanks for flagging @SteveLauC
  • Loading branch information
lwwmanning authored Sep 20, 2024
1 parent 7b79ed5 commit 833c253
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 6 deletions.
18 changes: 12 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,25 @@ fn pack_u16_into_u3() {
}

// Pack the values.
let values = [3u16; 1024];
let mut packed = [0; 128 * WIDTH / size_of::<u16>()];
BitPacking::bitpack::<WIDTH>(&values, &mut packed);
// prefer using the safe pack/unpack functions unless you have a specific reason to use the unchecked versions
// e.g. `BitPacking::pack::<WIDTH>(&values, &mut packed);`
// unfortunately the safe versions don't work in doctests since they depend on the unstable generic_const_exprs feature
// see a version of this example without unsafe in `src/lib.rs`
unsafe { BitPacking::unchecked_pack(WIDTH, &values, &mut packed); }

// Unpack the values.
let mut unpacked = [0u16; 1024];
BitPacking::bitunpack::<WIDTH>(&packed, &mut unpacked);
// e.g., `BitPacking::unpack::<WIDTH>(&packed, &mut unpacked);`
unsafe { BitPacking::unchecked_unpack(WIDTH, &packed, &mut unpacked); }
assert_eq!(values, unpacked);

// Unpack a single value at index 14.
// Note that for more than ~10 values, it can be faster to unpack all values and then
// Note that for more than ~10 values, it is typically faster to unpack all values and then
// access the desired one.
assert_eq!(BitPacking::bitunpack_single::<WIDTH>(&packed, 14), 14);
for i in 0..1024 {
// e.g., `BitPacking::unpack_single::<WIDTH>(&packed, i)`
assert_eq!(unsafe { BitPacking::unchecked_unpack_single(WIDTH, &packed, i) }, values[i]);
}
}
```

Expand Down
37 changes: 37 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,40 @@ mod test {
}
}
}

// run the example code in the README as a test
#[doc = include_str!("../README.md")]
#[cfg(doctest)]
pub struct ReadmeDoctests;

#[cfg(test)]
mod tests {
use crate::BitPacking;

#[test]
fn pack_u16_into_u3_no_unsafe() {
const WIDTH: usize = 3;

// Generate some values.
let mut values: [u16; 1024] = [0; 1024];
for i in 0..1024 {
values[i] = (i % (1 << WIDTH)) as u16;
}

// Pack the values.
let mut packed = [0; 128 * WIDTH / size_of::<u16>()];
BitPacking::pack::<WIDTH>(&values, &mut packed);

// Unpack the values.
let mut unpacked = [0u16; 1024];
BitPacking::unpack::<WIDTH>(&packed, &mut unpacked);
assert_eq!(values, unpacked);

// Unpack a single value at index 14.
// Note that for more than ~10 values, it can be faster to unpack all values and then
// access the desired one.
for i in 0..1024 {
assert_eq!(BitPacking::unpack_single::<WIDTH>(&packed, i), values[i]);
}
}
}

0 comments on commit 833c253

Please sign in to comment.