Skip to main content

zu_encoding/
delta.rs

1//! Delta plus bit packing (encoding id 5).
2//!
3//! Consecutive differences are zigzag mapped to u64 and fed through the
4//! frame-of-reference container. The layout is `base: u64 LE` holding the
5//! first value, then `for_bitpack` over zigzag deltas with the running
6//! previous seeded from `base`, so the first chunk's width reflects the
7//! gaps and never the absolute magnitude of the start. Sorted inputs such
8//! as CSR neighbor lists produce small non-negative deltas, which is where
9//! the bits-per-edge budget comes from; unsorted input stays correct, just
10//! larger.
11
12use zu_common::{Result, ZuError};
13
14use crate::for_bitpack;
15
16#[inline]
17pub(crate) fn zigzag(v: i64) -> u64 {
18    ((v << 1) ^ (v >> 63)) as u64
19}
20
21#[inline]
22pub(crate) fn unzigzag(v: u64) -> i64 {
23    ((v >> 1) as i64) ^ -((v & 1) as i64)
24}
25
26/// Encodes `values` into `out`, returning the encoded byte length.
27pub fn encode(values: &[u64], out: &mut Vec<u8>) -> usize {
28    let start = out.len();
29    let base = values.first().copied().unwrap_or(0);
30    out.extend_from_slice(&base.to_le_bytes());
31    let mut deltas = Vec::with_capacity(values.len());
32    let mut prev = base;
33    for &v in values {
34        deltas.push(zigzag(v.wrapping_sub(prev) as i64));
35        prev = v;
36    }
37    for_bitpack::encode(&deltas, out);
38    out.len() - start
39}
40
41/// Decodes an encoded buffer, appending at most `max_values` values to
42/// `out`; a container claiming more is rejected before allocation.
43pub fn decode(bytes: &[u8], max_values: usize, out: &mut Vec<u64>) -> Result<()> {
44    let base_bytes = bytes.get(..8).ok_or_else(|| ZuError::Corrupt {
45        what: "delta",
46        detail: "truncated base".to_string(),
47    })?;
48    let mut prev = u64::from_le_bytes(base_bytes.try_into().unwrap());
49    for_bitpack::decode_chunks(&bytes[8..], max_values, |min, scratch, take| {
50        out.extend(scratch[..take].iter().map(|&v| {
51            prev = prev.wrapping_add(unzigzag(min.wrapping_add(v)) as u64);
52            prev
53        }));
54    })?;
55    Ok(())
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn roundtrip_sorted() {
64        let values: Vec<u64> = (0..5000u64).map(|i| i * 7 + (i % 3)).collect();
65        let mut buf = Vec::new();
66        encode(&values, &mut buf);
67        let mut out = Vec::new();
68        decode(&buf, values.len(), &mut out).unwrap();
69        assert_eq!(values, out);
70    }
71
72    #[test]
73    fn roundtrip_unsorted_and_extremes() {
74        let values = vec![u64::MAX, 0, 1, u64::MAX / 2, 3, 3, 2];
75        let mut buf = Vec::new();
76        encode(&values, &mut buf);
77        let mut out = Vec::new();
78        decode(&buf, values.len(), &mut out).unwrap();
79        assert_eq!(values, out);
80    }
81
82    #[test]
83    fn sorted_ids_compress_hard() {
84        // 100k sorted ids with gaps around 20: about 6 bits each after
85        // zigzag, so the payload must land well under 2 bytes per value.
86        let mut rng = 0x9E3779B97F4A7C15u64;
87        let mut v = 0u64;
88        let values: Vec<u64> = (0..100_000)
89            .map(|_| {
90                rng ^= rng << 13;
91                rng ^= rng >> 7;
92                rng ^= rng << 17;
93                v += rng % 40;
94                v
95            })
96            .collect();
97        let mut buf = Vec::new();
98        let len = encode(&values, &mut buf);
99        assert!(len < values.len() * 2, "got {} bytes", len);
100    }
101}