turbo_tasks_hash/
xxh3_hash64.rs

1use std::hash::Hasher;
2
3use twox_hash::xxh3::{self, HasherExt};
4
5use crate::{DeterministicHash, DeterministicHasher};
6
7/// Hash some content with the Xxh3Hash64 non-cryptographic hash function.
8pub fn hash_xxh3_hash64<T: DeterministicHash>(input: T) -> u64 {
9    let mut hasher = Xxh3Hash64Hasher::new();
10    input.deterministic_hash(&mut hasher);
11    hasher.finish()
12}
13
14/// Hash some content with the Xxh3Hash128 non-cryptographic hash function. This longer hash is
15/// useful for avoiding collisions.
16pub fn hash_xxh3_hash128<T: DeterministicHash>(input: T) -> u128 {
17    // this isn't fully compatible with the 64-bit Hasher/DeterministicHasher APIs, so just use a
18    // private impl for this
19    struct Xxh3Hash128Hasher(xxh3::Hash128);
20
21    impl DeterministicHasher for Xxh3Hash128Hasher {
22        fn finish(&self) -> u64 {
23            unimplemented!("call self.0.finish_ext() instead!")
24        }
25
26        fn write_bytes(&mut self, bytes: &[u8]) {
27            self.0.write(bytes);
28        }
29    }
30
31    let mut hasher = Xxh3Hash128Hasher(xxh3::Hash128::with_seed(0));
32    input.deterministic_hash(&mut hasher);
33    hasher.0.finish_ext()
34}
35
36/// Xxh3Hash64 hasher.
37pub struct Xxh3Hash64Hasher(xxh3::Hash64);
38
39impl Xxh3Hash64Hasher {
40    /// Create a new hasher.
41    pub fn new() -> Self {
42        Self(xxh3::Hash64::with_seed(0))
43    }
44
45    /// Uses the DeterministicHash trait to hash the input in a
46    /// cross-platform way.
47    pub fn write_value<T: DeterministicHash>(&mut self, input: T) {
48        input.deterministic_hash(self);
49    }
50
51    /// Uses the DeterministicHash trait to hash the input in a
52    /// cross-platform way.
53    pub fn write_ref<T: DeterministicHash>(&mut self, input: &T) {
54        input.deterministic_hash(self);
55    }
56
57    /// Finish the hash computation and return the digest.
58    pub fn finish(&self) -> u64 {
59        self.0.finish()
60    }
61}
62
63impl DeterministicHasher for Xxh3Hash64Hasher {
64    fn finish(&self) -> u64 {
65        self.0.finish()
66    }
67
68    fn write_bytes(&mut self, bytes: &[u8]) {
69        self.0.write(bytes);
70    }
71}
72
73impl Default for Xxh3Hash64Hasher {
74    fn default() -> Self {
75        Self::new()
76    }
77}