Skip to main content

zu_encoding/
bitpack.rs

1//! Fixed-width bit packing over 1024-value chunks.
2//!
3//! A full chunk at width 2..=63 uses the FastLanes-style interleaved lane
4//! order: value i lives in lane i % 16, and the 16 lanes advance together,
5//! so both pack and unpack run 16 identical shift-mask operations on
6//! consecutive words per step and auto-vectorize. A full chunk at width w
7//! occupies exactly 128 * w bytes, so chunk starts are always word aligned
8//! and a point read touches one chunk only. A short tail packs LSB-first
9//! sequentially into just the words it needs, which keeps tiny streams such
10//! as RLE run values from ballooning to full-chunk size. A tail long enough
11//! to fill the full-chunk byte count is zero-padded and transposed like a
12//! full chunk, so the packed size alone tells unpack which layout it holds.
13//! Width 1 stays sequential in every case: those streams are presence
14//! bitmaps whose consumers walk set bits by position, so bit i must mean
15//! value i. Width 64 stays a plain little-endian value array.
16
17/// Values per chunk. Format-stable.
18pub const CHUNK: usize = 1024;
19
20/// Interleave factor of the transposed layout. Format-stable.
21const LANES: usize = 16;
22
23/// Packed size in bytes of `count` values at `width` bits, rounded up to
24/// whole words. A full chunk is `128 * width`.
25#[inline]
26pub const fn packed_bytes(width: u32, count: usize) -> usize {
27    (count * width as usize).div_ceil(64) * 8
28}
29
30/// Packs up to 1024 values at `width` bits into whole little-endian words.
31/// Values must already fit in `width` bits.
32pub fn pack(values: &[u64], width: u32, out: &mut Vec<u8>) {
33    assert!(values.len() <= CHUNK);
34    assert!(width <= 64);
35    if width == 0 {
36        return;
37    }
38    let mask = if width == 64 {
39        u64::MAX
40    } else {
41        (1u64 << width) - 1
42    };
43    if width > 1 && width < 64 && packed_bytes(width, values.len()) == 128 * width as usize {
44        pack_transposed(values, width, mask, out);
45        return;
46    }
47    let mut acc = 0u64;
48    let mut bits = 0u32;
49    for &raw in values {
50        let v = raw & mask;
51        acc |= v << bits;
52        bits += width;
53        if bits >= 64 {
54            out.extend_from_slice(&acc.to_le_bytes());
55            bits -= 64;
56            acc = if bits == 0 { 0 } else { v >> (width - bits) };
57        }
58    }
59    if bits > 0 {
60        out.extend_from_slice(&acc.to_le_bytes());
61    }
62}
63
64/// Full-chunk transposed pack. Word `16 * r + lane` holds bit row r of
65/// lane `lane`; value i sits at bit `(i / 16) * width` of lane `i % 16`.
66fn pack_transposed(values: &[u64], width: u32, mask: u64, out: &mut Vec<u8>) {
67    let w = width as usize;
68    let mut words = [0u64; LANES * 63];
69    let words = &mut words[..LANES * w];
70    for (i, &raw) in values.iter().enumerate() {
71        let bit = i / LANES * w;
72        let (r, s) = (bit >> 6, (bit & 63) as u32);
73        let v = raw & mask;
74        words[LANES * r + i % LANES] |= v << s;
75        if s + width > 64 {
76            words[LANES * (r + 1) + i % LANES] |= v >> (64 - s);
77        }
78    }
79    for &word in words.iter() {
80        out.extend_from_slice(&word.to_le_bytes());
81    }
82}
83
84/// Unpacks one chunk. `out` must be exactly `CHUNK` long; `packed` holds
85/// whole words and may cover fewer than 1024 values, in which case the
86/// remainder of `out` is zeroed.
87///
88/// Dispatches to a const-width loop so every shift is a compile-time
89/// constant; the generic rolling-window fallback is an order of magnitude
90/// slower on older cores and exists only in tests as the oracle.
91pub fn unpack(packed: &[u8], width: u32, out: &mut [u64]) {
92    assert_eq!(out.len(), CHUNK);
93    assert!(width <= 64);
94    assert_eq!(packed.len() % 8, 0);
95    if width == 0 {
96        out.fill(0);
97        return;
98    }
99    if width == 64 {
100        let n = (packed.len() / 8).min(CHUNK);
101        for (chunk, slot) in packed.as_chunks::<8>().0.iter().zip(out.iter_mut()) {
102            *slot = u64::from_le_bytes(*chunk);
103        }
104        out[n..].fill(0);
105        return;
106    }
107    let full = width > 1 && packed.len() == 128 * width as usize;
108    macro_rules! dispatch {
109        ($($w:literal)*) => {
110            match width {
111                $($w if full => unpack_transposed::<$w>(packed, out),)*
112                $($w => unpack_const::<$w>(packed, out),)*
113                _ => unreachable!(),
114            }
115        };
116    }
117    dispatch!(
118        1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
119        23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
120        45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
121    );
122}
123
124/// Full-chunk transposed unpack. Each step reads the same bit position in
125/// all 16 lanes, so the lane loop is 16 identical shift-mask operations on
126/// consecutive words and vectorizes; the word-crossing branch depends only
127/// on the step, never the lane.
128fn unpack_transposed<const W: u32>(packed: &[u8], out: &mut [u64]) {
129    let mask: u64 = (1u64 << W) - 1;
130    let mut words = [0u64; LANES * 63];
131    for (slot, chunk) in words[..LANES * W as usize]
132        .iter_mut()
133        .zip(packed.as_chunks::<8>().0)
134    {
135        *slot = u64::from_le_bytes(*chunk);
136    }
137    for (t, out16) in out.as_chunks_mut::<LANES>().0.iter_mut().enumerate() {
138        let bit = t as u32 * W;
139        let r = (bit >> 6) as usize;
140        let s = bit & 63;
141        let lo = &words[LANES * r..LANES * (r + 1)];
142        if s + W > 64 {
143            let hi = &words[LANES * (r + 1)..LANES * (r + 2)];
144            for ((o, &l), &h) in out16.iter_mut().zip(lo).zip(hi) {
145                *o = ((l >> s) | (h << (64 - s))) & mask;
146            }
147        } else {
148            for (o, &l) in out16.iter_mut().zip(lo) {
149                *o = (l >> s) & mask;
150            }
151        }
152    }
153}
154
155fn unpack_const<const W: u32>(packed: &[u8], out: &mut [u64]) {
156    let mask: u64 = (1u64 << W) - 1;
157    // 16 words per width bit, 8 KiB at the widest, within the 64 KiB
158    // scratch contract.
159    let mut words = [0u64; 16 * 63];
160    for (slot, chunk) in words[..16 * W as usize]
161        .iter_mut()
162        .zip(packed.as_chunks::<8>().0)
163    {
164        *slot = u64::from_le_bytes(*chunk);
165    }
166    // 64 values consume exactly W words, so unroll in blocks of 64 with a
167    // repeating in-block shift pattern the compiler can flatten.
168    for (block, out_block) in out.as_chunks_mut::<64>().0.iter_mut().enumerate() {
169        let base = block * W as usize;
170        for (i, slot) in out_block.iter_mut().enumerate() {
171            let bit = i as u32 * W;
172            let w = base + (bit >> 6) as usize;
173            let s = bit & 63;
174            let lo = words[w] >> s;
175            *slot = if s + W > 64 {
176                (lo | (words[w + 1] << (64 - s))) & mask
177            } else {
178                lo & mask
179            };
180        }
181    }
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    fn xorshift(state: &mut u64) -> u64 {
189        *state ^= *state << 13;
190        *state ^= *state >> 7;
191        *state ^= *state << 17;
192        *state
193    }
194
195    #[test]
196    fn roundtrip_every_width() {
197        let mut rng = 0x2545F4914F6CDD1Du64;
198        for width in 0..=64u32 {
199            let mask = if width == 64 {
200                u64::MAX
201            } else {
202                (1u64 << width) - 1
203            };
204            let values: Vec<u64> = (0..CHUNK).map(|_| xorshift(&mut rng) & mask).collect();
205            let mut packed = Vec::new();
206            pack(&values, width, &mut packed);
207            assert_eq!(packed.len(), packed_bytes(width, CHUNK));
208            let mut out = vec![0u64; CHUNK];
209            unpack(&packed, width, &mut out);
210            assert_eq!(values, out, "width {width}");
211        }
212    }
213
214    #[test]
215    fn short_tail_packs_tight() {
216        let values = [7u64, 7, 7];
217        let mut packed = Vec::new();
218        pack(&values, 3, &mut packed);
219        assert_eq!(packed.len(), packed_bytes(3, 3));
220        assert_eq!(packed.len(), 8);
221        let mut out = vec![1u64; CHUNK];
222        unpack(&packed, 3, &mut out);
223        assert_eq!(&out[..3], &values);
224        assert!(out[3..].iter().all(|&v| v == 0));
225    }
226
227    #[test]
228    fn tail_boundaries_every_width() {
229        let mut rng = 0xDEADBEEFu64;
230        for width in 1..=64u32 {
231            let mask = if width == 64 {
232                u64::MAX
233            } else {
234                (1u64 << width) - 1
235            };
236            // 1000 and 1023 cover tails whose packed size collides with
237            // the full-chunk size at small widths, which must take the
238            // padded transposed layout.
239            for len in [1usize, 63, 64, 65, 1000, 1023, CHUNK] {
240                let values: Vec<u64> = (0..len).map(|_| xorshift(&mut rng) & mask).collect();
241                let mut packed = Vec::new();
242                pack(&values, width, &mut packed);
243                assert_eq!(packed.len(), packed_bytes(width, len), "w{width} n{len}");
244                let mut out = vec![1u64; CHUNK];
245                unpack(&packed, width, &mut out);
246                assert_eq!(&out[..len], values.as_slice(), "w{width} n{len}");
247                assert!(out[len..].iter().all(|&v| v == 0), "w{width} n{len} pad");
248            }
249        }
250    }
251}