Skip to main content

rudb_encoding/
integer.rs

1//! The single column integer encodings and the cascade over them.
2//!
3//! `spec/06-compression.md` section 6.2 lists the encoding set and section 6.3 says the ratios are
4//! in the cascade rather than in any one encoding. This module is both: the seven candidate shapes
5//! for an integer column, each of which encodes its own output by calling back into the chooser, so
6//! that RLE over a dictionary over a bit packed code array is a thing that happens by construction
7//! rather than a case somebody wrote out.
8//!
9//! Everything here works on `i64`. A narrower column is widened on the way in and nothing is lost
10//! by it, because every encoding's size comes from the range of the values rather than from the
11//! declared width of the type: a `SMALLINT` column of values 100 to 130 packs to 5 bits whether it
12//! arrived as `i16` or as `i64`. The one place the widening would cost something is a raw copy, and
13//! there is no raw copy, because a bit packed unit at width 64 is exactly that and the chooser
14//! reaches it on its own when nothing else fits.
15//!
16//! ## The unit
17//!
18//! Bit packing is per 1024 values, per [`crate::bitpack`]. Everything else is per chunk, where a
19//! chunk is however many values the caller passes in and is meant to be a row group. The two
20//! granularities are the point rather than an accident. A frame of reference base that is chosen
21//! per 1024 values tracks a column that drifts, which is what a timestamp column and an
22//! autoincrementing key both do, and one base per row group would pay the whole range of the row
23//! group on every value. A dictionary, on the other hand, is worth more the larger the unit it
24//! covers, which is the argument section 6.5 takes all the way to a dictionary per table.
25//!
26//! ## The serialized form
27//!
28//! A chunk is a tag byte, a value count, and a body whose shape depends on the tag. Bodies that
29//! contain another array of integers contain a whole chunk, tag and all, which is what makes the
30//! decoder a fold and what makes the cascade free: nothing in `Rle` knows what its run lengths are
31//! encoded as. The header is fixed width little endian rather than a varint, because 5 bytes per
32//! chunk against a chunk that holds a row group is not worth the branch on the decode path.
33//!
34//! ## What the chooser does, and what it will have to do instead
35//!
36//! It encodes every candidate and keeps the smallest. That is the honest baseline for M1, which is
37//! a measurement of what the format can do rather than of how fast a writer can decide, and it is
38//! not what a write path can afford. Section 6.3 describes the real thing: evaluate the candidates
39//! on a systematic sample, not the first N rows, because column data is frequently clustered and
40//! the first 1024 rows of a sorted column look constant. Building that first would mean the numbers
41//! this milestone produces are the sampler's numbers rather than the format's, and there would be
42//! no way to tell how much the sampler is leaving behind.
43
44use std::collections::BTreeMap;
45use std::time::Instant;
46
47use rudb_common::{Error, Result};
48
49use crate::chooser::{Chooser, EXHAUSTIVE};
50use crate::reader::Reader;
51use crate::tally::{self, Family};
52
53use crate::bitpack::{self, VALUES};
54
55/// How deep a cascade is allowed to go.
56///
57/// Three levels is what section 6.3 says captures most of what a general compressor would find:
58/// dictionary, then bit packed codes, then nothing left worth doing. The limit exists because the
59/// chooser is exhaustive and a cascade that could nest forever would be exponential, and because a
60/// fourth level has never once been the smallest candidate in anything measured so far.
61const MAX_DEPTH: u8 = 3;
62
63/// How many values a run writes at once, whatever the run is.
64///
65/// A run length decode used to write a value at a time for the length of the run, which reads well
66/// and is the wrong shape for the data: a clustered join key runs two or three long, so the loop
67/// spent its time mispredicting its own exit and the branch cost more than the stores did. Writing
68/// a fixed eight and then moving on by the run's real length has no exit to predict, and whatever
69/// of the eight was surplus is overwritten by the run that follows, because every run writes at
70/// least its own length. Eight because it is two vector stores on every machine this runs on and
71/// longer than nearly every run in a column worth run length encoding at all.
72const RUN: usize = 8;
73
74/// The average run length from which a run length chunk is decoded into reserved room rather than
75/// a zeroed one. Past it the zeroing is most of the writes, and below it the fixed width write of
76/// [`RUN`] is the cheaper loop.
77const LONG_RUN: usize = 64;
78
79/// What a chunk is encoded as. The discriminant is the tag byte in the serialized form and is part
80/// of the format, so the numbers are written down rather than left to the compiler.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum Kind {
83    /// One value repeated. The whole chunk is the tag, the count and the value.
84    Constant = 0,
85    /// Frame of reference then bit packed, per 1024 values. Covers plain bit packing at base zero
86    /// and a raw copy at width 64.
87    Packed = 1,
88    /// Differences between neighbours, zigzagged so a decreasing column is as cheap as an
89    /// increasing one, then encoded as a chunk in its own right.
90    Delta = 2,
91    /// Run values and run lengths, each encoded as a chunk in its own right.
92    Rle = 3,
93    /// A dictionary of the distinct values and an array of codes into it, both encoded as chunks in
94    /// their own right.
95    Dict = 4,
96    /// One dominant value with an exception list of positions and values.
97    Sparse = 5,
98    /// A base and a common step, with the number of steps to each value encoded as a chunk in its
99    /// own right.
100    Strided = 6,
101}
102
103impl Kind {
104    /// Every kind, in tag order.
105    pub const ALL: [Self; 7] = [
106        Self::Constant,
107        Self::Packed,
108        Self::Delta,
109        Self::Rle,
110        Self::Dict,
111        Self::Sparse,
112        Self::Strided,
113    ];
114
115    fn tag(self) -> u8 {
116        self as u8
117    }
118
119    fn from_tag(tag: u8) -> Result<Self> {
120        match tag {
121            0 => Ok(Self::Constant),
122            1 => Ok(Self::Packed),
123            2 => Ok(Self::Delta),
124            3 => Ok(Self::Rle),
125            4 => Ok(Self::Dict),
126            5 => Ok(Self::Sparse),
127            6 => Ok(Self::Strided),
128            other => Err(Error::internal(format!("unknown encoding tag {other}"))),
129        }
130    }
131
132    /// The name that goes in a report.
133    #[must_use]
134    pub fn name(self) -> &'static str {
135        match self {
136            Self::Constant => "CONSTANT",
137            Self::Packed => "FOR+BITPACK",
138            Self::Delta => "DELTA",
139            Self::Rle => "RLE",
140            Self::Dict => "DICT",
141            Self::Sparse => "SPARSE",
142            Self::Strided => "STRIDE",
143        }
144    }
145}
146
147/// Encodes a chunk of integers, choosing the cascade that comes out smallest.
148///
149/// # Errors
150///
151/// If the chunk is longer than `u32::MAX`, or if an encoding produces something its own decoder
152/// would not accept, which is an internal inconsistency rather than a caller error.
153pub fn encode(values: &[i64]) -> Result<Vec<u8>> {
154    encode_with(values, &EXHAUSTIVE)
155}
156
157/// [`encode`] with somebody else deciding which candidates are worth encoding in full.
158///
159/// A chooser narrows the list and nothing else. It cannot offer a candidate that does not apply, so
160/// whatever it picks still has to encode the whole chunk and still has to decode, and the worst a
161/// bad one can do is come out bigger than [`encode`] would have.
162///
163/// # Errors
164///
165/// As [`encode`].
166pub fn encode_with(values: &[i64], chooser: &dyn Chooser) -> Result<Vec<u8>> {
167    encode_at(values, 0, chooser)
168}
169
170/// Decodes a chunk written by [`encode`].
171///
172/// # Errors
173///
174/// If the bytes are truncated, carry an unknown tag, or describe a chunk whose parts do not agree
175/// with each other.
176pub fn decode(bytes: &[u8]) -> Result<Vec<i64>> {
177    let mut reader = Reader::new(bytes);
178    let values = decode_chunk(&mut reader)?;
179    if reader.remaining() != 0 {
180        return Err(Error::internal(format!(
181            "{} bytes left over after decoding a chunk",
182            reader.remaining()
183        )));
184    }
185    Ok(values)
186}
187
188/// Decodes one encoded chunk straight into the integer type a column is declared at.
189///
190/// The same values [`decode`] gives, without the `i64` in between. A reader that wants a `SMALLINT`
191/// column used to fill eight bytes a row with zeros, write every value into them, and then copy the
192/// lot into two bytes a row, which on ClickBench Q1 was a fifth of the query. Constant, packed,
193/// sparse and run length chunks are written in the target type directly. The other kinds decode as
194/// before and are narrowed after, since they are rare at the top of a column.
195///
196/// # Errors
197///
198/// As [`decode`], or if a value does not fit in `T`, which is a chunk that disagrees with the type
199/// it was written for.
200pub fn decode_as<T: Lane>(bytes: &[u8]) -> Result<Vec<T>> {
201    let mut reader = Reader::new(bytes);
202    let values = decode_chunk_as(&mut reader)?;
203    if reader.remaining() != 0 {
204        return Err(Error::internal(format!(
205            "{} bytes left over after decoding a chunk",
206            reader.remaining()
207        )));
208    }
209    Ok(values)
210}
211
212/// An integer type a chunk can be decoded straight into. See [`decode_as`].
213pub trait Lane: Copy + Default {
214    /// The value in this type, or `None` when it does not fit.
215    fn fit(value: i64) -> Option<Self>;
216
217    /// The value in this type, for a value already known to fit.
218    fn wrap(value: i64) -> Self;
219}
220
221macro_rules! lanes {
222    ($($ty:ty),* $(,)?) => {$(
223        impl Lane for $ty {
224            fn fit(value: i64) -> Option<Self> {
225                Self::try_from(value).ok()
226            }
227
228            #[allow(
229                clippy::cast_possible_truncation,
230                clippy::cast_sign_loss,
231                clippy::unnecessary_cast,
232                reason = "only called on a value the caller has checked fits"
233            )]
234            fn wrap(value: i64) -> Self {
235                value as Self
236            }
237        }
238    )*};
239}
240
241lanes!(i8, u8, i16, u16, i32, u32, i64, u64);
242
243/// One value in the type the chunk is being decoded into, or the error for a value that is not.
244fn lane<T: Lane>(value: i64) -> Result<T> {
245    T::fit(value).ok_or_else(|| Error::internal(format!("{value} is outside the chunk's type")))
246}
247
248/// Counts values in one encoded chunk without expanding sparse or run-length chunks into rows.
249///
250/// The result is computed from the encoded row values when called. It is not a stored histogram.
251/// Other encodings use the ordinary decoder until they have a useful count form of their own.
252///
253/// # Errors
254///
255/// As [`decode`], or if a sparse position or run length is outside the chunk.
256pub fn tally(bytes: &[u8]) -> Result<(usize, Vec<(i64, u64)>)> {
257    let mut counts = BTreeMap::<i64, u64>::new();
258    let rows = fold(bytes, |value, count| {
259        *counts.entry(value).or_default() += count;
260        Ok(())
261    })?;
262    Ok((rows, counts.into_iter().collect()))
263}
264
265/// Visits the values of one encoded chunk with their runtime row counts. Sparse chunks written
266/// with sorted exception positions need no per-chunk count map. An older or malformed chunk with
267/// repeated positions keeps the decoder's last-write-wins behavior.
268///
269/// # Errors
270///
271/// As [`decode`], or if the callback rejects a count.
272pub fn fold(bytes: &[u8], mut emit: impl FnMut(i64, u64) -> Result<()>) -> Result<usize> {
273    let mut reader = Reader::new(bytes);
274    let kind = Kind::from_tag(reader.u8()?)?;
275    let count = reader.u32()? as usize;
276    match kind {
277        Kind::Constant => {
278            let value = reader.i64()?;
279            if count != 0 {
280                emit(value, count as u64)?;
281            }
282        }
283        Kind::Sparse => {
284            let dominant = reader.i64()?;
285            let exception_count = reader.u32()? as usize;
286            let positions = decode_chunk(&mut reader)?;
287            let values = decode_chunk(&mut reader)?;
288            if positions.len() != exception_count || values.len() != exception_count {
289                return Err(Error::internal("a sparse chunk disagrees about its exception count"));
290            }
291            let mut ordered = true;
292            let mut previous = None;
293            for &position in &positions {
294                let position = usize::try_from(position)
295                    .ok()
296                    .filter(|&position| position < count)
297                    .ok_or_else(|| Error::internal("a sparse exception is outside the chunk"))?;
298                if previous.is_some_and(|last| position <= last) {
299                    ordered = false;
300                }
301                previous = Some(position);
302            }
303            if ordered {
304                if count != exception_count {
305                    emit(dominant, (count - exception_count) as u64)?;
306                }
307                for value in values {
308                    emit(value, 1)?;
309                }
310            } else {
311                // The ordinary decoder lets a later exception overwrite an earlier one at the
312                // same position. Keep that rule for chunks the writer would not normally produce.
313                let mut exceptions = BTreeMap::<usize, i64>::new();
314                for (position, value) in positions.into_iter().zip(values) {
315                    exceptions.insert(position as usize, value);
316                }
317                if count != exceptions.len() {
318                    emit(dominant, (count - exceptions.len()) as u64)?;
319                }
320                for value in exceptions.into_values() {
321                    emit(value, 1)?;
322                }
323            }
324        }
325        Kind::Rle => {
326            let values = decode_chunk(&mut reader)?;
327            let lengths = decode_chunk(&mut reader)?;
328            if values.len() != lengths.len() {
329                return Err(Error::internal("an RLE chunk has more runs than run lengths"));
330            }
331            let mut rows = 0_usize;
332            for (value, length) in values.into_iter().zip(lengths) {
333                let length = usize::try_from(length)
334                    .map_err(|_| Error::internal("a negative RLE run length"))?;
335                rows = rows
336                    .checked_add(length)
337                    .filter(|&rows| rows <= count)
338                    .ok_or_else(|| Error::internal("an RLE run ends past its chunk"))?;
339                if length != 0 {
340                    emit(value, length as u64)?;
341                }
342            }
343            check_count(rows, count)?;
344        }
345        _ => {
346            // Re-read the header through the existing decoder for the other cascade shapes.
347            reader = Reader::new(bytes);
348            let values = decode_chunk(&mut reader)?;
349            check_count(values.len(), count)?;
350            for value in values {
351                emit(value, 1)?;
352            }
353        }
354    }
355    if reader.remaining() != 0 {
356        return Err(Error::internal(format!(
357            "{} bytes left over after counting a chunk",
358            reader.remaining()
359        )));
360    }
361    Ok(count)
362}
363
364/// How few of a packed unit's values a selected decode has to want before it finds each one on its
365/// own rather than unpacking the unit, as one in this many.
366const SPARSE: usize = 32;
367
368/// Decodes selected row positions from a chunk written by [`encode`].
369///
370/// Positions must be sorted and unique. Packed chunks read only the words holding those positions,
371/// and run length chunks walk their run boundaries without expanding the output. Other cascade
372/// shapes use the full decoder and select afterward until they have a point form of their own.
373///
374/// # Errors
375///
376/// As [`decode`], or if a position is outside the chunk or the positions are not strictly
377/// increasing.
378pub fn decode_selected(bytes: &[u8], positions: &[usize]) -> Result<Vec<i64>> {
379    if positions.windows(2).any(|pair| pair[0] >= pair[1]) {
380        return Err(Error::internal("selected integer positions are not sorted and unique"));
381    }
382    let mut reader = Reader::new(bytes);
383    let values = decode_selected_chunk(&mut reader, positions)?;
384    if reader.remaining() != 0 {
385        return Err(Error::internal(format!(
386            "{} bytes left over after decoding selected values",
387            reader.remaining()
388        )));
389    }
390    Ok(values)
391}
392
393/// Whether [`decode_selected`] reads a few rows of this chunk for less than decoding all of it.
394///
395/// True for the kinds whose rows can be found without the rows before them: a constant, packed
396/// units, and strides or dictionary codes over packed units. A run length chunk walks every run to
397/// find where a row is, and a delta chunk adds up every delta before it, so for those a caller that
398/// wants a few rows does better decoding the chunk the usual way and picking them out.
399#[must_use]
400pub fn pointed(bytes: &[u8]) -> bool {
401    let simple = |bytes: &[u8]| {
402        bytes
403            .first()
404            .and_then(|&tag| Kind::from_tag(tag).ok())
405            .is_some_and(|kind| matches!(kind, Kind::Constant | Kind::Packed))
406    };
407    match bytes.first().and_then(|&tag| Kind::from_tag(tag).ok()) {
408        Some(Kind::Constant | Kind::Packed) => true,
409        // The tag, the count, the base and the stride come before the steps.
410        Some(Kind::Strided) => bytes.get(1 + 4 + 8 + 8..).is_some_and(simple),
411        // The dictionary is read whole whatever the rows, so only the codes need a point form.
412        Some(Kind::Dict) => {
413            let mut reader = Reader::new(bytes.get(1 + 4..).unwrap_or_default());
414            skip_chunk(&mut reader).is_ok() && simple(reader.rest())
415        }
416        _ => false,
417    }
418}
419
420/// Decodes a chunk that sits at the front of a longer buffer, and says how many bytes it took.
421///
422/// A string column holds integer chunks inside its own body, and the reader on that side cannot
423/// know where the nested chunk ends until it has been read. A chunk is self delimiting, so this is
424/// the same work [`decode`] does without the check that nothing follows.
425///
426/// # Errors
427///
428/// As [`decode`], except that trailing bytes are what the caller asked about rather than an error.
429pub fn decode_prefix(bytes: &[u8]) -> Result<(Vec<i64>, usize)> {
430    let mut reader = Reader::new(bytes);
431    let values = decode_chunk(&mut reader)?;
432    Ok((values, reader.used()))
433}
434
435/// [`describe`] over a chunk at the front of a longer buffer, and how many bytes it took.
436///
437/// # Errors
438///
439/// As [`decode_prefix`].
440pub fn describe_prefix(bytes: &[u8]) -> Result<(String, usize)> {
441    let mut reader = Reader::new(bytes);
442    let text = describe_chunk(&mut reader)?;
443    Ok((text, reader.used()))
444}
445
446/// The size in bytes of every candidate, for a report that wants to say what the cascade was
447/// chosen over rather than only what it chose. A candidate that does not apply is absent.
448///
449/// # Errors
450///
451/// As [`encode`].
452pub fn candidate_sizes(values: &[i64]) -> Result<Vec<(Kind, usize)>> {
453    let mut sizes = Vec::new();
454    for kind in candidates(values, 0, &EXHAUSTIVE) {
455        if let Some(bytes) = encode_as(kind, values, 0, &EXHAUSTIVE)? {
456            sizes.push((kind, bytes.len()));
457        }
458    }
459    Ok(sizes)
460}
461
462/// Which candidates [`encode`] would try on this chunk, in the order it tries them.
463///
464/// The chooser is exhaustive, so this is also the list of encodes it pays for to return one of
465/// them. A caller measuring where the encode time goes needs the list separately from the sizes,
466/// because a candidate that is offered and turns out not to apply still costs whatever it spent
467/// finding that out.
468#[must_use]
469pub fn offered(values: &[i64]) -> Vec<Kind> {
470    candidates(values, 0, &EXHAUSTIVE)
471}
472
473/// One candidate on its own, which is what the chooser calls once per entry in [`offered`].
474///
475/// `None` when the encoding does not apply. This is here so that the time the chooser spends can be
476/// attributed to the candidate that spent it, which is the measurement F2 wants before anybody
477/// replaces the exhaustive search with a sampled one. It is not how a writer encodes a chunk:
478/// [`encode`] is, and picking a kind by hand gives up the only thing the chooser is for.
479///
480/// # Errors
481///
482/// As [`encode`].
483pub fn encode_only(kind: Kind, values: &[i64]) -> Result<Option<Vec<u8>>> {
484    encode_as(kind, values, 0, &EXHAUSTIVE)
485}
486
487/// How big one candidate comes out, which is all a sampling chooser needs from it.
488///
489/// The bytes are thrown away, so this says nothing [`encode_only`] does not. It is `pub(crate)` and
490/// separate so that the sampler in [`crate::chooser`] is not handing back buffers it will not read.
491pub(crate) fn size_as(kind: Kind, values: &[i64], depth: u8) -> Result<Option<usize>> {
492    Ok(encode_as(kind, values, depth, &EXHAUSTIVE)?.map(|bytes| bytes.len()))
493}
494
495/// The kind at every level of an encoded chunk, in the order the encoder chose them.
496///
497/// The order is the one [`encode_with`] asks its chooser in: a level, then everything under its
498/// first inner chunk, then everything under its second. So a chooser that hands these back one per
499/// question gets the same cascade on a chunk that offers the same kinds, without searching any of
500/// it. That is what a writer with many small parts of one column wants, because the search is
501/// most of what the encode costs and neighbouring parts nearly always come out the same shape.
502///
503/// # Errors
504///
505/// As [`decode`].
506pub fn shape(bytes: &[u8]) -> Result<Vec<Kind>> {
507    let mut reader = Reader::new(bytes);
508    let mut kinds = Vec::new();
509    shape_chunk(&mut reader, &mut kinds)?;
510    Ok(kinds)
511}
512
513/// The cascade a chunk was encoded as, as a line of text like `DICT(PACKED, PACKED)`.
514///
515/// # Errors
516///
517/// As [`decode`].
518pub fn describe(bytes: &[u8]) -> Result<String> {
519    let mut reader = Reader::new(bytes);
520    describe_chunk(&mut reader)
521}
522
523fn encode_at(values: &[i64], depth: u8, chooser: &dyn Chooser) -> Result<Vec<u8>> {
524    let started = Instant::now();
525    let offered = candidates(values, depth, chooser);
526    let narrowed = chooser.narrow_integers(values, &offered, depth);
527    // Only the top level is counted, so that a cascade's time is counted once. See `tally`.
528    let counted = depth == 0;
529    if counted {
530        tally::chose(Family::Integer, started);
531    }
532    let mut best: Option<(Kind, Vec<u8>)> = None;
533    for kind in narrowed {
534        let encoded = if counted {
535            tally::offer(Family::Integer, kind.tag(), || encode_as(kind, values, depth, chooser))?
536        } else {
537            encode_as(kind, values, depth, chooser)?
538        };
539        let Some(bytes) = encoded else {
540            continue;
541        };
542        if best.as_ref().is_none_or(|(_, current)| bytes.len() < current.len()) {
543            best = Some((kind, bytes));
544        }
545    }
546    // `Packed` applies to every input including the empty one, so the chooser always has at least
547    // one candidate and this cannot be reached without a bug in `candidates`.
548    let (kind, bytes) = best.ok_or_else(|| Error::internal("no encoding applied to the chunk"))?;
549    if counted {
550        tally::kept(Family::Integer, kind.tag());
551    }
552    Ok(bytes)
553}
554
555/// Which candidates are worth encoding for this input.
556///
557/// The filters here are not the cost model. They are the cases where the encoding cannot be
558/// expressed at all, or is provably larger than `Packed` on the same data, so that the exhaustive
559/// chooser does not spend a dictionary build on a column of 100,000 distinct values to discover
560/// what its distinct count already said.
561///
562/// A kind the chooser says it will never keep is not tested for at all. The test for a dictionary
563/// sorts a copy of the chunk, and this runs at every level of the cascade, so a chooser that never
564/// keeps a dictionary was paying for a sort per level to find out something it would ignore.
565fn candidates(values: &[i64], depth: u8, chooser: &dyn Chooser) -> Vec<Kind> {
566    let mut kinds = vec![Kind::Packed];
567    if depth >= MAX_DEPTH {
568        return kinds;
569    }
570    let Some(profile) = Profile::of(values) else {
571        return kinds;
572    };
573    if profile.runs == 1 {
574        // Nothing else can beat 13 bytes, so this is the whole answer rather than a candidate.
575        return vec![Kind::Constant];
576    }
577    let considered = |kind| chooser.considers_integer(kind, depth);
578    // Every neighbouring difference is no wider than the whole range, so a range that fits in an
579    // `i64` answers for all of them and only a chunk holding both ends of the type walks the pairs.
580    let fits = profile.max.checked_sub(profile.min).is_some();
581    if considered(Kind::Delta)
582        && (if fits { profile.deltas_pay(values) } else { deltas_fit(values) })
583    {
584        kinds.push(Kind::Delta);
585    }
586    if considered(Kind::Rle) && profile.runs * 4 <= values.len() * 3 {
587        kinds.push(Kind::Rle);
588    }
589    // A dictionary's codes are as wide as its distinct count, so one whose codes are no narrower
590    // than the values has only added a dictionary. On TPC-H SF1 it was offered 1,124 times, kept 16
591    // times and cost 30% of the integer cascade's time before this.
592    if considered(Kind::Dict) && profile.width() > 1 {
593        let distinct = spread_of(values).0;
594        if distinct * 2 <= values.len() && width_of(distinct as u64 - 1) < profile.width() {
595            kinds.push(Kind::Dict);
596        }
597    }
598    // A value in four rows out of five leaves a fifth for everything else, and each of those rows
599    // starts at most two runs, so a chunk with more runs than that has no such value and the vote
600    // is not taken.
601    if considered(Kind::Sparse)
602        && (profile.runs - 1) * 5 <= values.len() * 2
603        && majority(values).is_some_and(|(_, count)| count * 10 >= values.len() * 8)
604    {
605        kinds.push(Kind::Sparse);
606    }
607    if considered(Kind::Strided) && stride_from(values, profile.min).is_some() {
608        kinds.push(Kind::Strided);
609    }
610    kinds
611}
612
613/// What one pass over a chunk says about it, which is most of what the candidate tests ask.
614///
615/// The tests used to walk the chunk once each: once to see whether it was one value, once for the
616/// deltas, once to count runs, twice for the vote and once more for the smallest value under the
617/// stride. That is six passes on every chunk at every level of the cascade, and on ClickBench `hits`
618/// they were most of the tenth of the load's CPU that `encode_at` came to, since a replayed part
619/// still asks every question the fallback would. This is one pass, and the vote is only taken where
620/// the run count leaves room for it.
621///
622/// The same pass looks at the differences too, since it has both neighbours in hand. `DELTA` was
623/// offered on every chunk whose range fit, and on the `hits_0` load it was 3,325 offers, 20.6% of
624/// the integer cascade's time and never kept once. What it stores is the zigzagged differences, so
625/// their spread says how wide they pack and their runs say whether they would run-length code.
626struct Profile {
627    min: i64,
628    max: i64,
629    /// Runs of equal neighbours, which is one for a chunk of a single value.
630    runs: usize,
631    /// The smallest and largest zigzagged difference between neighbours. They wrap where the range
632    /// does not fit in an `i64`, and nothing reads them then.
633    delta_low: u64,
634    delta_high: u64,
635    /// Runs of equal differences, which is one for a chunk of fewer than three values.
636    delta_runs: usize,
637}
638
639impl Profile {
640    fn of(values: &[i64]) -> Option<Self> {
641        let first = *values.first()?;
642        let (mut min, mut max, mut breaks) = (first, first, 0usize);
643        let mut last = values.get(1).map_or(0, |second| second.wrapping_sub(first));
644        let (mut delta_low, mut delta_high, mut turns) = (u64::MAX, 0u64, 0usize);
645        for (before, after) in values.iter().zip(&values[1..]) {
646            min = min.min(*after);
647            max = max.max(*after);
648            breaks += usize::from(before != after);
649            let delta = after.wrapping_sub(*before);
650            let zigzagged = zigzag(delta);
651            delta_low = delta_low.min(zigzagged);
652            delta_high = delta_high.max(zigzagged);
653            turns += usize::from(delta != last);
654            last = delta;
655        }
656        Some(Self { min, max, runs: breaks + 1, delta_low, delta_high, delta_runs: turns + 1 })
657    }
658
659    /// How many bits `Packed` needs for a value of this chunk at most, from the whole range.
660    fn width(&self) -> u32 {
661        width_of(self.max.wrapping_sub(self.min) as u64)
662    }
663
664    /// Whether the differences are worth encoding, for a chunk whose range fits in an `i64`.
665    ///
666    /// They are when they pack narrower than the values, which is a sorted key or a slowly moving
667    /// counter, or when they run-length code and the values do not, which is a column that climbs
668    /// in steps, or when the first few take only a handful of values, which is a column that walks
669    /// a cycle and whose differences make a dictionary of a few entries. Anything else comes out no
670    /// smaller than `Packed` or `Rle` on the values.
671    fn deltas_pay(&self, values: &[i64]) -> bool {
672        let len = values.len();
673        let narrower = width_of(self.delta_high.wrapping_sub(self.delta_low)) < self.width();
674        // A chunk that run-length codes has differences that are nearly all zero, so they repeat
675        // and there are few of them, and `Rle` on the values still beats them.
676        let unruly = self.runs * 4 > len * 3;
677        let repeat = self.delta_runs * 4 <= len.saturating_sub(1) * 3;
678        narrower || (unruly && (repeat || few_deltas(values)))
679    }
680}
681
682/// Whether the first [`FEW_DELTAS_SEEN`] differences take no more than [`FEW_DELTAS`] values.
683///
684/// It stops at the first difference past that many, which on a chunk with nothing cyclic in it is
685/// a handful of pairs in.
686fn few_deltas(values: &[i64]) -> bool {
687    let mut seen = [0i64; FEW_DELTAS];
688    let mut count = 0;
689    for pair in values.windows(2).take(FEW_DELTAS_SEEN) {
690        let delta = pair[1].wrapping_sub(pair[0]);
691        if seen[..count].contains(&delta) {
692            continue;
693        }
694        if count == FEW_DELTAS {
695            return false;
696        }
697        seen[count] = delta;
698        count += 1;
699    }
700    true
701}
702
703/// How many distinct differences [`few_deltas`] allows.
704const FEW_DELTAS: usize = 4;
705
706/// How many differences [`few_deltas`] looks at.
707const FEW_DELTAS_SEEN: usize = 64;
708
709/// The bits a value up to `range` takes, which is zero for a range of zero.
710fn width_of(range: u64) -> u32 {
711    u64::BITS - range.leading_zeros()
712}
713
714/// `None` when the encoding does not apply to this input, which the caller treats as a candidate
715/// that did not run rather than as a failure.
716fn encode_as(
717    kind: Kind,
718    values: &[i64],
719    depth: u8,
720    chooser: &dyn Chooser,
721) -> Result<Option<Vec<u8>>> {
722    let mut out = Vec::new();
723    put_u8(&mut out, kind.tag());
724    put_u32(&mut out, u32::try_from(values.len()).map_err(|_| too_long(values.len()))?);
725    match kind {
726        Kind::Constant => {
727            let Some(first) = values.first() else {
728                return Ok(None);
729            };
730            if values.iter().any(|value| value != first) {
731                return Ok(None);
732            }
733            put_i64(&mut out, *first);
734        }
735        Kind::Packed => encode_packed(values, &mut out)?,
736        Kind::Delta => {
737            // An empty chunk has no first value to hang the differences off. The search never asks
738            // for one because `candidates` rules it out, but `encode_only` goes straight past that
739            // and used to index into the chunk anyway.
740            let (Some(first), Some(deltas)) = (values.first(), deltas(values)) else {
741                return Ok(None);
742            };
743            put_i64(&mut out, *first);
744            out.extend_from_slice(&encode_at(&deltas, depth + 1, chooser)?);
745        }
746        Kind::Rle => {
747            let (run_values, run_lengths) = runs(values);
748            if run_values.is_empty() {
749                return Ok(None);
750            }
751            out.extend_from_slice(&encode_at(&run_values, depth + 1, chooser)?);
752            out.extend_from_slice(&encode_at(&run_lengths, depth + 1, chooser)?);
753        }
754        Kind::Dict => {
755            let dictionary = distinct_values(values);
756            if dictionary.is_empty() {
757                return Ok(None);
758            }
759            let codes = codes_over(values, &dictionary);
760            out.extend_from_slice(&encode_at(&dictionary, depth + 1, chooser)?);
761            out.extend_from_slice(&encode_at(&codes, depth + 1, chooser)?);
762        }
763        Kind::Sparse => {
764            // The majority is the most frequent value whenever there is one, and a chunk the search
765            // offers this for always has one. `encode_only` can ask about any chunk, so the sort is
766            // still there for a chunk with no majority.
767            let Some((value, _)) = majority(values).or_else(|| spread_of(values).1) else {
768                return Ok(None);
769            };
770            let mut positions = Vec::new();
771            let mut exceptions = Vec::new();
772            for (index, other) in values.iter().enumerate() {
773                if *other != value {
774                    positions.push(index as i64);
775                    exceptions.push(*other);
776                }
777            }
778            put_i64(&mut out, value);
779            put_u32(
780                &mut out,
781                u32::try_from(positions.len()).map_err(|_| too_long(positions.len()))?,
782            );
783            out.extend_from_slice(&encode_at(&positions, depth + 1, chooser)?);
784            out.extend_from_slice(&encode_at(&exceptions, depth + 1, chooser)?);
785        }
786        Kind::Strided => {
787            let (Some(base), Some(stride)) = (values.iter().min().copied(), stride_of(values))
788            else {
789                return Ok(None);
790            };
791            let mut steps = Vec::with_capacity(values.len());
792            for value in values {
793                let step = offset_from(*value, base) / stride;
794                // A step count the recursion cannot hold. An offset is at most 65 bits because both
795                // ends came from an `i64`, and only a stride of one leaves it that wide, which is a
796                // stride this never offers. Refused rather than wrapped, because a candidate that
797                // does not apply is one the chooser skips.
798                let Ok(step) = i64::try_from(step) else {
799                    return Ok(None);
800                };
801                steps.push(step);
802            }
803            put_i64(&mut out, base);
804            put_u64(&mut out, stride);
805            out.extend_from_slice(&encode_at(&steps, depth + 1, chooser)?);
806        }
807    }
808    Ok(Some(out))
809}
810
811/// Frame of reference and bit packing, one base and one width per 1024 values.
812///
813/// A base per unit rather than per chunk is most of what makes this work on real columns. A
814/// timestamp column over a day drifts across a range that needs 47 bits, and the same column inside
815/// any one unit spans a few seconds and needs 12. One base per row group would pay the 47 on every
816/// value.
817///
818/// A unit shorter than 1024 values, which is the last one of any chunk whose length is not a
819/// multiple of the unit and is the only one of every short array in a cascade, goes through
820/// [`bitpack::pack_tail`] instead. The transposed layout has no partial form and would charge a
821/// five entry dictionary for 1024 entries.
822fn encode_packed(values: &[i64], out: &mut Vec<u8>) -> Result<()> {
823    // The same three buffers for every unit, because the chooser encodes every candidate it is
824    // offered before it picks one and this loop runs once per candidate per unit.
825    let mut offsets: Vec<u64> = Vec::with_capacity(VALUES);
826    // Held at the width 64 length, which is the largest a unit can be, so a narrower unit writes the
827    // front of it and there is no resize per unit.
828    let mut packed: Vec<u64> = vec![0; bitpack::packed_len::<u64>(64)];
829    let mut transposed = bitpack::Scratch::<u64>::new();
830    for unit in values.chunks(VALUES) {
831        let base = unit.iter().copied().min().unwrap_or(0);
832        offsets.clear();
833        offsets.extend(unit.iter().map(|value| offset_from(*value, base)));
834        let width = bitpack::required_width(&offsets);
835        put_i64(out, base);
836        put_u8(out, u8::try_from(width).map_err(|_| Error::internal("impossible width"))?);
837        if unit.len() == VALUES {
838            let words = bitpack::packed_len::<u64>(width);
839            bitpack::pack_with(&offsets, width, &mut packed[..words], &mut transposed)?;
840            for word in &packed[..words] {
841                put_u64(out, *word);
842            }
843        } else {
844            bitpack::pack_tail(&offsets, width, out)?;
845        }
846    }
847    Ok(())
848}
849
850fn decode_chunk(reader: &mut Reader<'_>) -> Result<Vec<i64>> {
851    let kind = Kind::from_tag(reader.u8()?)?;
852    let count = reader.u32()? as usize;
853    match kind {
854        Kind::Constant => Ok(vec![reader.i64()?; count]),
855        Kind::Packed => {
856            // One buffer for the chunk, and every value written into it once. Both unpackers take
857            // the frame of reference base and put the value it belongs to where it goes, so there
858            // is no unit of raw offsets in between and no second pass to fold the base back in, and
859            // both read the packed bytes where the chunk put them rather than through a copy.
860            let mut values = vec![0i64; count];
861            let mut done = 0;
862            while done < count {
863                let base = reader.i64()?;
864                let width = reader.u8()? as usize;
865                let wanted = (count - done).min(VALUES);
866                let into = &mut values[done..done + wanted];
867                if wanted == VALUES {
868                    let unit = reader.bytes(bitpack::unit_len(width))?;
869                    bitpack::unpack_unit_into(unit, width, into, |offset| {
870                        value_from(offset, base)
871                    })?;
872                } else {
873                    let bytes = reader.bytes(bitpack::tail_len(wanted, width))?;
874                    bitpack::unpack_tail_into(bytes, width, into, |offset| {
875                        value_from(offset, base)
876                    })?;
877                }
878                done += wanted;
879            }
880            Ok(values)
881        }
882        Kind::Delta => {
883            let first = reader.i64()?;
884            let mut values = decode_chunk(reader)?;
885            check_count(values.len() + 1, count)?;
886            // Each value is written over the difference that follows it, so the sums go into the
887            // vector the differences came in and only the last one is pushed on the end. Pushing
888            // every value into a second vector asked it for room once a value.
889            let mut current = first;
890            for value in &mut values {
891                let delta = unzigzag(*value as u64);
892                *value = current;
893                current = current.wrapping_add(delta);
894            }
895            values.push(current);
896            Ok(values)
897        }
898        Kind::Rle => {
899            let run_values = decode_chunk(reader)?;
900            let run_lengths = decode_chunk(reader)?;
901            expanded(&run_values, &run_lengths, count)
902        }
903        Kind::Dict => {
904            let dictionary = decode_chunk(reader)?;
905            let codes = decode_chunk(reader)?;
906            let mut values = Vec::with_capacity(count);
907            for code in codes {
908                let index =
909                    usize::try_from(code).ok().and_then(|index| dictionary.get(index)).ok_or_else(
910                        || Error::internal(format!("code {code} is not in the dictionary")),
911                    )?;
912                values.push(*index);
913            }
914            check_count(values.len(), count)?;
915            Ok(values)
916        }
917        Kind::Sparse => {
918            let value = reader.i64()?;
919            let exception_count = reader.u32()? as usize;
920            let positions = decode_chunk(reader)?;
921            let exceptions = decode_chunk(reader)?;
922            if positions.len() != exception_count || exceptions.len() != exception_count {
923                return Err(Error::internal("a sparse chunk disagrees about its exception count"));
924            }
925            let mut values = vec![value; count];
926            for (position, exception) in positions.into_iter().zip(exceptions) {
927                let position = usize::try_from(position)
928                    .ok()
929                    .filter(|position| *position < count)
930                    .ok_or_else(|| {
931                        Error::internal(format!("exception at {position} is outside the chunk"))
932                    })?;
933                values[position] = exception;
934            }
935            Ok(values)
936        }
937        Kind::Strided => {
938            let base = reader.i64()?;
939            let stride = reader.u64()?;
940            let steps = decode_chunk(reader)?;
941            check_count(steps.len(), count)?;
942            strided(steps, stride, base)
943        }
944    }
945}
946
947/// The values of a strided chunk, `base` plus each step times `stride`, written over the steps.
948///
949/// Over the steps rather than into a run of their own, so a chunk is one allocation rather than
950/// two, and with the one check a chunk needs taken over the whole run first, so the loop that makes
951/// the values has nothing in it but a multiply and an add and the compiler does it four lanes at a
952/// time. A value pushed at a time with the check inside was about thirteen instructions a value,
953/// and a decimal column of whole numbers, which TPC-H's `l_quantity` is, is stored this way.
954fn strided(mut steps: Vec<i64>, stride: u64, base: i64) -> Result<Vec<i64>> {
955    // Every bit of every step or'ed together has its sign bit set exactly when some step is negative.
956    if steps.iter().fold(0, |held, &step| held | step) < 0 {
957        return Err(Error::internal("a negative number of strides"));
958    }
959    for step in &mut steps {
960        *step = base.wrapping_add((*step as u64).wrapping_mul(stride) as i64);
961    }
962    Ok(steps)
963}
964
965/// The runs of an RLE chunk laid out one after another, in the type the chunk is decoded into.
966///
967/// Every check a run could fail is made once over all of them before anything is written: that no
968/// length is negative, that the lengths add up to the chunk, and that the lowest and highest value
969/// fit `T`. Made a run at a time they were a conversion, a checked add and a lane check between
970/// every two writes, about twenty five instructions a run against the four stores of the run
971/// itself, and `l_orderkey` is a million and a half runs. After the checks every run lands inside
972/// the chunk, so the loop is the write and the step.
973///
974/// A chunk whose runs are long on average, the way a sorted column's are thousands of rows each,
975/// has every run appended into reserved room, so that each value is written once by the run it
976/// belongs to. Zeroing the chunk first was a second write of all of it. Short runs are cheaper the
977/// other way, with room for one run past the end so that the write never has to ask how much of
978/// its fixed width landed inside the chunk, and appending those cost a few percent more on
979/// ClickBench 15, 17 and 31.
980fn expanded<T: Lane>(run_values: &[i64], run_lengths: &[i64], count: usize) -> Result<Vec<T>> {
981    if run_values.len() != run_lengths.len() {
982        return Err(Error::internal("an RLE chunk has more runs than run lengths"));
983    }
984    let (signs, longest, total) =
985        run_lengths.iter().fold((0, 0, 0u128), |(signs, longest, total), &length| {
986            (signs | length, longest.max(length), total + u128::from(length as u64))
987        });
988    if signs < 0 {
989        return Err(Error::internal("a negative RLE run length"));
990    }
991    if total > count as u128 {
992        return Err(Error::internal("an RLE run ends past its chunk"));
993    }
994    check_count(total as usize, count)?;
995    // A type that holds all of `i64` needs no look at the values, and the test folds away for it.
996    let wide = T::fit(i64::MIN).is_some() && T::fit(i64::MAX).is_some();
997    if !wide {
998        let (low, high) = run_values
999            .iter()
1000            .fold((i64::MAX, i64::MIN), |(low, high), &value| (low.min(value), high.max(value)));
1001        if !run_values.is_empty() {
1002            lane::<T>(low)?;
1003            lane::<T>(high)?;
1004        }
1005    }
1006    let runs = run_values.iter().zip(run_lengths);
1007    if run_values.len().saturating_mul(LONG_RUN) <= count {
1008        let mut values = Vec::with_capacity(count);
1009        for (&value, &length) in runs {
1010            values.resize(values.len() + length as usize, T::wrap(value));
1011        }
1012        return Ok(values);
1013    }
1014    let mut values = vec![T::default(); count + RUN];
1015    let mut at = 0;
1016    if longest as usize <= RUN {
1017        for (&value, &length) in runs {
1018            values[at..at + RUN].fill(T::wrap(value));
1019            at += length as usize;
1020        }
1021    } else {
1022        for (&value, &length) in runs {
1023            let length = length as usize;
1024            values[at..at + length.max(RUN)].fill(T::wrap(value));
1025            at += length;
1026        }
1027    }
1028    values.truncate(count);
1029    Ok(values)
1030}
1031
1032/// [`decode_chunk`] into `T`. See [`decode_as`].
1033fn decode_chunk_as<T: Lane>(reader: &mut Reader<'_>) -> Result<Vec<T>> {
1034    let Some(&tag) = reader.rest().first() else {
1035        return Err(Error::internal("a chunk ended before its encoding tag"));
1036    };
1037    match Kind::from_tag(tag)? {
1038        Kind::Constant | Kind::Packed | Kind::Sparse | Kind::Rle => {}
1039        // Every other kind is made wide as [`decode`] makes it and narrowed after, with the range of
1040        // the chunk taken once so that a chunk whose ends fit is narrowed with no check a value.
1041        //
1042        // The check a value is worth taking out twice over. It is the check itself, and it is that a
1043        // narrowing that cannot fail is a `Vec<i64>` walked into a `Vec<T>` of the same length, which
1044        // the standard library does in the allocation the wide values arrived in when the two widths
1045        // match. A `BIGINT` column is the case where they always match, so the whole narrowing is a
1046        // walk over a vector that stays where it is, where the checked form allocated a second
1047        // vector and copied every row into it.
1048        _ => {
1049            let values = decode_chunk(reader)?;
1050            let (low, high) = values.iter().fold((i64::MAX, i64::MIN), |(low, high), &value| {
1051                (low.min(value), high.max(value))
1052            });
1053            if values.is_empty() || T::fit(low).is_some() && T::fit(high).is_some() {
1054                return Ok(values.into_iter().map(T::wrap).collect());
1055            }
1056            return values.into_iter().map(lane).collect();
1057        }
1058    }
1059    let kind = Kind::from_tag(reader.u8()?)?;
1060    let count = reader.u32()? as usize;
1061    match kind {
1062        Kind::Constant => Ok(vec![lane(reader.i64()?)?; count]),
1063        Kind::Packed => {
1064            let mut values = vec![T::default(); count];
1065            let mut wide = [0i64; VALUES];
1066            let mut done = 0;
1067            while done < count {
1068                let base = reader.i64()?;
1069                let width = reader.u8()? as usize;
1070                let wanted = (count - done).min(VALUES);
1071                let into = &mut values[done..done + wanted];
1072                let whole = wanted == VALUES;
1073                let bytes = if whole {
1074                    reader.bytes(bitpack::unit_len(width))?
1075                } else {
1076                    reader.bytes(bitpack::tail_len(wanted, width))?
1077                };
1078                // Every value of a block is between its base and the base plus the widest offset its
1079                // width holds, so when both ends fit the whole block does and the unpack writes the
1080                // target type with no check a value. A block that could hold more than the type,
1081                // which a width rounded up past the range can, is unpacked wide and checked.
1082                let mask = if width >= 64 { u64::MAX } else { (1u64 << width) - 1 };
1083                let top = i64::try_from(i128::from(base) + i128::from(mask)).ok();
1084                if T::fit(base).is_some() && top.and_then(T::fit).is_some() {
1085                    let map = |offset| T::wrap(value_from(offset, base));
1086                    if whole {
1087                        bitpack::unpack_unit_into(bytes, width, into, map)?;
1088                    } else {
1089                        bitpack::unpack_tail_into(bytes, width, into, map)?;
1090                    }
1091                } else {
1092                    let wide = &mut wide[..wanted];
1093                    let map = |offset| value_from(offset, base);
1094                    if whole {
1095                        bitpack::unpack_unit_into(bytes, width, wide, map)?;
1096                    } else {
1097                        bitpack::unpack_tail_into(bytes, width, wide, map)?;
1098                    }
1099                    for (value, &held) in into.iter_mut().zip(wide.iter()) {
1100                        *value = lane(held)?;
1101                    }
1102                }
1103                done += wanted;
1104            }
1105            Ok(values)
1106        }
1107        Kind::Rle => {
1108            let run_values = decode_chunk(reader)?;
1109            let run_lengths = decode_chunk(reader)?;
1110            expanded(&run_values, &run_lengths, count)
1111        }
1112        Kind::Sparse => {
1113            let value = lane::<T>(reader.i64()?)?;
1114            let exception_count = reader.u32()? as usize;
1115            let positions = decode_chunk(reader)?;
1116            let exceptions = decode_chunk(reader)?;
1117            if positions.len() != exception_count || exceptions.len() != exception_count {
1118                return Err(Error::internal("a sparse chunk disagrees about its exception count"));
1119            }
1120            let mut values = vec![value; count];
1121            for (position, exception) in positions.into_iter().zip(exceptions) {
1122                let position = usize::try_from(position)
1123                    .ok()
1124                    .filter(|position| *position < count)
1125                    .ok_or_else(|| {
1126                        Error::internal(format!("exception at {position} is outside the chunk"))
1127                    })?;
1128                values[position] = lane(exception)?;
1129            }
1130            Ok(values)
1131        }
1132        Kind::Delta | Kind::Dict | Kind::Strided => {
1133            Err(Error::internal("a chunk kind that decodes wide reached the narrow decoder"))
1134        }
1135    }
1136}
1137
1138fn decode_selected_chunk(reader: &mut Reader<'_>, positions: &[usize]) -> Result<Vec<i64>> {
1139    let Some(&tag) = reader.rest().first() else {
1140        return Err(Error::internal("a chunk ended before its encoding tag"));
1141    };
1142    let kind = Kind::from_tag(tag)?;
1143    if !matches!(kind, Kind::Constant | Kind::Packed | Kind::Rle | Kind::Strided | Kind::Dict) {
1144        let values = decode_chunk(reader)?;
1145        return positions
1146            .iter()
1147            .map(|&position| {
1148                values.get(position).copied().ok_or_else(|| {
1149                    Error::internal(format!(
1150                        "selected integer position {position} is outside {} values",
1151                        values.len()
1152                    ))
1153                })
1154            })
1155            .collect();
1156    }
1157
1158    let decoded = Kind::from_tag(reader.u8()?)?;
1159    debug_assert_eq!(decoded, kind);
1160    let count = reader.u32()? as usize;
1161    if positions.last().is_some_and(|&position| position >= count) {
1162        return Err(Error::internal(format!(
1163            "selected integer position {} is outside {count} values",
1164            positions.last().expect("a last position exists")
1165        )));
1166    }
1167    match kind {
1168        Kind::Constant => {
1169            let value = reader.i64()?;
1170            Ok(vec![value; positions.len()])
1171        }
1172        Kind::Packed => {
1173            let mut out = Vec::with_capacity(positions.len());
1174            let mut from = 0;
1175            let mut done = 0;
1176            while done < count {
1177                let base = reader.i64()?;
1178                let width = reader.u8()? as usize;
1179                let wanted = (count - done).min(VALUES);
1180                let upto = positions.partition_point(|&position| position < done + wanted);
1181                if wanted == VALUES && (upto - from) * SPARSE > VALUES {
1182                    // Enough of the unit is wanted that unpacking all of it is cheaper than
1183                    // finding each value on its own.
1184                    let bytes = reader.bytes(bitpack::unit_len(width))?;
1185                    let mut unit = [0_i64; VALUES];
1186                    bitpack::unpack_unit_into(bytes, width, &mut unit, |offset| {
1187                        value_from(offset, base)
1188                    })?;
1189                    out.extend(positions[from..upto].iter().map(|&position| unit[position - done]));
1190                } else if wanted == VALUES {
1191                    let bytes = reader.bytes(bitpack::unit_len(width))?;
1192                    for &position in &positions[from..upto] {
1193                        let offset = bitpack::unpack_u64_at(bytes, width, position - done)?;
1194                        out.push(value_from(offset, base));
1195                    }
1196                } else {
1197                    let bytes = reader.bytes(bitpack::tail_len(wanted, width))?;
1198                    for &position in &positions[from..upto] {
1199                        let offset = bitpack::tail_at(bytes, width, position - done)?;
1200                        out.push(value_from(offset, base));
1201                    }
1202                }
1203                from = upto;
1204                done += wanted;
1205            }
1206            Ok(out)
1207        }
1208        Kind::Rle => {
1209            let run_value_bytes = reader.rest();
1210            let mut run_value_reader = Reader::new(run_value_bytes);
1211            let run_value_count = skip_chunk(&mut run_value_reader)?;
1212            let run_value_len = run_value_reader.used();
1213            reader.skip(run_value_len)?;
1214            let run_lengths = decode_chunk(reader)?;
1215            if run_value_count != run_lengths.len() {
1216                return Err(Error::internal("an RLE chunk has more runs than run lengths"));
1217            }
1218            let mut wanted_runs = Vec::new();
1219            let mut selected_per_run = Vec::new();
1220            let mut selected = 0;
1221            let mut at = 0usize;
1222            for (run, length) in run_lengths.into_iter().enumerate() {
1223                let length = usize::try_from(length)
1224                    .map_err(|_| Error::internal("a negative RLE run length"))?;
1225                let end = at
1226                    .checked_add(length)
1227                    .filter(|end| *end <= count)
1228                    .ok_or_else(|| Error::internal("an RLE run ends past its chunk"))?;
1229                let before = selected;
1230                while selected < positions.len() && positions[selected] < end {
1231                    if positions[selected] < at {
1232                        return Err(Error::internal("selected integer positions went backwards"));
1233                    }
1234                    selected += 1;
1235                }
1236                if selected != before {
1237                    wanted_runs.push(run);
1238                    selected_per_run.push(selected - before);
1239                }
1240                at = end;
1241            }
1242            check_count(at, count)?;
1243            if selected != positions.len() {
1244                return Err(Error::internal("an RLE chunk ended before a selected position"));
1245            }
1246            let run_values = decode_selected(&run_value_bytes[..run_value_len], &wanted_runs)?;
1247            let mut out = Vec::with_capacity(positions.len());
1248            for (value, repeat) in run_values.into_iter().zip(selected_per_run) {
1249                out.extend(std::iter::repeat_n(value, repeat));
1250            }
1251            Ok(out)
1252        }
1253        // The steps and the codes are chunks of their own, read at the same rows, and the dictionary
1254        // is read whole since a code can point anywhere in it.
1255        Kind::Strided => {
1256            let base = reader.i64()?;
1257            let stride = reader.u64()?;
1258            let steps = decode_selected_chunk(reader, positions)?;
1259            steps
1260                .into_iter()
1261                .map(|step| {
1262                    let step = u64::try_from(step)
1263                        .map_err(|_| Error::internal("a negative number of strides"))?;
1264                    Ok(value_from(step.wrapping_mul(stride), base))
1265                })
1266                .collect()
1267        }
1268        Kind::Dict => {
1269            let dictionary = decode_chunk(reader)?;
1270            let codes = decode_selected_chunk(reader, positions)?;
1271            codes
1272                .into_iter()
1273                .map(|code| {
1274                    usize::try_from(code)
1275                        .ok()
1276                        .and_then(|index| dictionary.get(index))
1277                        .copied()
1278                        .ok_or_else(|| {
1279                            Error::internal(format!("code {code} is not in the dictionary"))
1280                        })
1281                })
1282                .collect()
1283        }
1284        _ => unreachable!("unsupported kinds used the full decoder"),
1285    }
1286}
1287
1288/// Advances over one encoded chunk without materializing its values and returns its row count.
1289fn skip_chunk(reader: &mut Reader<'_>) -> Result<usize> {
1290    let kind = Kind::from_tag(reader.u8()?)?;
1291    let count = reader.u32()? as usize;
1292    match kind {
1293        Kind::Constant => reader.skip(8)?,
1294        Kind::Packed => skip_packed(reader, count)?,
1295        Kind::Delta => {
1296            reader.skip(8)?;
1297            skip_chunk(reader)?;
1298        }
1299        Kind::Rle | Kind::Dict => {
1300            skip_chunk(reader)?;
1301            skip_chunk(reader)?;
1302        }
1303        Kind::Sparse => {
1304            reader.skip(12)?;
1305            skip_chunk(reader)?;
1306            skip_chunk(reader)?;
1307        }
1308        Kind::Strided => {
1309            reader.skip(16)?;
1310            skip_chunk(reader)?;
1311        }
1312    }
1313    Ok(count)
1314}
1315
1316/// Advances over the units of a `Packed` body of `count` values.
1317fn skip_packed(reader: &mut Reader<'_>, count: usize) -> Result<()> {
1318    let mut done = 0;
1319    while done < count {
1320        reader.skip(8)?;
1321        let width = reader.u8()? as usize;
1322        if width > 64 {
1323            return Err(Error::internal(format!("a packed integer width of {width} is past 64")));
1324        }
1325        let wanted = (count - done).min(VALUES);
1326        let bytes = if wanted == VALUES {
1327            bitpack::packed_len::<u64>(width)
1328                .checked_mul(8)
1329                .ok_or_else(|| Error::internal("packed integer size overflow"))?
1330        } else {
1331            bitpack::tail_len(wanted, width)
1332        };
1333        reader.skip(bytes)?;
1334        done += wanted;
1335    }
1336    Ok(())
1337}
1338
1339/// [`shape`] for one chunk and everything inside it.
1340fn shape_chunk(reader: &mut Reader<'_>, kinds: &mut Vec<Kind>) -> Result<()> {
1341    let kind = Kind::from_tag(reader.u8()?)?;
1342    let count = reader.u32()? as usize;
1343    kinds.push(kind);
1344    match kind {
1345        Kind::Constant => reader.skip(8)?,
1346        Kind::Packed => skip_packed(reader, count)?,
1347        Kind::Delta => {
1348            reader.skip(8)?;
1349            shape_chunk(reader, kinds)?;
1350        }
1351        Kind::Rle | Kind::Dict => {
1352            shape_chunk(reader, kinds)?;
1353            shape_chunk(reader, kinds)?;
1354        }
1355        Kind::Sparse => {
1356            reader.skip(12)?;
1357            shape_chunk(reader, kinds)?;
1358            shape_chunk(reader, kinds)?;
1359        }
1360        Kind::Strided => {
1361            reader.skip(16)?;
1362            shape_chunk(reader, kinds)?;
1363        }
1364    }
1365    Ok(())
1366}
1367
1368fn describe_chunk(reader: &mut Reader<'_>) -> Result<String> {
1369    let kind = Kind::from_tag(reader.u8()?)?;
1370    let count = reader.u32()? as usize;
1371    Ok(match kind {
1372        Kind::Constant => {
1373            reader.i64()?;
1374            "CONSTANT".to_string()
1375        }
1376        Kind::Packed => {
1377            let mut widths = Vec::new();
1378            let mut seen = 0;
1379            while seen < count {
1380                reader.i64()?;
1381                let width = reader.u8()? as usize;
1382                let wanted = (count - seen).min(VALUES);
1383                if wanted == VALUES {
1384                    for _ in 0..bitpack::packed_len::<u64>(width) {
1385                        reader.u64()?;
1386                    }
1387                } else {
1388                    reader.bytes(bitpack::tail_len(wanted, width))?;
1389                }
1390                widths.push(width);
1391                seen += wanted;
1392            }
1393            let low = widths.iter().copied().min().unwrap_or(0);
1394            let high = widths.iter().copied().max().unwrap_or(0);
1395            // Square brackets rather than round ones, so that a reader and a test can both take a
1396            // parenthesis to mean one more level of cascade and nothing else.
1397            if low == high {
1398                format!("FOR+BITPACK[{low}]")
1399            } else {
1400                format!("FOR+BITPACK[{low}..{high}]")
1401            }
1402        }
1403        Kind::Delta => {
1404            reader.i64()?;
1405            format!("DELTA({})", describe_chunk(reader)?)
1406        }
1407        Kind::Rle => {
1408            let values = describe_chunk(reader)?;
1409            let lengths = describe_chunk(reader)?;
1410            format!("RLE({values}, {lengths})")
1411        }
1412        Kind::Dict => {
1413            let dictionary = describe_chunk(reader)?;
1414            let codes = describe_chunk(reader)?;
1415            format!("DICT({dictionary}, {codes})")
1416        }
1417        Kind::Sparse => {
1418            reader.i64()?;
1419            reader.u32()?;
1420            let positions = describe_chunk(reader)?;
1421            let exceptions = describe_chunk(reader)?;
1422            format!("SPARSE({positions}, {exceptions})")
1423        }
1424        Kind::Strided => {
1425            reader.i64()?;
1426            let stride = reader.u64()?;
1427            format!("STRIDE[{stride}]({})", describe_chunk(reader)?)
1428        }
1429    })
1430}
1431
1432/// The step every value of the chunk is a whole number of, or `None` when there is not one worth
1433/// having.
1434///
1435/// This is the greatest common divisor of every value's distance from the smallest one. A timestamp
1436/// column loaded from a source that recorded whole seconds holds microseconds that are all multiples
1437/// of a million, and without this the frame of reference pays twenty bits a value to write down the
1438/// twenty zero bits at the bottom of every one of them.
1439///
1440/// The walk stops the moment the divisor reaches one, which is what makes this affordable to ask on
1441/// every chunk. Two values that share no factor are enough to answer, and on a column of arbitrary
1442/// numbers that is almost always the first pair.
1443fn stride_of(values: &[i64]) -> Option<u64> {
1444    stride_from(values, values.iter().min().copied()?)
1445}
1446
1447/// [`stride_of`] for a chunk whose smallest value is already known.
1448fn stride_from(values: &[i64], base: i64) -> Option<u64> {
1449    let mut divisor = 0u64;
1450    for value in values {
1451        divisor = gcd(divisor, offset_from(*value, base));
1452        if divisor == 1 {
1453            return None;
1454        }
1455    }
1456    // Zero is every value being the base, which `Constant` already holds for nothing, and one is
1457    // the frame of reference on its own with two extra words of header.
1458    (divisor > 1).then_some(divisor)
1459}
1460
1461/// Binary GCD, which is the one without a division in it.
1462fn gcd(mut left: u64, mut right: u64) -> u64 {
1463    if left == 0 {
1464        return right;
1465    }
1466    if right == 0 {
1467        return left;
1468    }
1469    let shift = (left | right).trailing_zeros();
1470    left >>= left.trailing_zeros();
1471    loop {
1472        right >>= right.trailing_zeros();
1473        if left > right {
1474            std::mem::swap(&mut left, &mut right);
1475        }
1476        right -= left;
1477        if right == 0 {
1478            return left << shift;
1479        }
1480    }
1481}
1482
1483/// The distance from the frame of reference base, which is always representable in a `u64` because
1484/// both ends came from an `i64` and the width of the difference is at most 65 bits minus the sign.
1485fn offset_from(value: i64, base: i64) -> u64 {
1486    (i128::from(value) - i128::from(base)) as u64
1487}
1488
1489fn value_from(offset: u64, base: i64) -> i64 {
1490    (i128::from(base) + i128::from(offset)) as i64
1491}
1492
1493/// Zigzag, so that a column that counts down packs as narrowly as one that counts up. Without it a
1494/// delta of -1 is 64 bits of ones.
1495fn zigzag(value: i64) -> u64 {
1496    ((value << 1) ^ (value >> 63)) as u64
1497}
1498
1499fn unzigzag(value: u64) -> i64 {
1500    ((value >> 1) as i64) ^ -((value & 1) as i64)
1501}
1502
1503/// The zigzagged differences, or `None` if any difference is too wide to be one.
1504///
1505/// A column holding both `i64::MIN` and `i64::MAX` has a difference that does not fit in an `i64`,
1506/// and rather than widening every delta array to 128 bits for a case that does not occur in data,
1507/// the encoding declines to apply. `Packed` covers it.
1508/// Whether every neighbouring difference fits in an `i64`, which is the only thing the candidate
1509/// list needs to know about deltas.
1510///
1511/// The candidate list used to answer this by building the whole delta array and checking that it
1512/// came back, which is an allocation and a pass over the chunk thrown away on every chunk, and then
1513/// `Kind::Delta` built it again. This is the same pass with nothing kept.
1514fn deltas_fit(values: &[i64]) -> bool {
1515    values.windows(2).all(|pair| pair[1].checked_sub(pair[0]).is_some())
1516}
1517
1518fn deltas(values: &[i64]) -> Option<Vec<i64>> {
1519    let mut deltas = Vec::with_capacity(values.len().saturating_sub(1));
1520    for pair in values.windows(2) {
1521        let difference = pair[1].checked_sub(pair[0])?;
1522        deltas.push(zigzag(difference) as i64);
1523    }
1524    Some(deltas)
1525}
1526
1527/// The value and the length of every run of equal neighbours.
1528///
1529/// Each run is found by walking to its end and pushed once. This used to push the first value of a
1530/// run and then add one to the last length for every value after it, which kept both vectors'
1531/// lengths in memory across the whole loop and was the hottest loop left in `encode_at` once the
1532/// candidate tests became one pass.
1533fn runs(values: &[i64]) -> (Vec<i64>, Vec<i64>) {
1534    let mut run_values: Vec<i64> = Vec::new();
1535    let mut run_lengths: Vec<i64> = Vec::new();
1536    let mut start = 0;
1537    while let Some(&value) = values.get(start) {
1538        let length = values[start..].iter().take_while(|other| **other == value).count();
1539        run_values.push(value);
1540        run_lengths.push(length as i64);
1541        start += length;
1542    }
1543    (run_values, run_lengths)
1544}
1545
1546/// The distinct values in sorted order.
1547///
1548/// Sorted rather than in order of first appearance, because an ordered dictionary is what lets a
1549/// range predicate become a code range instead of a code set, per section 6.7, and because the
1550/// codes of a clustered column then run in order and delta encode.
1551/// How many distinct values there are and which one occurs most often, from one sort.
1552///
1553/// Both questions are about the histogram of the chunk and neither needs the histogram itself, so
1554/// one sorted copy and one walk over it answers both. They used to be two functions that each sorted
1555/// their own copy and threw it away, which is a chunk sorted twice on every chunk at every level of
1556/// the cascade before a single candidate has been encoded.
1557///
1558/// No hash map, because the sort is what makes the walk a scan of equal runs, and a hash map would
1559/// pay a lookup per value to learn the same thing.
1560fn spread_of(values: &[i64]) -> (usize, Option<(i64, usize)>) {
1561    let mut sorted = values.to_vec();
1562    sorted.sort_unstable();
1563    let mut distinct = 0;
1564    let mut best: Option<(i64, usize)> = None;
1565    let mut index = 0;
1566    while index < sorted.len() {
1567        let value = sorted[index];
1568        let mut end = index;
1569        while end < sorted.len() && sorted[end] == value {
1570            end += 1;
1571        }
1572        distinct += 1;
1573        let count = end - index;
1574        if best.is_none_or(|(_, seen)| count > seen) {
1575            best = Some((value, count));
1576        }
1577        index = end;
1578    }
1579    (distinct, best)
1580}
1581
1582/// The value more than half of the chunk holds, and how many times, found in two passes without
1583/// sorting anything.
1584///
1585/// This is the vote that keeps one candidate and a lead: a value that holds more than half the
1586/// chunk outlasts every other value put together, so it is the candidate left at the end, and the
1587/// second pass checks that the candidate really does hold more than half. When it does it is the
1588/// value [`spread_of`] would name as the most frequent, since a value over half the chunk has no tie.
1589fn majority(values: &[i64]) -> Option<(i64, usize)> {
1590    let mut candidate = *values.first()?;
1591    let mut lead = 0usize;
1592    for value in values {
1593        if lead == 0 {
1594            candidate = *value;
1595            lead = 1;
1596        } else if *value == candidate {
1597            lead += 1;
1598        } else {
1599            lead -= 1;
1600        }
1601    }
1602    let count = values.iter().filter(|value| **value == candidate).count();
1603    (count * 2 > values.len()).then_some((candidate, count))
1604}
1605
1606/// The distinct values in sorted order, for the same reason the string dictionary is sorted: an
1607/// ordered dictionary turns a range predicate into a code range rather than a code set.
1608fn distinct_values(values: &[i64]) -> Vec<i64> {
1609    let mut distinct = values.to_vec();
1610    distinct.sort_unstable();
1611    distinct.dedup();
1612    distinct
1613}
1614
1615/// Where each value sits in the dictionary.
1616///
1617/// The string side builds its dictionary and its codes together from one sort of a permutation,
1618/// because the alternative there is a copy of every value onto the heap and a `memcmp` per level of
1619/// a binary search per row. This side was changed to match and it measured slower, so it was changed
1620/// back. An integer dictionary only exists when the distinct count is at most half the row count, so
1621/// the search is over something small and cache resident, the comparison is one integer rather than
1622/// a string, and carrying the source index through the sort means sorting a padded sixteen byte pair
1623/// instead of an eight byte value. The search is cheaper than the wider sort.
1624fn codes_over(values: &[i64], dictionary: &[i64]) -> Vec<i64> {
1625    values
1626        .iter()
1627        .map(|value| {
1628            dictionary
1629                .binary_search(value)
1630                .expect("the dictionary is the distinct values of this chunk") as i64
1631        })
1632        .collect()
1633}
1634
1635fn check_count(actual: usize, expected: usize) -> Result<()> {
1636    if actual == expected {
1637        Ok(())
1638    } else {
1639        Err(Error::internal(format!(
1640            "a chunk says it holds {expected} values and decoded to {actual}"
1641        )))
1642    }
1643}
1644
1645fn too_long(len: usize) -> Error {
1646    Error::internal(format!("a chunk of {len} values is longer than the format allows"))
1647}
1648
1649fn put_u8(out: &mut Vec<u8>, value: u8) {
1650    out.push(value);
1651}
1652
1653fn put_u32(out: &mut Vec<u8>, value: u32) {
1654    out.extend_from_slice(&value.to_le_bytes());
1655}
1656
1657fn put_u64(out: &mut Vec<u8>, value: u64) {
1658    out.extend_from_slice(&value.to_le_bytes());
1659}
1660
1661fn put_i64(out: &mut Vec<u8>, value: i64) {
1662    out.extend_from_slice(&value.to_le_bytes());
1663}
1664
1665#[cfg(test)]
1666mod tests {
1667    use super::*;
1668
1669    fn round_trip(values: &[i64]) -> Vec<u8> {
1670        let bytes = encode(values).unwrap();
1671        assert_eq!(decode(&bytes).unwrap(), values, "{}", describe(&bytes).unwrap());
1672        bytes
1673    }
1674
1675    fn kind_of(bytes: &[u8]) -> Kind {
1676        Kind::from_tag(bytes[0]).unwrap()
1677    }
1678
1679    /// The same xorshift the bit packing tests use, for the same reason.
1680    struct Random(u64);
1681
1682    impl Random {
1683        fn new() -> Self {
1684            Self(0x9e37_79b9_7f4a_7c15)
1685        }
1686
1687        fn next(&mut self) -> u64 {
1688            self.0 ^= self.0 << 13;
1689            self.0 ^= self.0 >> 7;
1690            self.0 ^= self.0 << 17;
1691            self.0
1692        }
1693    }
1694
1695    #[test]
1696    fn the_dictionary_is_sorted_and_the_codes_point_back_at_the_values() {
1697        let values = vec![30i64, 10, 30, 20, 10, -5];
1698        let dictionary = distinct_values(&values);
1699        let codes = codes_over(&values, &dictionary);
1700        assert_eq!(dictionary, vec![-5, 10, 20, 30]);
1701        assert_eq!(codes, vec![3, 1, 3, 2, 1, 0]);
1702        for (code, value) in codes.iter().zip(&values) {
1703            assert_eq!(dictionary[*code as usize], *value);
1704        }
1705    }
1706
1707    #[test]
1708    fn one_sort_gives_the_distinct_count_and_the_most_frequent_value() {
1709        let values = vec![7i64, 7, 7, 1, 2, 2];
1710        assert_eq!(spread_of(&values), (3, Some((7, 3))));
1711        assert_eq!(spread_of(&[]), (0, None));
1712        assert_eq!(spread_of(&[9]), (1, Some((9, 1))));
1713
1714        // A tie goes to the value that sorts first, which is arbitrary but has to be stable,
1715        // because Sparse writes the dominant value into the chunk and the size depends on it.
1716        assert_eq!(spread_of(&[4i64, 4, 8, 8]), (2, Some((4, 2))));
1717    }
1718
1719    #[test]
1720    fn the_majority_is_the_most_frequent_value_whenever_there_is_one() {
1721        let chunks: Vec<Vec<i64>> = vec![
1722            vec![],
1723            vec![3],
1724            vec![1, 2],
1725            vec![1, 1, 2],
1726            vec![2, 1, 1],
1727            vec![4, 4, 8, 8],
1728            vec![7, 1, 7, 2, 7, 3, 7],
1729            vec![1, 2, 3, 9, 9, 9, 9],
1730            (0..1000).map(|index| if index % 5 == 0 { index } else { -4 }).collect(),
1731            (0..1000).map(|index| index % 3).collect(),
1732        ];
1733        for chunk in chunks {
1734            let (_, dominant) = spread_of(&chunk);
1735            let expected = dominant.filter(|(_, count)| count * 2 > chunk.len());
1736            assert_eq!(majority(&chunk), expected, "{chunk:?}");
1737        }
1738    }
1739
1740    /// The one pass offers exactly what the separate tests offered, including on the chunks where
1741    /// the shortcuts in it are the whole answer: a range too wide for an `i64`, and a chunk with too
1742    /// many runs to have a value in four rows out of five.
1743    #[test]
1744    fn the_one_pass_offers_what_the_separate_tests_offered() {
1745        let mut random = Random::new();
1746        let mut chunks: Vec<Vec<i64>> = vec![
1747            vec![],
1748            vec![5],
1749            vec![5, 5, 5],
1750            vec![i64::MIN, i64::MAX],
1751            vec![i64::MAX, i64::MIN, i64::MAX],
1752            vec![i64::MIN, 0, i64::MAX],
1753            vec![-1, i64::MAX],
1754            (0..1000).map(|index| if index % 5 == 0 { index } else { -4 }).collect(),
1755            (0..1000).map(|index| if index % 4 == 0 { index } else { -4 }).collect(),
1756            (0..1000).map(|index| index / 7).collect(),
1757            (0..1000).map(|index| index * 1_000_000).collect(),
1758        ];
1759        for _ in 0..200 {
1760            let len = (random.next() % 300) as usize;
1761            let spread = 1 + random.next() % 8;
1762            let common = (random.next() % 5) as i64;
1763            chunks.push(
1764                (0..len)
1765                    .map(|_| {
1766                        let draw = random.next();
1767                        if draw % 10 < spread { (draw >> 8) as i64 % 50 } else { common }
1768                    })
1769                    .collect(),
1770            );
1771        }
1772        for chunk in chunks {
1773            let mut expected = vec![Kind::Packed];
1774            if !chunk.is_empty() {
1775                if chunk.iter().all(|value| *value == chunk[0]) {
1776                    expected = vec![Kind::Constant];
1777                } else {
1778                    let runs = 1 + chunk.windows(2).filter(|pair| pair[0] != pair[1]).count();
1779                    let low = *chunk.iter().min().unwrap();
1780                    let high = *chunk.iter().max().unwrap();
1781                    let bits = |range: u128| 128 - range.leading_zeros();
1782                    let width = bits((i128::from(high) - i128::from(low)) as u128);
1783                    let zigzags: Vec<u128> = chunk
1784                        .windows(2)
1785                        .map(|pair| u128::from(zigzag(pair[1].wrapping_sub(pair[0]))))
1786                        .collect();
1787                    let spread = zigzags.iter().max().unwrap() - zigzags.iter().min().unwrap();
1788                    let turns = 1 + zigzags.windows(2).filter(|pair| pair[0] != pair[1]).count();
1789                    let mut first: Vec<u128> = zigzags.iter().take(64).copied().collect();
1790                    first.sort_unstable();
1791                    first.dedup();
1792                    let pays = bits(spread) < width
1793                        || (runs * 4 > chunk.len() * 3
1794                            && (turns * 4 <= (chunk.len() - 1) * 3 || first.len() <= 4));
1795                    if deltas_fit(&chunk) && pays {
1796                        expected.push(Kind::Delta);
1797                    }
1798                    if runs * 4 <= chunk.len() * 3 {
1799                        expected.push(Kind::Rle);
1800                    }
1801                    let distinct = spread_of(&chunk).0;
1802                    if distinct * 2 <= chunk.len() && bits(distinct as u128 - 1) < width {
1803                        expected.push(Kind::Dict);
1804                    }
1805                    if majority(&chunk).is_some_and(|(_, count)| count * 10 >= chunk.len() * 8) {
1806                        expected.push(Kind::Sparse);
1807                    }
1808                    if stride_of(&chunk).is_some() {
1809                        expected.push(Kind::Strided);
1810                    }
1811                }
1812            }
1813            assert_eq!(candidates(&chunk, 0, &EXHAUSTIVE), expected, "{chunk:?}");
1814        }
1815    }
1816
1817    #[test]
1818    fn runs_are_every_stretch_of_equal_neighbours_in_order() {
1819        assert_eq!(runs(&[]), (vec![], vec![]));
1820        assert_eq!(runs(&[4]), (vec![4], vec![1]));
1821        assert_eq!(runs(&[1, 1, 2, 1, 1, 1]), (vec![1, 2, 1], vec![2, 1, 3]));
1822    }
1823
1824    #[test]
1825    fn deltas_that_do_not_fit_are_refused_before_they_are_built() {
1826        assert!(deltas_fit(&[1i64, 2, 3]));
1827        assert!(deltas_fit(&[i64::MAX, i64::MAX]));
1828        assert!(!deltas_fit(&[i64::MIN, i64::MAX]));
1829        assert_eq!(deltas_fit(&[i64::MIN, i64::MAX]), deltas(&[i64::MIN, i64::MAX]).is_some());
1830        assert_eq!(deltas_fit(&[1i64, 2, 3]), deltas(&[1i64, 2, 3]).is_some());
1831    }
1832
1833    #[test]
1834    fn what_the_chooser_returns_is_the_smallest_of_what_it_was_offered() {
1835        // `offered` and `encode_only` are what `cargo xtask encode` splits the chooser's seconds
1836        // with, so they have to describe the chooser that actually runs rather than a second copy
1837        // of its rules that drifts. This is the assertion that keeps the two the same thing.
1838        let mut random = Random::new();
1839        let noise: Vec<i64> = (0..2000).map(|_| (random.next() % 5000) as i64).collect();
1840        let runs: Vec<i64> = (0..2000).map(|index: i64| index / 100).collect();
1841        let climbing: Vec<i64> = (0..2000).map(|index| 1_700_000_000 + index).collect();
1842        for values in [noise, runs, climbing, vec![7; 300], Vec::new()] {
1843            let chosen = encode(&values).unwrap();
1844            let mut smallest: Option<Vec<u8>> = None;
1845            for kind in offered(&values) {
1846                let Some(bytes) = encode_only(kind, &values).unwrap() else {
1847                    continue;
1848                };
1849                if smallest.as_ref().is_none_or(|best| bytes.len() < best.len()) {
1850                    smallest = Some(bytes);
1851                }
1852            }
1853            assert_eq!(smallest.as_deref(), Some(chosen.as_slice()), "{}", values.len());
1854        }
1855    }
1856
1857    #[test]
1858    fn a_column_of_whole_seconds_in_microseconds_pays_nothing_for_the_zeroes() {
1859        // What three ClickBench columns are. `epoch_ms(EventTime * 1000)` on a source that recorded
1860        // whole seconds gives microseconds with twenty zero bits under every value, and a frame of
1861        // reference over a part that spans a working day needs 36 bits to write them down.
1862        let mut random = Random::new();
1863        let day = 1_374_000_000_000_000i64;
1864        let values: Vec<i64> =
1865            (0..100_000).map(|_| day + (random.next() % 68_400) as i64 * 1_000_000).collect();
1866        let bytes = round_trip(&values);
1867        assert_eq!(kind_of(&bytes), Kind::Strided);
1868        assert!(describe(&bytes).unwrap().starts_with("STRIDE[1000000]"), "{:?}", describe(&bytes));
1869        // 17 bits a value for the range of seconds, against the 36 the microseconds need.
1870        let strided = 100_000 * 17 / 8;
1871        assert!(bytes.len() < strided + 2000, "{} bytes for {strided} of payload", bytes.len());
1872
1873        let plain = encode_only(Kind::Packed, &values).unwrap().expect("packing always applies");
1874        assert!(
1875            bytes.len() * 2 < plain.len(),
1876            "{} strided against {} packed",
1877            bytes.len(),
1878            plain.len()
1879        );
1880    }
1881
1882    #[test]
1883    fn a_stride_is_the_common_factor_of_the_distances_from_the_smallest_value() {
1884        assert_eq!(stride_of(&[10i64, 20, 40]), Some(10));
1885        // The base is the smallest value and not zero, so a column that does not start on a
1886        // multiple of its own step still has one.
1887        assert_eq!(stride_of(&[7i64, 17, 37]), Some(10));
1888        assert_eq!(stride_of(&[10i64, 20, 23]), None);
1889        // Every value the same is `Constant`'s case and this declines it rather than dividing by a
1890        // stride of zero.
1891        assert_eq!(stride_of(&[5i64; 100]), None);
1892        assert_eq!(stride_of(&[]), None);
1893        // The two ends of the type, where the distance needs 65 bits and only a `u64` holds it.
1894        assert_eq!(stride_of(&[i64::MIN, i64::MAX]), Some(u64::MAX));
1895    }
1896
1897    #[test]
1898    fn a_stride_across_the_whole_of_the_type_round_trips() {
1899        // The distance is 65 bits, so the step count is one and the offset it comes back as is a
1900        // number no `i64` holds. This is the arithmetic the encoder has to do in `u64`.
1901        for values in [vec![i64::MIN, i64::MAX], vec![i64::MIN, 0, i64::MAX]] {
1902            let bytes = round_trip(&values);
1903            assert_eq!(decode(&bytes).unwrap(), values);
1904        }
1905    }
1906
1907    #[test]
1908    fn a_column_with_no_common_factor_is_not_offered_a_stride() {
1909        let mut random = Random::new();
1910        let values: Vec<i64> = (0..2000).map(|_| (random.next() % 1_000_000) as i64).collect();
1911        assert!(!offered(&values).contains(&Kind::Strided));
1912        assert!(encode_only(Kind::Strided, &values).unwrap().is_none());
1913    }
1914
1915    #[test]
1916    fn an_empty_chunk_round_trips() {
1917        let bytes = round_trip(&[]);
1918        assert_eq!(bytes.len(), 5);
1919    }
1920
1921    #[test]
1922    fn a_constant_column_costs_thirteen_bytes_however_long_it_is() {
1923        let bytes = round_trip(&vec![42; 1_000_000]);
1924        assert_eq!(kind_of(&bytes), Kind::Constant);
1925        assert_eq!(bytes.len(), 13);
1926    }
1927
1928    #[test]
1929    fn a_narrow_range_is_packed_at_the_width_of_the_range_and_not_of_the_type() {
1930        // 100_000 values between 1000 and 1063 is 6 bits each, plus 9 bytes of header per 1024.
1931        let mut random = Random::new();
1932        let values: Vec<i64> = (0..100_000).map(|_| 1000 + (random.next() % 64) as i64).collect();
1933        let bytes = round_trip(&values);
1934        assert_eq!(kind_of(&bytes), Kind::Packed);
1935        let packed = 100_000 * 6 / 8;
1936        assert!(bytes.len() < packed + 2000, "{} bytes for {packed} of payload", bytes.len());
1937        assert!(bytes.len() > packed, "{} bytes cannot hold {packed}", bytes.len());
1938    }
1939
1940    #[test]
1941    fn a_counter_becomes_deltas_and_then_a_constant() {
1942        // The classic case and the reason DELTA exists. A million consecutive integers is a
1943        // difference of 1 a million times, which is a constant chunk under the delta.
1944        let values: Vec<i64> = (0..1_000_000).collect();
1945        let bytes = round_trip(&values);
1946        assert_eq!(kind_of(&bytes), Kind::Delta);
1947        assert_eq!(describe(&bytes).unwrap(), "DELTA(CONSTANT)");
1948        assert!(bytes.len() < 40, "{} bytes for a counter", bytes.len());
1949    }
1950
1951    #[test]
1952    fn a_column_that_counts_down_is_as_cheap_as_one_that_counts_up() {
1953        // What zigzag is for. Without it every delta is -1, which is 64 bits of ones.
1954        let up: Vec<i64> = (0..100_000).collect();
1955        let down: Vec<i64> = (0..100_000).rev().collect();
1956        assert_eq!(round_trip(&up).len(), round_trip(&down).len());
1957    }
1958
1959    #[test]
1960    fn long_runs_become_rle() {
1961        let mut values = Vec::new();
1962        for run in 0..1000 {
1963            values.extend(std::iter::repeat_n(run % 7, 200));
1964        }
1965        let bytes = round_trip(&values);
1966        assert_eq!(kind_of(&bytes), Kind::Rle);
1967        assert!(bytes.len() < 2000, "{} bytes for 1000 runs", bytes.len());
1968    }
1969
1970    #[test]
1971    fn a_low_cardinality_column_becomes_a_dictionary() {
1972        // Values that are far apart so that packing them directly is 30 bits each, and only 40 of
1973        // them so that the codes are 6 bits each. The dictionary has to win by a factor of five.
1974        //
1975        // Drawn at random rather than laid out at a fixed interval, because a fixed interval is a
1976        // stride and STRIDE writes the same codes without a dictionary to point them at.
1977        let mut random = Random::new();
1978        let dictionary: Vec<i64> =
1979            (0..40).map(|_| 1_000_000_000 + (random.next() % (1 << 30)) as i64).collect();
1980        let values: Vec<i64> =
1981            (0..100_000).map(|_| dictionary[(random.next() % 40) as usize]).collect();
1982        let bytes = round_trip(&values);
1983        assert_eq!(kind_of(&bytes), Kind::Dict);
1984        assert!(bytes.len() < 100_000, "{} bytes", bytes.len());
1985    }
1986
1987    #[test]
1988    fn a_nearly_constant_column_becomes_sparse() {
1989        let mut values = vec![0i64; 100_000];
1990        for index in 0..300 {
1991            values[index * 331] = 1 << 40;
1992        }
1993        let bytes = round_trip(&values);
1994        assert_eq!(kind_of(&bytes), Kind::Sparse);
1995        assert!(bytes.len() < 3000, "{} bytes for 300 exceptions", bytes.len());
1996    }
1997
1998    #[test]
1999    fn encoded_counts_match_decoded_rows_across_integer_shapes() {
2000        let mut sparse = vec![0_i64; 4096];
2001        for (index, value) in [(7, -3), (91, 12), (1001, -3), (3000, 12)] {
2002            sparse[index] = value;
2003        }
2004        let mut runs = Vec::new();
2005        for value in [0, 7, 0, -5] {
2006            runs.extend(std::iter::repeat_n(value, 500));
2007        }
2008        let mut random = Random::new();
2009        let packed = (0..2000).map(|_| (random.next() % 251) as i64).collect::<Vec<_>>();
2010        for values in [vec![0_i64; 1024], sparse, runs, packed] {
2011            let bytes = encode(&values).unwrap();
2012            let (rows, counts) = tally(&bytes).unwrap();
2013            let mut expected = BTreeMap::<i64, u64>::new();
2014            for value in decode(&bytes).unwrap() {
2015                *expected.entry(value).or_default() += 1;
2016            }
2017            assert_eq!(rows, values.len());
2018            assert_eq!(counts, expected.into_iter().collect::<Vec<_>>());
2019        }
2020    }
2021
2022    #[test]
2023    fn folded_sparse_exceptions_keep_the_last_value_at_a_repeated_position() {
2024        let mut bytes = vec![Kind::Sparse.tag()];
2025        put_u32(&mut bytes, 10);
2026        put_i64(&mut bytes, 0);
2027        put_u32(&mut bytes, 2);
2028        bytes.extend(encode(&[7, 7]).unwrap());
2029        bytes.extend(encode(&[3, 5]).unwrap());
2030
2031        let mut counts = BTreeMap::<i64, u64>::new();
2032        assert_eq!(
2033            fold(&bytes, |value, count| {
2034                *counts.entry(value).or_default() += count;
2035                Ok(())
2036            })
2037            .unwrap(),
2038            10
2039        );
2040        assert_eq!(counts, BTreeMap::from([(0, 9), (5, 1)]));
2041        assert_eq!(decode(&bytes).unwrap()[7], 5);
2042    }
2043
2044    #[test]
2045    fn the_cascade_goes_more_than_one_level_deep() {
2046        // The whole point of section 6.3. A dictionary over a clustered column produces codes that
2047        // run in long stretches, and the run lengths of those are themselves compressible.
2048        let mut values = Vec::new();
2049        for index in 0..2000i64 {
2050            values.extend(std::iter::repeat_n(1_000_000 + (index % 5) * 104_729, 100));
2051        }
2052        let bytes = round_trip(&values);
2053        let shape = describe(&bytes).unwrap();
2054        assert!(shape.contains('('), "{shape} is not a cascade");
2055        assert!(bytes.len() < 4000, "{} bytes: {shape}", bytes.len());
2056    }
2057
2058    #[test]
2059    fn random_data_is_packed_at_full_width_and_costs_what_it_costs() {
2060        // The case where nothing works, which has to come out at eight bytes a value plus change
2061        // rather than at eight bytes a value plus a dictionary of every value in the column.
2062        let mut random = Random::new();
2063        let values: Vec<i64> = (0..10_000).map(|_| random.next() as i64).collect();
2064        let bytes = round_trip(&values);
2065        assert_eq!(kind_of(&bytes), Kind::Packed);
2066        assert!(bytes.len() < 10_000 * 8 + 1000, "{} bytes", bytes.len());
2067    }
2068
2069    #[test]
2070    fn the_extremes_of_the_type_survive() {
2071        // Every offset and every delta in here overflows something if the arithmetic is done in 64
2072        // bits, which is why it is done in 128.
2073        let values = vec![i64::MIN, i64::MAX, 0, -1, i64::MIN, i64::MAX];
2074        round_trip(&values);
2075        round_trip(&[i64::MIN; 3]);
2076        round_trip(&[i64::MIN, i64::MIN + 1]);
2077    }
2078
2079    #[test]
2080    fn a_chunk_that_is_not_a_multiple_of_the_unit_round_trips() {
2081        for len in [1, 2, 1023, 1024, 1025, 2047, 2049] {
2082            let values: Vec<i64> = (0..len).map(|index| (index * 31 % 97) as i64).collect();
2083            round_trip(&values);
2084        }
2085    }
2086
2087    #[test]
2088    fn units_of_different_widths_in_one_chunk_do_not_read_each_others_leftovers() {
2089        // A decode reuses its buffers from one unit to the next instead of getting a zeroed one
2090        // each time, so a unit that wrote fewer bits than the unit before it would come back with
2091        // the older unit's values in the bits it did not write. Each run of 1024 here needs a
2092        // different width and the widths go up and down, and the last run repeats the first, which
2093        // is the pair that would agree by accident if the reuse were wrong in the obvious way.
2094        //
2095        // The values are random rather than written out because this has to stay one packed chunk
2096        // of six units to be testing anything, and the first version of it was arithmetic and got
2097        // cascaded into a delta of runs where every nested array was under a unit long. That was
2098        // caught by gating a panic on the second unit and rerunning, which this version reaches and
2099        // the old one did not, and the assertion on the shape below is there so it stays reached.
2100        let mut random = Random::new();
2101        let mut values = Vec::new();
2102        for width in [40u32, 3, 61, 1, 17, 40] {
2103            for _ in 0..1024 {
2104                values.push((random.next() & ((1u64 << width) - 1)) as i64);
2105            }
2106        }
2107        let bytes = encode(&values).unwrap();
2108        let described = describe(&bytes).unwrap();
2109        assert!(described.starts_with("FOR+BITPACK"), "expected one packed chunk, got {described}");
2110        assert_eq!(decode(&bytes).unwrap(), values, "{described}");
2111    }
2112
2113    #[test]
2114    fn a_chunk_that_cascades_more_than_one_level_deep_decodes_whole() {
2115        // A dictionary of deltas is three nested decodes, and each level reads the packed bytes of
2116        // its own unit out of the chunk where they lie. A chunk long enough to cascade and wide
2117        // enough to bit pack at more than one level is what says the levels do not read each
2118        // other's bytes.
2119        let mut values = Vec::new();
2120        for index in 0..8192i64 {
2121            values.push(1_600_000_000 + index / 4 + (index % 7) * 1_000);
2122        }
2123        let bytes = encode(&values).unwrap();
2124        let described = describe(&bytes).unwrap();
2125        assert!(described.contains('('), "expected a cascade, got {described}");
2126        assert_eq!(decode(&bytes).unwrap(), values, "{described}");
2127    }
2128
2129    #[test]
2130    fn selected_positions_agree_with_a_full_decode_for_every_kind_with_a_point_form() {
2131        let positions = [0, 1, 17, 1023, 1024, 4097, 8191];
2132        let packed: Vec<i64> = (0..8192).map(|index| index * 31 % 1_000_003).collect();
2133        let mut runs = Vec::new();
2134        for run in 0..160i64 {
2135            runs.extend(std::iter::repeat_n(run * 13, (run as usize % 71) + 2));
2136        }
2137        runs.resize(8192, -7);
2138        let strided: Vec<i64> = (0..8192).map(|index| 500 + index * 7 % 5003 * 100).collect();
2139        let coded: Vec<i64> =
2140            (0..8192).map(|index| [-9_000_000_000, 3, 77, 1 << 40][index % 4]).collect();
2141
2142        for (kind, values) in [
2143            (Kind::Packed, packed),
2144            (Kind::Rle, runs),
2145            (Kind::Strided, strided),
2146            (Kind::Dict, coded),
2147        ] {
2148            let bytes = encode_only(kind, &values).unwrap().expect("encoding applies");
2149            let selected = decode_selected(&bytes, &positions).unwrap();
2150            let expected = positions.iter().map(|&position| values[position]).collect::<Vec<_>>();
2151            assert_eq!(selected, expected, "{}", kind.name());
2152            let shape = describe(&bytes).unwrap();
2153            let simple = !shape.contains("RLE") && !shape.contains("DELTA");
2154            assert_eq!(pointed(&bytes), simple, "{shape}");
2155        }
2156    }
2157
2158    #[test]
2159    fn selected_positions_must_be_ordered_and_inside_the_chunk() {
2160        let bytes = encode_only(Kind::Packed, &(0..2048).collect::<Vec<_>>())
2161            .unwrap()
2162            .expect("packed applies");
2163        assert!(decode_selected(&bytes, &[7, 7]).is_err());
2164        assert!(decode_selected(&bytes, &[8, 3]).is_err());
2165        assert!(decode_selected(&bytes, &[2048]).is_err());
2166    }
2167
2168    #[test]
2169    fn a_partial_unit_costs_its_own_values_and_not_a_whole_unit() {
2170        // Three values that need 40 bits each. In the transposed layout a unit is 1024 values
2171        // whether it holds them or not, so this would be 5 KB, and every nested array in a cascade
2172        // is this short. It is 15 bytes of payload and 14 of header.
2173        let values = vec![1i64 << 39, (1 << 39) + 7, 1 << 38];
2174        let bytes = encode_only(Kind::Packed, &values).unwrap().unwrap();
2175        assert_eq!(bytes.len(), 5 + 9 + 15);
2176        assert_eq!(decode(&bytes).unwrap(), values);
2177    }
2178
2179    #[test]
2180    fn the_frame_of_reference_is_per_unit_and_not_per_chunk() {
2181        // A column that drifts, which is what a timestamp column and a clustered key both do. Each
2182        // unit here spans 1023 and packs at 10 bits, and a base per chunk would pay the 22 bits the
2183        // whole chunk spans on every value in it.
2184        let values: Vec<i64> =
2185            (0..4096i64).map(|index| (index / 1024) * 1_000_000 + (index % 1024)).collect();
2186        let bytes = encode_only(Kind::Packed, &values).unwrap().unwrap();
2187        assert_eq!(describe(&bytes).unwrap(), "FOR+BITPACK[10]");
2188        assert_eq!(decode(&bytes).unwrap(), values);
2189    }
2190
2191    #[test]
2192    fn every_candidate_that_applies_decodes_to_the_input() {
2193        // The chooser only ever hands back the smallest, so without this the other five are only
2194        // tested when they happen to win. Any of them being wrong is a wrong answer that appears
2195        // when a column's distribution shifts.
2196        let mut values = vec![5i64; 3000];
2197        for (index, value) in values.iter_mut().enumerate() {
2198            if index % 500 == 0 {
2199                *value = index as i64;
2200            }
2201        }
2202        let applicable = candidates(&values, 0, &EXHAUSTIVE);
2203        assert!(applicable.len() >= 4, "{applicable:?}");
2204        for kind in applicable {
2205            let bytes = encode_only(kind, &values).unwrap().unwrap();
2206            assert_eq!(decode(&bytes).unwrap(), values, "{}", kind.name());
2207        }
2208    }
2209
2210    /// The test above only asks the kinds `candidates` offered, so between them the two cover the
2211    /// encoders on input the search would give them and nothing else. `encode_only` does not go
2212    /// through `candidates` at all, so every one of its callers can hand an encoder a shape the
2213    /// filter would have refused, and the empty chunk is the shape that used to panic.
2214    #[test]
2215    fn every_kind_that_applies_decodes_to_what_it_was_given() {
2216        let shapes: Vec<Vec<i64>> = vec![
2217            Vec::new(),
2218            vec![5; 1024],
2219            vec![i64::MIN, i64::MAX, 0, -1],
2220            (0..1024).map(|at| at * 7).collect(),
2221            (0..1024).map(|at| at % 17).collect(),
2222            (0..1024).map(|at| if at % 100 == 0 { at } else { 3 }).collect(),
2223            (0..1024).map(|at| -at * 1_000_003).collect(),
2224            (0..1024_i64)
2225                .map(|at| {
2226                    at.wrapping_mul(6_364_136_223_846_793_005)
2227                        .wrapping_add(1_442_695_040_888_963_407)
2228                })
2229                .collect(),
2230        ];
2231        let kinds =
2232            [Kind::Constant, Kind::Packed, Kind::Delta, Kind::Rle, Kind::Dict, Kind::Sparse];
2233        for values in &shapes {
2234            for kind in kinds {
2235                let Some(bytes) = encode_only(kind, values).unwrap() else {
2236                    continue;
2237                };
2238                assert_eq!(
2239                    &decode(&bytes).unwrap(),
2240                    values,
2241                    "{} over {} values",
2242                    kind.name(),
2243                    values.len()
2244                );
2245            }
2246        }
2247    }
2248
2249    #[test]
2250    fn the_chooser_picks_the_smallest_candidate_rather_than_the_first_that_applies() {
2251        let mut values = vec![5i64; 3000];
2252        values[1500] = 9;
2253        let chosen = encode(&values).unwrap();
2254        for (_, size) in candidate_sizes(&values).unwrap() {
2255            assert!(chosen.len() <= size);
2256        }
2257    }
2258
2259    #[test]
2260    fn a_truncated_chunk_is_an_error_and_not_a_panic() {
2261        let bytes = encode(&[1, 2, 3, 4, 5]).unwrap();
2262        for len in 0..bytes.len() {
2263            let error = decode(&bytes[..len]).unwrap_err();
2264            assert!(error.message().contains("chunk"), "{error}");
2265        }
2266    }
2267
2268    #[test]
2269    fn trailing_bytes_are_an_error() {
2270        let mut bytes = encode(&[1, 2, 3]).unwrap();
2271        bytes.push(0);
2272        let error = decode(&bytes).unwrap_err();
2273        assert!(error.message().contains("left over"), "{error}");
2274    }
2275
2276    #[test]
2277    fn an_unknown_tag_is_an_error() {
2278        let error = decode(&[99, 0, 0, 0, 0]).unwrap_err();
2279        assert!(error.message().contains("unknown encoding tag"), "{error}");
2280    }
2281
2282    #[test]
2283    fn a_dictionary_code_outside_the_dictionary_is_an_error() {
2284        // A corrupted or malicious chunk must not index out of bounds, and this is the one place in
2285        // the decoder where a number that came off the disk is used as an index. Built by hand
2286        // rather than by corrupting a real chunk, because a byte offset into an encoding that the
2287        // chooser is free to change is a test that breaks for the wrong reason.
2288        let mut bytes = vec![Kind::Dict.tag()];
2289        put_u32(&mut bytes, 1);
2290        bytes.extend_from_slice(&encode(&[10]).unwrap());
2291        bytes.extend_from_slice(&encode(&[5]).unwrap());
2292        let error = decode(&bytes).unwrap_err();
2293        assert!(error.message().contains("not in the dictionary"), "{error}");
2294    }
2295
2296    #[test]
2297    fn a_negative_run_length_is_an_error() {
2298        // The other number off the disk that the decoder would otherwise trust, and the one that
2299        // would turn into an allocation of nine quintillion values.
2300        let mut bytes = vec![Kind::Rle.tag()];
2301        put_u32(&mut bytes, 4);
2302        bytes.extend_from_slice(&encode(&[7]).unwrap());
2303        bytes.extend_from_slice(&encode(&[-4]).unwrap());
2304        let error = decode(&bytes).unwrap_err();
2305        assert!(error.message().contains("negative"), "{error}");
2306    }
2307
2308    /// A run that ends past the chunk it is in is an error and not a write past the end.
2309    #[test]
2310    fn a_run_that_runs_past_its_chunk_is_an_error() {
2311        // The decode writes a fixed eight values per run and moves on by the run's own length, so
2312        // the buffer carries eight values of slack and a run that claims more rows than the chunk
2313        // holds would be the one way to reach past it. It is refused before the write rather than
2314        // caught by the count afterwards.
2315        let mut bytes = vec![Kind::Rle.tag()];
2316        put_u32(&mut bytes, 4);
2317        bytes.extend_from_slice(&encode(&[7]).unwrap());
2318        bytes.extend_from_slice(&encode(&[9]).unwrap());
2319        let error = decode(&bytes).unwrap_err();
2320        assert!(error.message().contains("past its chunk"), "{error}");
2321    }
2322
2323    /// Runs of every length around the eight that a run is written in, in one chunk.
2324    #[test]
2325    fn runs_shorter_and_longer_than_the_width_they_are_written_in_all_come_back() {
2326        // A run of one, several shorter than eight, one of exactly eight and two longer, with the
2327        // shortest run last so that the surplus of the write before it has nothing after it to be
2328        // overwritten by. The values differ from each other, because a surplus that was left in
2329        // place would be invisible against a neighbour holding the same value.
2330        let lengths = [1, 3, 7, 8, 9, 40, 2, 1];
2331        let mut values = Vec::new();
2332        for (at, length) in lengths.iter().enumerate() {
2333            let value = i64::try_from(at).expect("eight runs") * 1000 - 3;
2334            values.extend(std::iter::repeat_n(value, *length));
2335        }
2336        let bytes = encode(&values).expect("encodes");
2337        assert_eq!(decode(&bytes).expect("decodes"), values, "runs around the write width");
2338        // And the same rows a run at a time, which is the run length encoder's worst case and the
2339        // shape a column with no runs in it decodes as.
2340        let singles: Vec<i64> = (0..300).map(|index| index * 7 % 11).collect();
2341        let bytes = encode(&singles).expect("encodes");
2342        assert_eq!(decode(&bytes).expect("decodes"), singles, "no run longer than one");
2343    }
2344
2345    #[test]
2346    fn the_cascade_depth_is_bounded() {
2347        // Without the limit a chooser that finds a dictionary of a dictionary of a dictionary would
2348        // recurse until the values ran out, and the encode time of a wide column would be a
2349        // surprise rather than a number.
2350        let values: Vec<i64> = (0..50_000).map(|index| (index / 100) % 250).collect();
2351        let bytes = round_trip(&values);
2352        let shape = describe(&bytes).unwrap();
2353        let depth = shape.matches('(').count();
2354        assert!(depth <= MAX_DEPTH as usize, "{shape} is {depth} deep");
2355    }
2356
2357    #[test]
2358    fn candidate_sizes_reports_what_the_chooser_looked_at() {
2359        let values: Vec<i64> = (0..5000).map(|index| index % 17 * 1000).collect();
2360        let sizes = candidate_sizes(&values).unwrap();
2361        assert!(sizes.iter().any(|(kind, _)| *kind == Kind::Dict));
2362        assert!(sizes.iter().any(|(kind, _)| *kind == Kind::Packed));
2363        assert!(sizes.iter().all(|(_, size)| *size > 0));
2364    }
2365
2366    #[test]
2367    fn a_chunk_can_be_read_from_the_front_of_a_longer_buffer() {
2368        // What a string column does. It writes an integer chunk of lengths into the middle of its
2369        // own body and has to find the end of it again on the way back.
2370        let first = encode(&[1, 2, 3]).unwrap();
2371        let second: Vec<i64> = (0..3000).map(|index| index % 11).collect();
2372        let second_bytes = encode(&second).unwrap();
2373        let mut joined = first.clone();
2374        joined.extend_from_slice(&second_bytes);
2375        joined.extend_from_slice(b"and then something else");
2376
2377        let (values, used) = decode_prefix(&joined).unwrap();
2378        assert_eq!(values, vec![1, 2, 3]);
2379        assert_eq!(used, first.len());
2380        let (more, used_again) = decode_prefix(&joined[used..]).unwrap();
2381        assert_eq!(more, second);
2382        assert_eq!(used_again, second_bytes.len());
2383
2384        let (text, described) = describe_prefix(&joined).unwrap();
2385        assert_eq!(described, first.len());
2386        assert_eq!(text, describe(&first).unwrap());
2387    }
2388
2389    #[test]
2390    fn a_truncated_chunk_is_still_an_error_when_read_as_a_prefix() {
2391        let bytes = encode(&(0..2000).collect::<Vec<i64>>()).unwrap();
2392        for len in 0..bytes.len() {
2393            assert!(decode_prefix(&bytes[..len]).is_err(), "{len} bytes decoded");
2394        }
2395    }
2396
2397    /// Every kind decodes into a narrow type as the same values [`decode`] gives, whichever kind
2398    /// the chunk is at the top.
2399    #[test]
2400    fn decoding_into_a_narrow_type_agrees_with_the_wide_decoder() {
2401        let columns: Vec<Vec<i64>> = vec![
2402            vec![7; 3000],
2403            (0..3000).map(|i| (i * 37) % 200 - 100).collect(),
2404            (0..3000).map(|i| if i % 97 == 0 { i % 50 } else { 0 }).collect(),
2405            (0..3000).map(|i| i / 250).collect(),
2406            (0..3000).map(|i| i * 3 + 11).collect(),
2407            (0..3000).map(|i| [5, -9, 120][i as usize % 3]).collect(),
2408        ];
2409        let kinds = [
2410            Kind::Constant,
2411            Kind::Packed,
2412            Kind::Delta,
2413            Kind::Rle,
2414            Kind::Dict,
2415            Kind::Sparse,
2416            Kind::Strided,
2417        ];
2418        for values in &columns {
2419            for kind in kinds {
2420                let Some(bytes) = encode_only(kind, values).unwrap() else { continue };
2421                let wide = decode(&bytes).unwrap();
2422                let as_i16: Vec<i64> =
2423                    decode_as::<i16>(&bytes).unwrap().into_iter().map(i64::from).collect();
2424                let as_i32: Vec<i64> =
2425                    decode_as::<i32>(&bytes).unwrap().into_iter().map(i64::from).collect();
2426                assert_eq!(as_i16, wide, "{kind:?} as i16");
2427                assert_eq!(as_i32, wide, "{kind:?} as i32");
2428                assert_eq!(decode_as::<i64>(&bytes).unwrap(), wide, "{kind:?} as i64");
2429            }
2430            let chosen = encode(values).unwrap();
2431            let narrow: Vec<i64> =
2432                decode_as::<i16>(&chosen).unwrap().into_iter().map(i64::from).collect();
2433            assert_eq!(narrow, decode(&chosen).unwrap(), "the chosen cascade as i16");
2434        }
2435    }
2436
2437    /// A value is refused exactly where `TryFrom` refuses it, at both edges of every type.
2438    #[test]
2439    fn decoding_into_a_narrow_type_takes_what_fits_and_refuses_what_does_not() {
2440        fn check<T: Lane + TryFrom<i64> + PartialEq + std::fmt::Debug>(edges: [i64; 2]) {
2441            for edge in edges {
2442                for value in [edge - 1, edge, edge + 1] {
2443                    for kind in
2444                        [Kind::Constant, Kind::Packed, Kind::Rle, Kind::Sparse, Kind::Strided]
2445                    {
2446                        let values = [value, value, edges[0].max(0).min(edges[1]), value];
2447                        let Some(bytes) = encode_only(kind, &values).unwrap() else { continue };
2448                        let fits = values.iter().all(|&value| T::try_from(value).is_ok());
2449                        assert_eq!(decode_as::<T>(&bytes).is_ok(), fits, "{value} {kind:?}");
2450                    }
2451                }
2452            }
2453        }
2454        check::<i8>([-128, 127]);
2455        check::<u8>([0, 255]);
2456        check::<i16>([-32_768, 32_767]);
2457        check::<u16>([0, 65_535]);
2458        check::<i32>([i64::from(i32::MIN), i64::from(i32::MAX)]);
2459        check::<u32>([0, i64::from(u32::MAX)]);
2460    }
2461
2462    /// A packed block whose width reaches past the type while every value in it still fits, which
2463    /// is the block that has to be checked a value at a time rather than by its two ends.
2464    #[test]
2465    fn a_packed_block_wider_than_its_type_still_decodes_when_its_values_fit() {
2466        let values: Vec<i64> = (0..1500).map(|i| if i % 2 == 0 { -5 } else { 32_767 }).collect();
2467        let bytes = encode_only(Kind::Packed, &values).unwrap().expect("packing always applies");
2468        let narrow: Vec<i64> =
2469            decode_as::<i16>(&bytes).unwrap().into_iter().map(i64::from).collect();
2470        assert_eq!(narrow, values);
2471        let over: Vec<i64> = values.iter().map(|&value| value + 1).collect();
2472        let bytes = encode_only(Kind::Packed, &over).unwrap().expect("packing always applies");
2473        assert!(decode_as::<i16>(&bytes).is_err(), "32768 is not an i16");
2474    }
2475}