statsig_rust/hashing/
ahash.rs

1use ahash::RandomState;
2use std::hash::Hash;
3
4lazy_static::lazy_static! {
5    pub static ref HASHER: RandomState = RandomState::new();
6}
7
8/// Uses the ahash crate: https://crates.io/crates/ahash
9/// - Faster than djb2.
10/// - Randomized between each run of an application.
11/// - Non-cryptographic.
12/// - One way hash.
13///
14/// **Profiled**
15///
16/// djb2  time: 4.1869 ns
17///
18/// ahash time: 1.5757 ns
19///
20#[must_use]
21pub fn ahash_str(input: &str) -> u64 {
22    HASHER.hash_one(input)
23}
24
25pub fn hash_one<T: Hash>(x: T) -> u64 {
26    HASHER.hash_one(x)
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32    use std::collections::HashSet;
33    #[test]
34    fn test_gets_same_result_for_same_input() {
35        let input = "some_random_input";
36        let mut result = ahash_str(input);
37        for _ in 0..1000 {
38            let new_result = ahash_str(input);
39            assert_eq!(result, new_result);
40            result = new_result;
41        }
42    }
43
44    #[test]
45    fn test_gets_different_result_for_different_input() {
46        let mut seen = HashSet::new();
47        for i in 0..100_000 {
48            let result = ahash_str(&format!("iter_{i}"));
49            assert!(!seen.contains(&result));
50            seen.insert(result);
51        }
52    }
53}