Skip to main content

ahash/
lib.rs

1//! AHash is a high performance keyed hash function.
2//!
3//! It quickly provides a high quality hash where the result is not predictable without knowing the Key.
4//! AHash works with `HashMap` to hash keys, but without allowing for the possibility that a malicious user can
5//! induce a collision.
6//!
7//! # How aHash works
8//!
9//! When it is available aHash uses the hardware AES instructions to provide a keyed hash function.
10//! When it is not, aHash falls back on a slightly slower alternative algorithm.
11//!
12//! Because aHash does not have a fixed standard for its output, it is able to improve over time.
13//! But this also means that different computers or computers using different versions of ahash may observe different
14//! hash values for the same input.
15#![cfg_attr(
16    all(
17        feature = "std",
18        any(feature = "compile-time-rng", feature = "runtime-rng", feature = "no-rng")
19    ),
20    doc = r##"
21# Basic Usage
22AHash provides an implementation of the [Hasher] trait.
23To construct a HashMap using aHash as its hasher do the following:
24```
25use ahash::{AHasher, RandomState};
26use std::collections::HashMap;
27
28let mut map: HashMap<i32, i32, RandomState> = HashMap::default();
29map.insert(12, 34);
30```
31
32### Randomness
33
34The above requires a source of randomness to generate keys for the hashmap. By default this obtained from the OS.
35It is also possible to have randomness supplied via the `compile-time-rng` flag, or manually.
36
37### If randomness is not available
38
39[AHasher::default()] can be used to hash using fixed keys. This works with
40[BuildHasherDefault](std::hash::BuildHasherDefault). For example:
41
42```
43use std::hash::BuildHasherDefault;
44use std::collections::HashMap;
45use ahash::AHasher;
46
47let mut m: HashMap<_, _, BuildHasherDefault<AHasher>> = HashMap::default();
48 # m.insert(12, 34);
49```
50It is also possible to instantiate [RandomState] directly:
51
52```
53use ahash::HashMap;
54use ahash::RandomState;
55
56let mut m = HashMap::with_hasher(RandomState::with_seed(42));
57 # m.insert(1, 2);
58```
59Or for uses besides a hashhmap:
60```
61use std::hash::BuildHasher;
62use ahash::RandomState;
63
64let hash_builder = RandomState::with_seed(42);
65let hash = hash_builder.hash_one("Some Data");
66```
67There are several constructors for [RandomState] with different ways to supply seeds.
68
69# Convenience wrappers
70
71For convenience, both new-type wrappers and type aliases are provided.
72
73The new type wrappers are called called `AHashMap` and `AHashSet`.
74```
75use ahash::AHashMap;
76
77let mut map: AHashMap<i32, i32> = AHashMap::new();
78map.insert(12, 34);
79```
80This avoids the need to type "RandomState". (For convenience `From`, `Into`, and `Deref` are provided).
81
82# Aliases
83
84For even less typing and better interop with existing libraries (such as rayon) which require a `std::collection::HashMap` ,
85the type aliases [HashMap], [HashSet] are provided.
86
87```
88use ahash::{HashMap, HashMapExt};
89
90let mut map: HashMap<i32, i32> = HashMap::new();
91map.insert(12, 34);
92```
93Note the import of [HashMapExt]. This is needed for the constructor.
94
95"##
96)]
97#![deny(clippy::correctness, clippy::complexity, clippy::perf)]
98#![allow(clippy::pedantic, clippy::cast_lossless, clippy::unreadable_literal)]
99#![cfg_attr(all(not(test), not(feature = "std")), no_std)]
100#![cfg_attr(specialize, feature(min_specialization))]
101#![cfg_attr(
102    all(feature = "nightly-arm-aes", target_arch = "arm", target_feature = "aes", not(miri)),
103    feature(stdarch_arm_neon_intrinsics)
104)]
105
106#[macro_use]
107mod convert;
108
109mod fallback_hash;
110
111cfg_if::cfg_if! {
112    if #[cfg(aes_hash)] {
113        mod aes_hash;
114        pub use crate::aes_hash::AHasher;
115    } else {
116        pub use crate::fallback_hash::AHasher;
117    }
118}
119
120cfg_if::cfg_if! {
121    if #[cfg(feature = "std")] {
122        mod hash_map;
123        mod hash_set;
124
125        pub use crate::hash_map::AHashMap;
126        pub use crate::hash_set::AHashSet;
127
128        /// [Hasher]: std::hash::Hasher
129        /// [HashMap]: std::collections::HashMap
130        /// Type alias for [HashMap]<K, V, ahash::RandomState>
131        pub type HashMap<K, V> = std::collections::HashMap<K, V, crate::RandomState>;
132
133        /// Type alias for [HashSet]<K, ahash::RandomState>
134        pub type HashSet<K> = std::collections::HashSet<K, crate::RandomState>;
135    }
136}
137
138#[cfg(test)]
139mod aes_hash_test;
140#[cfg(test)]
141mod hash_quality_test;
142
143mod operations;
144pub mod random_state;
145mod specialize;
146
147pub use crate::random_state::RandomState;
148
149use core::hash::BuildHasher;
150
151#[cfg(feature = "std")]
152/// A convenience trait that can be used together with the type aliases defined to
153/// get access to the `new()` and `with_capacity()` methods for the HashMap type alias.
154pub trait HashMapExt {
155    /// Constructs a new HashMap
156    fn new() -> Self;
157    /// Constructs a new HashMap with a given initial capacity
158    fn with_capacity(capacity: usize) -> Self;
159}
160
161#[cfg(feature = "std")]
162/// A convenience trait that can be used together with the type aliases defined to
163/// get access to the `new()` and `with_capacity()` methods for the HashSet type aliases.
164pub trait HashSetExt {
165    /// Constructs a new HashSet
166    fn new() -> Self;
167    /// Constructs a new HashSet with a given initial capacity
168    fn with_capacity(capacity: usize) -> Self;
169}
170
171#[cfg(feature = "std")]
172impl<K, V, S> HashMapExt for std::collections::HashMap<K, V, S>
173where
174    S: BuildHasher + Default,
175{
176    fn new() -> Self {
177        std::collections::HashMap::with_hasher(S::default())
178    }
179
180    fn with_capacity(capacity: usize) -> Self {
181        std::collections::HashMap::with_capacity_and_hasher(capacity, S::default())
182    }
183}
184
185#[cfg(feature = "std")]
186impl<K, S> HashSetExt for std::collections::HashSet<K, S>
187where
188    S: BuildHasher + Default,
189{
190    fn new() -> Self {
191        std::collections::HashSet::with_hasher(S::default())
192    }
193
194    fn with_capacity(capacity: usize) -> Self {
195        std::collections::HashSet::with_capacity_and_hasher(capacity, S::default())
196    }
197}
198
199/// Provides a default [Hasher] with fixed keys.
200/// This is typically used in conjunction with [BuildHasherDefault] to create
201/// [AHasher]s in order to hash the keys of the map.
202///
203/// Generally it is preferable to use [RandomState] instead, so that different
204/// hashmaps will have different keys. However if fixed keys are desirable this
205/// may be used instead.
206///
207/// # Example
208/// ```
209/// use std::hash::BuildHasherDefault;
210/// use ahash::{AHasher, RandomState};
211/// use std::collections::HashMap;
212///
213/// let mut map: HashMap<i32, i32, BuildHasherDefault<AHasher>> = HashMap::default();
214/// map.insert(12, 34);
215/// ```
216///
217/// [BuildHasherDefault]: std::hash::BuildHasherDefault
218/// [Hasher]: std::hash::Hasher
219/// [HashMap]: std::collections::HashMap
220impl Default for AHasher {
221    /// Constructs a new [AHasher] with fixed keys.
222    /// If `std` is enabled these will be generated upon first invocation.
223    /// Otherwise if the `compile-time-rng`feature is enabled these will be generated at compile time.
224    /// If neither of these features are available, hardcoded constants will be used.
225    ///
226    /// Because the values are fixed, different hashers will all hash elements the same way.
227    /// This could make hash values predictable, if DOS attacks are a concern. If this behaviour is
228    /// not required, it may be preferable to use [RandomState] instead.
229    ///
230    /// # Examples
231    ///
232    /// ```
233    /// use ahash::AHasher;
234    /// use std::hash::Hasher;
235    ///
236    /// let mut hasher_1 = AHasher::default();
237    /// let mut hasher_2 = AHasher::default();
238    ///
239    /// hasher_1.write_u32(1234);
240    /// hasher_2.write_u32(1234);
241    ///
242    /// assert_eq!(hasher_1.finish(), hasher_2.finish());
243    /// ```
244    #[inline]
245    fn default() -> AHasher {
246        RandomState::with_fixed_keys().build_hasher()
247    }
248}
249
250// #[inline(never)]
251// #[doc(hidden)]
252// pub fn hash_test(input: &[u8]) -> u64 {
253//     let a = RandomState::with_seeds(11, 22, 33, 44);
254//     <[u8]>::get_hash(input, &a)
255// }
256
257#[cfg(feature = "std")]
258#[cfg(test)]
259mod test {
260    use crate::convert::Convert;
261    use crate::specialize::CallHasher;
262    use crate::*;
263    use core::hash::Hash;
264    use core::hash::Hasher;
265    use std::collections::HashMap;
266
267    #[test]
268    fn test_ahash_alias_map_construction() {
269        let mut map = super::HashMap::with_capacity(1234);
270        map.insert(1, "test");
271    }
272
273    #[test]
274    fn test_ahash_alias_set_construction() {
275        let mut set = super::HashSet::with_capacity(1234);
276        set.insert(1);
277    }
278
279    #[test]
280    fn test_default_builder() {
281        use core::hash::BuildHasherDefault;
282
283        let mut map = HashMap::<u32, u64, BuildHasherDefault<AHasher>>::default();
284        map.insert(1, 3);
285    }
286
287    #[test]
288    fn test_builder() {
289        let mut map = HashMap::<u32, u64, RandomState>::default();
290        map.insert(1, 3);
291    }
292
293    #[test]
294    fn test_conversion() {
295        let input: &[u8] = b"dddddddd";
296        let bytes: u64 = as_array!(input, 8).convert();
297        assert_eq!(bytes, 0x6464646464646464);
298    }
299
300    #[test]
301    fn test_non_zero() {
302        let mut hasher1 = AHasher::new_with_keys(0, 0);
303        let mut hasher2 = AHasher::new_with_keys(0, 0);
304        "foo".hash(&mut hasher1);
305        "bar".hash(&mut hasher2);
306        assert_ne!(hasher1.finish(), 0);
307        assert_ne!(hasher2.finish(), 0);
308        assert_ne!(hasher1.finish(), hasher2.finish());
309
310        let mut hasher1 = AHasher::new_with_keys(0, 0);
311        let mut hasher2 = AHasher::new_with_keys(0, 0);
312        3_u64.hash(&mut hasher1);
313        4_u64.hash(&mut hasher2);
314        assert_ne!(hasher1.finish(), 0);
315        assert_ne!(hasher2.finish(), 0);
316        assert_ne!(hasher1.finish(), hasher2.finish());
317    }
318
319    #[test]
320    fn test_non_zero_specialized() {
321        let hasher_build = RandomState::with_seeds(0, 0, 0, 0);
322
323        let h1 = str::get_hash("foo", &hasher_build);
324        let h2 = str::get_hash("bar", &hasher_build);
325        assert_ne!(h1, 0);
326        assert_ne!(h2, 0);
327        assert_ne!(h1, h2);
328
329        let h1 = u64::get_hash(&3_u64, &hasher_build);
330        let h2 = u64::get_hash(&4_u64, &hasher_build);
331        assert_ne!(h1, 0);
332        assert_ne!(h2, 0);
333        assert_ne!(h1, h2);
334    }
335
336    #[test]
337    fn test_ahasher_construction() {
338        let _ = AHasher::new_with_keys(1234, 5678);
339    }
340
341    #[test]
342    fn test_specialize_reference_hash() {
343        let hasher_build = RandomState::with_seeds(0, 0, 0, 0);
344        let h1 = hasher_build.hash_one(1u64);
345        let h2 = hasher_build.hash_one(&1u64);
346
347        assert_eq!(h1, h2);
348
349        let h1 = u64::get_hash(&1_u64, &hasher_build);
350        let h2 = <&u64>::get_hash(&&1_u64, &hasher_build);
351
352        assert_eq!(h1, h2);
353
354        let h1 = hasher_build.hash_one(1u128);
355        let h2 = hasher_build.hash_one(&1u128);
356
357        assert_eq!(h1, h2);
358    }
359}