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`] transposes 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 packs more than one unit should make one of these and pass it in. The unpacking
294/// side does not need one at all any more: see [`unpack`].
295///
296/// It starts empty and grows on the first unit that needs it, because a caller holds one for a whole
297/// decode and most chunks are not bit packed at all. Making the buffer in the constructor was tried
298/// and was worse than what it replaced, by more than the zeroing it saved.
299#[derive(Debug)]
300pub struct Scratch<T: Packable> {
301 transposed: Vec<T>,
302}
303
304impl<T: Packable> Scratch<T> {
305 /// A scratch buffer that has not made room for anything yet.
306 #[must_use]
307 pub const fn new() -> Self {
308 Self { transposed: Vec::new() }
309 }
310
311 /// Makes room for one unit. A no op every time after the first.
312 fn ready(&mut self) {
313 if self.transposed.len() != VALUES {
314 self.transposed.resize(VALUES, T::from_u64(0));
315 }
316 }
317}
318
319impl<T: Packable> Default for Scratch<T> {
320 fn default() -> Self {
321 Self::new()
322 }
323}
324
325/// Packs a vector given in row order, transposing it first.
326///
327/// The engine does not use this. Data written by the storage layer is transposed once on the way
328/// in and stays that way, per the module documentation. This exists for tests, for the format lab,
329/// and for the one place that has to hand back a vector in the order the user gave it.
330///
331/// # Errors
332///
333/// As [`pack_transposed`].
334pub fn pack<T: Packable>(input: &[T], width: usize, output: &mut [T]) -> Result<()> {
335 pack_with(input, width, output, &mut Scratch::new())
336}
337
338/// As [`pack`], through a buffer the caller keeps rather than one allocated per call.
339///
340/// # Errors
341///
342/// As [`pack_transposed`].
343pub fn pack_with<T: Packable>(
344 input: &[T],
345 width: usize,
346 output: &mut [T],
347 scratch: &mut Scratch<T>,
348) -> Result<()> {
349 check_vector_len(input.len(), "input")?;
350 scratch.ready();
351 transpose(input, &mut scratch.transposed)?;
352 pack_transposed(&scratch.transposed, width, output)
353}
354
355/// Unpacks into row order. The inverse of [`pack`].
356///
357/// This is what every scan of a packed integer column goes through, so it is written as one pass
358/// rather than as [`unpack_transposed`] followed by [`untranspose`]. Those two are still here and
359/// still the definition of the layout, and the test below checks this agrees with them at every
360/// width, but running them in sequence costs three things this does not. A 1024 value buffer to
361/// hold the middle, a second read of all of it, and a scatter: `untranspose` walks its input in
362/// order and writes all over its output, which is a store that misses and a loop no compiler will
363/// turn into wider instructions.
364///
365/// The fused form works because a row has the same bit schedule in every lane. That is the whole
366/// point of the layout. Row `r` of every lane takes bits `r * width` to `(r + 1) * width` of that
367/// lane's stream, so which word to read and how far to shift it are decided once for the row, and
368/// what is left for the lanes is a load, a shift, an or, a mask and a store with no branch and no
369/// carry from the lane before. The lanes of a row are next to each other in both the packed words
370/// and the output, so that inner loop reads and writes straight lines. Where a row lands in the
371/// output is the permutation `untranspose` was applying, and since the lane index is the low part
372/// of it, it comes out as a base address for the row and costs nothing.
373///
374/// # Errors
375///
376/// As [`unpack_transposed`].
377pub fn unpack<T: Packable>(input: &[T], width: usize, output: &mut [T]) -> Result<()> {
378 unpack_mapped(input, width, output, T::from_u64)
379}
380
381/// As [`unpack`], putting each value through `value` on the way out.
382///
383/// The caller that wants this is one whose output is not the packed type. Frame of reference coding
384/// stores offsets from a base and hands back the base plus the offset, and a decode that unpacks
385/// into a buffer of offsets and then walks that buffer adding the base writes every value twice and
386/// reads it once in between. There is nowhere for the second pass to hide: the buffer is 8 KB, a
387/// chunk is about one unit, and a scan reads a chunk per part per column, so the pass is the same
388/// order of work as the unpacking it follows.
389///
390/// The mapping belongs at the store rather than after it because that is the one place the value is
391/// already in a register. Both loops below end in a store, so `value` is applied to something
392/// nothing else has to load again, and for the identity it compiles to what [`unpack`] compiled to
393/// before this existed.
394///
395/// # Errors
396///
397/// As [`unpack_transposed`].
398pub fn unpack_mapped<T: Packable, U: Copy>(
399 input: &[T],
400 width: usize,
401 output: &mut [U],
402 value: impl Fn(u64) -> U,
403) -> Result<()> {
404 check_width::<T>(width)?;
405 check_vector_len(output.len(), "output")?;
406 if input.len() != packed_len::<T>(width) {
407 return Err(Error::internal(format!(
408 "a {width} bit packed vector is {} words, not {}",
409 packed_len::<T>(width),
410 input.len()
411 )));
412 }
413 if width == 0 {
414 output.fill(value(0));
415 return Ok(());
416 }
417
418 let mask = low_mask(width);
419 let lanes = T::LANES;
420 let group_size = T::WIDTH / 8;
421 for row in 0..T::WIDTH {
422 let bit = row * width;
423 let word = bit / T::WIDTH;
424 let shift = bit % T::WIDTH;
425 // The same arithmetic as `source_index` with the lane left off, because the lane is the low
426 // part of it and the lanes of a row are consecutive from here.
427 let base = ((row % group_size) * 8 + ORDER[row / group_size]) * lanes;
428 let low = &input[word * lanes..(word + 1) * lanes];
429 let into = &mut output[base..base + lanes];
430 if shift + width <= T::WIDTH {
431 for lane in 0..lanes {
432 into[lane] = value((low[lane].to_u64() >> shift) & mask);
433 }
434 } else {
435 // The value straddles two words, so `shift` is above zero, the carry in from the word
436 // above is a left shift by less than the word width, and neither shift can overflow.
437 // There is a word above to read: a value that straddles into word `word + 1` is one the
438 // packer wrote there, and it wrote `width` words a lane.
439 let carried = T::WIDTH - shift;
440 let high = &input[(word + 1) * lanes..(word + 2) * lanes];
441 for lane in 0..lanes {
442 let bits = (low[lane].to_u64() >> shift) | (high[lane].to_u64() << carried);
443 into[lane] = value(bits & mask);
444 }
445 }
446 }
447 Ok(())
448}
449
450/// Reads one value from a full transposed unit of packed `u64` values.
451///
452/// The serialized integer cascade stores packed words little endian. A point lookup starts from
453/// the row-order index, inverts the fixed FastLanes permutation, and reads the one or two words
454/// that hold that value. This is the point form of [`unpack`] for callers that need a sparse set of
455/// positions rather than a materialized vector.
456///
457/// # Errors
458///
459/// If `width` exceeds 64, `index` is outside a full unit, or `input` is not the exact byte length
460/// of a full unit at that width.
461pub fn unpack_u64_at(input: &[u8], width: usize, index: usize) -> Result<u64> {
462 check_width::<u64>(width)?;
463 if index >= VALUES {
464 return Err(Error::internal(format!(
465 "packed value {index} is outside a {VALUES} value unit"
466 )));
467 }
468 let expected = packed_len::<u64>(width) * size_of::<u64>();
469 if input.len() != expected {
470 return Err(Error::internal(format!(
471 "a {width} bit packed vector is {expected} bytes, not {}",
472 input.len()
473 )));
474 }
475 if width == 0 {
476 return Ok(0);
477 }
478
479 let lanes = <u64 as Packable>::LANES;
480 let block = index / lanes;
481 let lane = index % lanes;
482 // ORDER is its own inverse. `block` is the permuted row group and offset produced by
483 // `source_index`, so applying ORDER again recovers the original group.
484 let group = ORDER[block % 8];
485 let row = group * (<u64 as Packable>::WIDTH / 8) + block / 8;
486 let bit = row * width;
487 let word = bit / <u64 as Packable>::WIDTH;
488 let shift = bit % <u64 as Packable>::WIDTH;
489 let low = word_at(input, (word * lanes + lane) * size_of::<u64>());
490 let bits = if shift + width <= <u64 as Packable>::WIDTH {
491 low >> shift
492 } else {
493 let high = word_at(input, ((word + 1) * lanes + lane) * size_of::<u64>());
494 (low >> shift) | (high << (<u64 as Packable>::WIDTH - shift))
495 };
496 Ok(bits & low_mask(width))
497}
498
499/// How many bytes [`pack_tail`] writes for `count` values at `width` bits.
500#[must_use]
501pub fn tail_len(count: usize, width: usize) -> usize {
502 (count * width).div_ceil(8)
503}
504
505/// Packs fewer than [`VALUES`] values, sequentially and to a byte boundary.
506///
507/// The transposed layout is all or nothing. A value lives at a row and a lane, the lanes are
508/// interleaved through the whole buffer, and there is no prefix of a packed unit that holds a
509/// prefix of the values. So a unit holding 3 values costs the same as a unit holding 1024, which is
510/// 5 KB to store three numbers, and every nested array in a cascade is short: a dictionary of five
511/// entries, a run length array, an exception list.
512///
513/// This is the other layout for exactly those. It is the obvious sequential one, value 0 in the low
514/// bits, and it has the dependency chain the transposed layout was chosen to avoid. That is
515/// affordable here and only here: a tail is at most 1023 values and is decoded once, so the chain
516/// is bounded by a number that does not grow with the data, while a full unit is on the hot path of
517/// every scan in the system.
518///
519/// # Errors
520///
521/// If `count` is not below [`VALUES`], if `width` exceeds 64, or if a value does not fit.
522pub fn pack_tail(values: &[u64], width: usize, output: &mut Vec<u8>) -> Result<()> {
523 check_tail(values.len(), width)?;
524 pack_linear(values, width, output)
525}
526
527/// Packs any number of values in the layout [`pack_tail`] writes.
528///
529/// [`pack_tail`] is this with a bound, and the bound is a statement about columns rather than about
530/// the layout: a column that has a whole unit of values has a transposed unit to put them in, so
531/// the sequential layout is for the remainder and asking for it with a full unit in hand is a bug.
532///
533/// A key map is the other kind of caller. It is not a column, it is never decoded as a run, and
534/// every read of it is a single [`tail_at`] out of the middle of a binary search, so the transposed
535/// layout would buy it nothing and the bound would cost it the form: the sorted key map over
536/// fifteen million `orders` rows is fifteen million values in one array addressed by index. The
537/// writer's carry chain is still here and is still serial, and that is a build time cost paid once
538/// over a column that is being sorted anyway.
539///
540/// # Errors
541///
542/// If `width` exceeds 64, or if a value does not fit in `width` bits.
543pub fn pack_linear(values: &[u64], width: usize, output: &mut Vec<u8>) -> Result<()> {
544 if width > 64 {
545 return Err(Error::internal(format!("{width} bits does not fit in 64")));
546 }
547 if width == 0 {
548 return check_all_zero(values);
549 }
550 let mask = low_mask(width);
551 // 128 bits, because the accumulator holds up to 7 bits left over from the previous value plus a
552 // whole 64 bit one.
553 let mut accumulator: u128 = 0;
554 let mut filled = 0usize;
555 for value in values {
556 if value & !mask != 0 {
557 return Err(Error::internal(format!("value {value} does not fit in {width} bits")));
558 }
559 accumulator |= u128::from(*value) << filled;
560 filled += width;
561 while filled >= 8 {
562 output.push((accumulator & 0xff) as u8);
563 accumulator >>= 8;
564 filled -= 8;
565 }
566 }
567 if filled > 0 {
568 output.push((accumulator & 0xff) as u8);
569 }
570 Ok(())
571}
572
573/// Unpacks what [`pack_tail`] wrote.
574///
575/// The writer has a dependency chain because it has to know how many bits are left over from the
576/// value before, but the reader does not, and this does not carry one. Value `index` occupies the
577/// `width` bits starting at bit `index * width`, so its position is arithmetic rather than history,
578/// and since it begins at most seven bits into a byte and runs at most sixty four, it always lies
579/// inside sixteen bytes read from that byte. One unaligned load, one shift and one mask.
580///
581/// That matters more than the module documentation lets on. The argument there is that a tail is at
582/// most 1023 values and so is bounded by a number that does not grow with the data, which is true
583/// per call and misleading in aggregate, because a cascade puts a short array in every chunk and a
584/// scan reads every chunk. ClickBench 9 is where it showed. UserID is nearly unique, so its
585/// dictionary holds about a thousand sixty four bit values per part and lands one value short of a
586/// full unit, which sends the whole column down this path: nine hundred and seventy four parts,
587/// about a million values, and the byte at a time version fed eight bytes through a `u128` for each
588/// one. That was fifty five percent of the instructions of a scan of that column on its own.
589///
590/// # Errors
591///
592/// If `count` is not below [`VALUES`], if `width` exceeds 64, or if the input is shorter than
593/// [`tail_len`].
594pub fn unpack_tail(input: &[u8], width: usize, count: usize) -> Result<Vec<u64>> {
595 // Ahead of the buffer, so that a count off a corrupt file is refused rather than allocated for.
596 check_tail(count, width)?;
597 let mut values = vec![0u64; count];
598 unpack_tail_into(input, width, &mut values, |bits| bits)?;
599 Ok(values)
600}
601
602/// As [`unpack_tail`], into a buffer the caller owns and through a mapping on the way out.
603///
604/// How many values to read is `output.len()`. This is the form the decoders want and
605/// [`unpack_tail`] is now a wrapper over it, because a cascade calls this once per chunk and a scan
606/// reads a chunk per part per column: returning a fresh `Vec` is an allocation per chunk, and
607/// handing back raw offsets for the caller to add a base to in a second pass is a second write of
608/// every value. Both of those are per value costs wearing the clothes of a per call one. See
609/// [`unpack_mapped`] for why the mapping goes at the store.
610///
611/// # Errors
612///
613/// As [`unpack_tail`].
614pub fn unpack_tail_into<U: Copy>(
615 input: &[u8],
616 width: usize,
617 output: &mut [U],
618 value: impl Fn(u64) -> U,
619) -> Result<()> {
620 let count = output.len();
621 check_tail(count, width)?;
622 if width == 0 {
623 output.fill(value(0));
624 return Ok(());
625 }
626 if input.len() < tail_len(count, width) {
627 return Err(Error::internal(format!(
628 "{count} values at {width} bits need {} bytes and there are {}",
629 tail_len(count, width),
630 input.len()
631 )));
632 }
633 let mask = u128::from(low_mask(width));
634 let read = |window: u128, bit: usize| ((window >> bit) & mask) as u64;
635 // A buffer shorter than a window is one load for the whole call, because everything it holds is
636 // inside it. Short arrays are most of what a cascade stores, so this is the common case by
637 // count of calls even though it is the rare one by count of values.
638 if input.len() < WINDOW {
639 let mut window = [0u8; WINDOW];
640 window[..input.len()].copy_from_slice(input);
641 let word = u128::from_le_bytes(window);
642 for (index, slot) in output.iter_mut().enumerate() {
643 *slot = value(read(word, index * width));
644 }
645 return Ok(());
646 }
647 // Otherwise a value is read where it lies, until the window would run off the end.
648 let whole = (((input.len() - WINDOW) * 8) / width + 1).min(count);
649 if width <= NARROW {
650 // Half the window, because a value this wide that starts at most seven bits into a byte
651 // ends inside the eight bytes from that byte. The shift and the mask are then one
652 // instruction each where a 128 bit shift is three, and every real width is down here: the
653 // offsets a text block carries are seventeen bits and a dictionary code is fewer.
654 let mask = low_mask(width);
655 for (index, slot) in output[..whole].iter_mut().enumerate() {
656 let bit = index * width;
657 let word = word_at(input, bit / 8);
658 *slot = value((word >> (bit % 8)) & mask);
659 }
660 } else {
661 for (index, slot) in output[..whole].iter_mut().enumerate() {
662 let bit = index * width;
663 let mut window = [0u8; WINDOW];
664 window.copy_from_slice(&input[bit / 8..bit / 8 + WINDOW]);
665 *slot = value(read(u128::from_le_bytes(window), bit % 8));
666 }
667 }
668 if whole < count {
669 // Every value left over begins past the sixteenth byte from the end, by the definition of
670 // `whole` just above, and the buffer stops on the byte holding the top bits of the last
671 // one. So all of them lie inside the final window and one load serves the lot.
672 let base = input.len() - WINDOW;
673 let mut window = [0u8; WINDOW];
674 window.copy_from_slice(&input[base..]);
675 let word = u128::from_le_bytes(window);
676 for (offset, slot) in output[whole..].iter_mut().enumerate() {
677 *slot = value(read(word, (whole + offset) * width - base * 8));
678 }
679 }
680 Ok(())
681}
682
683/// One value of a run written by [`pack_tail`], read where it lies.
684///
685/// [`unpack_tail`] decodes the whole run, which is what a scan wants and what nearly every caller
686/// here is. A binary search is the other kind of caller: it wants one value out of the middle of a
687/// block, it makes about as many probes as the block has bits, and decoding the block to answer one
688/// of them would cost more than reading the value it was avoiding.
689///
690/// # Errors
691///
692/// If `width` exceeds 64, or if the value would run past the end of `input`.
693#[inline]
694pub fn tail_at(input: &[u8], width: usize, index: usize) -> Result<u64> {
695 if width > 64 {
696 return Err(Error::internal(format!("a width of {width} is past what a u64 holds")));
697 }
698 if width == 0 {
699 return Ok(0);
700 }
701 let start = index * width;
702 let end = start + width;
703 if end.div_ceil(8) > input.len() {
704 return Err(Error::internal(format!(
705 "value {index} at {width} bits ends past the {} bytes there are",
706 input.len()
707 )));
708 }
709 let first = start / 8;
710 let last = (end - 1) / 8;
711 // A value that ends inside the eight bytes it starts in is one load, one shift and one mask.
712 // The window below copies a length the compiler does not know, which is a call to `memcpy`
713 // rather than a load, and this reads one value at a time for every string a text column hands
714 // out. It was fifteen percent of ClickBench 27.
715 if first + 8 <= input.len() && last - first < 8 {
716 return Ok((word_at(input, first) >> (start % 8)) & low_mask(width));
717 }
718 let mut window = [0u8; WINDOW];
719 window[..=last - first].copy_from_slice(&input[first..=last]);
720 let word = u128::from_le_bytes(window);
721 Ok(((word >> (start % 8)) & u128::from(low_mask(width))) as u64)
722}
723
724/// Two neighbouring values of a run, read from one load where the pair fits inside it.
725///
726/// `index` is the later of the two and the answer is the pair at `index - 1` and `index`. A text
727/// column asks for exactly this once per string it hands out, because a value starts where the one
728/// before it ended. Two calls to [`tail_at`] read the same eight bytes twice and do the bounds
729/// arithmetic twice, where a pair of seventeen bit offsets, which is what a block of text carries,
730/// both lie inside one load.
731///
732/// # Errors
733///
734/// If `index` is zero, if `width` exceeds 64, or if the pair would run past the end of `input`.
735#[inline]
736pub fn tail_pair(input: &[u8], width: usize, index: usize) -> Result<(u64, u64)> {
737 let Some(before) = index.checked_sub(1) else {
738 return Err(Error::internal("a tail pair has nothing before its first value"));
739 };
740 if width == 0 {
741 return Ok((0, 0));
742 }
743 let start = before * width;
744 let shift = start % 8;
745 let first = start / 8;
746 if shift + 2 * width <= u64::BITS as usize && first + 8 <= input.len() {
747 let word = word_at(input, first) >> shift;
748 let mask = low_mask(width);
749 return Ok((word & mask, (word >> width) & mask));
750 }
751 Ok((tail_at(input, width, before)?, tail_at(input, width, index)?))
752}
753
754/// The bytes a single tail value can span, which is a shift of at most seven plus a width of at
755/// most sixty four, so seventy one bits and therefore nine bytes, rounded up to the load that
756/// covers it.
757const WINDOW: usize = 16;
758
759/// The widest value that always ends inside the eight bytes it starts in, which is sixty four bits
760/// less the seven a value can begin into its first byte.
761const NARROW: usize = 57;
762
763/// Eight bytes read where they lie, as one load.
764///
765/// The length is a constant the compiler can see, which is what makes it a load. The caller is
766/// responsible for `at + 8` being inside `input`, and the index below says so where it is not.
767#[inline]
768fn word_at(input: &[u8], at: usize) -> u64 {
769 let run: [u8; 8] = input[at..at + 8].try_into().expect("eight bytes");
770 u64::from_le_bytes(run)
771}
772
773fn check_tail(count: usize, width: usize) -> Result<()> {
774 if count >= VALUES {
775 return Err(Error::internal(format!(
776 "{count} values is a whole unit and belongs in the transposed layout"
777 )));
778 }
779 if width > 64 {
780 return Err(Error::internal(format!("{width} bits does not fit in 64")));
781 }
782 Ok(())
783}
784
785fn check_vector_len(len: usize, what: &str) -> Result<()> {
786 if len == VALUES {
787 Ok(())
788 } else {
789 Err(Error::internal(format!("{what} is {len} values, and a packed unit is {VALUES}")))
790 }
791}
792
793fn check_width<T: Packable>(width: usize) -> Result<()> {
794 if width <= T::WIDTH {
795 Ok(())
796 } else {
797 Err(Error::internal(format!("{width} bits does not fit in a {} bit type", T::WIDTH)))
798 }
799}
800
801fn check_all_zero<T: Packable>(input: &[T]) -> Result<()> {
802 match input.iter().position(|value| value.to_u64() != 0) {
803 None => Ok(()),
804 Some(index) => Err(Error::internal(format!(
805 "a zero bit vector cannot hold {:?} at {index}",
806 input[index]
807 ))),
808 }
809}
810
811#[cfg(test)]
812mod tests {
813 use super::*;
814
815 /// A xorshift, so that the test data is the same on every host and in every run without the
816 /// workspace growing a dependency for it.
817 struct Random(u64);
818
819 impl Random {
820 fn new() -> Self {
821 Self(0x2545_f491_4f6c_dd1d)
822 }
823
824 fn next(&mut self) -> u64 {
825 self.0 ^= self.0 << 13;
826 self.0 ^= self.0 >> 7;
827 self.0 ^= self.0 << 17;
828 self.0
829 }
830 }
831
832 fn sample<T: Packable>(width: usize) -> Vec<T> {
833 let mut random = Random::new();
834 (0..VALUES).map(|_| T::from_u64(random.next() & low_mask(width))).collect()
835 }
836
837 fn round_trip<T: Packable>(width: usize) {
838 let values = sample::<T>(width);
839 let mut packed = vec![T::from_u64(0); packed_len::<T>(width)];
840 pack(&values, width, &mut packed).unwrap();
841 let mut back = vec![T::from_u64(0); VALUES];
842 unpack(&packed, width, &mut back).unwrap();
843 assert_eq!(back, values, "{width} bits of a {} bit type", T::WIDTH);
844 }
845
846 #[test]
847 fn every_width_of_every_type_round_trips() {
848 for width in 0..=8 {
849 round_trip::<u8>(width);
850 }
851 for width in 0..=16 {
852 round_trip::<u16>(width);
853 }
854 for width in 0..=32 {
855 round_trip::<u32>(width);
856 }
857 for width in 0..=64 {
858 round_trip::<u64>(width);
859 }
860 }
861
862 #[test]
863 fn one_value_from_a_full_u64_unit_agrees_with_a_whole_unpack() {
864 for width in 0..=64 {
865 let values = sample::<u64>(width);
866 let mut packed = vec![0u64; packed_len::<u64>(width)];
867 pack(&values, width, &mut packed).unwrap();
868 let bytes = packed.iter().flat_map(|word| word.to_le_bytes()).collect::<Vec<_>>();
869 for (index, expected) in values.iter().enumerate() {
870 assert_eq!(
871 unpack_u64_at(&bytes, width, index).unwrap(),
872 *expected,
873 "value {index} at {width} bits"
874 );
875 }
876 }
877 }
878
879 #[test]
880 fn a_reused_scratch_gives_what_a_fresh_one_gives() {
881 // The buffer a unit transposes through is handed in so it is not zeroed per call, which is
882 // only sound if every element of it is written every time. If some were not, a narrow unit
883 // following a wide one would read whatever the wide one left behind, so the widths here go
884 // up and down rather than in order and each answer is checked against the same unit packed
885 // through a buffer nothing has touched.
886 let mut scratch = Scratch::<u64>::new();
887 for width in [64, 1, 33, 7, 64, 0, 17, 60, 3] {
888 let values = sample::<u64>(width);
889 let mut reused = vec![0u64; packed_len::<u64>(width)];
890 pack_with(&values, width, &mut reused, &mut scratch).unwrap();
891 let mut fresh = vec![0u64; packed_len::<u64>(width)];
892 pack(&values, width, &mut fresh).unwrap();
893 assert_eq!(reused, fresh, "at {width} bits after a wider unit");
894 let mut back = vec![0u64; VALUES];
895 unpack(&reused, width, &mut back).unwrap();
896 assert_eq!(back, values, "at {width} bits");
897 }
898 }
899
900 #[test]
901 fn the_one_pass_unpack_gives_what_the_two_passes_give() {
902 // `unpack` is the fused form of `unpack_transposed` followed by `untranspose`, and those two
903 // are the definition of the layout. So this checks the fast one against the slow one at
904 // every width of every type rather than against a remembered answer, which is the check that
905 // would catch the fused one getting a shift or a row base wrong at one width out of sixty
906 // five.
907 fn agree<T: Packable>() {
908 for width in 0..=T::WIDTH {
909 let values = sample::<T>(width);
910 let mut transposed = vec![T::from_u64(0); VALUES];
911 transpose(&values, &mut transposed).unwrap();
912 let mut packed = vec![T::from_u64(0); packed_len::<T>(width)];
913 pack_transposed(&transposed, width, &mut packed).unwrap();
914
915 let mut middle = vec![T::from_u64(0); VALUES];
916 unpack_transposed(&packed, width, &mut middle).unwrap();
917 let mut slow = vec![T::from_u64(0); VALUES];
918 untranspose(&middle, &mut slow).unwrap();
919
920 let mut fast = vec![T::from_u64(0); VALUES];
921 unpack(&packed, width, &mut fast).unwrap();
922
923 assert_eq!(fast, slow, "{} bit type at {width} bits", T::WIDTH);
924 assert_eq!(fast, values, "{} bit type at {width} bits round trip", T::WIDTH);
925 }
926 }
927 agree::<u8>();
928 agree::<u16>();
929 agree::<u32>();
930 agree::<u64>();
931 }
932
933 #[test]
934 fn a_mapped_unpack_gives_what_unpacking_and_then_mapping_gives() {
935 // The frame of reference decode is the caller, so the mapping under test is the one it
936 // uses: a signed base added to an unsigned offset, into an output of a different type from
937 // the packed words. Checked at every width because the two inner loops of `unpack_mapped`
938 // split on whether a value straddles two words, and which one runs depends on the width.
939 for width in 0..=64 {
940 let values = sample::<u64>(width);
941 let mut packed = vec![0u64; packed_len::<u64>(width)];
942 pack(&values, width, &mut packed).unwrap();
943
944 let base = -7i64;
945 let mut mapped = vec![0i64; VALUES];
946 unpack_mapped(&packed, width, &mut mapped, |offset| {
947 (i128::from(base) + i128::from(offset)) as i64
948 })
949 .unwrap();
950
951 let mut plain = vec![0u64; VALUES];
952 unpack(&packed, width, &mut plain).unwrap();
953 let expected: Vec<i64> = plain
954 .iter()
955 .map(|offset| (i128::from(base) + i128::from(*offset)) as i64)
956 .collect();
957 assert_eq!(mapped, expected, "at {width} bits");
958 }
959 }
960
961 #[test]
962 fn a_mapped_tail_gives_what_unpacking_the_tail_and_then_mapping_gives() {
963 // Every length, because `unpack_tail_into` has three paths through it and which one a call
964 // takes depends on how many bytes the run came to: everything inside one window, a walk
965 // that stops a window short of the end, and the leftovers after that walk.
966 for width in [0usize, 1, 7, 17, 32, 57, 58, 64] {
967 for count in [1usize, 2, 63, 64, 300, 1023] {
968 let values: Vec<u64> = sample::<u64>(width).into_iter().take(count).collect();
969 let mut packed = Vec::new();
970 pack_tail(&values, width, &mut packed).unwrap();
971
972 let base = 11i64;
973 let mut mapped = vec![0i64; count];
974 unpack_tail_into(&packed, width, &mut mapped, |offset| {
975 (i128::from(base) + i128::from(offset)) as i64
976 })
977 .unwrap();
978
979 let plain = unpack_tail(&packed, width, count).unwrap();
980 let expected: Vec<i64> = plain
981 .iter()
982 .map(|offset| (i128::from(base) + i128::from(*offset)) as i64)
983 .collect();
984 assert_eq!(mapped, expected, "{count} values at {width} bits");
985 }
986 }
987 }
988
989 #[test]
990 fn the_transposed_form_also_round_trips_without_being_reordered() {
991 // What the engine actually does: transpose once, then pack and unpack any number of times
992 // without ever going back to row order.
993 let values = sample::<u32>(19);
994 let mut transposed = vec![0u32; VALUES];
995 transpose(&values, &mut transposed).unwrap();
996 let mut packed = vec![0u32; packed_len::<u32>(19)];
997 pack_transposed(&transposed, 19, &mut packed).unwrap();
998 let mut back = vec![0u32; VALUES];
999 unpack_transposed(&packed, 19, &mut back).unwrap();
1000 assert_eq!(back, transposed);
1001 }
1002
1003 #[test]
1004 fn the_permutation_is_a_bijection() {
1005 // Every value has to land somewhere and no two may land in the same place, or a round trip
1006 // would silently drop rows. Checked for all four widths because the group size changes.
1007 fn check<T: Packable>() {
1008 let mut seen = vec![false; VALUES];
1009 for row in 0..T::WIDTH {
1010 for lane in 0..T::LANES {
1011 let index = source_index::<T>(row, lane);
1012 assert!(!seen[index], "{index} is written twice for {} bits", T::WIDTH);
1013 seen[index] = true;
1014 }
1015 }
1016 assert!(seen.into_iter().all(|hit| hit));
1017 }
1018 check::<u8>();
1019 check::<u16>();
1020 check::<u32>();
1021 check::<u64>();
1022 }
1023
1024 #[test]
1025 fn transposing_is_not_the_identity() {
1026 // If it were, the test above would be passing on a layout that is not the FastLanes one.
1027 let values: Vec<u32> = (0..VALUES).map(|index| index as u32).collect();
1028 let mut transposed = vec![0u32; VALUES];
1029 transpose(&values, &mut transposed).unwrap();
1030 assert_ne!(transposed, values);
1031 let mut back = vec![0u32; VALUES];
1032 untranspose(&transposed, &mut back).unwrap();
1033 assert_eq!(back, values);
1034 }
1035
1036 #[test]
1037 fn a_full_width_pack_is_the_data_itself() {
1038 // 64 bits of a 64 bit type has no packing to do, and the loop that handles the general case
1039 // has to get the degenerate one right rather than shifting by 64 and wrapping.
1040 let values = sample::<u64>(64);
1041 let mut transposed = vec![0u64; VALUES];
1042 transpose(&values, &mut transposed).unwrap();
1043 let mut packed = vec![0u64; packed_len::<u64>(64)];
1044 pack_transposed(&transposed, 64, &mut packed).unwrap();
1045 assert_eq!(packed, transposed);
1046 }
1047
1048 #[test]
1049 fn a_zero_width_vector_stores_nothing_and_reads_back_as_zeros() {
1050 let values = vec![0u32; VALUES];
1051 assert_eq!(required_width(&values), 0);
1052 let mut packed = Vec::new();
1053 pack(&values, 0, &mut packed).unwrap();
1054 let mut back = vec![7u32; VALUES];
1055 unpack(&packed, 0, &mut back).unwrap();
1056 assert_eq!(back, values);
1057 }
1058
1059 #[test]
1060 fn required_width_is_the_bits_of_the_largest_value() {
1061 assert_eq!(required_width::<u32>(&[]), 0);
1062 assert_eq!(required_width::<u32>(&[0, 0]), 0);
1063 assert_eq!(required_width::<u32>(&[1]), 1);
1064 assert_eq!(required_width::<u32>(&[255, 3]), 8);
1065 assert_eq!(required_width::<u32>(&[256]), 9);
1066 assert_eq!(required_width::<u64>(&[u64::MAX]), 64);
1067 }
1068
1069 #[test]
1070 fn a_value_too_wide_for_the_width_is_an_error_rather_than_silent_truncation() {
1071 let mut values = vec![0u32; VALUES];
1072 values[500] = 8;
1073 let mut transposed = vec![0u32; VALUES];
1074 transpose(&values, &mut transposed).unwrap();
1075 let mut packed = vec![0u32; packed_len::<u32>(3)];
1076 let error = pack_transposed(&transposed, 3, &mut packed).unwrap_err();
1077 assert!(error.message().contains("does not fit in 3 bits"), "{error}");
1078 }
1079
1080 #[test]
1081 fn a_wrong_sized_buffer_is_an_error() {
1082 let values = vec![0u32; VALUES];
1083 let mut packed = vec![0u32; 3];
1084 let error = pack(&values, 5, &mut packed).unwrap_err();
1085 assert!(error.message().contains("words"), "{error}");
1086
1087 let short = vec![0u32; 7];
1088 let mut output = vec![0u32; VALUES];
1089 let error = unpack(&short, 5, &mut output).unwrap_err();
1090 assert!(error.message().contains("words"), "{error}");
1091 }
1092
1093 #[test]
1094 fn a_nonzero_value_at_zero_width_is_an_error() {
1095 let mut values = vec![0u32; VALUES];
1096 values[9] = 1;
1097 let mut packed = Vec::new();
1098 let error = pack(&values, 0, &mut packed).unwrap_err();
1099 assert!(error.message().contains("zero bit vector"), "{error}");
1100 }
1101
1102 #[test]
1103 fn packing_at_a_width_the_type_cannot_hold_is_an_error() {
1104 let values = vec![0u16; VALUES];
1105 let mut packed = vec![0u16; 17 * 64];
1106 let error = pack(&values, 17, &mut packed).unwrap_err();
1107 assert!(error.message().contains("16 bit type"), "{error}");
1108 }
1109
1110 #[test]
1111 fn a_tail_round_trips_at_every_width_and_every_length() {
1112 let mut random = Random::new();
1113 for width in 0..=64usize {
1114 for count in [0usize, 1, 2, 7, 8, 9, 100, 1023] {
1115 let values: Vec<u64> =
1116 (0..count).map(|_| random.next() & low_mask(width)).collect();
1117 let mut bytes = Vec::new();
1118 pack_tail(&values, width, &mut bytes).unwrap();
1119 assert_eq!(bytes.len(), tail_len(count, width), "{count} at {width}");
1120 assert_eq!(
1121 unpack_tail(&bytes, width, count).unwrap(),
1122 values,
1123 "{count} at {width}"
1124 );
1125 }
1126 }
1127 }
1128
1129 /// Reading one value where it lies agrees with decoding the whole run.
1130 ///
1131 /// Every width and every position, since the point of it is the arithmetic that finds the bytes
1132 /// a value straddles, and that is what is off by one.
1133 ///
1134 /// A value that runs off the buffer is an error. The buffer stops on a byte boundary and a value
1135 /// does not, so an index a little past the count can still lie inside the padding of the last
1136 /// byte and that reads rather than complains. It is the caller that knows how many values it
1137 /// wrote, the same way it does for `unpack_tail`.
1138 #[test]
1139 fn one_value_of_a_tail_reads_the_same_as_the_whole_of_it() {
1140 let mut random = Random::new();
1141 for width in 0..=64usize {
1142 let count = 37;
1143 let values: Vec<u64> = (0..count).map(|_| random.next() & low_mask(width)).collect();
1144 let mut bytes = Vec::new();
1145 pack_tail(&values, width, &mut bytes).unwrap();
1146 for (index, value) in values.iter().enumerate() {
1147 assert_eq!(tail_at(&bytes, width, index).unwrap(), *value, "{index} at {width}");
1148 }
1149 let Some(fits) = (bytes.len() * 8).checked_div(width) else { continue };
1150 assert!(tail_at(&bytes, width, fits + 1).is_err(), "past the end at {width}");
1151 }
1152 }
1153
1154 /// The two halves of the reader agree with each other.
1155 ///
1156 /// A value is read with one sixteen byte load, which the values near the end of the buffer
1157 /// cannot have because the buffer stops on the byte holding the top bits of the last one. Those
1158 /// go through a zero padded copy instead, and the split between the two is arithmetic on
1159 /// lengths, which is the kind of thing that is off by one. Handing the same bytes to the reader
1160 /// twice, once exactly sized so the last values take the padded path and once with slack on the
1161 /// end so every value takes the fast one, makes the two paths check each other at every width.
1162 #[test]
1163 fn the_padded_end_of_a_tail_reads_the_same_as_the_windowed_start() {
1164 let mut random = Random::new();
1165 for width in 1..=64usize {
1166 for count in [1usize, 2, 3, 17, 129, 1023] {
1167 let values: Vec<u64> =
1168 (0..count).map(|_| random.next() & low_mask(width)).collect();
1169 let mut exact = Vec::new();
1170 pack_tail(&values, width, &mut exact).unwrap();
1171 let mut slack = exact.clone();
1172 slack.extend_from_slice(&[0u8; WINDOW]);
1173 assert_eq!(
1174 unpack_tail(&exact, width, count).unwrap(),
1175 values,
1176 "{count} at {width}"
1177 );
1178 assert_eq!(
1179 unpack_tail(&slack, width, count).unwrap(),
1180 values,
1181 "{count} at {width}"
1182 );
1183 }
1184 }
1185 }
1186
1187 /// The pair read agrees with two single reads, at every width and every position.
1188 ///
1189 /// The pair has its own arithmetic for the case where both values fit one load, so the thing to
1190 /// check is that it falls back to the same answer everywhere that does not hold, which is every
1191 /// width past thirty two and every value near the end of the buffer.
1192 #[test]
1193 fn a_pair_of_tail_values_reads_the_same_as_the_two_of_them_apart() {
1194 let mut random = Random::new();
1195 for width in 0..=64usize {
1196 let count = 37;
1197 let values: Vec<u64> = (0..count).map(|_| random.next() & low_mask(width)).collect();
1198 let mut bytes = Vec::new();
1199 pack_tail(&values, width, &mut bytes).unwrap();
1200 for index in 1..count {
1201 assert_eq!(
1202 tail_pair(&bytes, width, index).unwrap(),
1203 (values[index - 1], values[index]),
1204 "{index} at {width}"
1205 );
1206 }
1207 assert!(tail_pair(&bytes, width, 0).is_err(), "nothing before the first at {width}");
1208 }
1209 }
1210
1211 #[test]
1212 fn a_tail_costs_its_own_values_and_not_a_whole_unit() {
1213 // The reason it exists. Three 40 bit values in the transposed layout is a 5 KB buffer.
1214 let values = vec![(1u64 << 39) + 1; 3];
1215 let mut bytes = Vec::new();
1216 pack_tail(&values, 40, &mut bytes).unwrap();
1217 assert_eq!(bytes.len(), 15);
1218 assert_eq!(packed_len::<u64>(40) * 8, 5120);
1219 }
1220
1221 #[test]
1222 fn a_whole_unit_is_refused_by_the_tail_packer() {
1223 let values = vec![0u64; VALUES];
1224 let error = pack_tail(&values, 4, &mut Vec::new()).unwrap_err();
1225 assert!(error.message().contains("whole unit"), "{error}");
1226 }
1227
1228 #[test]
1229 fn a_short_tail_buffer_is_an_error() {
1230 let error = unpack_tail(&[0, 0], 8, 5).unwrap_err();
1231 assert!(error.message().contains("need 5 bytes"), "{error}");
1232 }
1233
1234 #[test]
1235 fn the_packed_size_is_the_same_as_the_naive_layout() {
1236 for width in 0..=32 {
1237 assert_eq!(packed_len::<u32>(width) * 32, width * VALUES);
1238 }
1239 }
1240}