Skip to main content

zstd_native/
xxhash.rs

1//! XXH64, the content checksum of zstd frames (the low 32 bits are stored).
2
3const P1: u64 = 0x9E37_79B1_85EB_CA87;
4const P2: u64 = 0xC2B2_AE3D_27D4_EB4F;
5const P3: u64 = 0x1656_67B1_9E37_79F9;
6const P4: u64 = 0x85EB_CA77_C2B2_AE63;
7const P5: u64 = 0x27D4_EB2F_1656_67C5;
8
9#[inline(always)]
10fn read64(b: &[u8]) -> u64 {
11    u64::from_le_bytes(b[..8].try_into().unwrap())
12}
13
14#[inline(always)]
15fn read32(b: &[u8]) -> u32 {
16    u32::from_le_bytes(b[..4].try_into().unwrap())
17}
18
19#[inline(always)]
20fn round(acc: u64, input: u64) -> u64 {
21    acc.wrapping_add(input.wrapping_mul(P2))
22        .rotate_left(31)
23        .wrapping_mul(P1)
24}
25
26#[inline(always)]
27fn merge_round(acc: u64, val: u64) -> u64 {
28    (acc ^ round(0, val)).wrapping_mul(P1).wrapping_add(P4)
29}
30
31/// Streaming XXH64 with seed 0.
32#[derive(Clone)]
33pub(crate) struct Xxh64 {
34    v: [u64; 4],
35    buf: [u8; 32],
36    buf_len: usize,
37    total: u64,
38}
39
40impl core::fmt::Debug for Xxh64 {
41    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
42        f.debug_struct("Xxh64")
43            .field("total", &self.total)
44            .finish_non_exhaustive()
45    }
46}
47
48impl Default for Xxh64 {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54impl Xxh64 {
55    pub(crate) const fn new() -> Self {
56        Xxh64 {
57            v: [P1.wrapping_add(P2), P2, 0, 0u64.wrapping_sub(P1)],
58            buf: [0; 32],
59            buf_len: 0,
60            total: 0,
61        }
62    }
63
64    #[inline]
65    fn stripes(v: &mut [u64; 4], data: &[u8]) {
66        let (mut a, mut b, mut c, mut d) = (v[0], v[1], v[2], v[3]);
67        for s in data.as_chunks::<32>().0 {
68            a = round(a, read64(&s[0..]));
69            b = round(b, read64(&s[8..]));
70            c = round(c, read64(&s[16..]));
71            d = round(d, read64(&s[24..]));
72        }
73        *v = [a, b, c, d];
74    }
75
76    pub(crate) fn update(&mut self, mut data: &[u8]) {
77        self.total += data.len() as u64;
78        if self.buf_len > 0 {
79            let take = (32 - self.buf_len).min(data.len());
80            self.buf[self.buf_len..self.buf_len + take].copy_from_slice(&data[..take]);
81            self.buf_len += take;
82            data = &data[take..];
83            if self.buf_len < 32 {
84                return;
85            }
86            let buf = self.buf;
87            Self::stripes(&mut self.v, &buf);
88            self.buf_len = 0;
89        }
90        let full = data.len() & !31;
91        Self::stripes(&mut self.v, &data[..full]);
92        let rest = &data[full..];
93        self.buf[..rest.len()].copy_from_slice(rest);
94        self.buf_len = rest.len();
95    }
96
97    pub(crate) fn digest(&self) -> u64 {
98        let mut h = if self.total >= 32 {
99            let [a, b, c, d] = self.v;
100            let mut h = a
101                .rotate_left(1)
102                .wrapping_add(b.rotate_left(7))
103                .wrapping_add(c.rotate_left(12))
104                .wrapping_add(d.rotate_left(18));
105            h = merge_round(h, a);
106            h = merge_round(h, b);
107            h = merge_round(h, c);
108            merge_round(h, d)
109        } else {
110            self.v[2].wrapping_add(P5)
111        };
112        h = h.wrapping_add(self.total);
113        finalize(h, &self.buf[..self.buf_len])
114    }
115}
116
117fn finalize(mut h: u64, mut rest: &[u8]) -> u64 {
118    while rest.len() >= 8 {
119        h ^= round(0, read64(rest));
120        h = h.rotate_left(27).wrapping_mul(P1).wrapping_add(P4);
121        rest = &rest[8..];
122    }
123    if rest.len() >= 4 {
124        h ^= u64::from(read32(rest)).wrapping_mul(P1);
125        h = h.rotate_left(23).wrapping_mul(P2).wrapping_add(P3);
126        rest = &rest[4..];
127    }
128    for &b in rest {
129        h ^= u64::from(b).wrapping_mul(P5);
130        h = h.rotate_left(11).wrapping_mul(P1);
131    }
132    h ^= h >> 33;
133    h = h.wrapping_mul(P2);
134    h ^= h >> 29;
135    h = h.wrapping_mul(P3);
136    h ^ (h >> 32)
137}
138
139/// XXH64 of `data` with seed 0.
140pub fn xxh64(data: &[u8]) -> u64 {
141    let mut s = Xxh64::new();
142    s.update(data);
143    s.digest()
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    #[test]
151    fn known_values() {
152        assert_eq!(xxh64(b""), 0xEF46_DB37_51D8_E999);
153        assert_eq!(xxh64(b"a"), 0xD24E_C4F1_A98C_6E5B);
154        assert_eq!(xxh64(b"abc"), 0x44BC_2CF5_AD77_0999);
155        assert_eq!(
156            xxh64(b"Nobody inspects the spammish repetition"),
157            0xFBCE_A83C_8A37_8BF1
158        );
159    }
160
161    #[test]
162    fn streaming_matches_oneshot() {
163        let data: alloc::vec::Vec<u8> = (0..1000u32).map(|i| (i * 7 + i / 13) as u8).collect();
164        for split in [0, 1, 5, 31, 32, 33, 64, 100, 999, 1000] {
165            let mut s = Xxh64::new();
166            s.update(&data[..split]);
167            s.update(&data[split..]);
168            assert_eq!(s.digest(), xxh64(&data), "split {split}");
169        }
170    }
171}