diff --git a/README.md b/README.md index 88f0040..3e20b41 100644 --- a/README.md +++ b/README.md @@ -24,19 +24,25 @@ fn pack_u16_into_u3() { } // Pack the values. - let values = [3u16; 1024]; let mut packed = [0; 128 * WIDTH / size_of::()]; - BitPacking::bitpack::(&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::(&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::(&packed, &mut unpacked); + // e.g., `BitPacking::unpack::(&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::(&packed, 14), 14); + for i in 0..1024 { + // e.g., `BitPacking::unpack_single::(&packed, i)` + assert_eq!(unsafe { BitPacking::unchecked_unpack_single(WIDTH, &packed, i) }, values[i]); + } } ``` diff --git a/src/lib.rs b/src/lib.rs index 4bf858d..6483eaa 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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::()]; + BitPacking::pack::(&values, &mut packed); + + // Unpack the values. + let mut unpacked = [0u16; 1024]; + BitPacking::unpack::(&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::(&packed, i), values[i]); + } + } +}