Skip to main content

zu_encoding/
delta_patch.rs

1//! Delta plus patched bit packing (encoding id 12).
2//!
3//! Same front end as encoding id 5: `base: u64 LE`, then zigzag deltas
4//! with the running previous seeded from the base. The difference is the
5//! container: deltas go through `patch` instead of `for_bitpack`, so a
6//! rare wide gap becomes an exception instead of setting the packed
7//! width for its whole 1024-value chunk. This is the encoding CSR
8//! adjacency wants: within a neighbor list the gaps are small, and the
9//! hub jumps and list restarts that used to price every chunk at 23 bits
10//! on LiveJournal move into the exception stream.
11
12use zu_common::{Result, ZuError};
13
14use crate::delta::{unzigzag, zigzag};
15use crate::patch;
16
17/// Encodes `values` into `out`, returning the encoded byte length.
18pub fn encode(values: &[u64], out: &mut Vec<u8>) -> usize {
19    let start = out.len();
20    let base = values.first().copied().unwrap_or(0);
21    out.extend_from_slice(&base.to_le_bytes());
22    let mut deltas = Vec::with_capacity(values.len());
23    let mut prev = base;
24    for &v in values {
25        deltas.push(zigzag(v.wrapping_sub(prev) as i64));
26        prev = v;
27    }
28    patch::encode(&deltas, out);
29    out.len() - start
30}
31
32/// Decodes an encoded buffer, appending at most `max_values` values to
33/// `out`; a container claiming more is rejected before allocation.
34pub fn decode(bytes: &[u8], max_values: usize, out: &mut Vec<u64>) -> Result<()> {
35    let base_bytes = bytes.get(..8).ok_or_else(|| ZuError::Corrupt {
36        what: "delta_patch",
37        detail: "truncated base".to_string(),
38    })?;
39    let mut prev = u64::from_le_bytes(base_bytes.try_into().unwrap());
40    patch::decode_chunks(&bytes[8..], max_values, |deltas, take| {
41        out.extend(deltas[..take].iter().map(|&d| {
42            prev = prev.wrapping_add(unzigzag(d) as u64);
43            prev
44        }));
45    })?;
46    Ok(())
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    fn roundtrip(values: &[u64]) -> usize {
54        let mut buf = Vec::new();
55        let len = encode(values, &mut buf);
56        let mut out = Vec::new();
57        decode(&buf, values.len(), &mut out).unwrap();
58        assert_eq!(values, out.as_slice());
59        len
60    }
61
62    #[test]
63    fn adjacency_shape_beats_plain_delta() {
64        // Concatenated sorted neighbor lists: 14 tight ids per list, one
65        // hub near zero, list starts scattered over 4M ids. Every list
66        // carries two wide deltas (the restart and the hub jump), so the
67        // floor for this shape is about 10 bits; plain delta pays ~23 for
68        // every value.
69        let mut rng = 0x9E3779B97F4A7C15u64;
70        let mut values = Vec::new();
71        for list in 0..10_000u64 {
72            let anchor = (list.wrapping_mul(0x2545F4914F6CDD1D) % 4_000_000).max(1);
73            values.push(anchor % 1000); // hub neighbor, low id
74            let mut v = anchor;
75            for _ in 0..13 {
76                rng ^= rng << 13;
77                rng ^= rng >> 7;
78                rng ^= rng << 17;
79                v += 1 + rng % 30;
80                values.push(v);
81            }
82        }
83        let len = roundtrip(&values);
84        assert!(
85            len * 8 < values.len() * 11,
86            "got {} bits/value",
87            len * 8 / values.len()
88        );
89        let mut plain = Vec::new();
90        crate::delta::encode(&values, &mut plain);
91        assert!(
92            len * 2 < plain.len(),
93            "patched {} vs delta {}",
94            len,
95            plain.len()
96        );
97    }
98
99    #[test]
100    fn unsorted_extremes_roundtrip() {
101        roundtrip(&[]);
102        roundtrip(&[u64::MAX, 0, 1, u64::MAX / 2, 3, 3, 2]);
103    }
104
105    #[test]
106    fn truncated_base_rejected() {
107        let mut out = Vec::new();
108        assert!(decode(&[1, 2, 3], 16, &mut out).is_err());
109    }
110}