Skip to main content

zu_encoding/
dict.rs

1//! Dictionary encoding (encoding id 3).
2//!
3//! Distinct values are sorted into a dictionary and rows become codes, both
4//! stored in the frame-of-reference container. Sorted dictionaries keep
5//! range predicates cheap and delta-compress well.
6//! Layout: `dict_len: u32 LE`, dictionary container, codes container.
7
8use zu_common::{Result, ZuError};
9
10use crate::for_bitpack;
11
12/// Format rule: a dictionary holds at most this many entries, which is
13/// exactly the 64 KiB scratch ceiling from the docs/04 decoding
14/// contract once materialized as u64. The selector never offers Dict
15/// past this cardinality, and the decoder rejects a container claiming
16/// more, so readers can size the dictionary buffer before parsing.
17pub const MAX_ENTRIES: usize = 8192;
18
19/// Encodes `values` into `out`, returning the encoded byte length.
20pub fn encode(values: &[u64], out: &mut Vec<u8>) -> usize {
21    let start = out.len();
22    let mut dict: Vec<u64> = values.to_vec();
23    dict.sort_unstable();
24    dict.dedup();
25    let codes: Vec<u64> = values
26        .iter()
27        .map(|v| dict.binary_search(v).unwrap() as u64)
28        .collect();
29    let mut dict_buf = Vec::new();
30    for_bitpack::encode(&dict, &mut dict_buf);
31    out.extend_from_slice(&(dict_buf.len() as u32).to_le_bytes());
32    out.extend_from_slice(&dict_buf);
33    for_bitpack::encode(&codes, out);
34    out.len() - start
35}
36
37/// Decodes an encoded buffer, appending at most `max_values` values to
38/// `out`. The caller ceiling bounds the code stream and the format cap
39/// bounds the dictionary, so the one materialized intermediate never
40/// grows past 64 KiB whatever the container claims.
41pub fn decode(bytes: &[u8], max_values: usize, out: &mut Vec<u64>) -> Result<()> {
42    let corrupt = |detail: &str| ZuError::Corrupt {
43        what: "dict",
44        detail: detail.to_string(),
45    };
46    let dict_len = u32::from_le_bytes(
47        bytes
48            .get(..4)
49            .ok_or_else(|| corrupt("truncated header"))?
50            .try_into()
51            .unwrap(),
52    ) as usize;
53    let dict_bytes = bytes
54        .get(4..4 + dict_len)
55        .ok_or_else(|| corrupt("truncated dictionary"))?;
56    let codes_bytes = bytes
57        .get(4 + dict_len..)
58        .ok_or_else(|| corrupt("truncated codes"))?;
59    let mut dict = Vec::new();
60    for_bitpack::decode(dict_bytes, MAX_ENTRIES.min(max_values), &mut dict)?;
61    let start = out.len();
62    for_bitpack::decode(codes_bytes, max_values, out)?;
63    for slot in &mut out[start..] {
64        let code = *slot as usize;
65        *slot = *dict.get(code).ok_or_else(|| corrupt("code out of range"))?;
66    }
67    Ok(())
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73
74    #[test]
75    fn roundtrip_low_cardinality() {
76        let cities = [90_001u64, 10_115, 75_000, 90_001];
77        let values: Vec<u64> = (0..10_000).map(|i| cities[i % cities.len()]).collect();
78        let mut buf = Vec::new();
79        let len = encode(&values, &mut buf);
80        assert!(
81            len < values.len(),
82            "3 distinct values should pack below 1 B/row"
83        );
84        let mut out = Vec::new();
85        decode(&buf, values.len(), &mut out).unwrap();
86        assert_eq!(values, out);
87    }
88
89    #[test]
90    fn roundtrip_all_distinct() {
91        let values: Vec<u64> = (0..3000u64).rev().map(|i| i * 17).collect();
92        let mut buf = Vec::new();
93        encode(&values, &mut buf);
94        let mut out = Vec::new();
95        decode(&buf, values.len(), &mut out).unwrap();
96        assert_eq!(values, out);
97    }
98
99    #[test]
100    fn corrupt_code_rejected() {
101        let mut buf = Vec::new();
102        encode(&[5, 6, 5], &mut buf);
103        let mut out = Vec::new();
104        assert!(decode(&buf[..5], 16, &mut out).is_err());
105    }
106
107    #[test]
108    fn dictionary_at_and_past_the_cap() {
109        // Exactly the cap decodes; one entry more is a format violation
110        // the reader must reject however large the caller ceiling is.
111        let at_cap: Vec<u64> = (0..MAX_ENTRIES as u64).map(|i| i * 3).collect();
112        let mut buf = Vec::new();
113        encode(&at_cap, &mut buf);
114        let mut out = Vec::new();
115        decode(&buf, at_cap.len(), &mut out).unwrap();
116        assert_eq!(out, at_cap);
117        let past: Vec<u64> = (0..MAX_ENTRIES as u64 + 1).map(|i| i * 3).collect();
118        let mut buf = Vec::new();
119        encode(&past, &mut buf);
120        let mut out = Vec::new();
121        assert!(decode(&buf, past.len(), &mut out).is_err());
122        assert!(out.is_empty(), "a rejected payload must not touch out");
123    }
124}