Skip to main content

aoc/util/
hash.rs

1//! Provides fast [`HashSet`] and [`HashMap`] implementations based on a simplified implementation
2//! of the fast [rustc hash algorithm](https://github.com/rust-lang/rustc-hash) also used by
3//! [Firefox](https://nnethercote.github.io/2021/12/08/a-brutally-effective-hash-function-in-rust.html).
4//!
5//! By default, Rust's [`HashMap`] and [`HashSet`] use a [DDoS](https://en.wikipedia.org/wiki/Denial-of-service_attack)
6//! resistant but slower hashing algorithm. [`FxHasher`] is much faster (between 2x and 5x from my
7//! testing).
8use std::collections::{HashMap, HashSet};
9use std::hash::{BuildHasher, Hash, Hasher};
10
11const K: u64 = 0x517cc1b727220a95;
12
13/// Type alias for [`HashSet`] using [`FxHasher`].
14pub type FastSet<T> = HashSet<T, BuildFxHasher>;
15
16/// Type alias for [`HashMap`] using [`FxHasher`].
17pub type FastMap<K, V> = HashMap<K, V, BuildFxHasher>;
18
19/// Convenience methods to construct a [`FastSet`].
20pub trait FastSetExt<T> {
21    #[must_use]
22    fn new() -> Self;
23    #[must_use]
24    fn with_capacity(capacity: usize) -> Self;
25    #[must_use]
26    fn build<const N: usize>(array: [T; N]) -> Self;
27}
28
29impl<T: Eq + Hash> FastSetExt<T> for FastSet<T> {
30    fn new() -> Self {
31        Self::with_hasher(BuildFxHasher)
32    }
33
34    fn with_capacity(capacity: usize) -> Self {
35        Self::with_capacity_and_hasher(capacity, BuildFxHasher)
36    }
37
38    fn build<const N: usize>(array: [T; N]) -> Self {
39        Self::from_iter(array)
40    }
41}
42
43/// Convenience methods to construct a [`FastMap`].
44pub trait FastMapExt<K, V> {
45    #[must_use]
46    fn new() -> Self;
47    #[must_use]
48    fn with_capacity(capacity: usize) -> Self;
49    #[must_use]
50    fn build<const N: usize>(array: [(K, V); N]) -> Self;
51}
52
53impl<K: Eq + Hash, V> FastMapExt<K, V> for FastMap<K, V> {
54    fn new() -> Self {
55        Self::with_hasher(BuildFxHasher)
56    }
57
58    fn with_capacity(capacity: usize) -> Self {
59        Self::with_capacity_and_hasher(capacity, BuildFxHasher)
60    }
61
62    fn build<const N: usize>(array: [(K, V); N]) -> Self {
63        Self::from_iter(array)
64    }
65}
66
67/// If you want an instance of [`FxHasher`] then this has you covered.
68#[derive(Clone, Copy, Default)]
69pub struct BuildFxHasher;
70
71impl BuildHasher for BuildFxHasher {
72    type Hasher = FxHasher;
73
74    #[inline]
75    fn build_hasher(&self) -> Self::Hasher {
76        FxHasher { hash: 0 }
77    }
78}
79
80/// Simplified implementation. In particular, running on a system with 64-bit `usize` is assumed.
81///
82/// Check out the [Firefox code](https://searchfox.org/mozilla-central/rev/633345116df55e2d37be9be6555aa739656c5a7d/mfbt/HashFunctions.h#109-153)
83/// for a full description.
84pub struct FxHasher {
85    hash: u64,
86}
87
88impl FxHasher {
89    #[inline]
90    fn add(&mut self, i: u64) {
91        self.hash = (self.hash.rotate_left(5) ^ i).wrapping_mul(K);
92    }
93}
94
95impl Hasher for FxHasher {
96    #[inline]
97    fn write(&mut self, mut bytes: &[u8]) {
98        while let Some((&head, tail)) = bytes.split_first_chunk() {
99            self.add(u64::from_ne_bytes(head));
100            bytes = tail;
101        }
102        if let Some((&head, tail)) = bytes.split_first_chunk() {
103            self.add(u32::from_ne_bytes(head) as u64);
104            bytes = tail;
105        }
106        if let Some((&head, tail)) = bytes.split_first_chunk() {
107            self.add(u16::from_ne_bytes(head) as u64);
108            bytes = tail;
109        }
110        if !bytes.is_empty() {
111            self.add(bytes[0] as u64);
112        }
113    }
114
115    #[inline]
116    fn write_u8(&mut self, i: u8) {
117        self.add(i as u64);
118    }
119
120    #[inline]
121    fn write_u16(&mut self, i: u16) {
122        self.add(i as u64);
123    }
124
125    #[inline]
126    fn write_u32(&mut self, i: u32) {
127        self.add(i as u64);
128    }
129
130    #[inline]
131    fn write_u64(&mut self, i: u64) {
132        self.add(i);
133    }
134
135    #[inline]
136    fn write_usize(&mut self, i: usize) {
137        self.add(i as u64);
138    }
139
140    #[inline]
141    fn finish(&self) -> u64 {
142        self.hash
143    }
144}