Skip to main content

turbo_tasks_hash/
xxh3_hash128.rs

1use std::hash::Hasher;
2
3use xxhash_rust::xxh3::Xxh3Default;
4
5use crate::{DeterministicHash, DeterministicHasher};
6
7/// Hash some content with the Xxh3Hash128 non-cryptographic hash function.
8pub fn hash_xxh3_hash128<T: DeterministicHash>(input: T) -> [u8; 16] {
9    let mut hasher = Xxh3Hash128Hasher::new();
10    input.deterministic_hash(&mut hasher);
11    hasher.finish_bytes()
12}
13
14/// Xxh3Hash128 hasher.
15pub struct Xxh3Hash128Hasher(Xxh3Default);
16
17impl Xxh3Hash128Hasher {
18    /// Create a new hasher.
19    pub fn new() -> Self {
20        Self(Xxh3Default::new())
21    }
22
23    /// Uses the DeterministicHash trait to hash the input in a
24    /// cross-platform way.
25    pub fn write_value<T: DeterministicHash>(&mut self, input: T) {
26        input.deterministic_hash(self);
27    }
28
29    /// Uses the DeterministicHash trait to hash the input in a
30    /// cross-platform way.
31    pub fn write_ref<T: DeterministicHash>(&mut self, input: &T) {
32        input.deterministic_hash(self);
33    }
34
35    /// Finish the hash computation and return the digest as bytes.
36    pub fn finish_bytes(&self) -> [u8; 16] {
37        self.0.digest128().to_le_bytes()
38    }
39
40    /// Finish the hash computation and return the digest as u128.
41    pub fn finish(&self) -> u128 {
42        self.0.digest128()
43    }
44}
45
46impl DeterministicHasher for Xxh3Hash128Hasher {
47    fn finish(&self) -> u64 {
48        panic!("use the Xxh3Hash128Hasher non-trait function instead");
49    }
50
51    fn write_bytes(&mut self, bytes: &[u8]) {
52        Xxh3Default::write(&mut self.0, bytes);
53    }
54}
55
56impl Default for Xxh3Hash128Hasher {
57    fn default() -> Self {
58        Self::new()
59    }
60}