Skip to main content

rudb_encoding/
string.rs

1//! The string column, which is offsets, bytes, and the choice between compressing the bytes and
2//! not storing most of them at all.
3//!
4//! ClickBench `hits` is a string dataset before it is anything else. `URL`, `Referer`, `Title` and
5//! the referer derived columns are most of the 20.46 GB DuckDB writes for it, so most of what
6//! `spec/02-the-goal.md` promises on the resource axis has to come out of this file.
7//!
8//! ## The five shapes
9//!
10//! `CONSTANT` when every value is the same. `PLAIN`, which is lengths and raw bytes and is the
11//! baseline the others have to beat. `FSST`, which is a symbol table and the same lengths over
12//! compressed bytes. `DICT`, which is the distinct values and an array of codes. `FRONT`, which is
13//! the length of the prefix each value shares with the one before it and the rest of the value.
14//!
15//! `DICT_FSST` from the section 6.2 table is not a sixth shape. A dictionary's entries are a string
16//! column, and encoding them goes back through the same chooser, so a dictionary whose entries are
17//! FSST compressed is what the chooser produces on its own whenever that is smaller. The same
18//! recursion gives run length encoding of strings for free, because the codes are an integer chunk
19//! and `crate::integer` already knows what to do with a column of long runs.
20//!
21//! ## Why front coding is here
22//!
23//! The whole file measurement in M1 says the chooser produces 11.65 GB for `hits` against Parquet's
24//! 13.76 GB, and that `URL`, `Referer` and `OriginalURL` are 6.11 GB of it, and that on those three
25//! the chooser loses to Parquet's Snappy. The shape it picked on all three was `DICT(FSST[255])`,
26//! so the cascade was working and FSST was still losing.
27//!
28//! The reason is structural. FSST compresses each value on its own against a 255 symbol table, and
29//! a block compressor has the previous few kilobytes of the page to point back into. Two URLs that
30//! share a host and half a path are most of a back reference to each other and are nothing at all
31//! to a symbol table, which can only spend eight bytes of a symbol on the part they share and has
32//! to spend it again on every value. On a sorted dictionary of URLs the value before is the closest
33//! thing in the column to the value in hand, and the bytes they share are the redundancy Snappy was
34//! finding. Front coding is what reaches those bytes, and it composes with everything else here:
35//! the suffixes it leaves behind are a string column and go back through the chooser, so
36//! `DICT(FRONT(FSST))` is a shape the chooser can arrive at without anyone naming it.
37//!
38//! The chain has no restarts, so reading entry `n` means walking from entry zero. That is the right
39//! trade while a dictionary is decoded whole, which is what `decode` does. When something wants one
40//! entry out of a dictionary without materialising the rest, the answer is a restart every so many
41//! entries, and it costs one full value per block.
42//!
43//! ## Lengths, not offsets
44//!
45//! The usual layout is `n + 1` offsets and Arrow does it that way because a slice of an array has
46//! to be free. On disk the offsets are a monotonically increasing sequence whose differences are
47//! the lengths, and the differences are what compress: URL lengths in a real column are a few dozen
48//! distinct values in a narrow band, which the integer cascade turns into a handful of bits each,
49//! while the offsets themselves need enough bits to address the whole chunk. The integer cascade
50//! would find that by choosing DELTA, and storing lengths directly gets to the same place without
51//! spending a level of the cascade on it. Offsets are a prefix sum away and that is a decode time
52//! cost of one add per value.
53//!
54//! ## What is not here
55//!
56//! Nulls. A chunk here is N byte strings and an empty string is a value like any other. Validity is
57//! a bitmap that belongs to the column rather than to the encoding, per `spec/05-storage.md`, and
58//! `ROARING` in the section 6.2 table is what encodes it.
59//!
60//! Shared symbol tables and shared dictionaries across columns, which are section 6.4 and are the
61//! measurement this milestone exists for. Everything here is one column on its own, which is the
62//! baseline they get compared against.
63
64use std::time::Instant;
65
66use rudb_common::{Error, Result};
67
68use crate::chooser::{Chooser, EXHAUSTIVE, Settled};
69use crate::fsst::{MAX_SYMBOL_LEN, SymbolTable};
70use crate::integer;
71use crate::lz;
72use crate::reader::Reader;
73use crate::tally::{self, Family};
74
75/// How deep the recursion goes. A dictionary of a dictionary is not a thing, so this only has to
76/// stop the dictionary's own entries from being dictionary encoded again.
77const MAX_DEPTH: u8 = 2;
78
79/// How little sharing between neighbours is still worth offering front coding for, as one over
80/// this. A twentieth of the column is around where the prefix lengths start paying for themselves,
81/// and below it the candidate is an encode of the whole column that loses.
82const SHARE_DIVISOR: usize = 20;
83
84/// How few bytes is too few to bother looking for repeats in.
85///
86/// The matcher costs a hash table and a pass over the bytes whether it wins or not, and the chooser
87/// is exhaustive, so an ungated candidate is a tax on every string column in the database. Four
88/// kilobytes is about where a 32 KiB window has enough behind it to find anything.
89const LZ_FLOOR: usize = 4096;
90
91/// How many bytes of a column the symbol table is trained on.
92///
93/// The paper trains on about 16 KB. This is four times that, because training happens once per
94/// chunk here rather than once per block, and because the cost of a symbol that is only in the
95/// sample by accident is paid on every value in the chunk.
96pub(crate) const SAMPLE_BYTES: usize = 64 * 1024;
97
98/// What a string chunk is encoded as. The discriminant is the tag byte and is part of the format.
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum Kind {
101    /// One value repeated.
102    Constant = 0,
103    /// Lengths and raw bytes.
104    Plain = 1,
105    /// Lengths, a symbol table, and FSST compressed bytes.
106    Fsst = 2,
107    /// The distinct values as a string chunk of their own, and codes into it as an integer chunk.
108    Dict = 3,
109    /// Shared prefix lengths as an integer chunk, and what is left of each value as a string chunk.
110    Front = 4,
111    /// Value lengths, copy lengths and copy offsets as integer chunks, and the bytes no copy
112    /// covered as a string chunk. See the `lz` module for what the matcher does and why it is here.
113    Lz = 5,
114}
115
116impl Kind {
117    /// Every kind, in tag order.
118    pub const ALL: [Self; 6] =
119        [Self::Constant, Self::Plain, Self::Fsst, Self::Dict, Self::Front, Self::Lz];
120
121    fn tag(self) -> u8 {
122        self as u8
123    }
124
125    fn from_tag(tag: u8) -> Result<Self> {
126        match tag {
127            0 => Ok(Self::Constant),
128            1 => Ok(Self::Plain),
129            2 => Ok(Self::Fsst),
130            3 => Ok(Self::Dict),
131            4 => Ok(Self::Front),
132            5 => Ok(Self::Lz),
133            other => Err(Error::internal(format!("unknown string encoding tag {other}"))),
134        }
135    }
136
137    /// The name that goes in a report.
138    #[must_use]
139    pub fn name(self) -> &'static str {
140        match self {
141            Self::Constant => "CONSTANT",
142            Self::Plain => "PLAIN",
143            Self::Fsst => "FSST",
144            Self::Dict => "DICT",
145            Self::Front => "FRONT",
146            Self::Lz => "LZ",
147        }
148    }
149}
150
151/// Encodes a chunk of strings, choosing whatever comes out smallest.
152///
153/// Every candidate that applies is encoded in full and the smallest is kept, which is what this has
154/// always done and is what every size this crate has reported came out of. [`encode_with`] is the
155/// same thing with the search made swappable.
156///
157/// # Errors
158///
159/// If the chunk is longer than `u32::MAX` values, or if an encoding produces something its own
160/// decoder would not accept.
161pub fn encode(values: &[&[u8]]) -> Result<Vec<u8>> {
162    encode_with(values, &EXHAUSTIVE)
163}
164
165/// [`encode`] with somebody else deciding which candidates are worth encoding in full.
166///
167/// A chooser narrows the list and nothing else. It cannot offer a candidate that does not apply, so
168/// whatever it picks still has to encode the whole chunk and still has to decode, and the worst a
169/// bad one can do is come out bigger than [`encode`] would have.
170///
171/// # Errors
172///
173/// As [`encode`].
174pub fn encode_with(values: &[&[u8]], chooser: &dyn Chooser) -> Result<Vec<u8>> {
175    encode_at(values, 0, chooser)
176}
177
178/// A decoded chunk as one buffer with the values laid end to end, and where each one ends in it.
179///
180/// This is what the decoder builds and [`decode`] is a copy out of it. The cascade is why: a nest
181/// like `FRONT(LZ(FSST))` decodes three levels to produce one, and a level that hands its caller a
182/// `Vec<Vec<u8>>` has allocated once per value and copied every byte it holds. Three levels of that
183/// on a chunk of a thousand URLs is three thousand allocations to produce a thousand strings that
184/// the caller almost always wants back to back anyway.
185///
186/// It also makes the levels cheaper on their own terms. `PLAIN` is one `memcpy` of the whole
187/// payload because the values are already end to end in the file. `FRONT` copies a shared prefix
188/// out of the buffer it is writing into, so the previous value never has to be somewhere else.
189/// `LZ` replays straight into the buffer, which is what its copy offsets meant in the first place.
190#[derive(Debug, Clone, Default, PartialEq, Eq)]
191pub struct Flat {
192    bytes: Vec<u8>,
193    /// Where each value ends, so a value starts where the one before it ended and the last entry
194    /// is the length of `bytes`. Ends rather than offsets because a value is appended and its end
195    /// is what is known at that moment.
196    ends: Vec<usize>,
197}
198
199impl Flat {
200    fn with_capacity(count: usize, bytes: usize) -> Self {
201        Self { bytes: Vec::with_capacity(bytes), ends: Vec::with_capacity(count) }
202    }
203
204    fn push(&mut self, value: &[u8]) {
205        self.bytes.extend_from_slice(value);
206        self.ends.push(self.bytes.len());
207    }
208
209    /// Where the value at `index` starts, which is where the one before it ended.
210    fn start(&self, index: usize) -> usize {
211        if index == 0 { 0 } else { self.ends[index - 1] }
212    }
213
214    /// How many values the chunk holds.
215    #[must_use]
216    pub fn len(&self) -> usize {
217        self.ends.len()
218    }
219
220    /// Whether the chunk holds no values at all, which is not the same as holding empty ones.
221    #[must_use]
222    pub fn is_empty(&self) -> bool {
223        self.ends.is_empty()
224    }
225
226    /// The values laid end to end. A caller that already knows the boundaries, which is what a
227    /// global dictionary's offsets are, needs nothing else.
228    #[must_use]
229    pub fn bytes(&self) -> &[u8] {
230        &self.bytes
231    }
232
233    /// The value at `index`, or `None` past the end.
234    #[must_use]
235    pub fn get(&self, index: usize) -> Option<&[u8]> {
236        let end = *self.ends.get(index)?;
237        self.bytes.get(self.start(index)..end)
238    }
239
240    /// Every value in order.
241    pub fn iter(&self) -> impl Iterator<Item = &[u8]> {
242        let mut at = 0;
243        self.ends.iter().map(move |end| {
244            let value = self.bytes.get(at..*end).unwrap_or_default();
245            at = *end;
246            value
247        })
248    }
249
250    /// The buffer on its own, for a caller that wanted the bytes rather than the values.
251    #[must_use]
252    pub fn into_bytes(self) -> Vec<u8> {
253        self.bytes
254    }
255
256    /// The buffer and the ends that divide it, for a caller building its own layout over them.
257    ///
258    /// [`into_bytes`](Self::into_bytes) is enough for a caller that already knows where the values
259    /// end, which is what a global dictionary's stored offsets are. A caller that does not know has
260    /// only [`iter`](Self::iter), and walking that to build a run of boundaries copies out numbers
261    /// the chunk already holds. This hands both halves over and keeps the one allocation each.
262    #[must_use]
263    pub fn into_parts(self) -> (Vec<u8>, Vec<usize>) {
264        (self.bytes, self.ends)
265    }
266
267    fn into_values(self) -> Vec<Vec<u8>> {
268        let mut values = Vec::with_capacity(self.len());
269        let mut at = 0;
270        for end in &self.ends {
271            values.push(self.bytes[at..*end].to_vec());
272            at = *end;
273        }
274        values
275    }
276}
277
278/// Decodes a chunk written by [`encode`] without taking it apart into a value each.
279///
280/// # Errors
281///
282/// As [`decode`].
283pub fn decode_flat(bytes: &[u8]) -> Result<Flat> {
284    let mut reader = Reader::new(bytes);
285    let flat = decode_chunk(&mut reader)?;
286    if reader.remaining() != 0 {
287        return Err(Error::internal(format!(
288            "{} bytes left over after decoding a string chunk",
289            reader.remaining()
290        )));
291    }
292    Ok(flat)
293}
294
295/// Decodes only the values at `positions` of a chunk written by [`encode`], in that order.
296///
297/// A compressed chunk keeps every run's length, so the runs that are not wanted are stepped over
298/// by adding their lengths and never decompressed. That is what a scan wants when a join has
299/// already said which rows it keeps: in TPC-H q10 the customer scan keeps a quarter of its rows,
300/// and decompressing the other three quarters of four string columns was most of what it did. The
301/// other shapes are decoded whole and picked from, which costs what reading them always did.
302///
303/// # Errors
304///
305/// As [`decode`], and if the positions do not rise or one is past the end of the chunk.
306pub fn decode_flat_at(bytes: &[u8], positions: &[u32]) -> Result<Flat> {
307    if positions.windows(2).any(|pair| pair[0] >= pair[1]) {
308        return Err(Error::internal("the positions to decode do not rise"));
309    }
310    let mut reader = Reader::new(bytes);
311    let flat = if bytes.first() == Some(&Kind::Fsst.tag()) {
312        reader.u8()?;
313        let count = reader.u32()? as usize;
314        let runs = read_compressed(&mut reader, count)?;
315        let mut flat = Flat::with_capacity(positions.len(), runs.payload.len());
316        let mut at = 0;
317        let mut next = 0;
318        for &position in positions {
319            let position = position as usize;
320            if position >= count {
321                return Err(Error::internal(format!("value {position} is not in the chunk")));
322            }
323            at += runs.lengths[next..position].iter().sum::<usize>();
324            runs.run_into(position, &mut at, &mut flat.bytes)?;
325            flat.ends.push(flat.bytes.len());
326            next = position + 1;
327        }
328        flat
329    } else {
330        let whole = decode_chunk(&mut reader)?;
331        let mut flat = Flat::with_capacity(positions.len(), 0);
332        for &position in positions {
333            let value = whole
334                .get(position as usize)
335                .ok_or_else(|| Error::internal(format!("value {position} is not in the chunk")))?;
336            flat.push(value);
337        }
338        flat
339    };
340    if reader.remaining() != 0 {
341        return Err(Error::internal(format!(
342            "{} bytes left over after decoding a string chunk",
343            reader.remaining()
344        )));
345    }
346    Ok(flat)
347}
348
349/// Decodes a chunk that sits at the front of a longer buffer, and says how many bytes it took.
350///
351/// A column group holds one of these per column, and the decoder on that side cannot know where
352/// one ends until it has been read.
353///
354/// # Errors
355///
356/// As [`decode`], except that trailing bytes are what the caller asked about rather than an error.
357pub fn decode_prefix(bytes: &[u8]) -> Result<(Vec<Vec<u8>>, usize)> {
358    let mut reader = Reader::new(bytes);
359    let values = decode_chunk(&mut reader)?;
360    Ok((values.into_values(), reader.used()))
361}
362
363/// [`describe`] over a chunk at the front of a longer buffer, and how many bytes it took.
364///
365/// # Errors
366///
367/// As [`decode_prefix`].
368pub fn describe_prefix(bytes: &[u8]) -> Result<(String, usize)> {
369    let mut reader = Reader::new(bytes);
370    let text = describe_chunk(&mut reader)?;
371    Ok((text, reader.used()))
372}
373
374/// Decodes a chunk written by [`encode`].
375///
376/// # Errors
377///
378/// If the bytes are truncated, carry an unknown tag, or describe a chunk whose parts disagree.
379pub fn decode(bytes: &[u8]) -> Result<Vec<Vec<u8>>> {
380    Ok(decode_flat(bytes)?.into_values())
381}
382
383/// The size of every candidate that applies, for a report that wants to say what was chosen over
384/// what.
385///
386/// # Errors
387///
388/// As [`encode`].
389pub fn candidate_sizes(values: &[&[u8]]) -> Result<Vec<(Kind, usize)>> {
390    let mut sizes = Vec::new();
391    for kind in candidates(values, 0) {
392        if let Some(bytes) = encode_as(kind, values, 0, &EXHAUSTIVE)? {
393            sizes.push((kind, bytes.len()));
394        }
395    }
396    Ok(sizes)
397}
398
399/// Which candidates [`encode`] would try on this chunk, in the order it tries them.
400///
401/// The chooser is exhaustive, so this is also the list of encodes it pays for to return one of
402/// them. A caller measuring where the encode time goes needs the list separately from the sizes,
403/// because a candidate that is offered and turns out not to apply still costs whatever it spent
404/// finding that out.
405#[must_use]
406pub fn offered(values: &[&[u8]]) -> Vec<Kind> {
407    candidates(values, 0)
408}
409
410/// One candidate on its own, which is what the chooser calls once per entry in [`offered`].
411///
412/// `None` when the encoding does not apply, which is what the chooser treats as a candidate that
413/// did not run rather than as a failure. This is here so that the time the chooser spends can be
414/// attributed to the candidate that spent it, which is the measurement F2 wants before anybody
415/// replaces the exhaustive search with a sampled one. It is not how a writer encodes a chunk:
416/// [`encode`] is, and picking a kind by hand gives up the only thing the chooser is for.
417///
418/// # Errors
419///
420/// As [`encode`].
421pub fn encode_only(kind: Kind, values: &[&[u8]]) -> Result<Option<Vec<u8>>> {
422    encode_as(kind, values, 0, &EXHAUSTIVE)
423}
424
425/// How big one candidate comes out, which is all a sampling chooser needs from it.
426///
427/// The bytes are thrown away, so this says nothing [`encode_only`] does not. It is `pub(crate)` and
428/// separate so that the sampler in [`crate::chooser`] is not handing back buffers it will not read.
429pub(crate) fn size_as(kind: Kind, values: &[&[u8]], depth: u8) -> Result<Option<usize>> {
430    Ok(encode_as(kind, values, depth, &EXHAUSTIVE)?.map(|bytes| bytes.len()))
431}
432
433/// The shape a chunk was encoded as, as a line of text like `DICT(FSST, RLE(...))`.
434///
435/// # Errors
436///
437/// As [`decode`].
438pub fn describe(bytes: &[u8]) -> Result<String> {
439    let mut reader = Reader::new(bytes);
440    describe_chunk(&mut reader)
441}
442
443/// `shape` with one symbol table for the whole column, trained on what reaches FSST in `blocks`.
444///
445/// A settled shape is used for thousands of blocks of one column, and every block that tries FSST
446/// trains its own table. On ClickBench `hits` that was 35 seconds of a 150 second load, most of it
447/// on the literals `FRONT` then `LZ` leaves behind in `URL` and `Referer`, where the table comes
448/// out much the same block after block. So the blocks the shape was settled on are taken down the
449/// shape's levels here, the values that arrive at the FSST level are sampled together, and the
450/// table trained on them is handed to every block through [`Chooser::symbols`].
451///
452/// A shape that ends in `PLAIN` before any FSST level comes back as it was. So does one whose
453/// table comes out empty, which leaves each block to train its own as before.
454#[must_use]
455pub fn with_symbols(shape: Settled, blocks: &[Vec<&[u8]>]) -> Settled {
456    let kinds = shape.strings();
457    let Some(depth) =
458        (0..=kinds.len()).find(|&at| matches!(kinds.get(at), Some(Kind::Fsst) | None))
459    else {
460        return shape;
461    };
462    let leads =
463        kinds[..depth].iter().all(|kind| matches!(kind, Kind::Front | Kind::Lz | Kind::Dict));
464    if !leads || depth > usize::from(MAX_DEPTH) {
465        return shape;
466    }
467    let mut reached: Vec<Vec<u8>> = Vec::new();
468    for block in blocks {
469        let mut values: Vec<Vec<u8>> = block.iter().map(|value| value.to_vec()).collect();
470        for kind in &kinds[..depth] {
471            let refs: Vec<&[u8]> = values.iter().map(Vec::as_slice).collect();
472            values = match kind {
473                Kind::Front => front_code(&refs).1.into_iter().map(<[u8]>::to_vec).collect(),
474                Kind::Dict => dictionary_of(&refs).0.into_iter().map(<[u8]>::to_vec).collect(),
475                _ => {
476                    let joined = refs.concat();
477                    lz::tokens_of(&joined).literals.into_iter().map(<[u8]>::to_vec).collect()
478                }
479            };
480        }
481        reached.extend(values);
482    }
483    let refs: Vec<&[u8]> = reached.iter().map(Vec::as_slice).collect();
484    let table = SymbolTable::train(&sample_of(&refs));
485    if table.is_empty() {
486        return shape;
487    }
488    shape.with_symbols(depth as u8, table)
489}
490
491fn encode_at(values: &[&[u8]], depth: u8, chooser: &dyn Chooser) -> Result<Vec<u8>> {
492    let started = Instant::now();
493    let offered = candidates(values, depth);
494    let narrowed = chooser.narrow_strings(values, &offered, depth);
495    // Only the top level is counted, so that a cascade's time is counted once. See `tally`.
496    let counted = depth == 0;
497    if counted {
498        tally::chose(Family::String, started);
499    }
500    let mut best: Option<(Kind, Vec<u8>)> = None;
501    for kind in narrowed {
502        let encoded = if counted {
503            tally::offer(Family::String, kind.tag(), || encode_as(kind, values, depth, chooser))?
504        } else {
505            encode_as(kind, values, depth, chooser)?
506        };
507        let Some(bytes) = encoded else {
508            continue;
509        };
510        if best.as_ref().is_none_or(|(_, current)| bytes.len() < current.len()) {
511            best = Some((kind, bytes));
512        }
513    }
514    let (kind, bytes) =
515        best.ok_or_else(|| Error::internal("no string encoding applied to the chunk"))?;
516    if counted {
517        tally::kept(Family::String, kind.tag());
518    }
519    Ok(bytes)
520}
521
522fn candidates(values: &[&[u8]], depth: u8) -> Vec<Kind> {
523    let mut kinds = vec![Kind::Plain];
524    if values.is_empty() {
525        return kinds;
526    }
527    if values.iter().all(|value| *value == values[0]) {
528        return vec![Kind::Constant];
529    }
530    kinds.push(Kind::Fsst);
531    if depth < MAX_DEPTH && has_duplicates(values) {
532        kinds.push(Kind::Dict);
533    }
534    if depth < MAX_DEPTH && sharing_of(values) >= total_len(values) / SHARE_DIVISOR {
535        kinds.push(Kind::Front);
536    }
537    if depth < MAX_DEPTH && total_len(values) >= LZ_FLOOR {
538        kinds.push(Kind::Lz);
539    }
540    kinds
541}
542
543/// How many bytes each value shares with the value before it, added up.
544///
545/// This is a full pass over the column, and it is here rather than on a sample because it is byte
546/// comparisons that stop at the first difference, which on a column with nothing to share stops
547/// immediately. Against training a symbol table and compressing the whole column, which is what
548/// offering the candidate would cost, it is not worth sampling.
549fn sharing_of(values: &[&[u8]]) -> usize {
550    let mut shared = 0;
551    for pair in values.windows(2) {
552        shared += shared_prefix(pair[0], pair[1]);
553    }
554    shared
555}
556
557/// Every value split into the bytes it shares with the value before it and the bytes it does not.
558///
559/// The suffixes point into the values, so this costs the prefix lengths and nothing else. It is
560/// shared with [`crate::multi`], which front codes a column before compressing it against a symbol
561/// table that belongs to the whole group.
562pub(crate) fn front_code<'a>(values: &[&'a [u8]]) -> (Vec<i64>, Vec<&'a [u8]>) {
563    let mut prefixes = Vec::with_capacity(values.len());
564    let mut suffixes: Vec<&'a [u8]> = Vec::with_capacity(values.len());
565    let mut previous: &[u8] = b"";
566    for value in values {
567        let value: &'a [u8] = value;
568        let shared = shared_prefix(previous, value);
569        prefixes.push(shared as i64);
570        suffixes.push(&value[shared..]);
571        previous = value;
572    }
573    (prefixes, suffixes)
574}
575
576/// The other half. The suffixes are consumed because the values are built out of them.
577///
578/// # Errors
579///
580/// If a prefix is negative or is longer than the value it is a prefix of, which is what a corrupt
581/// or hand written chunk looks like from here.
582pub(crate) fn front_decode(prefixes: &[i64], suffixes: Vec<Vec<u8>>) -> Result<Vec<Vec<u8>>> {
583    let mut values: Vec<Vec<u8>> = Vec::with_capacity(suffixes.len());
584    for (index, suffix) in suffixes.into_iter().enumerate() {
585        let shared = usize::try_from(prefixes[index])
586            .map_err(|_| Error::internal("a negative shared prefix length"))?;
587        let previous: &[u8] = if index == 0 { b"" } else { &values[index - 1] };
588        if shared > previous.len() {
589            return Err(Error::internal(format!(
590                "a value shares {shared} bytes with a value {} bytes long",
591                previous.len()
592            )));
593        }
594        let mut value = Vec::with_capacity(shared + suffix.len());
595        value.extend_from_slice(&previous[..shared]);
596        value.extend_from_slice(&suffix);
597        values.push(value);
598    }
599    Ok(values)
600}
601
602fn shared_prefix(previous: &[u8], value: &[u8]) -> usize {
603    let limit = previous.len().min(value.len());
604    let mut shared = 0;
605    while shared < limit && previous[shared] == value[shared] {
606        shared += 1;
607    }
608    shared
609}
610
611fn total_len(values: &[&[u8]]) -> usize {
612    values.iter().map(|value| value.len()).sum()
613}
614
615fn encode_as(
616    kind: Kind,
617    values: &[&[u8]],
618    depth: u8,
619    chooser: &dyn Chooser,
620) -> Result<Option<Vec<u8>>> {
621    let mut out = vec![kind.tag()];
622    put_u32(&mut out, u32::try_from(values.len()).map_err(|_| too_long(values.len()))?);
623    match kind {
624        Kind::Constant => {
625            let Some(first) = values.first() else {
626                return Ok(None);
627            };
628            if values.iter().any(|value| value != first) {
629                return Ok(None);
630            }
631            put_u32(&mut out, u32::try_from(first.len()).map_err(|_| too_long(first.len()))?);
632            out.extend_from_slice(first);
633        }
634        Kind::Plain => {
635            out.extend_from_slice(&encode_lengths(values, chooser)?);
636            for value in values {
637                out.extend_from_slice(value);
638            }
639        }
640        Kind::Fsst => {
641            let trained;
642            let table = match chooser.symbols(depth) {
643                Some(table) => table,
644                None => {
645                    trained = SymbolTable::train(&sample_of(values));
646                    &trained
647                }
648            };
649            if table.is_empty() {
650                return Ok(None);
651            }
652            let mut compressed = Vec::new();
653            let mut lengths = Vec::with_capacity(values.len());
654            for value in values {
655                let before = compressed.len();
656                table.compress(value, &mut compressed);
657                lengths.push((compressed.len() - before) as i64);
658            }
659            table.serialize(&mut out);
660            out.extend_from_slice(&integer::encode_with(&lengths, chooser)?);
661            out.extend_from_slice(&compressed);
662        }
663        Kind::Dict => {
664            let (entries, codes) = dictionary_of(values);
665            if entries.is_empty() {
666                return Ok(None);
667            }
668            out.extend_from_slice(&encode_at(&entries, depth + 1, chooser)?);
669            out.extend_from_slice(&integer::encode_with(&codes, chooser)?);
670        }
671        Kind::Front => {
672            let (prefixes, suffixes) = front_code(values);
673            out.extend_from_slice(&integer::encode_with(&prefixes, chooser)?);
674            out.extend_from_slice(&encode_at(&suffixes, depth + 1, chooser)?);
675        }
676        Kind::Lz => {
677            let mut joined = Vec::with_capacity(total_len(values));
678            let mut sizes = Vec::with_capacity(values.len());
679            for value in values {
680                joined.extend_from_slice(value);
681                sizes.push(value.len() as i64);
682            }
683            let tokens = lz::tokens_of(&joined);
684            out.extend_from_slice(&integer::encode_with(&sizes, chooser)?);
685            out.extend_from_slice(&integer::encode_with(&tokens.lengths, chooser)?);
686            out.extend_from_slice(&integer::encode_with(&tokens.offsets, chooser)?);
687            out.extend_from_slice(&encode_at(&tokens.literals, depth + 1, chooser)?);
688        }
689    }
690    Ok(Some(out))
691}
692
693fn decode_chunk(reader: &mut Reader<'_>) -> Result<Flat> {
694    let kind = Kind::from_tag(reader.u8()?)?;
695    let count = reader.u32()? as usize;
696    match kind {
697        Kind::Constant => {
698            let len = reader.u32()? as usize;
699            let value = reader.bytes(len)?;
700            let mut flat = Flat::with_capacity(count, len.saturating_mul(count));
701            for _ in 0..count {
702                flat.push(value);
703            }
704            Ok(flat)
705        }
706        Kind::Plain => {
707            let lengths = decode_lengths(reader, count)?;
708            // One copy of the whole payload rather than one a value, which the file already laid
709            // out end to end and which is the layout wanted back.
710            let total = sum_of(&lengths)?;
711            let payload = reader.bytes(total)?;
712            let mut flat = Flat::with_capacity(count, total);
713            flat.bytes.extend_from_slice(payload);
714            let mut at = 0;
715            for length in lengths {
716                at += length;
717                flat.ends.push(at);
718            }
719            Ok(flat)
720        }
721        Kind::Fsst => {
722            let runs = read_compressed(reader, count)?;
723            let mut flat = Flat::with_capacity(count, 0);
724            runs.all_into(&mut flat)?;
725            Ok(flat)
726        }
727        Kind::Dict => {
728            let dictionary = decode_chunk(reader)?;
729            let codes = decode_integers(reader)?;
730            if codes.len() != count {
731                return Err(Error::internal(format!(
732                    "a dictionary chunk says it holds {count} values and has {} codes",
733                    codes.len()
734                )));
735            }
736            let mut flat = Flat::with_capacity(count, dictionary.bytes.len());
737            for code in codes {
738                let entry =
739                    usize::try_from(code).ok().and_then(|index| dictionary.get(index)).ok_or_else(
740                        || Error::internal(format!("code {code} is not in the dictionary")),
741                    )?;
742                flat.push(entry);
743            }
744            Ok(flat)
745        }
746        Kind::Front => {
747            let prefixes = decode_integers(reader)?;
748            let suffixes = decode_chunk(reader)?;
749            if prefixes.len() != count || suffixes.len() != count {
750                return Err(Error::internal(format!(
751                    "a front coded chunk says it holds {count} values and has {} prefixes and {} suffixes",
752                    prefixes.len(),
753                    suffixes.len()
754                )));
755            }
756            // The shared prefix is copied out of the buffer being written into, so a value never
757            // has to exist anywhere but where it belongs. The buffer is sized for the prefixes as
758            // well as the suffixes, since sized for the suffixes alone a sorted block of URLs,
759            // whose values share most of their bytes, doubled its way up and copied itself each
760            // time. Walking the lengths first also checks every prefix against the value before
761            // it, so a corrupt one is refused before anything is allocated for it.
762            let mut room = 0usize;
763            let mut previous = 0usize;
764            for (index, prefix) in prefixes.iter().enumerate() {
765                let shared = usize::try_from(*prefix)
766                    .map_err(|_| Error::internal("a negative shared prefix length"))?;
767                if shared > previous {
768                    return Err(Error::internal(format!(
769                        "a value shares {shared} bytes with a value {previous} bytes long"
770                    )));
771                }
772                previous = shared + suffixes.get(index).map_or(0, <[u8]>::len);
773                room = room
774                    .checked_add(previous)
775                    .ok_or_else(|| Error::internal("a string chunk longer than memory"))?;
776            }
777            let mut flat = Flat::with_capacity(count, room);
778            for (index, &prefix) in prefixes.iter().enumerate() {
779                let shared = prefix as usize;
780                let from = if index == 0 { 0 } else { flat.start(index - 1) };
781                flat.bytes.extend_from_within(from..from + shared);
782                flat.bytes.extend_from_slice(suffixes.get(index).expect("in range"));
783                flat.ends.push(flat.bytes.len());
784            }
785            Ok(flat)
786        }
787        Kind::Lz => {
788            let sizes = decode_integers(reader)?;
789            let lengths = decode_integers(reader)?;
790            let offsets = decode_integers(reader)?;
791            if sizes.len() != count {
792                return Err(Error::internal(format!(
793                    "a matched chunk says it holds {count} values and has {} lengths",
794                    sizes.len()
795                )));
796            }
797            let mut total = 0usize;
798            let mut widths = Vec::with_capacity(count);
799            for size in sizes {
800                let width = usize::try_from(size)
801                    .map_err(|_| Error::internal("a negative string length"))?;
802                total = total
803                    .checked_add(width)
804                    .ok_or_else(|| Error::internal("a string chunk longer than memory"))?;
805                widths.push(width);
806            }
807            // The copies point back into the bytes already replayed, which is the buffer the values
808            // are going into, so the replay is the decode and there is nothing to cut up after it.
809            // The room past the end is what the replay's wide stores want, and leaving it out had
810            // the replay grow the buffer, which copied every block once more into fresh pages.
811            let mut flat = Flat::with_capacity(count, total.saturating_add(REPLAY_SLACK));
812            replay_literals(reader, &lengths, &offsets, total, &mut flat.bytes)?;
813            if flat.bytes.len() != total {
814                return Err(Error::internal(format!(
815                    "a matched chunk rebuilt {} bytes where its lengths add up to {total}",
816                    flat.bytes.len()
817                )));
818            }
819            let mut at = 0;
820            for width in widths {
821                at += width;
822                flat.ends.push(at);
823            }
824            Ok(flat)
825        }
826    }
827}
828
829/// A compressed chunk's symbol table and its runs, left where the file put them.
830///
831/// Reading a compressed chunk into this rather than straight into a buffer is what lets a run be
832/// decompressed where the run belongs. The payload is one slice, the run boundaries come from the
833/// length array, and so asking for a run is a decompress of a subslice and nothing else.
834struct Compressed<'a> {
835    /// The table the runs were compressed against.
836    table: SymbolTable,
837    /// How many compressed bytes each run holds, in order.
838    lengths: Vec<usize>,
839    /// Every run's compressed bytes, end to end.
840    payload: &'a [u8],
841}
842
843impl Compressed<'_> {
844    /// Decompresses run `index` onto the end of `out`, with `at` saying where the run starts.
845    ///
846    /// The caller carries the offset because the runs are asked for in order, and adding a length
847    /// per run is cheaper than the prefix sum the alternative wants.
848    ///
849    /// # Errors
850    ///
851    /// If there is no such run, if it runs off the end of the payload, or if it does not decompress.
852    fn run_into(&self, index: usize, at: &mut usize, out: &mut Vec<u8>) -> Result<()> {
853        self.table.decompress(self.run(index, at)?, out)
854    }
855
856    /// Decompresses every run in order onto the end of `flat`.
857    ///
858    /// Each symbol is one eight byte store into room made ahead of it, which is what
859    /// [`SymbolTable::decompress_at`] is for. A run of `n` codes writes at most `n` symbols of at
860    /// most [`MAX_SYMBOL_LEN`] bytes, the last store included, so that much room past where the run
861    /// starts is all it needs. The room is made by doubling, so the zeroes written to make it add up
862    /// to at most twice what the chunk decompresses to. Growing a vector a symbol at a time and
863    /// cutting it back was a fifth of TPC-H q13, all of it the order comment.
864    ///
865    /// # Errors
866    ///
867    /// If a run is past the end of the chunk or does not decompress.
868    fn all_into(&self, flat: &mut Flat) -> Result<()> {
869        let out = &mut flat.bytes;
870        let mut at = out.len();
871        let mut payload = self.payload;
872        for &run in &self.lengths {
873            let Some((codes, rest)) = payload.split_at_checked(run) else {
874                return Err(Error::internal("a compressed run is past the end of its chunk"));
875            };
876            payload = rest;
877            let need = run
878                .checked_mul(MAX_SYMBOL_LEN)
879                .and_then(|room| room.checked_add(at))
880                .ok_or_else(|| Error::internal("a compressed chunk longer than memory"))?;
881            if out.len() < need {
882                out.resize(need.max(out.len() * 2), 0);
883            }
884            at = self.table.decompress_at(codes, out, at)?;
885            flat.ends.push(at);
886        }
887        out.truncate(at);
888        Ok(())
889    }
890
891    /// The compressed bytes of run `index`, with `at` saying where the run starts and left where
892    /// the next one does.
893    fn run(&self, index: usize, at: &mut usize) -> Result<&[u8]> {
894        let length = *self
895            .lengths
896            .get(index)
897            .ok_or_else(|| Error::internal(format!("run {index} is not in the chunk")))?;
898        let end = at
899            .checked_add(length)
900            .ok_or_else(|| Error::internal("a compressed chunk longer than memory"))?;
901        let run = self
902            .payload
903            .get(*at..end)
904            .ok_or_else(|| Error::internal("a compressed run is past the end of its chunk"))?;
905        *at = end;
906        Ok(run)
907    }
908}
909
910/// Reads a compressed chunk's table, run lengths and payload without decompressing any of it.
911///
912/// The tag and the count have already been read.
913///
914/// # Errors
915///
916/// If the table does not deserialize, if the length array is not `count` long, or if the lengths
917/// add up to more than the chunk has left.
918fn read_compressed<'a>(reader: &mut Reader<'a>, count: usize) -> Result<Compressed<'a>> {
919    let (table, used) = SymbolTable::deserialize(reader.rest())?;
920    reader.skip(used)?;
921    let lengths = decode_lengths(reader, count)?;
922    // The compressed total is what the payload holds and it is also the only sane guess at the
923    // decompressed one, so it is checked before it is believed.
924    let compressed_len = sum_of(&lengths)?;
925    if compressed_len > reader.remaining() {
926        return Err(Error::internal(format!(
927            "a compressed chunk says it holds {compressed_len} bytes and has {}",
928            reader.remaining()
929        )));
930    }
931    let payload = reader.bytes(compressed_len)?;
932    Ok(Compressed { table, lengths, payload })
933}
934
935/// Replays a matched chunk's tokens, reading the literal runs out of the nested chunk holding them.
936///
937/// The nested chunk is decoded into a buffer and copied out of, the way anything nested is, unless
938/// it is compressed. On the ClickBench `URL` column it always is, and there a block of a thousand
939/// values holds about eight thousand seven hundred literal runs, so that buffer is the whole
940/// block's bytes and copying the runs out of it writes every one of them a second time.
941/// Decompressing a run straight to where it belongs skips the buffer, the length array that would
942/// cut it up, and that second pass over the bytes.
943///
944/// # Errors
945///
946/// Whatever reading the literals or replaying the tokens reports.
947fn replay_literals(
948    reader: &mut Reader<'_>,
949    lengths: &[i64],
950    offsets: &[i64],
951    total: usize,
952    out: &mut Vec<u8>,
953) -> Result<()> {
954    if reader.rest().first() == Some(&Kind::Fsst.tag()) {
955        reader.u8()?;
956        let runs = reader.u32()? as usize;
957        let compressed = read_compressed(reader, runs)?;
958        return replay_in_place(&compressed, lengths, offsets, total, out);
959    }
960    let literals = decode_chunk(reader)?;
961    lz::rebuild_into(&literals, lengths, offsets, out)
962}
963
964/// Room past the end of a replay, for the stores that write whole words past where a value ends.
965///
966/// A symbol is stored as eight bytes and a copy as sixteen at a time, and each is followed by a
967/// step of the cursor to where the bytes it meant end. What lands past that is written over by
968/// whatever comes next, or cut off at the end.
969const REPLAY_SLACK: usize = 16;
970
971/// [`lz::replay`] over compressed literal runs, into a buffer made the length of the output first.
972///
973/// The output length is known before a byte is decoded, because the chunk stores the length of
974/// every value. So the buffer is sized once and written through a cursor, and a symbol or a copy is
975/// a fixed width store rather than a push that checks capacity and moves a length. The copies were
976/// the reason: on ClickBench `URL` a block of a thousand values replays about eight thousand seven
977/// hundred of them, most of them a few tens of bytes, and each one was a call into `memmove`.
978///
979/// # Errors
980///
981/// As [`lz::replay`], and if the tokens build more than `total` bytes.
982fn replay_in_place(
983    compressed: &Compressed<'_>,
984    lengths: &[i64],
985    offsets: &[i64],
986    total: usize,
987    out: &mut Vec<u8>,
988) -> Result<()> {
989    let runs = compressed.lengths.len();
990    if runs != lengths.len() || lengths.len() != offsets.len() {
991        return Err(Error::internal(format!(
992            "a matched chunk has {runs} literal runs, {} lengths and {} offsets",
993            lengths.len(),
994            offsets.len()
995        )));
996    }
997    let base = out.len();
998    let room = total
999        .checked_add(REPLAY_SLACK)
1000        .ok_or_else(|| Error::internal("a string chunk longer than memory"))?;
1001    out.resize(base + room, 0);
1002    let mut payload = compressed.payload;
1003    let mut at = base;
1004    for ((&run, &length), &offset) in compressed.lengths.iter().zip(lengths).zip(offsets) {
1005        let Some((codes, rest)) = payload.split_at_checked(run) else {
1006            return Err(Error::internal("a compressed run is past the end of its chunk"));
1007        };
1008        payload = rest;
1009        at = compressed.table.decompress_at(codes, out, at)?;
1010        let length =
1011            usize::try_from(length).map_err(|_| Error::internal("a negative copy length"))?;
1012        if length == 0 {
1013            continue;
1014        }
1015        let offset =
1016            usize::try_from(offset).map_err(|_| Error::internal("a negative copy offset"))?;
1017        at = copy_back(out, base, at, offset, length)?;
1018    }
1019    if at > base + total {
1020        return Err(Error::internal(format!(
1021            "a matched chunk rebuilt {} bytes where its lengths add up to {total}",
1022            at - base
1023        )));
1024    }
1025    out.truncate(at);
1026    Ok(())
1027}
1028
1029/// Copies `length` bytes from `offset` back to `at`, handing back where the copy ends.
1030///
1031/// Sixteen bytes at a time where the copy starts at least sixteen bytes back, since then no store
1032/// reads a byte it has not been given yet, and eight at a time where it starts eight back. Nearer
1033/// than that the copy is repeating a short run and goes a byte at a time, the way it always did.
1034/// The whole width stores need room past the end of the copy, and a copy near the end of the buffer
1035/// that does not have it goes a byte at a time too.
1036fn copy_back(
1037    out: &mut [u8],
1038    base: usize,
1039    at: usize,
1040    offset: usize,
1041    length: usize,
1042) -> Result<usize> {
1043    if offset == 0 || offset > at - base {
1044        return Err(Error::internal(format!(
1045            "a copy reaches {offset} bytes back into {} bytes of output",
1046            at - base
1047        )));
1048    }
1049    let end = at
1050        .checked_add(length)
1051        .filter(|&end| end <= out.len())
1052        .ok_or_else(|| Error::internal("a matched chunk rebuilds more than its lengths say"))?;
1053    let from = at - offset;
1054    let wide = end + REPLAY_SLACK <= out.len();
1055    if wide && offset >= 16 {
1056        let mut step = 0;
1057        while step < length {
1058            out.copy_within(from + step..from + step + 16, at + step);
1059            step += 16;
1060        }
1061    } else if wide && offset >= 8 {
1062        let mut step = 0;
1063        while step < length {
1064            out.copy_within(from + step..from + step + 8, at + step);
1065            step += 8;
1066        }
1067    } else {
1068        for step in 0..length {
1069            out[at + step] = out[from + step];
1070        }
1071    }
1072    Ok(end)
1073}
1074
1075fn describe_chunk(reader: &mut Reader<'_>) -> Result<String> {
1076    let kind = Kind::from_tag(reader.u8()?)?;
1077    let count = reader.u32()? as usize;
1078    Ok(match kind {
1079        Kind::Constant => {
1080            let len = reader.u32()? as usize;
1081            reader.bytes(len)?;
1082            "CONSTANT".to_string()
1083        }
1084        Kind::Plain => {
1085            let (shape, lengths) = describe_lengths(reader, count)?;
1086            reader.skip(lengths.iter().sum())?;
1087            format!("PLAIN({shape})")
1088        }
1089        Kind::Fsst => {
1090            let (table, used) = SymbolTable::deserialize(reader.rest())?;
1091            reader.skip(used)?;
1092            let (shape, lengths) = describe_lengths(reader, count)?;
1093            reader.skip(lengths.iter().sum())?;
1094            format!("FSST[{}]({shape})", table.len())
1095        }
1096        Kind::Dict => {
1097            let entries = describe_chunk(reader)?;
1098            let codes = describe_integers(reader)?;
1099            format!("DICT({entries}, {codes})")
1100        }
1101        Kind::Front => {
1102            let prefixes = describe_integers(reader)?;
1103            let suffixes = describe_chunk(reader)?;
1104            format!("FRONT({prefixes}, {suffixes})")
1105        }
1106        Kind::Lz => {
1107            let sizes = describe_integers(reader)?;
1108            let lengths = describe_integers(reader)?;
1109            let offsets = describe_integers(reader)?;
1110            let literals = describe_chunk(reader)?;
1111            format!("LZ({sizes}, {lengths}, {offsets}, {literals})")
1112        }
1113    })
1114}
1115
1116/// The shape of the length array and the lengths themselves, because a describe has to walk past
1117/// the payload to leave the reader where the next chunk starts and the payload size is the sum of
1118/// the lengths.
1119fn describe_lengths(reader: &mut Reader<'_>, count: usize) -> Result<(String, Vec<usize>)> {
1120    let (shape, _) = integer::describe_prefix(reader.rest())?;
1121    let lengths = decode_lengths(reader, count)?;
1122    Ok((shape, lengths))
1123}
1124
1125fn encode_lengths(values: &[&[u8]], chooser: &dyn Chooser) -> Result<Vec<u8>> {
1126    let lengths: Vec<i64> = values.iter().map(|value| value.len() as i64).collect();
1127    integer::encode_with(&lengths, chooser)
1128}
1129
1130fn decode_lengths(reader: &mut Reader<'_>, count: usize) -> Result<Vec<usize>> {
1131    let lengths = decode_integers(reader)?;
1132    if lengths.len() != count {
1133        return Err(Error::internal(format!(
1134            "a string chunk says it holds {count} values and has {} lengths",
1135            lengths.len()
1136        )));
1137    }
1138    lengths
1139        .into_iter()
1140        .map(|length| {
1141            usize::try_from(length).map_err(|_| Error::internal("a negative string length"))
1142        })
1143        .collect()
1144}
1145
1146/// How long the values add up to, refusing a length array that adds up to more than memory.
1147///
1148/// A truncated chunk used to be caught by the read of the value that ran off the end. Reading the
1149/// payload in one go means the total has to be trusted before the read rather than after it, and a
1150/// corrupt length array is the only thing that could overflow it.
1151fn sum_of(lengths: &[usize]) -> Result<usize> {
1152    lengths
1153        .iter()
1154        .try_fold(0usize, |total, length| total.checked_add(*length))
1155        .ok_or_else(|| Error::internal("a string chunk longer than memory"))
1156}
1157
1158/// Reads one nested integer chunk. The integer decoder wants a slice of exactly its own chunk and
1159/// the reader does not know how long that is, so it decodes from the rest of the buffer and is told
1160/// afterwards how much it used.
1161fn decode_integers(reader: &mut Reader<'_>) -> Result<Vec<i64>> {
1162    let (values, used) = integer::decode_prefix(reader.rest())?;
1163    reader.skip(used)?;
1164    Ok(values)
1165}
1166
1167fn describe_integers(reader: &mut Reader<'_>) -> Result<String> {
1168    let (text, used) = integer::describe_prefix(reader.rest())?;
1169    reader.skip(used)?;
1170    Ok(text)
1171}
1172
1173/// A sample of the column spread across the whole of it, taken at random skips rather than at a
1174/// fixed stride.
1175///
1176/// Section 6.3 makes the point about choosing an encoding from a sample and it applies at least as
1177/// much to training a symbol table. Column data is frequently sorted or clustered, so the first
1178/// 64 KB of a URL column is the hosts that sort first and a table trained on it escapes most of the
1179/// rest of the column.
1180///
1181/// The skips are random rather than fixed because a fixed stride aliases. Column data is also
1182/// frequently periodic, and a stride that shares a factor with the period samples one phase of it
1183/// and never sees the others. That is not a hypothetical: the first version of this took every
1184/// `n`th value, and on a test column whose values cycle with a period that the stride happened to
1185/// divide, the table it trained was 3.4 times worse than one trained on the whole column, because
1186/// it learned eight byte symbols that only line up with the phase it saw and had no shorter symbols
1187/// left to fall back on.
1188///
1189/// The generator is a fixed seed xorshift, so the sample is a function of the column and encoding
1190/// the same values twice produces the same bytes.
1191pub(crate) fn sample_of<'a>(values: &[&'a [u8]]) -> Vec<&'a [u8]> {
1192    sample_bytes_of(values, SAMPLE_BYTES)
1193}
1194
1195/// [`sample_of`] with the byte budget spelled out, for a caller training one table over several
1196/// columns that has to split the budget between them.
1197pub(crate) fn sample_bytes_of<'a>(values: &[&'a [u8]], budget: usize) -> Vec<&'a [u8]> {
1198    let budget = budget.max(1);
1199    let total: usize = values.iter().map(|value| value.len()).sum();
1200    if total <= budget {
1201        return values.to_vec();
1202    }
1203    let stride = total.div_ceil(budget).max(1);
1204    let span = (stride * 2 - 1).max(1) as u64;
1205    let mut state = 0x2545_f491_4f6c_dd1du64;
1206    let mut sample = Vec::with_capacity(values.len() / stride + 1);
1207    let mut at = 0usize;
1208    while at < values.len() {
1209        sample.push(values[at]);
1210        state ^= state << 13;
1211        state ^= state >> 7;
1212        state ^= state << 17;
1213        at += 1 + (state % span) as usize;
1214    }
1215    sample
1216}
1217
1218/// The distinct values in sorted order and the code of every value, in one pass over one sort.
1219///
1220/// The dictionary is sorted for the same reason the integer one is: an ordered dictionary turns a
1221/// range predicate into a code range rather than a code set, and front coding over the entries needs
1222/// them sorted anyway.
1223///
1224/// It sorts a permutation of indices rather than the values, which is the whole point. Sorting the
1225/// values means copying every one of them onto the heap first, and the codes then have to be found
1226/// by searching the dictionary back for each value, which is a binary search of string comparisons
1227/// per row. Walking the permutation gives the codes away for free, because the position a value
1228/// sorted to is the position its code was assigned at.
1229fn dictionary_of<'a>(values: &[&'a [u8]]) -> (Vec<&'a [u8]>, Vec<i64>) {
1230    let mut order: Vec<u32> = (0..values.len() as u32).collect();
1231    order.sort_unstable_by(|left, right| values[*left as usize].cmp(values[*right as usize]));
1232    let mut entries: Vec<&'a [u8]> = Vec::new();
1233    let mut codes = vec![0i64; values.len()];
1234    for &index in &order {
1235        let value = values[index as usize];
1236        if entries.last() != Some(&value) {
1237            entries.push(value);
1238        }
1239        codes[index as usize] = (entries.len() - 1) as i64;
1240    }
1241    (entries, codes)
1242}
1243
1244/// Whether any value appears twice, which is the only thing the candidate list wants to know.
1245///
1246/// This used to build the whole sorted dictionary and compare its length against the input, which
1247/// is a copy of the chunk and a sort of it paid on every chunk at every level whether the dictionary
1248/// was ever encoded or not. It is a linear probe over hashes instead: expected O(n), no allocation
1249/// per value, and it stops at the first duplicate it finds, which on a column with any repetition at
1250/// all is immediately.
1251///
1252/// A hash collision is resolved by comparing the bytes, so the answer is exact rather than probable.
1253fn has_duplicates(values: &[&[u8]]) -> bool {
1254    let Some(slots) = values.len().checked_mul(2).map(usize::next_power_of_two) else {
1255        return false;
1256    };
1257    let mask = slots - 1;
1258    let mut table = vec![u32::MAX; slots];
1259    for (index, value) in values.iter().enumerate() {
1260        let mut at = hash_of(value) as usize & mask;
1261        loop {
1262            let held = table[at];
1263            if held == u32::MAX {
1264                table[at] = index as u32;
1265                break;
1266            }
1267            if values[held as usize] == *value {
1268                return true;
1269            }
1270            at = (at + 1) & mask;
1271        }
1272    }
1273    false
1274}
1275
1276/// FNV-1a over the bytes, eight at a time.
1277///
1278/// Good enough for a table that verifies every hit, and it is not part of the format, so nothing
1279/// depends on which hash this is. Eight bytes at a time because a URL column is long values and a
1280/// byte at a time over a hundred bytes of every one of 122,880 rows is the loop this is here to
1281/// avoid.
1282fn hash_of(value: &[u8]) -> u64 {
1283    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
1284    let mut chunks = value.chunks_exact(8);
1285    for chunk in &mut chunks {
1286        let word = u64::from_le_bytes(chunk.try_into().expect("chunks_exact(8) gives eight bytes"));
1287        hash = (hash ^ word).wrapping_mul(0x1_0000_01b3);
1288    }
1289    for byte in chunks.remainder() {
1290        hash = (hash ^ u64::from(*byte)).wrapping_mul(0x1_0000_01b3);
1291    }
1292    (hash ^ (value.len() as u64)).wrapping_mul(0x1_0000_01b3)
1293}
1294
1295fn too_long(len: usize) -> Error {
1296    Error::internal(format!("a string chunk of {len} is longer than the format allows"))
1297}
1298
1299fn put_u32(out: &mut Vec<u8>, value: u32) {
1300    out.extend_from_slice(&value.to_le_bytes());
1301}
1302
1303#[cfg(test)]
1304mod tests {
1305    use super::*;
1306
1307    fn urls(count: usize) -> Vec<Vec<u8>> {
1308        let hosts = ["www.example.com", "shop.example.com", "news.other.example.org"];
1309        let paths = ["/index.html", "/catalog/item", "/search", "/user/profile/settings"];
1310        (0..count)
1311            .map(|index| {
1312                let host = hosts[index % hosts.len()];
1313                let path = paths[(index / 3) % paths.len()];
1314                format!("http://{host}{path}?session={}&ref=google", index * 7).into_bytes()
1315            })
1316            .collect()
1317    }
1318
1319    /// Only the values asked for come back, in order, from a compressed chunk that steps over the
1320    /// rest and from every other shape, which is decoded whole and picked from.
1321    #[test]
1322    fn the_values_at_some_positions_are_the_ones_a_whole_decode_has_there() {
1323        let values = urls(1000);
1324        let refs: Vec<&[u8]> = values.iter().map(Vec::as_slice).collect();
1325        let positions = [0_u32, 3, 4, 500, 998, 999];
1326        let wanted: Vec<Vec<u8>> =
1327            positions.iter().map(|&at| values[at as usize].clone()).collect();
1328        for kind in offered(&refs) {
1329            let Some(encoded) = encode_only(kind, &refs).expect("encoded") else { continue };
1330            let flat = decode_flat_at(&encoded, &positions).expect("decoded");
1331            assert_eq!(flat.into_values(), wanted, "{kind:?}");
1332            let none = decode_flat_at(&encoded, &[]).expect("decoded");
1333            assert!(none.is_empty(), "{kind:?}");
1334            assert!(decode_flat_at(&encoded, &[4, 3]).is_err(), "{kind:?}");
1335            assert!(decode_flat_at(&encoded, &[1000]).is_err(), "{kind:?}");
1336        }
1337        let fsst = encode_only(Kind::Fsst, &refs).expect("encoded").expect("compressible");
1338        assert_eq!(decode_flat_at(&fsst, &positions).expect("decoded").into_values(), wanted);
1339    }
1340
1341    fn front_lz() -> Settled {
1342        Settled::new(vec![Kind::Front, Kind::Lz], vec![integer::Kind::Packed])
1343    }
1344
1345    /// The point of the table: every block of a column compresses against one table trained once,
1346    /// and what it writes still reads back as the values, including a block the table was not
1347    /// trained on.
1348    #[test]
1349    fn a_block_compressed_against_the_column_table_reads_back() {
1350        let values = urls(4096);
1351        let refs: Vec<&[u8]> = values.iter().map(Vec::as_slice).collect();
1352        let blocks: Vec<Vec<&[u8]>> = refs.chunks(1024).take(2).map(<[&[u8]]>::to_vec).collect();
1353        let shape = with_symbols(front_lz(), &blocks);
1354        assert!(shape.symbols(2).is_some(), "FRONT then LZ leaves FSST the third level");
1355        assert!(shape.symbols(1).is_none(), "and only that one");
1356        for block in refs.chunks(1024) {
1357            let encoded = encode_with(block, &shape).expect("encoded");
1358            assert_eq!(decode(&encoded).expect("decoded"), block.to_vec());
1359        }
1360    }
1361
1362    /// A shape that settles on `PLAIN` never tries FSST, so there is nothing to train.
1363    #[test]
1364    fn a_shape_ending_in_plain_gets_no_table() {
1365        let values = urls(1024);
1366        let refs: Vec<&[u8]> = values.iter().map(Vec::as_slice).collect();
1367        let plain = Settled::new(vec![Kind::Lz, Kind::Plain], vec![integer::Kind::Packed]);
1368        let shape = with_symbols(plain, std::slice::from_ref(&refs));
1369        assert!((0..=MAX_DEPTH).all(|depth| shape.symbols(depth).is_none()));
1370        let fsst = Settled::new(vec![Kind::Fsst], vec![integer::Kind::Packed]);
1371        assert!(with_symbols(fsst, &[refs]).symbols(0).is_some());
1372    }
1373
1374    /// The same values with a scrambled identifier stuck on the front of each, for the tests that
1375    /// need neighbouring values to have nothing in common. Shuffling the order is not enough,
1376    /// because two URLs picked at random still agree on a scheme and often on a host.
1377    fn keyed(values: Vec<Vec<u8>>) -> Vec<Vec<u8>> {
1378        values
1379            .into_iter()
1380            .enumerate()
1381            .map(|(index, value)| {
1382                let key = (index as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15) % 1_000_000_007;
1383                let mut out = format!("{key:010}/").into_bytes();
1384                out.extend_from_slice(&value);
1385                out
1386            })
1387            .collect()
1388    }
1389
1390    fn borrow(values: &[Vec<u8>]) -> Vec<&[u8]> {
1391        values.iter().map(Vec::as_slice).collect()
1392    }
1393
1394    fn round_trip(values: &[Vec<u8>]) -> Vec<u8> {
1395        let borrowed = borrow(values);
1396        let bytes = encode(&borrowed).unwrap();
1397        let back = decode(&bytes).unwrap();
1398        assert_eq!(back, values, "{}", describe(&bytes).unwrap());
1399        check_flat(&bytes, values);
1400        bytes
1401    }
1402
1403    /// The flat form holds the same values and lays them out the way a caller with its own offsets
1404    /// expects. Called from [`round_trip`], so every shape any test in here reaches is checked.
1405    fn check_flat(bytes: &[u8], values: &[Vec<u8>]) {
1406        let flat = decode_flat(bytes).unwrap();
1407        let shape = describe(bytes).unwrap();
1408        assert_eq!(flat.len(), values.len(), "{shape}");
1409        assert_eq!(flat.iter().collect::<Vec<_>>(), borrow(values), "{shape}");
1410        assert_eq!(flat.bytes(), values.concat(), "{shape}");
1411        assert_eq!(flat.get(values.len()), None, "{shape}");
1412    }
1413
1414    fn kind_of(bytes: &[u8]) -> Kind {
1415        Kind::from_tag(bytes[0]).unwrap()
1416    }
1417
1418    #[test]
1419    fn every_shape_decodes_flat_to_what_it_decodes_split() {
1420        // round_trip only sees the shape the chooser picked, which on any one column is one of the
1421        // six. This walks all of them, so PLAIN reading its payload in one go and FRONT copying a
1422        // prefix out of the buffer it is filling are both covered on data they apply to.
1423        let columns =
1424            [urls(600), keyed(urls(600)), vec![b"same".to_vec(); 400], vec![Vec::new(); 7]];
1425        for values in &columns {
1426            let borrowed = borrow(values);
1427            for kind in offered(&borrowed) {
1428                let Some(bytes) = encode_only(kind, &borrowed).unwrap() else {
1429                    continue;
1430                };
1431                assert_eq!(decode(&bytes).unwrap(), *values, "{}", kind.name());
1432                let flat = decode_flat(&bytes).unwrap();
1433                assert_eq!(flat.iter().collect::<Vec<_>>(), borrowed, "{}", kind.name());
1434                assert_eq!(flat.bytes(), values.concat(), "{}", kind.name());
1435            }
1436        }
1437    }
1438
1439    #[test]
1440    fn a_front_coded_chunk_that_shares_more_than_it_has_is_an_error() {
1441        // The prefix chain is the one place the flat decoder reads back out of the buffer it is
1442        // filling, so a prefix longer than the value before it is what would hand back somebody
1443        // else's bytes rather than fail. Built by hand because no encoder produces one.
1444        let suffixes: [&[u8]; 2] = [b"abc", b"x"];
1445        let mut bytes = vec![Kind::Front.tag()];
1446        put_u32(&mut bytes, 2);
1447        bytes.extend_from_slice(&integer::encode(&[0, 9]).unwrap());
1448        bytes.extend_from_slice(&encode_only(Kind::Plain, &suffixes).unwrap().unwrap());
1449        let error = decode_flat(&bytes).expect_err("a nine byte prefix of a three byte value");
1450        assert_eq!(error.message(), "a value shares 9 bytes with a value 3 bytes long");
1451        assert_eq!(decode(&bytes).unwrap_err().message(), error.message());
1452    }
1453
1454    #[test]
1455    fn the_dictionary_is_sorted_and_the_codes_point_back_at_the_values() {
1456        // The two things the dictionary path has to get right, and the reason it is one function
1457        // now rather than a sort followed by a binary search per row.
1458        let values = vec![
1459            b"pear".to_vec(),
1460            b"apple".to_vec(),
1461            b"pear".to_vec(),
1462            b"cherry".to_vec(),
1463            b"apple".to_vec(),
1464        ];
1465        let borrowed = borrow(&values);
1466        let (entries, codes) = dictionary_of(&borrowed);
1467        assert_eq!(entries, vec![b"apple".as_slice(), b"cherry".as_slice(), b"pear".as_slice()]);
1468        assert_eq!(codes, vec![2, 0, 2, 1, 0]);
1469        for (code, value) in codes.iter().zip(&borrowed) {
1470            assert_eq!(entries[*code as usize], *value);
1471        }
1472    }
1473
1474    #[test]
1475    fn a_column_with_nothing_repeated_has_no_duplicates_and_one_with_anything_does() {
1476        let distinct: Vec<Vec<u8>> =
1477            (0..5000).map(|index| format!("value-{index}").into_bytes()).collect();
1478        assert!(!has_duplicates(&borrow(&distinct)));
1479
1480        // One repeat at the far end, so a check that gave up early would miss it.
1481        let mut repeated = distinct.clone();
1482        repeated.push(b"value-0".to_vec());
1483        assert!(has_duplicates(&borrow(&repeated)));
1484
1485        assert!(!has_duplicates(&borrow(&Vec::new())));
1486        assert!(!has_duplicates(&borrow(&[b"one".to_vec()])));
1487        assert!(has_duplicates(&borrow(&vec![b"same".to_vec(); 2])));
1488    }
1489
1490    #[test]
1491    fn long_values_that_differ_only_at_the_end_are_not_confused_for_each_other() {
1492        // The hash is eight bytes at a time and the table verifies every hit, so this is the case
1493        // that says the verify is really there rather than the hash being trusted.
1494        let stem = "http://www.example.com/a/very/long/path/that/goes/on?session=";
1495        let values: Vec<Vec<u8>> =
1496            (0..2000).map(|index| format!("{stem}{index}").into_bytes()).collect();
1497        assert!(!has_duplicates(&borrow(&values)));
1498        let (entries, codes) = dictionary_of(&borrow(&values));
1499        assert_eq!(entries.len(), values.len());
1500        assert_eq!(codes.len(), values.len());
1501    }
1502
1503    #[test]
1504    fn what_the_chooser_returns_is_the_smallest_of_what_it_was_offered() {
1505        // `offered` and `encode_only` are what `cargo xtask encode` splits the chooser's seconds
1506        // with, so they have to describe the chooser that actually runs rather than a second copy
1507        // of its rules that drifts. This is the assertion that keeps the two the same thing: walk
1508        // the list, encode each one alone, and the smallest has to be byte for byte what `encode`
1509        // came back with.
1510        for values in [urls(400), keyed(urls(400)), vec![b"same".to_vec(); 50], Vec::new()] {
1511            let borrowed = borrow(&values);
1512            let chosen = encode(&borrowed).unwrap();
1513            let mut smallest: Option<Vec<u8>> = None;
1514            for kind in offered(&borrowed) {
1515                let Some(bytes) = encode_only(kind, &borrowed).unwrap() else {
1516                    continue;
1517                };
1518                if smallest.as_ref().is_none_or(|best| bytes.len() < best.len()) {
1519                    smallest = Some(bytes);
1520                }
1521            }
1522            assert_eq!(smallest.as_deref(), Some(chosen.as_slice()), "{}", values.len());
1523        }
1524    }
1525
1526    fn raw_size(values: &[Vec<u8>]) -> usize {
1527        values.iter().map(Vec::len).sum::<usize>() + values.len() * 4
1528    }
1529
1530    #[test]
1531    fn a_matched_chunk_replays_literals_whether_or_not_they_are_compressed() {
1532        // The literals of a matched chunk are a chunk of their own, and when that chunk is
1533        // compressed the replay decompresses each run straight into the output instead of into a
1534        // buffer it then copies out of. Both columns here are checked value for value by
1535        // round_trip, so what is left is to show that one of them takes the fused path and the
1536        // other takes the one that decodes the literals first, and that the two agree.
1537        let compressed = describe(&round_trip(&keyed(urls(20_000)))).unwrap();
1538        assert!(compressed.starts_with("LZ(") && compressed.contains(", FSST["), "{compressed}");
1539
1540        let buffered = describe(&round_trip(&keyed(urls(300)))).unwrap();
1541        assert!(buffered.starts_with("LZ(") && buffered.contains(", PLAIN("), "{buffered}");
1542    }
1543
1544    #[test]
1545    fn a_copy_back_writes_what_a_byte_at_a_time_copy_writes_at_every_distance() {
1546        // The wide stores read bytes the same copy wrote a step earlier once the copy is longer
1547        // than its distance, so every distance either side of eight and sixteen is checked against
1548        // the plain loop, at lengths that end short of, on and past a whole store.
1549        let seed: Vec<u8> = (0..40u8).map(|byte| byte.wrapping_mul(37).wrapping_add(11)).collect();
1550        for offset in 1..=seed.len() {
1551            for length in 1..=50 {
1552                let mut wanted = seed.clone();
1553                for _ in 0..length {
1554                    wanted.push(wanted[wanted.len() - offset]);
1555                }
1556                let mut out = seed.clone();
1557                out.resize(seed.len() + length + REPLAY_SLACK, 0);
1558                let end = copy_back(&mut out, 0, seed.len(), offset, length).unwrap();
1559                assert_eq!(&out[..end], wanted.as_slice(), "offset {offset} length {length}");
1560            }
1561        }
1562        let mut short = vec![1, 2, 3, 0];
1563        assert!(copy_back(&mut short, 0, 3, 1, 2).is_err(), "past the end of the buffer");
1564        assert!(copy_back(&mut short, 0, 3, 4, 1).is_err(), "further back than the output");
1565    }
1566
1567    #[test]
1568    fn an_empty_chunk_round_trips() {
1569        let bytes = round_trip(&[]);
1570        assert_eq!(kind_of(&bytes), Kind::Plain);
1571    }
1572
1573    #[test]
1574    fn a_constant_column_costs_what_one_value_costs() {
1575        let values = vec![b"https://www.example.com/".to_vec(); 100_000];
1576        let bytes = round_trip(&values);
1577        assert_eq!(kind_of(&bytes), Kind::Constant);
1578        assert_eq!(bytes.len(), 9 + 24);
1579    }
1580
1581    #[test]
1582    fn a_url_column_of_unique_values_is_matched_rather_than_only_compressed() {
1583        // Every value distinct, so a dictionary is the values plus an index and cannot win, and
1584        // every value starts with an identifier of its own, so neighbours share nothing and front
1585        // coding cannot win either. This used to be the case that fell back to FSST, on the
1586        // reasoning that a symbol table was the only thing that could reach repeated vocabulary
1587        // with no structure around it. That reasoning was wrong and #575 is the measurement: the
1588        // vocabulary repeats at a distance, and a match finder reaches distance where a 255 symbol
1589        // table of at most eight bytes each does not.
1590        let values = keyed(urls(20_000));
1591        let bytes = round_trip(&values);
1592        assert_eq!(kind_of(&bytes), Kind::Lz);
1593
1594        // Against the encoding that used to win, on the same values, so the claim is a comparison
1595        // and not just a label.
1596        let borrowed: Vec<&[u8]> = values.iter().map(Vec::as_slice).collect();
1597        let fsst = encode_as(Kind::Fsst, &borrowed, 0, &EXHAUSTIVE).unwrap().unwrap();
1598        assert!(bytes.len() < fsst.len(), "{} against FSST {}", bytes.len(), fsst.len());
1599
1600        // Eleven bytes of every value are the identifier and a separator and nothing compresses
1601        // them, so the ratio here is lower than the one FSST gets on the URLs on their own.
1602        let ratio = raw_size(&values) as f64 / bytes.len() as f64;
1603        assert!(ratio > 4.0, "{ratio:.2}x");
1604    }
1605
1606    #[test]
1607    fn a_sample_of_a_periodic_column_learns_every_phase_of_it() {
1608        // This column is periodic and its period is what a fixed stride would have divided. The
1609        // sample has to see all of it, because a table trained on one phase learns eight byte
1610        // symbols that only line up with that phase and has nothing shorter to fall back on. The
1611        // measured cost of getting this wrong was 3.4 times the compressed size.
1612        let values = urls(20_000);
1613        let borrowed = borrow(&values);
1614        let sample = sample_of(&borrowed);
1615        let mut phases: Vec<&[u8]> = sample
1616            .iter()
1617            .map(|value| {
1618                let query =
1619                    value.iter().position(|byte| *byte == b'?').expect("every value has a query");
1620                &value[..query]
1621            })
1622            .collect();
1623        phases.sort_unstable();
1624        phases.dedup();
1625        // Three hosts and four paths, and the sample has to contain all twelve of the combinations.
1626        assert_eq!(phases.len(), 12);
1627        let whole = SymbolTable::train(&borrowed);
1628        let sampled = SymbolTable::train(&sample);
1629        let mut on_whole = Vec::new();
1630        let mut on_sample = Vec::new();
1631        for value in &borrowed {
1632            whole.compress(value, &mut on_whole);
1633            sampled.compress(value, &mut on_sample);
1634        }
1635        // Training on a twentieth of the column is allowed to cost something. It is not allowed to
1636        // cost a factor.
1637        assert!(
1638            on_sample.len() < on_whole.len() * 5 / 4,
1639            "{} against {}",
1640            on_sample.len(),
1641            on_whole.len()
1642        );
1643    }
1644
1645    #[test]
1646    fn a_repeating_column_becomes_a_dictionary_of_compressed_entries() {
1647        // The DICT_FSST row of the section 6.2 table, which is not an encoding of its own here: it
1648        // is a dictionary whose entries went back through the chooser. What the entries then get
1649        // is whatever wins on them, and since #575 that is the match finder rather than front
1650        // coding with the leftovers FSST compressed. The point of the test is unchanged: nobody
1651        // named the shape and the chooser arrived at it.
1652        //
1653        // The rows pick their value by a hash of the row number. They used to walk the values in
1654        // a fixed stride, which makes the dictionary codes a cycle whose differences take a
1655        // quarter as many values as the codes do, and a real column's codes are not that.
1656        let distinct = urls(500);
1657        let values: Vec<Vec<u8>> = (0..50_000_u64)
1658            .map(|index| {
1659                let hashed = (index.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 32) as usize;
1660                distinct[hashed % distinct.len()].clone()
1661            })
1662            .collect();
1663        let bytes = round_trip(&values);
1664        assert_eq!(kind_of(&bytes), Kind::Dict);
1665        let shape = describe(&bytes).unwrap();
1666        assert!(shape.starts_with("DICT(LZ("), "{shape}");
1667        let ratio = raw_size(&values) as f64 / bytes.len() as f64;
1668        assert!(ratio > 20.0, "{ratio:.2}x, {shape}");
1669    }
1670
1671    #[test]
1672    fn a_column_of_long_runs_costs_almost_nothing() {
1673        // A dictionary makes the codes an integer chunk, and the integer chunk knows what to do
1674        // with runs, so run length encoding of strings falls out of the recursion.
1675        let distinct = urls(50);
1676        let mut values = Vec::new();
1677        for entry in &distinct {
1678            values.extend(std::iter::repeat_n(entry.clone(), 1000));
1679        }
1680        let bytes = round_trip(&values);
1681        let shape = describe(&bytes).unwrap();
1682        assert!(shape.contains("RLE"), "{shape}");
1683        assert!(bytes.len() < 2000, "{} bytes: {shape}", bytes.len());
1684    }
1685
1686    #[test]
1687    fn incompressible_strings_stay_close_to_their_own_size() {
1688        // The case where nothing works. It has to land on PLAIN or on an FSST that is not much
1689        // worse, rather than on a dictionary of every value in the column.
1690        let mut state = 0x2545_f491_4f6c_dd1du64;
1691        let values: Vec<Vec<u8>> = (0..2000)
1692            .map(|_| {
1693                (0..32)
1694                    .map(|_| {
1695                        state ^= state << 13;
1696                        state ^= state >> 7;
1697                        state ^= state << 17;
1698                        state as u8
1699                    })
1700                    .collect()
1701            })
1702            .collect();
1703        let bytes = round_trip(&values);
1704        assert!(bytes.len() < 2000 * 32 + 3000, "{} bytes", bytes.len());
1705    }
1706
1707    #[test]
1708    fn lengths_are_stored_rather_than_offsets() {
1709        // Every value is 24 bytes, so the lengths are a constant chunk and cost 13 bytes for the
1710        // whole column. Offsets would be 100,000 increasing integers.
1711        let values: Vec<Vec<u8>> =
1712            (0..100_000).map(|index| format!("{index:024}").into_bytes()).collect();
1713        let borrowed = borrow(&values);
1714        let bytes = encode_only(Kind::Plain, &borrowed).unwrap().unwrap();
1715        assert_eq!(bytes.len(), 5 + 13 + 100_000 * 24);
1716    }
1717
1718    #[test]
1719    fn empty_strings_are_values_and_not_nulls() {
1720        let values = vec![Vec::new(), b"a".to_vec(), Vec::new(), b"bb".to_vec()];
1721        round_trip(&values);
1722    }
1723
1724    #[test]
1725    fn a_chunk_with_one_value_round_trips() {
1726        round_trip(&[b"only".to_vec()]);
1727    }
1728
1729    #[test]
1730    fn every_candidate_that_applies_decodes_to_the_input() {
1731        let values = urls(3000);
1732        let borrowed = borrow(&values);
1733        let applicable = candidates(&borrowed, 0);
1734        assert!(applicable.len() >= 2, "{applicable:?}");
1735        for kind in applicable {
1736            let bytes = encode_only(kind, &borrowed).unwrap().unwrap();
1737            assert_eq!(decode(&bytes).unwrap(), values, "{}", kind.name());
1738        }
1739    }
1740
1741    #[test]
1742    fn the_chooser_picks_the_smallest_candidate() {
1743        let values = urls(2000);
1744        let borrowed = borrow(&values);
1745        let chosen = encode(&borrowed).unwrap();
1746        for (_, size) in candidate_sizes(&borrowed).unwrap() {
1747            assert!(chosen.len() <= size);
1748        }
1749    }
1750
1751    #[test]
1752    fn a_truncated_chunk_is_an_error_and_not_a_panic() {
1753        let values = urls(40);
1754        let bytes = encode(&borrow(&values)).unwrap();
1755        for len in 0..bytes.len() {
1756            assert!(decode(&bytes[..len]).is_err(), "{len} bytes decoded");
1757        }
1758    }
1759
1760    #[test]
1761    fn trailing_bytes_are_an_error() {
1762        let mut bytes = encode(&borrow(&urls(10))).unwrap();
1763        bytes.push(0);
1764        let error = decode(&bytes).unwrap_err();
1765        assert!(error.message().contains("left over"), "{error}");
1766    }
1767
1768    #[test]
1769    fn an_unknown_tag_is_an_error() {
1770        let error = decode(&[99, 0, 0, 0, 0]).unwrap_err();
1771        assert!(error.message().contains("unknown string encoding tag"), "{error}");
1772    }
1773
1774    #[test]
1775    fn a_dictionary_code_outside_the_dictionary_is_an_error() {
1776        let mut bytes = vec![Kind::Dict.tag()];
1777        put_u32(&mut bytes, 1);
1778        bytes.extend_from_slice(&encode(&[b"one".as_slice()]).unwrap());
1779        bytes.extend_from_slice(&integer::encode(&[9]).unwrap());
1780        let error = decode(&bytes).unwrap_err();
1781        assert!(error.message().contains("not in the dictionary"), "{error}");
1782    }
1783
1784    #[test]
1785    fn a_sorted_column_of_urls_is_front_coded() {
1786        // The M1 finding, in a test. Sorted URLs share a host and most of a path with the URL next
1787        // to them, FSST cannot reach those bytes because it compresses each value on its own, and
1788        // front coding is the shape that reaches them.
1789        let mut values = urls(20_000);
1790        values.sort();
1791        let bytes = round_trip(&values);
1792        assert_eq!(kind_of(&bytes), Kind::Front);
1793        let shape = describe(&bytes).unwrap();
1794        let mut plain = Vec::new();
1795        let borrowed = borrow(&values);
1796        for (kind, size) in candidate_sizes(&borrowed).unwrap() {
1797            if kind == Kind::Fsst {
1798                plain.push(size);
1799            }
1800        }
1801        let fsst = plain[0];
1802        assert!(bytes.len() * 2 < fsst, "{} against FSST {fsst}: {shape}", bytes.len());
1803    }
1804
1805    #[test]
1806    fn a_column_with_nothing_to_share_is_not_offered_front_coding() {
1807        // The candidate costs an encode of the whole column, so a column whose neighbours have
1808        // nothing in common must not be paying for it.
1809        let mut state = 0x9e37_79b9_7f4a_7c15u64;
1810        let values: Vec<Vec<u8>> = (0..2000)
1811            .map(|_| {
1812                (0..24)
1813                    .map(|_| {
1814                        state ^= state << 13;
1815                        state ^= state >> 7;
1816                        state ^= state << 17;
1817                        (state % 251) as u8
1818                    })
1819                    .collect()
1820            })
1821            .collect();
1822        let borrowed = borrow(&values);
1823        assert!(!candidates(&borrowed, 0).contains(&Kind::Front));
1824    }
1825
1826    #[test]
1827    fn a_prefix_longer_than_the_value_before_it_is_an_error() {
1828        let mut bytes = vec![Kind::Front.tag()];
1829        put_u32(&mut bytes, 2);
1830        bytes.extend_from_slice(&integer::encode(&[0, 9]).unwrap());
1831        bytes.extend_from_slice(&encode(&[b"one".as_slice(), b"two".as_slice()]).unwrap());
1832        let error = decode(&bytes).unwrap_err();
1833        assert!(error.message().contains("shares 9 bytes"), "{error}");
1834    }
1835
1836    #[test]
1837    fn a_negative_prefix_is_an_error() {
1838        let mut bytes = vec![Kind::Front.tag()];
1839        put_u32(&mut bytes, 1);
1840        bytes.extend_from_slice(&integer::encode(&[-1]).unwrap());
1841        bytes.extend_from_slice(&encode(&[b"one".as_slice()]).unwrap());
1842        let error = decode(&bytes).unwrap_err();
1843        assert!(error.message().contains("negative shared prefix"), "{error}");
1844    }
1845
1846    #[test]
1847    fn a_negative_length_is_an_error() {
1848        let mut bytes = vec![Kind::Plain.tag()];
1849        put_u32(&mut bytes, 1);
1850        bytes.extend_from_slice(&integer::encode(&[-1]).unwrap());
1851        let error = decode(&bytes).unwrap_err();
1852        assert!(error.message().contains("negative string length"), "{error}");
1853    }
1854
1855    #[test]
1856    fn the_sample_is_spread_across_the_chunk_and_not_taken_from_the_front() {
1857        // A sorted column whose first 64 KB says nothing about the rest of it. If the sample were
1858        // the front, the table would learn `aaaa` and escape every `zzzz`.
1859        let mut values: Vec<Vec<u8>> = Vec::new();
1860        for index in 0..20_000 {
1861            let head = if index < 10_000 { "aaaaaaaaaaaaaaaa" } else { "zzzzzzzzzzzzzzzz" };
1862            values.push(format!("{head}/{index:08}").into_bytes());
1863        }
1864        let borrowed = borrow(&values);
1865        let sample = sample_of(&borrowed);
1866        let first_half = sample.iter().filter(|value| value.starts_with(b"aaaa")).count();
1867        let second_half = sample.len() - first_half;
1868        assert!(first_half > 0 && second_half > 0, "{first_half} and {second_half}");
1869        let bytes = round_trip(&values);
1870        let ratio = raw_size(&values) as f64 / bytes.len() as f64;
1871        assert!(ratio > 4.0, "{ratio:.2}x");
1872    }
1873}