Skip to main content

rudb_encoding/
bitpack.rs

1//! Bit packing in the FastLanes unified transposed layout.
2//!
3//! Packing N values of a fixed bit width into a dense buffer is the bottom of every integer
4//! encoding in `spec/06-compression.md` section 6.2. FOR subtracts a base and packs. DELTA
5//! differences and packs. DICT produces codes and packs them. So this is the one kernel that runs
6//! over more bytes than anything else in the system, and the layout it uses decides whether the
7//! decoder can be data parallel or has to walk a dependency chain.
8//!
9//! The obvious layout writes value 0 in the low bits of the first word, value 1 above it, and so
10//! on. Unpacking that requires knowing where the previous value ended, which is a sequential
11//! dependency, and a SIMD implementation has to fight it with shuffles that differ per width and
12//! per instruction set. FastLanes takes the other road. The 1024 values of a vector are seen as a
13//! matrix of `T` rows by `1024 / T` lanes, where `T` is the bit width of the type, and the packing
14//! runs down the rows of every lane at once. Every lane has the same bit schedule, so unpacking
15//! lane 0 and lane 31 is the same instruction sequence with no cross lane data movement at all.
16//! That is what makes one scalar reference implementation and one AVX-512 implementation and one
17//! NEON implementation agree bit for bit, and it is why the vector size is 1024 rather than a
18//! rounder number.
19//!
20//! The price is that the values come out permuted within the vector. Row `r` lane `l` is not the
21//! `r * lanes + l`th value of the input. Section 6.2 says why that is acceptable: an operator
22//! working inside one vector does not care what order the rows are in, so the permutation only
23//! has to be undone when a vector is materialized in row order. [`transpose`] and [`untranspose`]
24//! are that step, and they are deliberately separate from [`pack_transposed`] and
25//! [`unpack_transposed`] so that the engine can keep data permuted through a whole pipeline and
26//! pay for the reordering once at the end rather than twice per operator.
27//!
28//! There is a second layout in here, in [`pack_tail`], and it is the sequential one this module
29//! opens by arguing against. The transposed layout is all or nothing: a value lives at a row and a
30//! lane, the lanes are interleaved through the whole buffer, and no prefix of a packed unit holds a
31//! prefix of the values. So a unit holding 3 values costs exactly what a unit holding 1024 costs,
32//! and a cascade is full of short arrays. A five entry dictionary, a run length array, an exception
33//! list. Storing three numbers in 5 KB is not a compressed format. The tail packer handles anything
34//! shorter than a unit, it has the dependency chain the transposed layout exists to avoid, and that
35//! is affordable there and nowhere else, because a tail is at most 1023 values and is decoded once
36//! while a full unit is on the hot path of every scan in the system.
37//!
38//! The permutation itself is a fixed shuffle of the eight bit groups of a row index, in the order
39//! 0, 4, 2, 6, 1, 5, 3, 7. That order is not arbitrary. It is the one that makes an eight way
40//! interleave of the rows land back in sequence under the pairwise unpacking pattern the paper
41//! uses, and the important property for us is only that it is a bijection that both directions
42//! agree on.
43
44use rudb_common::{Error, Result};
45
46/// How many values a packed unit holds. One vector, per `spec/06-compression.md` section 6.2.
47pub const VALUES: usize = 1024;
48
49/// The interleaving order of the eight row groups. See the module documentation.
50const ORDER: [usize; 8] = [0, 4, 2, 6, 1, 5, 3, 7];
51
52mod sealed {
53    pub trait Sealed {}
54    impl Sealed for u8 {}
55    impl Sealed for u16 {}
56    impl Sealed for u32 {}
57    impl Sealed for u64 {}
58}
59
60/// An unsigned integer type that can be bit packed.
61///
62/// Sealed, because the layout constants are only correct for the four widths that divide 1024 into
63/// a whole number of lanes, and because every kernel here does its arithmetic in `u64` and relies
64/// on every implementor fitting in one.
65pub trait Packable: sealed::Sealed + Copy + Ord + std::fmt::Debug {
66    /// Width of the type in bits. `T` in the module documentation.
67    const WIDTH: usize;
68    /// How many of these fit in the 1024 bit virtual register, which is how many lanes there are.
69    const LANES: usize = VALUES / Self::WIDTH;
70
71    /// Widens to the type the packing arithmetic is done in.
72    fn to_u64(self) -> u64;
73    /// Narrows back. The high bits are already known to be zero.
74    fn from_u64(value: u64) -> Self;
75}
76
77macro_rules! impl_packable {
78    ($($ty:ty),*) => {$(
79        impl Packable for $ty {
80            const WIDTH: usize = <$ty>::BITS as usize;
81
82            #[inline]
83            fn to_u64(self) -> u64 {
84                u64::from(self)
85            }
86
87            #[inline]
88            fn from_u64(value: u64) -> Self {
89                value as $ty
90            }
91        }
92    )*};
93}
94
95impl_packable!(u8, u16, u32, u64);
96
97/// A mask of the low `bits` bits, correct at 0 and at 64 where the shift would overflow.
98#[inline]
99const fn low_mask(bits: usize) -> u64 {
100    if bits >= 64 { u64::MAX } else { (1u64 << bits) - 1 }
101}
102
103/// A right shift that saturates to zero at 64 rather than overflowing.
104#[inline]
105const fn shift_right(value: u64, bits: usize) -> u64 {
106    if bits >= 64 { 0 } else { value >> bits }
107}
108
109/// Where the value at row `row` lane `lane` of the transposed matrix came from in the input.
110///
111/// The row index is split into a group and an offset within the group, the group is permuted by
112/// the fixed order in the module documentation, and the two are recombined with the offset as the
113/// high part. The lane index is untouched, which is the property that makes the layout lane
114/// parallel.
115///
116/// # Panics
117///
118/// If `row` is not below `T::WIDTH` or `lane` is not below `T::LANES`.
119#[inline]
120#[must_use]
121pub fn source_index<T: Packable>(row: usize, lane: usize) -> usize {
122    assert!(row < T::WIDTH, "row {row} is outside a {} bit type", T::WIDTH);
123    assert!(lane < T::LANES, "lane {lane} is outside {} lanes", T::LANES);
124    let group_size = T::WIDTH / 8;
125    let group = row / group_size;
126    let offset = row % group_size;
127    ((offset * 8) + ORDER[group]) * T::LANES + lane
128}
129
130/// Rewrites 1024 values from row order into the transposed layout.
131///
132/// # Errors
133///
134/// If either slice is not exactly [`VALUES`] long.
135pub fn transpose<T: Packable>(input: &[T], output: &mut [T]) -> Result<()> {
136    check_vector_len(input.len(), "input")?;
137    check_vector_len(output.len(), "output")?;
138    for row in 0..T::WIDTH {
139        for lane in 0..T::LANES {
140            output[row * T::LANES + lane] = input[source_index::<T>(row, lane)];
141        }
142    }
143    Ok(())
144}
145
146/// Rewrites 1024 values from the transposed layout back into row order.
147///
148/// # Errors
149///
150/// If either slice is not exactly [`VALUES`] long.
151pub fn untranspose<T: Packable>(input: &[T], output: &mut [T]) -> Result<()> {
152    check_vector_len(input.len(), "input")?;
153    check_vector_len(output.len(), "output")?;
154    for row in 0..T::WIDTH {
155        for lane in 0..T::LANES {
156            output[source_index::<T>(row, lane)] = input[row * T::LANES + lane];
157        }
158    }
159    Ok(())
160}
161
162/// How many words of `T` a packed vector of the given width occupies.
163///
164/// Every lane contributes `width` words, which is the same `width * 1024` bits the naive layout
165/// would use. The layout costs nothing in space.
166#[must_use]
167pub fn packed_len<T: Packable>(width: usize) -> usize {
168    width * T::LANES
169}
170
171/// The smallest bit width that can hold every value in the slice. Zero for an empty slice or a
172/// slice of zeros, which [`pack_transposed`] handles as the degenerate case that stores nothing.
173#[must_use]
174pub fn required_width<T: Packable>(values: &[T]) -> usize {
175    let max = values.iter().copied().max().map_or(0, T::to_u64);
176    (64 - max.leading_zeros()) as usize
177}
178
179/// Packs a transposed vector at a fixed bit width.
180///
181/// The input is 1024 values already in the layout [`transpose`] produces, and the output is
182/// [`packed_len`] words. Every lane is packed independently and the loop over lanes is the one a
183/// SIMD implementation replaces with a single register.
184///
185/// # Errors
186///
187/// If the input is not [`VALUES`] long, if the output is not [`packed_len`] long, if `width`
188/// exceeds the width of the type, or if a value does not fit in `width` bits.
189pub fn pack_transposed<T: Packable>(input: &[T], width: usize, output: &mut [T]) -> Result<()> {
190    check_vector_len(input.len(), "input")?;
191    check_width::<T>(width)?;
192    if output.len() != packed_len::<T>(width) {
193        return Err(Error::internal(format!(
194            "a {width} bit packed vector is {} words, not {}",
195            packed_len::<T>(width),
196            output.len()
197        )));
198    }
199    if width == 0 {
200        // Nothing is stored. The caller has already established that every value is zero, either
201        // by asking for `required_width` or by being the CONSTANT encoding, and the check below
202        // enforces it rather than trusting it.
203        return check_all_zero(input);
204    }
205
206    let mask = low_mask(width);
207    let lanes = T::LANES;
208    for lane in 0..lanes {
209        // Bits already sitting in `accumulator`, always below `T::WIDTH` between iterations.
210        let mut filled = 0usize;
211        let mut accumulator = 0u64;
212        let mut word = 0usize;
213        for row in 0..T::WIDTH {
214            let value = input[row * lanes + lane].to_u64();
215            if value & !mask != 0 {
216                return Err(Error::internal(format!("value {value} does not fit in {width} bits")));
217            }
218            accumulator |= value << filled;
219            filled += width;
220            if filled >= T::WIDTH {
221                output[word * lanes + lane] = T::from_u64(accumulator & low_mask(T::WIDTH));
222                word += 1;
223                // The only value that can straddle the word boundary is the one just written, so
224                // the carry is a shift of it rather than anything kept from earlier rows.
225                let consumed = width - (filled - T::WIDTH);
226                filled -= T::WIDTH;
227                accumulator = shift_right(value, consumed);
228            }
229        }
230        debug_assert_eq!(filled, 0, "a packed lane always ends on a word boundary");
231    }
232    Ok(())
233}
234
235/// Unpacks into the transposed layout. The inverse of [`pack_transposed`].
236///
237/// # Errors
238///
239/// If the input is not [`packed_len`] long, if the output is not [`VALUES`] long, or if `width`
240/// exceeds the width of the type.
241pub fn unpack_transposed<T: Packable>(input: &[T], width: usize, output: &mut [T]) -> Result<()> {
242    check_width::<T>(width)?;
243    check_vector_len(output.len(), "output")?;
244    if input.len() != packed_len::<T>(width) {
245        return Err(Error::internal(format!(
246            "a {width} bit packed vector is {} words, not {}",
247            packed_len::<T>(width),
248            input.len()
249        )));
250    }
251    if width == 0 {
252        output.fill(T::from_u64(0));
253        return Ok(());
254    }
255
256    let mask = low_mask(width);
257    let lanes = T::LANES;
258    for lane in 0..lanes {
259        // Bits of the current word not yet handed out, right aligned in `buffer`.
260        let mut available = 0usize;
261        let mut buffer = 0u64;
262        let mut word = 0usize;
263        for row in 0..T::WIDTH {
264            let value = if available >= width {
265                let value = buffer & mask;
266                buffer = shift_right(buffer, width);
267                available -= width;
268                value
269            } else {
270                let next = input[word * lanes + lane].to_u64();
271                word += 1;
272                let taken = width - available;
273                let value = buffer | ((next & low_mask(taken)) << available);
274                buffer = shift_right(next, taken);
275                available = T::WIDTH - taken;
276                value
277            };
278            output[row * lanes + lane] = T::from_u64(value);
279        }
280    }
281    Ok(())
282}
283
284/// The buffer [`pack_with`] and [`unpack_with`] transpose through, kept so it can be reused.
285///
286/// Going between row order and the transposed layout needs somewhere to put the other order, and
287/// that somewhere is [`VALUES`] values, which is 8 KB for a `u64`. Allocating it per call is not the
288/// expensive part. Zeroing it is, because the allocator hands back a page it has to clear and the
289/// transpose then writes every element of it anyway. On a scan of a packed integer column that is
290/// once per 1024 rows, and it showed up as the largest single item in a ClickBench profile, larger
291/// than the unpacking it was making room for.
292///
293/// So a caller that unpacks more than one unit should make one of these and pass it in.
294///
295/// It starts empty and grows on the first unit that needs it, because a caller holds one for a whole
296/// decode and most chunks are not bit packed at all. Making the buffer in the constructor was tried
297/// and was worse than what it replaced, by more than the zeroing it saved.
298#[derive(Debug)]
299pub struct Scratch<T: Packable> {
300    transposed: Vec<T>,
301}
302
303impl<T: Packable> Scratch<T> {
304    /// A scratch buffer that has not made room for anything yet.
305    #[must_use]
306    pub const fn new() -> Self {
307        Self { transposed: Vec::new() }
308    }
309
310    /// Makes room for one unit. A no op every time after the first.
311    fn ready(&mut self) {
312        if self.transposed.len() != VALUES {
313            self.transposed.resize(VALUES, T::from_u64(0));
314        }
315    }
316}
317
318impl<T: Packable> Default for Scratch<T> {
319    fn default() -> Self {
320        Self::new()
321    }
322}
323
324/// Packs a vector given in row order, transposing it first.
325///
326/// The engine does not use this. Data written by the storage layer is transposed once on the way
327/// in and stays that way, per the module documentation. This exists for tests, for the format lab,
328/// and for the one place that has to hand back a vector in the order the user gave it.
329///
330/// # Errors
331///
332/// As [`pack_transposed`].
333pub fn pack<T: Packable>(input: &[T], width: usize, output: &mut [T]) -> Result<()> {
334    pack_with(input, width, output, &mut Scratch::new())
335}
336
337/// As [`pack`], through a buffer the caller keeps rather than one allocated per call.
338///
339/// # Errors
340///
341/// As [`pack_transposed`].
342pub fn pack_with<T: Packable>(
343    input: &[T],
344    width: usize,
345    output: &mut [T],
346    scratch: &mut Scratch<T>,
347) -> Result<()> {
348    check_vector_len(input.len(), "input")?;
349    scratch.ready();
350    transpose(input, &mut scratch.transposed)?;
351    pack_transposed(&scratch.transposed, width, output)
352}
353
354/// Unpacks into row order. The inverse of [`pack`], and see its note about who should call it.
355///
356/// # Errors
357///
358/// As [`unpack_transposed`].
359pub fn unpack<T: Packable>(input: &[T], width: usize, output: &mut [T]) -> Result<()> {
360    unpack_with(input, width, output, &mut Scratch::new())
361}
362
363/// As [`unpack`], through a buffer the caller keeps rather than one allocated per call.
364///
365/// # Errors
366///
367/// As [`unpack_transposed`].
368pub fn unpack_with<T: Packable>(
369    input: &[T],
370    width: usize,
371    output: &mut [T],
372    scratch: &mut Scratch<T>,
373) -> Result<()> {
374    check_vector_len(output.len(), "output")?;
375    scratch.ready();
376    unpack_transposed(input, width, &mut scratch.transposed)?;
377    untranspose(&scratch.transposed, output)
378}
379
380/// How many bytes [`pack_tail`] writes for `count` values at `width` bits.
381#[must_use]
382pub fn tail_len(count: usize, width: usize) -> usize {
383    (count * width).div_ceil(8)
384}
385
386/// Packs fewer than [`VALUES`] values, sequentially and to a byte boundary.
387///
388/// The transposed layout is all or nothing. A value lives at a row and a lane, the lanes are
389/// interleaved through the whole buffer, and there is no prefix of a packed unit that holds a
390/// prefix of the values. So a unit holding 3 values costs the same as a unit holding 1024, which is
391/// 5 KB to store three numbers, and every nested array in a cascade is short: a dictionary of five
392/// entries, a run length array, an exception list.
393///
394/// This is the other layout for exactly those. It is the obvious sequential one, value 0 in the low
395/// bits, and it has the dependency chain the transposed layout was chosen to avoid. That is
396/// affordable here and only here: a tail is at most 1023 values and is decoded once, so the chain
397/// is bounded by a number that does not grow with the data, while a full unit is on the hot path of
398/// every scan in the system.
399///
400/// # Errors
401///
402/// If `count` is not below [`VALUES`], if `width` exceeds 64, or if a value does not fit.
403pub fn pack_tail(values: &[u64], width: usize, output: &mut Vec<u8>) -> Result<()> {
404    check_tail(values.len(), width)?;
405    if width == 0 {
406        return check_all_zero(values);
407    }
408    let mask = low_mask(width);
409    // 128 bits, because the accumulator holds up to 7 bits left over from the previous value plus a
410    // whole 64 bit one.
411    let mut accumulator: u128 = 0;
412    let mut filled = 0usize;
413    for value in values {
414        if value & !mask != 0 {
415            return Err(Error::internal(format!("value {value} does not fit in {width} bits")));
416        }
417        accumulator |= u128::from(*value) << filled;
418        filled += width;
419        while filled >= 8 {
420            output.push((accumulator & 0xff) as u8);
421            accumulator >>= 8;
422            filled -= 8;
423        }
424    }
425    if filled > 0 {
426        output.push((accumulator & 0xff) as u8);
427    }
428    Ok(())
429}
430
431/// Unpacks what [`pack_tail`] wrote.
432///
433/// The writer has a dependency chain because it has to know how many bits are left over from the
434/// value before, but the reader does not, and this does not carry one. Value `index` occupies the
435/// `width` bits starting at bit `index * width`, so its position is arithmetic rather than history,
436/// and since it begins at most seven bits into a byte and runs at most sixty four, it always lies
437/// inside sixteen bytes read from that byte. One unaligned load, one shift and one mask.
438///
439/// That matters more than the module documentation lets on. The argument there is that a tail is at
440/// most 1023 values and so is bounded by a number that does not grow with the data, which is true
441/// per call and misleading in aggregate, because a cascade puts a short array in every chunk and a
442/// scan reads every chunk. ClickBench 9 is where it showed. UserID is nearly unique, so its
443/// dictionary holds about a thousand sixty four bit values per part and lands one value short of a
444/// full unit, which sends the whole column down this path: nine hundred and seventy four parts,
445/// about a million values, and the byte at a time version fed eight bytes through a `u128` for each
446/// one. That was fifty five percent of the instructions of a scan of that column on its own.
447///
448/// # Errors
449///
450/// If `count` is not below [`VALUES`], if `width` exceeds 64, or if the input is shorter than
451/// [`tail_len`].
452pub fn unpack_tail(input: &[u8], width: usize, count: usize) -> Result<Vec<u64>> {
453    check_tail(count, width)?;
454    if width == 0 {
455        return Ok(vec![0; count]);
456    }
457    if input.len() < tail_len(count, width) {
458        return Err(Error::internal(format!(
459            "{count} values at {width} bits need {} bytes and there are {}",
460            tail_len(count, width),
461            input.len()
462        )));
463    }
464    let mask = u128::from(low_mask(width));
465    let mut values = Vec::with_capacity(count);
466    let read = |window: u128, bit: usize| ((window >> bit) & mask) as u64;
467    // A buffer shorter than a window is one load for the whole call, because everything it holds is
468    // inside it. Short arrays are most of what a cascade stores, so this is the common case by
469    // count of calls even though it is the rare one by count of values.
470    if input.len() < WINDOW {
471        let mut window = [0u8; WINDOW];
472        window[..input.len()].copy_from_slice(input);
473        let word = u128::from_le_bytes(window);
474        for index in 0..count {
475            values.push(read(word, index * width));
476        }
477        return Ok(values);
478    }
479    // Otherwise a value is read where it lies, until the window would run off the end.
480    let whole = (((input.len() - WINDOW) * 8) / width + 1).min(count);
481    for index in 0..whole {
482        let bit = index * width;
483        let mut window = [0u8; WINDOW];
484        window.copy_from_slice(&input[bit / 8..bit / 8 + WINDOW]);
485        values.push(read(u128::from_le_bytes(window), bit % 8));
486    }
487    if whole < count {
488        // Every value left over begins past the sixteenth byte from the end, by the definition of
489        // `whole` just above, and the buffer stops on the byte holding the top bits of the last
490        // one. So all of them lie inside the final window and one load serves the lot.
491        let base = input.len() - WINDOW;
492        let mut window = [0u8; WINDOW];
493        window.copy_from_slice(&input[base..]);
494        let word = u128::from_le_bytes(window);
495        for index in whole..count {
496            values.push(read(word, index * width - base * 8));
497        }
498    }
499    Ok(values)
500}
501
502/// The bytes a single tail value can span, which is a shift of at most seven plus a width of at
503/// most sixty four, so seventy one bits and therefore nine bytes, rounded up to the load that
504/// covers it.
505/// One value of a run written by [`pack_tail`], read where it lies.
506///
507/// [`unpack_tail`] decodes the whole run, which is what a scan wants and what nearly every caller
508/// here is. A binary search is the other kind of caller: it wants one value out of the middle of a
509/// block, it makes about as many probes as the block has bits, and decoding the block to answer one
510/// of them would cost more than reading the value it was avoiding.
511///
512/// # Errors
513///
514/// If `width` exceeds 64, or if the value would run past the end of `input`.
515pub fn tail_at(input: &[u8], width: usize, index: usize) -> Result<u64> {
516    if width > 64 {
517        return Err(Error::internal(format!("a width of {width} is past what a u64 holds")));
518    }
519    if width == 0 {
520        return Ok(0);
521    }
522    let start = index * width;
523    let end = start + width;
524    if end.div_ceil(8) > input.len() {
525        return Err(Error::internal(format!(
526            "value {index} at {width} bits ends past the {} bytes there are",
527            input.len()
528        )));
529    }
530    // The value spans at most nine bytes, which is a whole `u64` straddling a byte boundary, so one
531    // window covers it wherever it starts.
532    let first = start / 8;
533    let last = (end - 1) / 8;
534    let mut window = [0u8; WINDOW];
535    window[..=last - first].copy_from_slice(&input[first..=last]);
536    let word = u128::from_le_bytes(window);
537    Ok(((word >> (start % 8)) & u128::from(low_mask(width))) as u64)
538}
539
540const WINDOW: usize = 16;
541
542fn check_tail(count: usize, width: usize) -> Result<()> {
543    if count >= VALUES {
544        return Err(Error::internal(format!(
545            "{count} values is a whole unit and belongs in the transposed layout"
546        )));
547    }
548    if width > 64 {
549        return Err(Error::internal(format!("{width} bits does not fit in 64")));
550    }
551    Ok(())
552}
553
554fn check_vector_len(len: usize, what: &str) -> Result<()> {
555    if len == VALUES {
556        Ok(())
557    } else {
558        Err(Error::internal(format!("{what} is {len} values, and a packed unit is {VALUES}")))
559    }
560}
561
562fn check_width<T: Packable>(width: usize) -> Result<()> {
563    if width <= T::WIDTH {
564        Ok(())
565    } else {
566        Err(Error::internal(format!("{width} bits does not fit in a {} bit type", T::WIDTH)))
567    }
568}
569
570fn check_all_zero<T: Packable>(input: &[T]) -> Result<()> {
571    match input.iter().position(|value| value.to_u64() != 0) {
572        None => Ok(()),
573        Some(index) => Err(Error::internal(format!(
574            "a zero bit vector cannot hold {:?} at {index}",
575            input[index]
576        ))),
577    }
578}
579
580#[cfg(test)]
581mod tests {
582    use super::*;
583
584    /// A xorshift, so that the test data is the same on every host and in every run without the
585    /// workspace growing a dependency for it.
586    struct Random(u64);
587
588    impl Random {
589        fn new() -> Self {
590            Self(0x2545_f491_4f6c_dd1d)
591        }
592
593        fn next(&mut self) -> u64 {
594            self.0 ^= self.0 << 13;
595            self.0 ^= self.0 >> 7;
596            self.0 ^= self.0 << 17;
597            self.0
598        }
599    }
600
601    fn sample<T: Packable>(width: usize) -> Vec<T> {
602        let mut random = Random::new();
603        (0..VALUES).map(|_| T::from_u64(random.next() & low_mask(width))).collect()
604    }
605
606    fn round_trip<T: Packable>(width: usize) {
607        let values = sample::<T>(width);
608        let mut packed = vec![T::from_u64(0); packed_len::<T>(width)];
609        pack(&values, width, &mut packed).unwrap();
610        let mut back = vec![T::from_u64(0); VALUES];
611        unpack(&packed, width, &mut back).unwrap();
612        assert_eq!(back, values, "{width} bits of a {} bit type", T::WIDTH);
613    }
614
615    #[test]
616    fn every_width_of_every_type_round_trips() {
617        for width in 0..=8 {
618            round_trip::<u8>(width);
619        }
620        for width in 0..=16 {
621            round_trip::<u16>(width);
622        }
623        for width in 0..=32 {
624            round_trip::<u32>(width);
625        }
626        for width in 0..=64 {
627            round_trip::<u64>(width);
628        }
629    }
630
631    #[test]
632    fn a_reused_scratch_gives_what_a_fresh_one_gives() {
633        // The buffer a unit transposes through is now handed in so it is not zeroed per call, which
634        // is only sound if every element of it is written every time. If some were not, a narrow
635        // unit following a wide one would read whatever the wide one left behind, so the widths here
636        // go up and down rather than in order and each answer is checked against the same unit
637        // unpacked through a buffer nothing has touched.
638        let mut scratch = Scratch::<u64>::new();
639        for width in [64, 1, 33, 7, 64, 0, 17, 60, 3] {
640            let values = sample::<u64>(width);
641            let mut packed = vec![0u64; packed_len::<u64>(width)];
642            pack_with(&values, width, &mut packed, &mut scratch).unwrap();
643            let mut reused = vec![0u64; VALUES];
644            unpack_with(&packed, width, &mut reused, &mut scratch).unwrap();
645            let mut fresh = vec![0u64; VALUES];
646            unpack(&packed, width, &mut fresh).unwrap();
647            assert_eq!(reused, fresh, "at {width} bits after a wider unit");
648            assert_eq!(reused, values, "at {width} bits");
649        }
650    }
651
652    #[test]
653    fn the_transposed_form_also_round_trips_without_being_reordered() {
654        // What the engine actually does: transpose once, then pack and unpack any number of times
655        // without ever going back to row order.
656        let values = sample::<u32>(19);
657        let mut transposed = vec![0u32; VALUES];
658        transpose(&values, &mut transposed).unwrap();
659        let mut packed = vec![0u32; packed_len::<u32>(19)];
660        pack_transposed(&transposed, 19, &mut packed).unwrap();
661        let mut back = vec![0u32; VALUES];
662        unpack_transposed(&packed, 19, &mut back).unwrap();
663        assert_eq!(back, transposed);
664    }
665
666    #[test]
667    fn the_permutation_is_a_bijection() {
668        // Every value has to land somewhere and no two may land in the same place, or a round trip
669        // would silently drop rows. Checked for all four widths because the group size changes.
670        fn check<T: Packable>() {
671            let mut seen = vec![false; VALUES];
672            for row in 0..T::WIDTH {
673                for lane in 0..T::LANES {
674                    let index = source_index::<T>(row, lane);
675                    assert!(!seen[index], "{index} is written twice for {} bits", T::WIDTH);
676                    seen[index] = true;
677                }
678            }
679            assert!(seen.into_iter().all(|hit| hit));
680        }
681        check::<u8>();
682        check::<u16>();
683        check::<u32>();
684        check::<u64>();
685    }
686
687    #[test]
688    fn transposing_is_not_the_identity() {
689        // If it were, the test above would be passing on a layout that is not the FastLanes one.
690        let values: Vec<u32> = (0..VALUES).map(|index| index as u32).collect();
691        let mut transposed = vec![0u32; VALUES];
692        transpose(&values, &mut transposed).unwrap();
693        assert_ne!(transposed, values);
694        let mut back = vec![0u32; VALUES];
695        untranspose(&transposed, &mut back).unwrap();
696        assert_eq!(back, values);
697    }
698
699    #[test]
700    fn a_full_width_pack_is_the_data_itself() {
701        // 64 bits of a 64 bit type has no packing to do, and the loop that handles the general case
702        // has to get the degenerate one right rather than shifting by 64 and wrapping.
703        let values = sample::<u64>(64);
704        let mut transposed = vec![0u64; VALUES];
705        transpose(&values, &mut transposed).unwrap();
706        let mut packed = vec![0u64; packed_len::<u64>(64)];
707        pack_transposed(&transposed, 64, &mut packed).unwrap();
708        assert_eq!(packed, transposed);
709    }
710
711    #[test]
712    fn a_zero_width_vector_stores_nothing_and_reads_back_as_zeros() {
713        let values = vec![0u32; VALUES];
714        assert_eq!(required_width(&values), 0);
715        let mut packed = Vec::new();
716        pack(&values, 0, &mut packed).unwrap();
717        let mut back = vec![7u32; VALUES];
718        unpack(&packed, 0, &mut back).unwrap();
719        assert_eq!(back, values);
720    }
721
722    #[test]
723    fn required_width_is_the_bits_of_the_largest_value() {
724        assert_eq!(required_width::<u32>(&[]), 0);
725        assert_eq!(required_width::<u32>(&[0, 0]), 0);
726        assert_eq!(required_width::<u32>(&[1]), 1);
727        assert_eq!(required_width::<u32>(&[255, 3]), 8);
728        assert_eq!(required_width::<u32>(&[256]), 9);
729        assert_eq!(required_width::<u64>(&[u64::MAX]), 64);
730    }
731
732    #[test]
733    fn a_value_too_wide_for_the_width_is_an_error_rather_than_silent_truncation() {
734        let mut values = vec![0u32; VALUES];
735        values[500] = 8;
736        let mut transposed = vec![0u32; VALUES];
737        transpose(&values, &mut transposed).unwrap();
738        let mut packed = vec![0u32; packed_len::<u32>(3)];
739        let error = pack_transposed(&transposed, 3, &mut packed).unwrap_err();
740        assert!(error.message().contains("does not fit in 3 bits"), "{error}");
741    }
742
743    #[test]
744    fn a_wrong_sized_buffer_is_an_error() {
745        let values = vec![0u32; VALUES];
746        let mut packed = vec![0u32; 3];
747        let error = pack(&values, 5, &mut packed).unwrap_err();
748        assert!(error.message().contains("words"), "{error}");
749
750        let short = vec![0u32; 7];
751        let mut output = vec![0u32; VALUES];
752        let error = unpack(&short, 5, &mut output).unwrap_err();
753        assert!(error.message().contains("words"), "{error}");
754    }
755
756    #[test]
757    fn a_nonzero_value_at_zero_width_is_an_error() {
758        let mut values = vec![0u32; VALUES];
759        values[9] = 1;
760        let mut packed = Vec::new();
761        let error = pack(&values, 0, &mut packed).unwrap_err();
762        assert!(error.message().contains("zero bit vector"), "{error}");
763    }
764
765    #[test]
766    fn packing_at_a_width_the_type_cannot_hold_is_an_error() {
767        let values = vec![0u16; VALUES];
768        let mut packed = vec![0u16; 17 * 64];
769        let error = pack(&values, 17, &mut packed).unwrap_err();
770        assert!(error.message().contains("16 bit type"), "{error}");
771    }
772
773    #[test]
774    fn a_tail_round_trips_at_every_width_and_every_length() {
775        let mut random = Random::new();
776        for width in 0..=64usize {
777            for count in [0usize, 1, 2, 7, 8, 9, 100, 1023] {
778                let values: Vec<u64> =
779                    (0..count).map(|_| random.next() & low_mask(width)).collect();
780                let mut bytes = Vec::new();
781                pack_tail(&values, width, &mut bytes).unwrap();
782                assert_eq!(bytes.len(), tail_len(count, width), "{count} at {width}");
783                assert_eq!(
784                    unpack_tail(&bytes, width, count).unwrap(),
785                    values,
786                    "{count} at {width}"
787                );
788            }
789        }
790    }
791
792    /// Reading one value where it lies agrees with decoding the whole run.
793    ///
794    /// Every width and every position, since the point of it is the arithmetic that finds the bytes
795    /// a value straddles, and that is what is off by one.
796    ///
797    /// A value that runs off the buffer is an error. The buffer stops on a byte boundary and a value
798    /// does not, so an index a little past the count can still lie inside the padding of the last
799    /// byte and that reads rather than complains. It is the caller that knows how many values it
800    /// wrote, the same way it does for `unpack_tail`.
801    #[test]
802    fn one_value_of_a_tail_reads_the_same_as_the_whole_of_it() {
803        let mut random = Random::new();
804        for width in 0..=64usize {
805            let count = 37;
806            let values: Vec<u64> = (0..count).map(|_| random.next() & low_mask(width)).collect();
807            let mut bytes = Vec::new();
808            pack_tail(&values, width, &mut bytes).unwrap();
809            for (index, value) in values.iter().enumerate() {
810                assert_eq!(tail_at(&bytes, width, index).unwrap(), *value, "{index} at {width}");
811            }
812            let Some(fits) = (bytes.len() * 8).checked_div(width) else { continue };
813            assert!(tail_at(&bytes, width, fits + 1).is_err(), "past the end at {width}");
814        }
815    }
816
817    /// The two halves of the reader agree with each other.
818    ///
819    /// A value is read with one sixteen byte load, which the values near the end of the buffer
820    /// cannot have because the buffer stops on the byte holding the top bits of the last one. Those
821    /// go through a zero padded copy instead, and the split between the two is arithmetic on
822    /// lengths, which is the kind of thing that is off by one. Handing the same bytes to the reader
823    /// twice, once exactly sized so the last values take the padded path and once with slack on the
824    /// end so every value takes the fast one, makes the two paths check each other at every width.
825    #[test]
826    fn the_padded_end_of_a_tail_reads_the_same_as_the_windowed_start() {
827        let mut random = Random::new();
828        for width in 1..=64usize {
829            for count in [1usize, 2, 3, 17, 129, 1023] {
830                let values: Vec<u64> =
831                    (0..count).map(|_| random.next() & low_mask(width)).collect();
832                let mut exact = Vec::new();
833                pack_tail(&values, width, &mut exact).unwrap();
834                let mut slack = exact.clone();
835                slack.extend_from_slice(&[0u8; WINDOW]);
836                assert_eq!(
837                    unpack_tail(&exact, width, count).unwrap(),
838                    values,
839                    "{count} at {width}"
840                );
841                assert_eq!(
842                    unpack_tail(&slack, width, count).unwrap(),
843                    values,
844                    "{count} at {width}"
845                );
846            }
847        }
848    }
849
850    #[test]
851    fn a_tail_costs_its_own_values_and_not_a_whole_unit() {
852        // The reason it exists. Three 40 bit values in the transposed layout is a 5 KB buffer.
853        let values = vec![(1u64 << 39) + 1; 3];
854        let mut bytes = Vec::new();
855        pack_tail(&values, 40, &mut bytes).unwrap();
856        assert_eq!(bytes.len(), 15);
857        assert_eq!(packed_len::<u64>(40) * 8, 5120);
858    }
859
860    #[test]
861    fn a_whole_unit_is_refused_by_the_tail_packer() {
862        let values = vec![0u64; VALUES];
863        let error = pack_tail(&values, 4, &mut Vec::new()).unwrap_err();
864        assert!(error.message().contains("whole unit"), "{error}");
865    }
866
867    #[test]
868    fn a_short_tail_buffer_is_an_error() {
869        let error = unpack_tail(&[0, 0], 8, 5).unwrap_err();
870        assert!(error.message().contains("need 5 bytes"), "{error}");
871    }
872
873    #[test]
874    fn the_packed_size_is_the_same_as_the_naive_layout() {
875        for width in 0..=32 {
876            assert_eq!(packed_len::<u32>(width) * 32, width * VALUES);
877        }
878    }
879}