wasm_bitpack/traits.rs
1//! The [`BitPacker`] trait — the single definition of codec behavior, implemented by
2//! [`Scalar`](crate::Scalar) and [`Wasm128`](crate::Wasm128).
3
4mod private {
5 pub trait Sealed {}
6 impl Sealed for crate::Scalar {}
7 impl Sealed for crate::Wasm128 {}
8}
9
10/// A fixed-block-size integer bit-packing codec.
11///
12/// Packs `u32` values into a tightly-bit-packed byte buffer at a caller-chosen bit width,
13/// and unpacks them back out. Every implementation operates on exactly
14/// [`BLOCK_LEN`](Self::BLOCK_LEN) values at a time — arbitrary-length input is handled by
15/// the [`pack`](crate::pack)/[`unpack`](crate::unpack) wrapper, not by this trait directly.
16///
17/// This trait is sealed: it can only be implemented by types defined in this crate, so
18/// adding a new required method here is never a breaking change for downstream users.
19///
20/// # Examples
21///
22/// ```
23/// use wasm_bitpack::{BitPacker, Scalar};
24///
25/// let values = vec![7u32; Scalar::BLOCK_LEN];
26/// let num_bits = Scalar::num_bits(&values);
27///
28/// let mut compressed = vec![0u8; Scalar::BLOCK_LEN * num_bits as usize / 8];
29/// let written = Scalar::compress(&values, &mut compressed, num_bits);
30///
31/// let mut decompressed = vec![0u32; Scalar::BLOCK_LEN];
32/// let read = Scalar::decompress(&compressed[..written], &mut decompressed, num_bits);
33/// assert_eq!(read, written);
34/// assert_eq!(decompressed, values);
35/// ```
36pub trait BitPacker: private::Sealed {
37 /// The number of `u32` values a single block holds. `128` for every v0.1
38 /// implementation.
39 const BLOCK_LEN: usize;
40
41 /// Returns the minimum number of bits needed to represent every value in
42 /// `decompressed`.
43 fn num_bits(decompressed: &[u32]) -> u8;
44
45 /// Packs exactly [`BLOCK_LEN`](Self::BLOCK_LEN) values from `decompressed` into
46 /// `compressed` at `num_bits` bits per value, returning the number of bytes written.
47 ///
48 /// # Panics
49 ///
50 /// Panics if `decompressed.len() != Self::BLOCK_LEN`, if `compressed` is too small to
51 /// hold `Self::BLOCK_LEN * num_bits` bits, or if `num_bits` is `0` or greater than
52 /// `32`.
53 fn compress(decompressed: &[u32], compressed: &mut [u8], num_bits: u8) -> usize;
54
55 /// Unpacks exactly [`BLOCK_LEN`](Self::BLOCK_LEN) values from `compressed` into
56 /// `decompressed`, returning the number of bytes read.
57 ///
58 /// # Panics
59 ///
60 /// Panics if `decompressed.len() != Self::BLOCK_LEN`, if `compressed` is too small to
61 /// hold `Self::BLOCK_LEN * num_bits` bits, or if `num_bits` is `0` or greater than
62 /// `32`.
63 fn decompress(compressed: &[u8], decompressed: &mut [u32], num_bits: u8) -> usize;
64}