Skip to main content

zu_encoding/
patch.rs

1//! Patched bit packing, the exception container behind encoding id 12.
2//!
3//! Plain per-chunk packing pays the width of the widest value for all
4//! 1024 values, which is exactly how adjacency deltas die: neighbor lists
5//! average about 14 values on social graphs, a chunk crosses about 70
6//! lists, and nearly every chunk holds one hub-sized gap that prices the
7//! whole chunk at 23 bits. Here the encoder picks the packed width that
8//! minimizes total bytes; values wider than the pick become exceptions,
9//! stored at the chunk's max width behind a presence bitmap while their
10//! packed slots hold zero.
11//!
12//! Layout: `count: u32 LE`, then per 1024-value chunk a header of
13//! `width: u8, exc_width: u8`, a packed body of
14//! `packed_bytes(width, take)` bytes, a presence bitmap of
15//! `packed_bytes(1, take)` bytes, and the exceptions in position order,
16//! `packed_bytes(exc_width, popcount)` bytes.
17
18use zu_common::{Result, ZuError};
19
20use crate::bitpack::{self, CHUNK};
21use crate::bits_needed;
22
23/// Encodes `values` into `out`, returning the encoded byte length.
24pub fn encode(values: &[u64], out: &mut Vec<u8>) -> usize {
25    let start = out.len();
26    out.extend_from_slice(&(values.len() as u32).to_le_bytes());
27    let mut low = [0u64; CHUNK];
28    let mut flags = [0u64; CHUNK];
29    let mut excs = Vec::with_capacity(64);
30    for chunk in values.chunks(CHUNK) {
31        let take = chunk.len();
32        // Width histogram, then a reverse suffix walk prices every
33        // candidate width in one pass.
34        let mut hist = [0usize; 65];
35        let mut max_width = 0u32;
36        for &v in chunk {
37            let w = bits_needed(v);
38            hist[w as usize] += 1;
39            max_width = max_width.max(w);
40        }
41        let mut width = max_width;
42        let mut best = bitpack::packed_bytes(max_width, take) + bitpack::packed_bytes(1, take);
43        let mut exc_count = 0usize;
44        for w in (0..max_width).rev() {
45            exc_count += hist[w as usize + 1];
46            let cost = bitpack::packed_bytes(w, take)
47                + bitpack::packed_bytes(1, take)
48                + bitpack::packed_bytes(max_width, exc_count);
49            if cost < best {
50                best = cost;
51                width = w;
52            }
53        }
54
55        excs.clear();
56        for (i, &v) in chunk.iter().enumerate() {
57            if bits_needed(v) > width {
58                low[i] = 0;
59                flags[i] = 1;
60                excs.push(v);
61            } else {
62                low[i] = v;
63                flags[i] = 0;
64            }
65        }
66        out.push(width as u8);
67        out.push(max_width as u8);
68        bitpack::pack(&low[..take], width, out);
69        bitpack::pack(&flags[..take], 1, out);
70        bitpack::pack(&excs, max_width, out);
71    }
72    out.len() - start
73}
74
75/// Parses the container and hands each patched chunk to `sink` as
76/// `(values, take)`. Shared with the delta-patch decoder. `max_values`
77/// is the caller's ceiling; a claimed count above it is rejected before
78/// any work scales with it.
79pub(crate) fn decode_chunks(
80    bytes: &[u8],
81    max_values: usize,
82    mut sink: impl FnMut(&[u64], usize),
83) -> Result<usize> {
84    let corrupt = |detail: String| ZuError::Corrupt {
85        what: "patch",
86        detail,
87    };
88    let count = u32::from_le_bytes(
89        bytes
90            .get(..4)
91            .ok_or_else(|| corrupt("truncated count".into()))?
92            .try_into()
93            .unwrap(),
94    ) as usize;
95    if count > max_values {
96        return Err(corrupt(format!(
97            "claims {count} values, caller allows {max_values}"
98        )));
99    }
100    let mut pos = 4usize;
101    let mut low = [0u64; CHUNK];
102    let mut excs = [0u64; CHUNK];
103    let mut remaining = count;
104    while remaining > 0 {
105        let header = bytes
106            .get(pos..pos + 2)
107            .ok_or_else(|| corrupt("truncated chunk header".into()))?;
108        let (width, exc_width) = (u32::from(header[0]), u32::from(header[1]));
109        if width > 64 || exc_width > 64 {
110            return Err(corrupt("width > 64".into()));
111        }
112        pos += 2;
113        let take = remaining.min(CHUNK);
114
115        let plen = bitpack::packed_bytes(width, take);
116        let packed = bytes
117            .get(pos..pos + plen)
118            .ok_or_else(|| corrupt("truncated chunk body".into()))?;
119        bitpack::unpack(packed, width, &mut low);
120        pos += plen;
121
122        let blen = bitpack::packed_bytes(1, take);
123        let bitmap = bytes
124            .get(pos..pos + blen)
125            .ok_or_else(|| corrupt("truncated bitmap".into()))?;
126        pos += blen;
127        let exc_count: usize = bitmap.iter().map(|&b| b.count_ones() as usize).sum();
128
129        let elen = bitpack::packed_bytes(exc_width, exc_count);
130        let packed_excs = bytes
131            .get(pos..pos + elen)
132            .ok_or_else(|| corrupt("truncated exceptions".into()))?;
133        bitpack::unpack(packed_excs, exc_width, &mut excs);
134        pos += elen;
135
136        // Walk set bits only: patch work scales with the exception count,
137        // not the chunk size. The encoder never sets padding bits past
138        // `take`; hostile ones are ignored here and cannot index out of
139        // bounds because popcount bounded exc_count above.
140        let mut next = 0usize;
141        for (word_idx, word_bytes) in bitmap.as_chunks::<8>().0.iter().enumerate() {
142            let mut word = u64::from_le_bytes(*word_bytes);
143            while word != 0 {
144                let i = word_idx * 64 + word.trailing_zeros() as usize;
145                if i < take {
146                    low[i] = excs[next];
147                }
148                next += 1;
149                word &= word - 1;
150            }
151        }
152        sink(&low, take);
153        remaining -= take;
154    }
155    Ok(count)
156}
157
158/// Decodes an encoded buffer, appending at most `max_values` values to
159/// `out`; a container claiming more is rejected before allocation.
160pub fn decode(bytes: &[u8], max_values: usize, out: &mut Vec<u64>) -> Result<()> {
161    decode_chunks(bytes, max_values, |values, take| {
162        out.extend_from_slice(&values[..take]);
163    })?;
164    Ok(())
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    fn roundtrip(values: &[u64]) -> usize {
172        let mut buf = Vec::new();
173        let len = encode(values, &mut buf);
174        assert_eq!(len, buf.len());
175        let mut out = Vec::new();
176        decode(&buf, values.len(), &mut out).unwrap();
177        assert_eq!(values, out.as_slice());
178        len
179    }
180
181    #[test]
182    fn outliers_stop_pricing_the_chunk() {
183        // 1% hub-sized values in a sea of 4-bit gaps. Plain packing pays
184        // 24 bits each; patched must land under 7 bits per value.
185        let values: Vec<u64> = (0..10_000u64)
186            .map(|i| if i % 100 == 7 { 10_000_000 + i } else { i % 13 })
187            .collect();
188        let len = roundtrip(&values);
189        assert!(len * 8 < values.len() * 7, "got {} bytes", len);
190        let mut plain = Vec::new();
191        crate::for_bitpack::encode(&values, &mut plain);
192        assert!(len * 2 < plain.len());
193    }
194
195    #[test]
196    fn uniform_width_needs_no_exceptions() {
197        let values: Vec<u64> = (0..2048u64).map(|i| i % 256).collect();
198        let len = roundtrip(&values);
199        // 8-bit body plus 1-bit bitmap plus headers, nothing more.
200        assert!(len <= 4 + 2 * (2 + 1024 + 128));
201    }
202
203    #[test]
204    fn extremes_and_short_tails() {
205        roundtrip(&[]);
206        roundtrip(&[u64::MAX]);
207        roundtrip(&[0, u64::MAX, 0, 1]);
208        let values: Vec<u64> = (0..CHUNK as u64 + 1).collect();
209        roundtrip(&values);
210    }
211
212    #[test]
213    fn hostile_input_rejected() {
214        let mut out = Vec::new();
215        assert!(decode(&[1, 0], 16, &mut out).is_err());
216        // Count says one value, then a chunk header claiming width 65.
217        assert!(decode(&[1, 0, 0, 0, 65, 0], 16, &mut out).is_err());
218        // Valid header, truncated body.
219        assert!(decode(&[100, 0, 0, 0, 8, 8, 1], 100, &mut out).is_err());
220    }
221}