Skip to main content

zu_encoding/
fsst.rs

1//! FSST string compression (encoding id 8), the Boncz, Neumann and Leis
2//! static symbol table: up to 255 symbols of 1 to 8 bytes replace common
3//! substrings with one-byte codes, and code 255 escapes a literal byte.
4//! Decompression is a table lookup per code with no entropy coding, which
5//! is what lets it hit the 1 GB/s decode floor while still halving
6//! typical text; random access into a compressed segment only needs the
7//! 2 KiB table, not the whole block, which is why FullZip string
8//! segments will ride it.
9//!
10//! The encoder trains on a sample with the iterative construction from
11//! the paper: parse the sample with the current table, credit each
12//! matched symbol and each concatenation of adjacent matches with the
13//! bytes it would save, and keep the highest earners for the next round.
14//! Operates on a flat byte buffer; string boundaries are structural
15//! (offsets live with the FullZip layout) and no symbol ever crosses a
16//! value boundary in practice because the training sample keeps them
17//! rare and correctness never depends on it.
18//!
19//! Layout: `raw_len: u32 LE`, `symbol_count: u8`, one length byte per
20//! symbol (1 to 8), the concatenated symbol bytes, then the code stream.
21
22use std::collections::HashMap;
23
24use zu_common::{Result, ZuError};
25
26const MAX_SYMBOLS: usize = 255;
27const MAX_SYMBOL_LEN: usize = 8;
28const ESCAPE: u8 = 255;
29// Symbols double in length once per round, so eight-byte symbols need
30// rounds to grow single bytes into pairs, fours, then eights, plus a
31// couple of rounds for the survivors to settle against each other.
32const TRAIN_ROUNDS: usize = 7;
33const SAMPLE_TARGET: usize = 64 << 10;
34/// No symbol, in a chain link or a one-byte slot.
35const NONE: u16 = u16::MAX;
36
37/// A symbol table arranged for longest-match lookup: a slot per byte for
38/// the one-byte symbols, and a chain per two-byte prefix for the rest,
39/// each chain ordered longest symbol first so the first match found is
40/// the match.
41///
42/// The obvious version of this is a `HashMap<Vec<u8>, u8>` probed once
43/// per length from eight down to one, and that is what this was. It
44/// costs up to eight sip hashes of the bytes at every position of every
45/// buffer trained on or encoded, and it dominated writing a string
46/// column: a million short strings took 4.19s to encode, nearly all of
47/// it hashing. Two bytes of the input pick a chain that almost always
48/// holds one symbol, so a lookup is an index and a comparison of at
49/// most eight bytes, the same million strings take 1.14s, and the
50/// bytes written come out the same to the byte.
51struct Index {
52    syms: Vec<Vec<u8>>,
53    /// Code of the one-byte symbol for each byte value, or [`NONE`].
54    single: [u16; 256],
55    /// First symbol of the chain for each two-byte prefix, or [`NONE`].
56    heads: Box<[u16]>,
57    /// Next symbol in the chain, parallel to `syms`.
58    next: Vec<u16>,
59}
60
61impl Index {
62    fn new(syms: Vec<Vec<u8>>) -> Index {
63        let mut single = [NONE; 256];
64        let mut heads = vec![NONE; 1 << 16].into_boxed_slice();
65        let mut next = vec![NONE; syms.len()];
66        // Shortest first, pushing each onto the front of its chain, so
67        // every chain comes out longest first.
68        let mut order: Vec<u16> = (0..syms.len() as u16).collect();
69        order.sort_by_key(|&i| syms[i as usize].len());
70        for i in order {
71            let sym = &syms[i as usize];
72            if sym.len() == 1 {
73                single[sym[0] as usize] = i;
74            } else {
75                let bucket = ((sym[0] as usize) << 8) | sym[1] as usize;
76                next[i as usize] = heads[bucket];
77                heads[bucket] = i;
78            }
79        }
80        Index {
81            syms,
82            single,
83            heads,
84            next,
85        }
86    }
87
88    /// Longest-match lookup at `pos`; returns the code and matched
89    /// length, or None when the position starts no symbol.
90    fn best_match(&self, bytes: &[u8], pos: usize) -> Option<(u8, usize)> {
91        let rest = &bytes[pos..];
92        if rest.len() >= 2 {
93            let bucket = ((rest[0] as usize) << 8) | rest[1] as usize;
94            let mut i = self.heads[bucket];
95            while i != NONE {
96                let sym = &self.syms[i as usize];
97                if rest.starts_with(sym) {
98                    return Some((i as u8, sym.len()));
99                }
100                i = self.next[i as usize];
101            }
102        }
103        match self.single[rest[0] as usize] {
104            NONE => None,
105            code => Some((code as u8, 1)),
106        }
107    }
108}
109
110/// A candidate symbol during training: up to eight bytes and a length,
111/// which is a fixed size key rather than the `Vec` it stands for. The
112/// training loop proposes one candidate per position and one per pair of
113/// adjacent positions, so the `Vec` was two allocations and two hashes
114/// of a heap pointer's worth of bytes per position.
115#[derive(Clone, Copy, PartialEq, Eq, Hash)]
116struct Candidate {
117    bytes: [u8; MAX_SYMBOL_LEN],
118    len: u8,
119}
120
121impl Candidate {
122    fn new(bytes: &[u8]) -> Candidate {
123        let mut out = [0u8; MAX_SYMBOL_LEN];
124        out[..bytes.len()].copy_from_slice(bytes);
125        Candidate {
126            bytes: out,
127            len: bytes.len() as u8,
128        }
129    }
130
131    fn as_slice(&self) -> &[u8] {
132        &self.bytes[..self.len as usize]
133    }
134
135    fn to_vec(self) -> Vec<u8> {
136        self.bytes[..self.len as usize].to_vec()
137    }
138}
139
140/// FNV over the nine bytes of a [`Candidate`], with a final mix so the
141/// low bits a hash table indexes with carry the whole key. Sip hashing
142/// keys this small is most of what training used to cost, and nothing
143/// here is exposed to a chosen key: the input is bytes of a sample the
144/// writer drew itself, and a bad round of collisions costs time and not
145/// correctness.
146#[derive(Default)]
147struct SymHasher(u64);
148
149impl std::hash::Hasher for SymHasher {
150    fn write(&mut self, bytes: &[u8]) {
151        for &b in bytes {
152            self.0 = (self.0 ^ b as u64).wrapping_mul(0x0100_0000_01b3);
153        }
154    }
155
156    fn finish(&self) -> u64 {
157        let mut x = self.0;
158        x ^= x >> 33;
159        x = x.wrapping_mul(0xff51_afd7_ed55_8ccd);
160        x ^= x >> 29;
161        x
162    }
163}
164
165type SymHash = std::hash::BuildHasherDefault<SymHasher>;
166
167/// A sample of evenly spaced chunks so a table trained on a long buffer
168/// still sees its tail, capped near 64 KiB to keep training flat-cost.
169fn sample(bytes: &[u8]) -> Vec<u8> {
170    if bytes.len() <= SAMPLE_TARGET {
171        return bytes.to_vec();
172    }
173    // 512-byte fragments, following the reference implementation: a
174    // symbol is at most 8 bytes, so a fragment carries plenty of
175    // adjacency context, and many scattered fragments keep the table
176    // from memorizing whatever ids one region of the input holds.
177    let chunk = 512;
178    let chunks = SAMPLE_TARGET / chunk;
179    let stride = bytes.len() / chunks;
180    let mut out = Vec::with_capacity(SAMPLE_TARGET);
181    for i in 0..chunks {
182        let start = i * stride;
183        out.extend_from_slice(&bytes[start..bytes.len().min(start + chunk)]);
184    }
185    out
186}
187
188/// Iterative table construction: each round parses the sample with the
189/// current table and proposes concatenations of adjacent matches, and
190/// the candidates that would save the most bytes survive. Ties break on
191/// the symbol bytes so training is deterministic.
192fn train(sample: &[u8]) -> Vec<Vec<u8>> {
193    let mut table: Vec<Vec<u8>> = Vec::new();
194    for _ in 0..TRAIN_ROUNDS {
195        let index = Index::new(table);
196        let mut gain: HashMap<Candidate, u64, SymHash> = HashMap::default();
197        let mut prev: Option<(usize, usize)> = None;
198        let mut pos = 0;
199        while pos < sample.len() {
200            let len = index.best_match(sample, pos).map_or(1, |(_, len)| len);
201            *gain
202                .entry(Candidate::new(&sample[pos..pos + len]))
203                .or_insert(0) += len as u64;
204            if let Some((p_pos, p_len)) = prev
205                && p_len + len <= MAX_SYMBOL_LEN
206            {
207                *gain
208                    .entry(Candidate::new(&sample[p_pos..pos + len]))
209                    .or_insert(0) += (p_len + len) as u64;
210            }
211            prev = Some((pos, len));
212            pos += len;
213        }
214        // The survivors, without a heap allocation per candidate and
215        // without ordering the ones that lose. A round on text that
216        // compresses badly proposes a candidate per position, tens of
217        // thousands of them, and all but 255 are about to be thrown
218        // away: sorting them cost more than parsing the sample did, and
219        // holding each as a `Vec` cost an allocation and a pointer chase
220        // per comparison. The key is already eight bytes and a length,
221        // so the order is the same and only the top of it is sorted.
222        let mut candidates: Vec<(Candidate, u64)> = gain.into_iter().collect();
223        let better = |a: &(Candidate, u64), b: &(Candidate, u64)| {
224            b.1.cmp(&a.1)
225                .then_with(|| a.0.as_slice().cmp(b.0.as_slice()))
226        };
227        let keep = candidates.len().min(MAX_SYMBOLS);
228        if candidates.len() > keep {
229            candidates.select_nth_unstable_by(keep - 1, better);
230            candidates.truncate(keep);
231        }
232        candidates.sort_unstable_by(better);
233        table = candidates.into_iter().map(|(c, _)| c.to_vec()).collect();
234    }
235    table
236}
237
238/// A trained symbol table, separated from the encode pass because the two
239/// cost wildly different amounts: training a table for one 1024-row chunk
240/// of short strings runs about 3.4ms and encoding that chunk against it
241/// runs about 0.13ms, so a writer that trains per chunk spends 96% of its
242/// time in training. A writer holding a column of chunks that are alike
243/// trains once, on a sample drawn across the whole column, and encodes
244/// every chunk with the result. Nothing about the encoded form changes:
245/// each buffer still carries the table it was encoded with, so a decoder
246/// cannot tell which of the two a writer did.
247pub struct Table {
248    index: Index,
249}
250
251impl Table {
252    /// Trains on `bytes`, sampling it first when it is long.
253    pub fn train(bytes: &[u8]) -> Table {
254        Table {
255            index: Index::new(train(&sample(bytes))),
256        }
257    }
258
259    /// Reads back the table a buffer was encoded with.
260    ///
261    /// Training is the whole cost of writing a string column, and a
262    /// writer that rewrites a column it already wrote is training on
263    /// data it already trained on. The table is in the buffer already,
264    /// so a rewrite can encode with that one instead and pay nothing;
265    /// the codes it produces are as good as the codes on disk were,
266    /// which is what a rewrite of the same column wants. A column that
267    /// drifts away from its table is caught where it always was, by the
268    /// writer measuring a chunk against the table and buying it one of
269    /// its own.
270    pub fn read(bytes: &[u8]) -> Result<Table> {
271        let corrupt = |detail: &str| ZuError::Corrupt {
272            what: "fsst",
273            detail: detail.to_string(),
274        };
275        let header = bytes.get(..5).ok_or_else(|| corrupt("truncated header"))?;
276        let count = header[4] as usize;
277        let lens = bytes
278            .get(5..5 + count)
279            .ok_or_else(|| corrupt("truncated symbol lengths"))?;
280        if lens.iter().any(|&l| l == 0 || l as usize > MAX_SYMBOL_LEN) {
281            return Err(corrupt("symbol length outside 1..=8"));
282        }
283        let total: usize = lens.iter().map(|&l| l as usize).sum();
284        let syms = bytes
285            .get(5 + count..5 + count + total)
286            .ok_or_else(|| corrupt("truncated symbol bytes"))?;
287        let mut at = 0usize;
288        let table = lens
289            .iter()
290            .map(|&l| {
291                let sym = syms[at..at + l as usize].to_vec();
292                at += l as usize;
293                sym
294            })
295            .collect();
296        Ok(Table {
297            index: Index::new(table),
298        })
299    }
300
301    /// The symbols, in code order.
302    fn symbols(&self) -> &[Vec<u8>] {
303        &self.index.syms
304    }
305
306    /// What every encoded buffer pays to carry this table: the fixed
307    /// header, one length byte per symbol and the symbol bytes. A writer
308    /// comparing two encodings of different sizes has to take this out
309    /// first, because a table costing 2 KiB is nothing against a whole
310    /// column and a seventh of one 1024-row chunk of short strings.
311    pub fn header_len(&self) -> usize {
312        5 + self.symbols().len() + self.symbols().iter().map(Vec::len).sum::<usize>()
313    }
314
315    /// Encodes `bytes` into `out`, returning the encoded byte length.
316    pub fn encode(&self, bytes: &[u8], out: &mut Vec<u8>) -> usize {
317        let start = out.len();
318        out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
319        out.push(self.symbols().len() as u8);
320        for sym in self.symbols() {
321            out.push(sym.len() as u8);
322        }
323        for sym in self.symbols() {
324            out.extend_from_slice(sym);
325        }
326        let mut pos = 0;
327        while pos < bytes.len() {
328            match self.index.best_match(bytes, pos) {
329                Some((code, len)) => {
330                    out.push(code);
331                    pos += len;
332                }
333                None => {
334                    out.push(ESCAPE);
335                    out.push(bytes[pos]);
336                    pos += 1;
337                }
338            }
339        }
340        out.len() - start
341    }
342}
343
344/// Trains a table on `bytes` and encodes `bytes` with it, returning the
345/// encoded byte length. [`Table`] is the form to reach for when more than
346/// one buffer is going to be encoded the same way.
347pub fn encode(bytes: &[u8], out: &mut Vec<u8>) -> usize {
348    Table::train(bytes).encode(bytes, out)
349}
350
351/// Decodes an encoded buffer, appending at most `max_bytes` bytes to
352/// `out`. The claimed length, every symbol length, and every code are
353/// checked, and a rejected payload leaves `out` untouched. Scratch is
354/// the 255-entry padded table, well under the 64 KiB decoder ceiling.
355pub fn decode(bytes: &[u8], max_bytes: usize, out: &mut Vec<u8>) -> Result<()> {
356    let corrupt = |detail: &str| ZuError::Corrupt {
357        what: "fsst",
358        detail: detail.to_string(),
359    };
360    let header = bytes.get(..5).ok_or_else(|| corrupt("truncated header"))?;
361    let raw_len = u32::from_le_bytes(header[..4].try_into().unwrap()) as usize;
362    let count = header[4] as usize;
363    if raw_len > max_bytes {
364        return Err(corrupt("length above the caller ceiling"));
365    }
366    let lens = bytes
367        .get(5..5 + count)
368        .ok_or_else(|| corrupt("truncated symbol lengths"))?;
369    if lens.iter().any(|&l| l == 0 || l as usize > MAX_SYMBOL_LEN) {
370        return Err(corrupt("symbol length outside 1..=8"));
371    }
372    let total: usize = lens.iter().map(|&l| l as usize).sum();
373    let syms = bytes
374        .get(5 + count..5 + count + total)
375        .ok_or_else(|| corrupt("truncated symbol bytes"))?;
376    let payload = &bytes[5 + count + total..];
377    // Every entry is padded to 8 bytes so the hot loop is always one
378    // fixed-size copy, and the lengths live in a fixed array so a code
379    // that passed the count check indexes without another bounds test.
380    let mut table = [[0u8; MAX_SYMBOL_LEN]; MAX_SYMBOLS];
381    let mut tlen = [0u8; MAX_SYMBOLS];
382    let mut sym_pos = 0;
383    for (i, &l) in lens.iter().enumerate() {
384        table[i][..l as usize].copy_from_slice(&syms[sym_pos..sym_pos + l as usize]);
385        tlen[i] = l;
386        sym_pos += l as usize;
387    }
388    // The output is sized up front from the validated claim, with 8
389    // bytes of slack so every symbol write stays in bounds while n is
390    // at most raw_len, which the overshoot check below maintains. That
391    // turns the hot loop into indexed stores with no capacity checks or
392    // length updates; hostile payloads cost at most one iteration past
393    // the claim before the error path restores `out` exactly.
394    let base = out.len();
395    out.resize(base + raw_len + MAX_SYMBOL_LEN, 0);
396    let dst = &mut out[base..];
397    let mut n = 0;
398    let mut i = 0;
399    let mut bad: Option<&str> = None;
400    // The write window doubles as the overshoot check: the slack sizing
401    // makes get_mut fail exactly when n has passed the claimed length,
402    // so the hot path is one compare, one 8-byte copy, one add. n can
403    // finish up to 7 bytes past the claim through the slack; the final
404    // equality check catches that with the rest.
405    while i < payload.len() {
406        let code = payload[i] as usize;
407        i += 1;
408        if code < count {
409            let Some(w) = dst.get_mut(n..n + MAX_SYMBOL_LEN) else {
410                bad = Some("decoded past the claimed length");
411                break;
412            };
413            w.copy_from_slice(&table[code]);
414            n += tlen[code] as usize;
415        } else if code == ESCAPE as usize {
416            let Some(&literal) = payload.get(i) else {
417                bad = Some("payload ends inside an escape");
418                break;
419            };
420            i += 1;
421            let Some(slot) = dst.get_mut(n) else {
422                bad = Some("decoded past the claimed length");
423                break;
424            };
425            *slot = literal;
426            n += 1;
427        } else {
428            bad = Some("code past the symbol count");
429            break;
430        }
431    }
432    if bad.is_none() && n != raw_len {
433        bad = Some("decoded length disagrees with the claim");
434    }
435    if let Some(detail) = bad {
436        out.truncate(base);
437        return Err(corrupt(detail));
438    }
439    out.truncate(base + raw_len);
440    Ok(())
441}
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446
447    fn text_corpus() -> Vec<u8> {
448        let mut text = Vec::new();
449        for i in 0..4000u64 {
450            text.extend_from_slice(
451                format!(
452                    "https://example.com/user/{}/posts?page={}\n",
453                    i * 37,
454                    i % 12
455                )
456                .as_bytes(),
457            );
458        }
459        text
460    }
461
462    #[test]
463    fn table_read_back_encodes_the_same_bytes() {
464        let text = text_corpus();
465        let mut first = Vec::new();
466        let len = Table::train(&text).encode(&text, &mut first);
467        assert_eq!(len, first.len());
468        // The table off the buffer has to be the table that wrote it,
469        // byte for byte, or a rewrite would change what a column costs.
470        let table = Table::read(&first).expect("table");
471        let mut again = Vec::new();
472        table.encode(&text, &mut again);
473        assert_eq!(first, again);
474        let mut out = Vec::new();
475        decode(&again, text.len(), &mut out).expect("decode");
476        assert_eq!(out, text);
477    }
478
479    #[test]
480    fn table_read_rejects_rubbish() {
481        assert!(Table::read(&[1, 2, 3]).is_err());
482        // A count that claims more symbols than the buffer holds.
483        let mut buf = 4u32.to_le_bytes().to_vec();
484        buf.push(9);
485        buf.extend_from_slice(&[1, 1]);
486        assert!(Table::read(&buf).is_err());
487        // A zero length symbol is not one this encoder ever writes.
488        let mut buf = 4u32.to_le_bytes().to_vec();
489        buf.push(1);
490        buf.extend_from_slice(&[0, b'a']);
491        assert!(Table::read(&buf).is_err());
492    }
493
494    #[test]
495    fn roundtrip_compresses_text() {
496        let text = text_corpus();
497        let mut buf = Vec::new();
498        let len = encode(&text, &mut buf);
499        assert!(
500            len * 2 < text.len(),
501            "repetitive urls should halve, got {len} from {}",
502            text.len()
503        );
504        let mut out = Vec::new();
505        decode(&buf, text.len(), &mut out).unwrap();
506        assert_eq!(text, out);
507    }
508
509    #[test]
510    fn roundtrip_edges() {
511        let noise: Vec<u8> = (0..2048u32)
512            .map(|i| (i.wrapping_mul(2654435761) >> 13) as u8)
513            .collect();
514        for bytes in [vec![], vec![7u8], vec![0xFF; 300], noise] {
515            let mut buf = Vec::new();
516            encode(&bytes, &mut buf);
517            let mut out = Vec::new();
518            decode(&buf, bytes.len(), &mut out).unwrap();
519            assert_eq!(bytes, out);
520        }
521    }
522
523    #[test]
524    fn corrupt_and_hostile() {
525        let mut out = vec![1u8, 2, 3];
526        assert!(decode(&[1, 2], 16, &mut out).is_err());
527        // A flood claim dies on the ceiling before anything materializes.
528        let mut buf = u32::MAX.to_le_bytes().to_vec();
529        buf.push(0);
530        assert!(decode(&buf, 1 << 20, &mut out).is_err());
531        // Zero and oversized symbol lengths are rejected.
532        for bad_len in [0u8, 9] {
533            let mut buf = 1u32.to_le_bytes().to_vec();
534            buf.extend_from_slice(&[1, bad_len, b'x', 0]);
535            assert!(decode(&buf, 16, &mut out).is_err());
536        }
537        // A code past the symbol count, a payload ending inside an
538        // escape, and a stream that misses its claimed length are all
539        // Corrupt errors that leave `out` exactly as it was.
540        for payload in [&[5u8][..], &[ESCAPE], &[]] {
541            let mut buf = 1u32.to_le_bytes().to_vec();
542            buf.extend_from_slice(&[1, 1, b'x']);
543            buf.extend_from_slice(payload);
544            assert!(decode(&buf, 16, &mut out).is_err());
545        }
546        // Overshoot: two 8-byte symbols against a claim of 9.
547        let mut buf = 9u32.to_le_bytes().to_vec();
548        buf.extend_from_slice(&[1, 8]);
549        buf.extend_from_slice(b"abcdefgh");
550        buf.extend_from_slice(&[0, 0]);
551        assert!(decode(&buf, 64, &mut out).is_err());
552        assert_eq!(out, [1, 2, 3], "a rejected payload must not touch out");
553    }
554
555    #[test]
556    fn a_table_encodes_buffers_it_did_not_train_on() {
557        // What a column writer does: train once, encode every chunk with
558        // it. A buffer the table never saw still has to round-trip, both
559        // when it is more of the same and when it shares nothing with the
560        // sample and every byte escapes.
561        let table = Table::train(&text_corpus());
562        for text in [
563            b"https://example.com/user/999999/posts?page=3".to_vec(),
564            (0..=255u8).collect(),
565            Vec::new(),
566        ] {
567            let mut buf = Vec::new();
568            let len = table.encode(&text, &mut buf);
569            assert_eq!(len, buf.len());
570            let mut out = Vec::new();
571            decode(&buf, text.len().max(1), &mut out).unwrap();
572            assert_eq!(text, out);
573        }
574    }
575
576    #[test]
577    fn training_is_deterministic() {
578        let text = text_corpus();
579        let mut a = Vec::new();
580        let mut b = Vec::new();
581        encode(&text, &mut a);
582        encode(&text, &mut b);
583        assert_eq!(a, b);
584    }
585}