Skip to main content

zu_encoding/
rle.rs

1//! Run-length encoding (encoding id 2).
2//!
3//! Runs are split into two streams, values and run lengths, each stored in
4//! the frame-of-reference container so both compress with the same machinery
5//! chunk-granular readers already understand.
6//! Layout: `run_count: u32 LE`, `values_len: u32 LE`, values container,
7//! lengths container.
8
9use zu_common::{Result, ZuError};
10
11use crate::bitpack::CHUNK;
12use crate::for_bitpack;
13
14/// Encodes `values` into `out`, returning the encoded byte length.
15pub fn encode(values: &[u64], out: &mut Vec<u8>) -> usize {
16    let start = out.len();
17    let mut run_values = Vec::new();
18    let mut run_lengths = Vec::new();
19    let mut iter = values.iter().copied();
20    if let Some(first) = iter.next() {
21        let mut cur = first;
22        let mut len = 1u64;
23        for v in iter {
24            if v == cur {
25                len += 1;
26            } else {
27                run_values.push(cur);
28                run_lengths.push(len);
29                cur = v;
30                len = 1;
31            }
32        }
33        run_values.push(cur);
34        run_lengths.push(len);
35    }
36    out.extend_from_slice(&(run_values.len() as u32).to_le_bytes());
37    let mut values_buf = Vec::new();
38    for_bitpack::encode(&run_values, &mut values_buf);
39    out.extend_from_slice(&(values_buf.len() as u32).to_le_bytes());
40    out.extend_from_slice(&values_buf);
41    for_bitpack::encode(&run_lengths, out);
42    out.len() - start
43}
44
45/// Decodes an encoded buffer, appending at most `max_values` values to
46/// `out`. The ceiling bounds the run streams (every run carries at
47/// least one value) and the materialized total, and the total is summed
48/// checked so hostile run lengths cannot overflow it past the wall.
49/// The two containers stream chunk by chunk in lockstep, so scratch
50/// stays two MiniBlock chunks however many runs the segment holds.
51pub fn decode(bytes: &[u8], max_values: usize, out: &mut Vec<u64>) -> Result<()> {
52    let corrupt = |detail: String| ZuError::Corrupt {
53        what: "rle",
54        detail,
55    };
56    let header = bytes
57        .get(..8)
58        .ok_or_else(|| corrupt("truncated header".into()))?;
59    let run_count = u32::from_le_bytes(header[..4].try_into().unwrap()) as usize;
60    let values_len = u32::from_le_bytes(header[4..8].try_into().unwrap()) as usize;
61    if run_count > max_values {
62        return Err(corrupt(format!(
63            "claims {run_count} runs, caller allows {max_values} values"
64        )));
65    }
66    let values_bytes = bytes
67        .get(8..8 + values_len)
68        .ok_or_else(|| corrupt("truncated values".into()))?;
69    let lengths_bytes = bytes
70        .get(8 + values_len..)
71        .ok_or_else(|| corrupt("truncated lengths".into()))?;
72    let mut values_cur = for_bitpack::ChunkCursor::new(values_bytes, run_count)?;
73    let mut lengths_cur = for_bitpack::ChunkCursor::new(lengths_bytes, run_count)?;
74    if values_cur.count() != run_count || lengths_cur.count() != run_count {
75        return Err(corrupt("stream length mismatch".into()));
76    }
77    let base = out.len();
78    let mut sv = [0u64; CHUNK];
79    let mut sl = [0u64; CHUNK];
80    let mut total = 0u64;
81    let bad = 'chunks: loop {
82        let (vmin, tv) = match values_cur.next(&mut sv) {
83            Ok(Some(chunk)) => chunk,
84            Ok(None) => break None,
85            Err(e) => break Some(e),
86        };
87        let (lmin, tl) = match lengths_cur.next(&mut sl) {
88            Ok(Some(chunk)) => chunk,
89            Ok(None) => break Some(corrupt("length stream ended early".into())),
90            Err(e) => break Some(e),
91        };
92        for (&v, &l) in sv[..tv.min(tl)].iter().zip(&sl) {
93            let len = lmin.wrapping_add(l);
94            total = match total.checked_add(len) {
95                Some(t) if t <= max_values as u64 => t,
96                Some(t) => {
97                    break 'chunks Some(corrupt(format!(
98                        "claims {t} values, caller allows {max_values}"
99                    )));
100                }
101                None => break 'chunks Some(corrupt("total length overflow".into())),
102            };
103            out.extend(std::iter::repeat_n(vmin.wrapping_add(v), len as usize));
104        }
105    };
106    if let Some(e) = bad {
107        out.truncate(base);
108        return Err(e);
109    }
110    Ok(())
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116
117    #[test]
118    fn roundtrip_runs() {
119        let mut values = Vec::new();
120        for (v, n) in [(7u64, 500usize), (0, 1), (7, 200), (u64::MAX, 3)] {
121            values.extend(std::iter::repeat_n(v, n));
122        }
123        let mut buf = Vec::new();
124        encode(&values, &mut buf);
125        assert!(
126            buf.len() < 100,
127            "4 runs should encode tiny, got {}",
128            buf.len()
129        );
130        let mut out = Vec::new();
131        decode(&buf, values.len(), &mut out).unwrap();
132        assert_eq!(values, out);
133    }
134
135    #[test]
136    fn roundtrip_no_runs() {
137        let values: Vec<u64> = (0..2000).collect();
138        let mut buf = Vec::new();
139        encode(&values, &mut buf);
140        let mut out = Vec::new();
141        decode(&buf, values.len(), &mut out).unwrap();
142        assert_eq!(values, out);
143    }
144
145    #[test]
146    fn empty_and_corrupt() {
147        let mut buf = Vec::new();
148        encode(&[], &mut buf);
149        let mut out = Vec::new();
150        decode(&buf, 0, &mut out).unwrap();
151        assert!(out.is_empty());
152        assert!(decode(&buf[..3], 16, &mut out).is_err());
153    }
154
155    #[test]
156    fn hostile_lengths_cannot_overflow_or_flood() {
157        // Two runs whose lengths sum past u64: the checked sum must
158        // reject them instead of wrapping into a small reservation.
159        let mut buf = 2u32.to_le_bytes().to_vec();
160        let mut values_buf = Vec::new();
161        for_bitpack::encode(&[1, 2], &mut values_buf);
162        buf.extend_from_slice(&(values_buf.len() as u32).to_le_bytes());
163        buf.extend_from_slice(&values_buf);
164        for_bitpack::encode(&[u64::MAX, 2], &mut buf);
165        let mut out = Vec::new();
166        assert!(decode(&buf, 1 << 20, &mut out).is_err());
167
168        // A single run claiming a billion values dies on the ceiling,
169        // not in the allocator.
170        let mut buf = 1u32.to_le_bytes().to_vec();
171        let mut values_buf = Vec::new();
172        for_bitpack::encode(&[7], &mut values_buf);
173        buf.extend_from_slice(&(values_buf.len() as u32).to_le_bytes());
174        buf.extend_from_slice(&values_buf);
175        for_bitpack::encode(&[1_000_000_000], &mut buf);
176        assert!(decode(&buf, 1 << 20, &mut out).is_err());
177    }
178
179    #[test]
180    fn rejected_midstream_leaves_out_untouched() {
181        // The first run fits and streams into out before the second
182        // breaks the ceiling; the rejection must roll those writes back.
183        let mut buf = 2u32.to_le_bytes().to_vec();
184        let mut values_buf = Vec::new();
185        for_bitpack::encode(&[9, 8], &mut values_buf);
186        buf.extend_from_slice(&(values_buf.len() as u32).to_le_bytes());
187        buf.extend_from_slice(&values_buf);
188        for_bitpack::encode(&[3, 100], &mut buf);
189        let mut out = vec![1, 2];
190        assert!(decode(&buf, 10, &mut out).is_err());
191        assert_eq!(out, [1, 2], "a rejected payload must not touch out");
192    }
193}