Skip to main content

zu_encoding/
frequency.rs

1//! Frequency encoding (encoding id 10), the BtrBlocks shape for columns
2//! where one value dominates but the rest are wide and scattered, so
3//! neither RLE (short runs) nor Dict (high exception cardinality) wins.
4//!
5//! The dominant value is stored once; everything else becomes an
6//! exception patched back in by position. Both exception streams ride
7//! the frame-of-reference container.
8//! Layout: `count: u32 LE`, `top: u64 LE`, `positions_len: u32 LE`,
9//! positions container, values container.
10
11use zu_common::{Result, ZuError};
12
13use crate::bitpack::CHUNK;
14use crate::for_bitpack;
15
16/// Encodes `values` into `out`, returning the encoded byte length.
17pub fn encode(values: &[u64], out: &mut Vec<u8>) -> usize {
18    let start = out.len();
19    // The dominant value, off the shared counting table rather than a
20    // hash map: the map hashed every value of every chunk with SipHash,
21    // and this encoder is on the write path of every fold.
22    let top = match values.is_empty() {
23        true => 0,
24        false => crate::counts::count(values, values.len()).top,
25    };
26    let mut positions = Vec::new();
27    let mut exceptions = Vec::new();
28    for (i, &v) in values.iter().enumerate() {
29        if v != top {
30            positions.push(i as u64);
31            exceptions.push(v);
32        }
33    }
34    out.extend_from_slice(&(values.len() as u32).to_le_bytes());
35    out.extend_from_slice(&top.to_le_bytes());
36    let mut positions_buf = Vec::new();
37    for_bitpack::encode(&positions, &mut positions_buf);
38    out.extend_from_slice(&(positions_buf.len() as u32).to_le_bytes());
39    out.extend_from_slice(&positions_buf);
40    for_bitpack::encode(&exceptions, out);
41    out.len() - start
42}
43
44/// Decodes an encoded buffer, appending at most `max_values` values to
45/// `out`. The count and both exception streams are claims until checked:
46/// the count against the caller ceiling, the streams against each other,
47/// and every position against the materialized range. The exception
48/// streams patch chunk by chunk in lockstep, so scratch stays two
49/// MiniBlock chunks however many exceptions the segment holds.
50pub fn decode(bytes: &[u8], max_values: usize, out: &mut Vec<u64>) -> Result<()> {
51    let corrupt = |detail: &str| ZuError::Corrupt {
52        what: "frequency",
53        detail: detail.to_string(),
54    };
55    let header = bytes.get(..16).ok_or_else(|| corrupt("truncated header"))?;
56    let count = u32::from_le_bytes(header[..4].try_into().unwrap()) as usize;
57    let top = u64::from_le_bytes(header[4..12].try_into().unwrap());
58    let positions_len = u32::from_le_bytes(header[12..16].try_into().unwrap()) as usize;
59    if count > max_values {
60        return Err(corrupt("count above the caller ceiling"));
61    }
62    let positions_bytes = bytes
63        .get(16..16 + positions_len)
64        .ok_or_else(|| corrupt("truncated positions"))?;
65    let values_bytes = bytes
66        .get(16 + positions_len..)
67        .ok_or_else(|| corrupt("truncated exception values"))?;
68    let mut positions_cur = for_bitpack::ChunkCursor::new(positions_bytes, count)?;
69    let mut values_cur = for_bitpack::ChunkCursor::new(values_bytes, count)?;
70    if positions_cur.count() != values_cur.count() {
71        return Err(corrupt("stream length mismatch"));
72    }
73    let base = out.len();
74    out.extend(std::iter::repeat_n(top, count));
75    let mut sp = [0u64; CHUNK];
76    let mut sv = [0u64; CHUNK];
77    let bad = 'chunks: loop {
78        let (pmin, tp) = match positions_cur.next(&mut sp) {
79            Ok(Some(chunk)) => chunk,
80            Ok(None) => break None,
81            Err(e) => break Some(e),
82        };
83        let (vmin, tv) = match values_cur.next(&mut sv) {
84            Ok(Some(chunk)) => chunk,
85            Ok(None) => break Some(corrupt("value stream ended early")),
86            Err(e) => break Some(e),
87        };
88        for (&p, &v) in sp[..tp.min(tv)].iter().zip(&sv) {
89            let pos = pmin.wrapping_add(p);
90            if pos >= count as u64 {
91                break 'chunks Some(corrupt("position past the value count"));
92            }
93            out[base + pos as usize] = vmin.wrapping_add(v);
94        }
95    };
96    if let Some(e) = bad {
97        out.truncate(base);
98        return Err(e);
99    }
100    Ok(())
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    #[test]
108    fn roundtrip_dominant_scattered() {
109        let mut rng = 0x9E3779B97F4A7C15u64;
110        let values: Vec<u64> = (0..10_000)
111            .map(|i| {
112                rng ^= rng << 13;
113                rng ^= rng >> 7;
114                rng ^= rng << 17;
115                if i % 10 == 3 { rng } else { 777 }
116            })
117            .collect();
118        let mut buf = Vec::new();
119        let len = encode(&values, &mut buf);
120        assert!(
121            len < values.len() * 2,
122            "10% exceptions should encode near a tenth of raw, got {len}"
123        );
124        let mut out = Vec::new();
125        decode(&buf, values.len(), &mut out).unwrap();
126        assert_eq!(values, out);
127    }
128
129    #[test]
130    fn roundtrip_edges() {
131        for values in [vec![], vec![5u64], vec![1, 2, 3, 4], vec![0; 100]] {
132            let mut buf = Vec::new();
133            encode(&values, &mut buf);
134            let mut out = Vec::new();
135            decode(&buf, values.len(), &mut out).unwrap();
136            assert_eq!(values, out);
137        }
138    }
139
140    #[test]
141    fn corrupt_and_hostile() {
142        let mut out = Vec::new();
143        assert!(decode(&[1, 2, 3], 16, &mut out).is_err());
144        // A flood claim dies on the ceiling before anything materializes.
145        let mut buf = u32::MAX.to_le_bytes().to_vec();
146        buf.extend_from_slice(&[0; 12]);
147        assert!(decode(&buf, 1 << 20, &mut out).is_err());
148        assert!(out.is_empty());
149    }
150
151    #[test]
152    fn hostile_position_past_count_rejected() {
153        // A valid-looking payload whose exception position lands outside
154        // the materialized range must be a Corrupt error, not a write
155        // into whatever the caller already had in `out`.
156        let mut buf = 4u32.to_le_bytes().to_vec();
157        buf.extend_from_slice(&7u64.to_le_bytes());
158        let mut positions_buf = Vec::new();
159        for_bitpack::encode(&[3], &mut positions_buf);
160        buf.extend_from_slice(&(positions_buf.len() as u32).to_le_bytes());
161        buf.extend_from_slice(&positions_buf);
162        for_bitpack::encode(&[99], &mut buf);
163        let mut out = Vec::new();
164        decode(&buf, 16, &mut out).unwrap();
165        assert_eq!(out, [7, 7, 7, 99]);
166        // Same payload, position 4 in a count of 4.
167        let mut buf = 4u32.to_le_bytes().to_vec();
168        buf.extend_from_slice(&7u64.to_le_bytes());
169        let mut positions_buf = Vec::new();
170        for_bitpack::encode(&[4], &mut positions_buf);
171        buf.extend_from_slice(&(positions_buf.len() as u32).to_le_bytes());
172        buf.extend_from_slice(&positions_buf);
173        for_bitpack::encode(&[99], &mut buf);
174        let mut out = vec![1, 2, 3];
175        assert!(decode(&buf, 16, &mut out).is_err());
176        assert_eq!(out, [1, 2, 3], "a rejected payload must not touch out");
177    }
178}