1use twox_hash::XxHash3_128;
12
13pub const FNV64_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
15const FNV64_PRIME: u64 = 0x0000_0100_0000_01b3;
16const FNV32_OFFSET: u32 = 0x811c_9dc5;
17const FNV32_PRIME: u32 = 0x0100_0193;
18
19#[derive(Debug, Clone, Copy)]
21pub struct Fnv1a64(u64);
22
23impl Default for Fnv1a64 {
24 fn default() -> Self {
25 Self::new()
26 }
27}
28
29impl Fnv1a64 {
30 pub const fn new() -> Self {
31 Self(FNV64_OFFSET)
32 }
33
34 pub fn write(&mut self, bytes: &[u8]) -> &mut Self {
36 self.0 = fnv1a64_extend(self.0, bytes);
37 self
38 }
39
40 pub fn mix_word(&mut self, word: u64) -> &mut Self {
43 self.0 ^= word;
44 self.0 = self.0.wrapping_mul(FNV64_PRIME);
45 self
46 }
47
48 pub const fn finish(&self) -> u64 {
49 self.0
50 }
51}
52
53pub fn fnv1a64_extend(state: u64, bytes: &[u8]) -> u64 {
56 bytes.iter().fold(state, |h, &b| (h ^ u64::from(b)).wrapping_mul(FNV64_PRIME))
57}
58
59pub fn fnv1a64(bytes: &[u8]) -> u64 {
61 Fnv1a64::new().write(bytes).finish()
62}
63
64pub fn fnv1a32(bytes: &[u8]) -> u32 {
66 bytes.iter().fold(FNV32_OFFSET, |h, &b| (h ^ u32::from(b)).wrapping_mul(FNV32_PRIME))
67}
68
69pub struct ContentHash(XxHash3_128);
72
73impl Default for ContentHash {
74 fn default() -> Self {
75 Self::new()
76 }
77}
78
79impl ContentHash {
80 pub fn new() -> Self {
81 Self(XxHash3_128::new())
82 }
83
84 pub fn write(&mut self, bytes: &[u8]) -> &mut Self {
85 self.0.write(bytes);
86 self
87 }
88
89 pub fn write_u64(&mut self, v: u64) -> &mut Self {
90 self.write(&v.to_le_bytes())
91 }
92
93 pub fn write_f32s(&mut self, data: &[f32]) -> &mut Self {
96 self.write_u64(data.len() as u64);
97 self.write(bytemuck::cast_slice::<f32, u8>(data))
98 }
99
100 pub fn write_u32s(&mut self, data: &[u32]) -> &mut Self {
102 self.write_u64(data.len() as u64);
103 self.write(bytemuck::cast_slice::<u32, u8>(data))
104 }
105
106 pub fn finish(&self) -> u128 {
107 self.0.finish_128()
108 }
109}
110
111#[cfg(test)]
112#[path = "hash_tests.rs"]
113mod tests;