Skip to main content

zu_encoding/
bool_bitpack.rs

1//! Boolean bitpacking (encoding id 9).
2//!
3//! Values must be 0 or 1; each becomes one bit, LSB first within a byte.
4//! Layout: `count: u32 LE`, then `ceil(count / 8)` packed bytes. The
5//! cascade only offers this encoding when the whole input is binary, so
6//! the encoder asserts that instead of masking, which would break the
7//! roundtrip silently.
8
9use zu_common::{Result, ZuError};
10
11/// Encodes `values` into `out`, returning the encoded byte length.
12/// Every value must be 0 or 1.
13pub fn encode(values: &[u64], out: &mut Vec<u8>) -> usize {
14    let start = out.len();
15    out.extend_from_slice(&(values.len() as u32).to_le_bytes());
16    for chunk in values.chunks(8) {
17        let mut byte = 0u8;
18        for (bit, &v) in chunk.iter().enumerate() {
19            debug_assert!(v <= 1, "bool_bitpack fed a non-binary value");
20            byte |= (v as u8) << bit;
21        }
22        out.push(byte);
23    }
24    out.len() - start
25}
26
27/// Decodes an encoded buffer, appending at most `max_values` values to
28/// `out`. The count is a claim until checked against the ceiling.
29pub fn decode(bytes: &[u8], max_values: usize, out: &mut Vec<u64>) -> Result<()> {
30    let corrupt = |detail: &str| ZuError::Corrupt {
31        what: "bool_bitpack",
32        detail: detail.to_string(),
33    };
34    let count = u32::from_le_bytes(
35        bytes
36            .get(..4)
37            .ok_or_else(|| corrupt("truncated count"))?
38            .try_into()
39            .unwrap(),
40    ) as usize;
41    if count > max_values {
42        return Err(corrupt("count above the caller ceiling"));
43    }
44    let body = bytes
45        .get(4..4 + count.div_ceil(8))
46        .ok_or_else(|| corrupt("truncated body"))?;
47    out.reserve(count);
48    let full = count / 8;
49    for &byte in &body[..full] {
50        for bit in 0..8 {
51            out.push(u64::from(byte >> bit & 1));
52        }
53    }
54    for bit in 0..count % 8 {
55        out.push(u64::from(body[full] >> bit & 1));
56    }
57    Ok(())
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[test]
65    fn roundtrip() {
66        let values: Vec<u64> = (0..10_000u64).map(|i| (i * i / 7) & 1).collect();
67        let mut buf = Vec::new();
68        let len = encode(&values, &mut buf);
69        assert_eq!(len, 4 + 1250);
70        let mut out = Vec::new();
71        decode(&buf, values.len(), &mut out).unwrap();
72        assert_eq!(values, out);
73    }
74
75    #[test]
76    fn roundtrip_ragged_tail() {
77        for n in [0usize, 1, 7, 8, 9, 15, 17] {
78            let values: Vec<u64> = (0..n as u64).map(|i| i & 1).collect();
79            let mut buf = Vec::new();
80            encode(&values, &mut buf);
81            let mut out = Vec::new();
82            decode(&buf, n, &mut out).unwrap();
83            assert_eq!(values, out, "count {n}");
84        }
85    }
86
87    #[test]
88    fn corrupt_and_hostile() {
89        let mut out = Vec::new();
90        assert!(decode(&[1, 0], 16, &mut out).is_err());
91        // A count past the body must read as truncation, not zeros.
92        let buf = [100u32.to_le_bytes().as_slice(), &[0xFF; 3]].concat();
93        assert!(decode(&buf, 1 << 20, &mut out).is_err());
94        // A flood claim dies on the ceiling before the reserve.
95        let buf = [u32::MAX.to_le_bytes().as_slice(), &[0xFF; 8]].concat();
96        assert!(decode(&buf, 1 << 20, &mut out).is_err());
97        assert!(out.is_empty());
98    }
99}