Skip to main content

zu_encoding/
for_bitpack.rs

1//! Frame-of-reference plus bit packing (encoding id 4).
2//!
3//! Layout: `count: u32 LE`, then per 1024-value chunk a header of
4//! `min: u64 LE, width: u8` followed by the packed body, which is
5//! `bitpack::packed_bytes(width, chunk_len)` bytes. Full chunks are
6//! independently decodable at fixed offsets, which is what makes
7//! chunk-granular point reads cheap; only the final chunk can be short.
8
9use zu_common::{Result, ZuError};
10
11use crate::bitpack::{self, CHUNK};
12use crate::bits_needed;
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    out.extend_from_slice(&(values.len() as u32).to_le_bytes());
18    let mut scratch = [0u64; CHUNK];
19    for chunk in values.chunks(CHUNK) {
20        let min = chunk.iter().copied().min().unwrap_or(0);
21        let max = chunk.iter().copied().max().unwrap_or(0);
22        let width = bits_needed(max - min);
23        out.extend_from_slice(&min.to_le_bytes());
24        out.push(width as u8);
25        for (slot, &v) in scratch.iter_mut().zip(chunk) {
26            *slot = v - min;
27        }
28        bitpack::pack(&scratch[..chunk.len()], width, out);
29    }
30    out.len() - start
31}
32
33/// A pull cursor over a container's chunks, for decoders that walk two
34/// streams in lockstep or stream chunks straight into typed output.
35/// `next` unpacks the following chunk into `scratch` without the frame
36/// minimum applied and returns `(min, take)`, or None past the end.
37/// The claimed count is rejected against `max_values` up front: width-0
38/// chunks mean 9 bytes of input can claim 1024 values, so nothing may
39/// scale with the claim before that wall.
40pub(crate) struct ChunkCursor<'a> {
41    bytes: &'a [u8],
42    pos: usize,
43    remaining: usize,
44    count: usize,
45}
46
47impl<'a> ChunkCursor<'a> {
48    pub(crate) fn new(bytes: &'a [u8], max_values: usize) -> Result<Self> {
49        let corrupt = |detail: String| ZuError::Corrupt {
50            what: "for_bitpack",
51            detail,
52        };
53        let count = u32::from_le_bytes(
54            bytes
55                .get(..4)
56                .ok_or_else(|| corrupt("truncated count".into()))?
57                .try_into()
58                .unwrap(),
59        ) as usize;
60        if count > max_values {
61            return Err(corrupt(format!(
62                "claims {count} values, caller allows {max_values}"
63            )));
64        }
65        Ok(Self {
66            bytes,
67            pos: 4,
68            remaining: count,
69            count,
70        })
71    }
72
73    pub(crate) fn count(&self) -> usize {
74        self.count
75    }
76
77    pub(crate) fn next(&mut self, scratch: &mut [u64; CHUNK]) -> Result<Option<(u64, usize)>> {
78        if self.remaining == 0 {
79            return Ok(None);
80        }
81        let corrupt = |detail: &str| ZuError::Corrupt {
82            what: "for_bitpack",
83            detail: detail.to_string(),
84        };
85        let header = self
86            .bytes
87            .get(self.pos..self.pos + 9)
88            .ok_or_else(|| corrupt("truncated chunk header"))?;
89        let min = u64::from_le_bytes(header[..8].try_into().unwrap());
90        let width = u32::from(header[8]);
91        if width > 64 {
92            return Err(corrupt("width > 64"));
93        }
94        self.pos += 9;
95        let take = self.remaining.min(CHUNK);
96        let plen = bitpack::packed_bytes(width, take);
97        let packed = self
98            .bytes
99            .get(self.pos..self.pos + plen)
100            .ok_or_else(|| corrupt("truncated chunk body"))?;
101        bitpack::unpack(packed, width, scratch);
102        self.pos += plen;
103        self.remaining -= take;
104        Ok(Some((min, take)))
105    }
106}
107
108/// Parses the container and hands each decoded chunk to `sink` as
109/// `(min, values, take)`. Shared with the delta decoder so both stay
110/// single pass.
111pub(crate) fn decode_chunks(
112    bytes: &[u8],
113    max_values: usize,
114    mut sink: impl FnMut(u64, &[u64], usize),
115) -> Result<usize> {
116    let mut cursor = ChunkCursor::new(bytes, max_values)?;
117    let mut scratch = [0u64; CHUNK];
118    while let Some((min, take)) = cursor.next(&mut scratch)? {
119        sink(min, &scratch, take);
120    }
121    Ok(cursor.count())
122}
123
124/// Decodes an encoded buffer, appending at most `max_values` values to
125/// `out`. A container claiming more than the caller's ceiling is
126/// rejected before anything is allocated for it.
127pub fn decode(bytes: &[u8], max_values: usize, out: &mut Vec<u64>) -> Result<()> {
128    decode_chunks(bytes, max_values, |min, scratch, take| {
129        out.extend(scratch[..take].iter().map(|&v| min.wrapping_add(v)));
130    })?;
131    Ok(())
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn roundtrip_multi_chunk() {
140        let values: Vec<u64> = (0..3000u64).map(|i| 1_000_000 + i * 3).collect();
141        let mut buf = Vec::new();
142        let len = encode(&values, &mut buf);
143        assert_eq!(len, buf.len());
144        let mut out = Vec::new();
145        decode(&buf, values.len(), &mut out).unwrap();
146        assert_eq!(values, out);
147    }
148
149    #[test]
150    fn constant_chunk_is_tiny() {
151        let values = vec![42u64; CHUNK];
152        let mut buf = Vec::new();
153        encode(&values, &mut buf);
154        assert_eq!(buf.len(), 4 + 9);
155    }
156
157    #[test]
158    fn empty_and_truncated() {
159        let mut buf = Vec::new();
160        encode(&[], &mut buf);
161        let mut out = Vec::new();
162        decode(&buf, 0, &mut out).unwrap();
163        assert!(out.is_empty());
164        assert!(decode(&[1, 0], 16, &mut out).is_err());
165        assert!(decode(&[10, 0, 0, 0, 1], 16, &mut out).is_err());
166    }
167
168    #[test]
169    fn hostile_count_is_rejected_against_the_ceiling() {
170        // Width-0 chunks make the container 9 bytes per claimed 1024
171        // values, so the count wall is what stands between a small
172        // input and an allocation the caller never asked for.
173        let values = vec![7u64; 100];
174        let mut buf = Vec::new();
175        encode(&values, &mut buf);
176        let mut out = Vec::new();
177        assert!(decode(&buf, 99, &mut out).is_err());
178        decode(&buf, 100, &mut out).unwrap();
179        assert_eq!(out, values);
180        let mut hostile = u32::MAX.to_le_bytes().to_vec();
181        hostile.extend_from_slice(&[0u8; 9]);
182        assert!(decode(&hostile, 1 << 20, &mut out).is_err());
183    }
184}