Skip to main content

ahash/
random_state.rs

1use core::hash::Hash;
2
3#[cfg(feature = "serde")]
4use serde::{Deserialize, Serialize};
5
6cfg_if::cfg_if! {
7    if #[cfg(aes_hash)] {
8        use crate::aes_hash::*;
9    } else {
10        use crate::fallback_hash::*;
11    }
12}
13cfg_if::cfg_if! {
14    if #[cfg(feature = "std")] {
15        extern crate std as alloc;
16    } else {
17        extern crate alloc;
18    }
19}
20
21#[cfg(not(feature = "atomic-polyfill"))]
22use core::sync::atomic;
23#[cfg(feature = "atomic-polyfill")]
24use portable_atomic as atomic;
25
26use alloc::boxed::Box;
27use atomic::{AtomicUsize, Ordering};
28use core::any::{Any, TypeId};
29use core::fmt;
30use core::hash::BuildHasher;
31use core::hash::Hasher;
32
33pub(crate) const PI_U64X4: [u64; 4] = [
34    0x243f_6a88_85a3_08d3,
35    0x1319_8a2e_0370_7344,
36    0xa409_3822_299f_31d0,
37    0x082e_fa98_ec4e_6c89,
38];
39
40pub(crate) const PI_U128X2: [u128; 2] = [
41    0x1319_8a2e_0370_7344_243f_6a88_85a3_08d3,
42    0x082e_fa98_ec4e_6c89_a409_3822_299f_31d0,
43];
44
45pub(crate) const PI2: [u64; 4] = [
46    0x4528_21e6_38d0_1377,
47    0xbe54_66cf_34e9_0c6c,
48    0xc0ac_29b7_c97c_50dd,
49    0x3f84_d5b5_b547_0917,
50];
51
52cfg_if::cfg_if! {
53    if #[cfg(all(feature = "compile-time-rng", any(test, fuzzing)))] {
54        #[inline]
55        fn get_fixed_seeds() -> &'static [[u64; 4]; 2] {
56            use const_random::const_random;
57
58            const RAND: [[u64; 4]; 2] = [
59                [
60                    const_random!(u64),
61                    const_random!(u64),
62                    const_random!(u64),
63                    const_random!(u64),
64                ], [
65                    const_random!(u64),
66                    const_random!(u64),
67                    const_random!(u64),
68                    const_random!(u64),
69                ]
70            ];
71            &RAND
72        }
73    } else if #[cfg(all(feature = "runtime-rng", not(fuzzing)))] {
74        #[inline]
75        fn get_fixed_seeds() -> &'static [[u64; 4]; 2] {
76            use crate::convert::Convert;
77
78            static SEEDS: OnceBox<[[u64; 4]; 2]> = OnceBox::new();
79
80            SEEDS.get_or_init(|| {
81                let mut result: [u8; 64] = [0; 64];
82                getrandom::fill(&mut result).expect("getrandom::fill() failed.");
83                Box::new(result.convert())
84            })
85        }
86    } else if #[cfg(feature = "compile-time-rng")] {
87        #[inline]
88        fn get_fixed_seeds() -> &'static [[u64; 4]; 2] {
89            use const_random::const_random;
90
91            const RAND: [[u64; 4]; 2] = [
92                [
93                    const_random!(u64),
94                    const_random!(u64),
95                    const_random!(u64),
96                    const_random!(u64),
97                ], [
98                    const_random!(u64),
99                    const_random!(u64),
100                    const_random!(u64),
101                    const_random!(u64),
102                ]
103            ];
104            &RAND
105        }
106    } else {
107        #[inline]
108        fn get_fixed_seeds() -> &'static [[u64; 4]; 2] {
109            &[PI_U64X4, PI2]
110        }
111    }
112}
113
114cfg_if::cfg_if! {
115    if #[cfg(not(all(target_arch = "arm", target_os = "none")))] {
116        use once_cell::race::OnceBox;
117
118        static RAND_SOURCE: OnceBox<Box<dyn RandomSource + Send + Sync>> = OnceBox::new();
119    }
120}
121/// A supplier of Randomness used for different hashers.
122/// See [set_random_source].
123///
124/// If [set_random_source] aHash will default to the best available source of randomness.
125/// In order this is:
126/// 1. OS provided random number generator (available if the `runtime-rng` flag is enabled which it is by default) - This should be very strong.
127/// 2. Strong compile time random numbers used to permute a static "counter". (available if `compile-time-rng` is enabled.
128/// __Enabling this is recommended if `runtime-rng` is not possible__)
129/// 3. A static counter that adds the memory address of each [RandomState] created permuted with fixed constants.
130/// (Similar to above but with fixed keys) - This is the weakest option. The strength of this heavily depends on whether or not ASLR is enabled.
131/// (Rust enables ASLR by default)
132pub trait RandomSource {
133    fn gen_hasher_seed(&self) -> usize;
134}
135
136struct DefaultRandomSource {
137    counter: AtomicUsize,
138}
139
140impl DefaultRandomSource {
141    fn new() -> DefaultRandomSource {
142        DefaultRandomSource {
143            counter: AtomicUsize::new(&PI_U64X4 as *const _ as usize),
144        }
145    }
146
147    #[cfg(all(target_arch = "arm", target_os = "none"))]
148    const fn default() -> DefaultRandomSource {
149        DefaultRandomSource {
150            counter: AtomicUsize::new(PI_U64X4[3] as usize),
151        }
152    }
153}
154
155impl RandomSource for DefaultRandomSource {
156    cfg_if::cfg_if! {
157        if #[cfg(all(target_arch = "arm", target_os = "none"))] {
158            fn gen_hasher_seed(&self) -> usize {
159                let stack = self as *const _ as usize;
160                let previous = self.counter.load(Ordering::Relaxed);
161                let new = previous.wrapping_add(stack);
162                self.counter.store(new, Ordering::Relaxed);
163                new
164            }
165        } else {
166            fn gen_hasher_seed(&self) -> usize {
167                let stack = self as *const _ as usize;
168                self.counter.fetch_add(stack, Ordering::Relaxed)
169            }
170        }
171    }
172}
173
174cfg_if::cfg_if! {
175        if #[cfg(all(target_arch = "arm", target_os = "none"))] {
176            #[inline]
177            fn get_src() -> &'static dyn RandomSource {
178                static RAND_SOURCE: DefaultRandomSource = DefaultRandomSource::default();
179                &RAND_SOURCE
180            }
181        } else {
182            /// Provides an optional way to manually supply a source of randomness for Hasher keys.
183            ///
184            /// The provided [RandomSource] will be used to be used as a source of randomness by [RandomState] to generate new states.
185            /// If this method is not invoked the standard source of randomness is used as described in the Readme.
186            ///
187            /// The source of randomness can only be set once, and must be set before the first RandomState is created.
188            /// If the source has already been specified `Err` is returned with a `bool` indicating if the set failed because
189            /// method was previously invoked (true) or if the default source is already being used (false).
190            #[cfg(not(all(target_arch = "arm", target_os = "none")))]
191            pub fn set_random_source(source: impl RandomSource + Send + Sync + 'static) -> Result<(), bool> {
192                RAND_SOURCE.set(Box::new(Box::new(source))).map_err(|s| s.as_ref().type_id() != TypeId::of::<&DefaultRandomSource>())
193            }
194
195            #[inline]
196            fn get_src() -> &'static dyn RandomSource {
197                RAND_SOURCE.get_or_init(|| Box::new(Box::new(DefaultRandomSource::new()))).as_ref()
198            }
199        }
200}
201
202/// Provides a [Hasher] factory. This is typically used (e.g. by [HashMap]) to create
203/// [AHasher]s in order to hash the keys of the map. See `build_hasher` below.
204///
205/// [build_hasher]: ahash::
206/// [Hasher]: std::hash::Hasher
207/// [BuildHasher]: std::hash::BuildHasher
208/// [HashMap]: std::collections::HashMap
209///
210/// There are multiple constructors each is documented in more detail below:
211///
212/// | Constructor   | Dynamically random? | Seed |
213/// |---------------|---------------------|------|
214/// |`new`          | Each instance unique|_[RandomSource]_|
215/// |`generate_with`| Each instance unique|`u64` x 4 + [RandomSource]|
216/// |`with_seed`    | Fixed per process   |`u64` + static random number|
217/// |`with_seeds`   | Fixed               |`u64` x 4|
218///
219#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
220#[derive(Clone)]
221pub struct RandomState {
222    pub(crate) k0: u64,
223    pub(crate) k1: u64,
224    pub(crate) k2: u64,
225    pub(crate) k3: u64,
226}
227
228impl fmt::Debug for RandomState {
229    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
230        f.pad("RandomState { .. }")
231    }
232}
233
234impl RandomState {
235    /// Create a new `RandomState` `BuildHasher` using random keys.
236    ///
237    /// Each instance will have a unique set of keys derived from [RandomSource].
238    ///
239    #[inline]
240    pub fn new() -> RandomState {
241        let src = get_src();
242        let fixed = get_fixed_seeds();
243        Self::from_keys(&fixed[0], &fixed[1], src.gen_hasher_seed())
244    }
245
246    /// Create a new `RandomState` `BuildHasher` based on the provided seeds, but in such a way
247    /// that each time it is called the resulting state will be different and of high quality.
248    /// This allows fixed constant or poor quality seeds to be provided without the problem of different
249    /// `BuildHasher`s being identical or weak.
250    ///
251    /// This is done via permuting the provided values with the value of a static counter and memory address.
252    /// (This makes this method somewhat more expensive than `with_seeds` below which does not do this).
253    ///
254    /// The provided values (k0-k3) do not need to be of high quality but they should not all be the same value.
255    #[inline]
256    pub fn generate_with(k0: u64, k1: u64, k2: u64, k3: u64) -> RandomState {
257        let src = get_src();
258        let fixed = get_fixed_seeds();
259        RandomState::from_keys(&fixed[0], &[k0, k1, k2, k3], src.gen_hasher_seed())
260    }
261
262    fn from_keys(a: &[u64; 4], b: &[u64; 4], c: usize) -> RandomState {
263        let &[k0, k1, k2, k3] = a;
264        let mut hasher = AHasher::from_random_state(&RandomState { k0, k1, k2, k3 });
265        hasher.write_usize(c);
266        let mix = |l: u64, r: u64| {
267            let mut h = hasher.clone();
268            h.write_u64(l);
269            h.write_u64(r);
270            h.finish()
271        };
272        RandomState {
273            k0: mix(b[0], b[2]),
274            k1: mix(b[1], b[3]),
275            k2: mix(b[2], b[1]),
276            k3: mix(b[3], b[0]),
277        }
278    }
279
280    /// Internal. Used by Default.
281    #[inline]
282    pub(crate) fn with_fixed_keys() -> RandomState {
283        let [k0, k1, k2, k3] = get_fixed_seeds()[0];
284        RandomState { k0, k1, k2, k3 }
285    }
286
287    /// Build a `RandomState` from a single key. The provided key does not need to be of high quality,
288    /// but all `RandomState`s created from the same key will produce identical hashers.
289    /// (In contrast to `generate_with` above)
290    ///
291    /// This allows for explicitly setting the seed to be used.
292    ///
293    /// Note: This method does not require the provided seed to be strong.
294    #[inline]
295    pub fn with_seed(key: usize) -> RandomState {
296        let fixed = get_fixed_seeds();
297        RandomState::from_keys(&fixed[0], &fixed[1], key)
298    }
299
300    /// Allows for explicitly setting the seeds to be used.
301    /// All `RandomState`s created with the same set of keys will produce identical hashers.
302    /// (In contrast to `generate_with` above)
303    ///
304    /// Note: If DOS resistance is desired one of these should be a decent quality random number.
305    /// If 4 high quality random numbers are not cheaply available this method is robust against 0s being passed for
306    /// one or more of the parameters or the same value being passed for more than one parameter.
307    /// It is recommended to pass numbers in order from highest to lowest quality (if there is any difference).
308    #[inline]
309    pub const fn with_seeds(k0: u64, k1: u64, k2: u64, k3: u64) -> RandomState {
310        RandomState {
311            k0: k0 ^ PI2[0],
312            k1: k1 ^ PI2[1],
313            k2: k2 ^ PI2[2],
314            k3: k3 ^ PI2[3],
315        }
316    }
317
318    /// Calculates the hash of a single value. This provides a more convenient (and faster) way to obtain a hash:
319    /// For example:
320    #[cfg_attr(
321        feature = "std",
322        doc = r##" # Examples
323```
324    use std::hash::BuildHasher;
325    use ahash::RandomState;
326
327    let hash_builder = RandomState::new();
328    let hash = hash_builder.hash_one("Some Data");
329```
330    "##
331    )]
332    /// This is similar to:
333    #[cfg_attr(
334        feature = "std",
335        doc = r##" # Examples
336```
337    use std::hash::{BuildHasher, Hash, Hasher};
338    use ahash::RandomState;
339
340    let hash_builder = RandomState::new();
341    let mut hasher = hash_builder.build_hasher();
342    "Some Data".hash(&mut hasher);
343    let hash = hasher.finish();
344```
345    "##
346    )]
347    /// (Note that these two ways to get a hash may not produce the same value for the same data)
348    ///
349    /// This is intended as a convenience for code which *consumes* hashes, such
350    /// as the implementation of a hash table or in unit tests that check
351    /// whether a custom [`Hash`] implementation behaves as expected.
352    ///
353    /// This must not be used in any code which *creates* hashes, such as in an
354    /// implementation of [`Hash`].  The way to create a combined hash of
355    /// multiple values is to call [`Hash::hash`] multiple times using the same
356    /// [`Hasher`], not to call this method repeatedly and combine the results.
357    #[inline]
358    pub fn hash_one<T: Hash>(&self, x: T) -> u64
359    where
360        Self: Sized,
361    {
362        use crate::specialize::CallHasher;
363        T::get_hash(&x, self)
364    }
365}
366
367/// Creates an instance of RandomState using keys obtained from the random number generator.
368/// Each instance created in this way will have a unique set of keys. (But the resulting instance
369/// can be used to create many hashers each or which will have the same keys.)
370///
371/// This is the same as [RandomState::new()]
372///
373/// NOTE: For safety this trait impl is only available if either of the flags `runtime-rng` (on by default) or
374/// `compile-time-rng` are enabled. This is to prevent weakly keyed maps from being accidentally created. Instead one of
375/// constructors for [RandomState] must be used.
376#[cfg(any(feature = "compile-time-rng", feature = "runtime-rng", feature = "no-rng"))]
377impl Default for RandomState {
378    #[inline]
379    fn default() -> Self {
380        Self::new()
381    }
382}
383
384impl BuildHasher for RandomState {
385    type Hasher = AHasher;
386
387    /// Constructs a new [AHasher] with keys based on this [RandomState] object.
388    /// This means that two different [RandomState]s will generate
389    /// [AHasher]s that will return different hashcodes, but [Hasher]s created from the same [BuildHasher]
390    /// will generate the same hashes for the same input data.
391    ///
392    #[cfg_attr(
393        feature = "std",
394        doc = r##" # Examples
395```
396        use ahash::{AHasher, RandomState};
397        use std::hash::{Hasher, BuildHasher};
398
399        let build_hasher = RandomState::new();
400        let mut hasher_1 = build_hasher.build_hasher();
401        let mut hasher_2 = build_hasher.build_hasher();
402
403        hasher_1.write_u32(1234);
404        hasher_2.write_u32(1234);
405
406        assert_eq!(hasher_1.finish(), hasher_2.finish());
407
408        let other_build_hasher = RandomState::new();
409        let mut different_hasher = other_build_hasher.build_hasher();
410        different_hasher.write_u32(1234);
411        assert_ne!(different_hasher.finish(), hasher_1.finish());
412```
413    "##
414    )]
415    /// [Hasher]: std::hash::Hasher
416    /// [BuildHasher]: std::hash::BuildHasher
417    /// [HashMap]: std::collections::HashMap
418    #[inline]
419    fn build_hasher(&self) -> AHasher {
420        AHasher::from_random_state(self)
421    }
422
423    /// Calculates the hash of a single value. This provides a more convenient (and faster) way to obtain a hash:
424    /// For example:
425    #[cfg_attr(
426        feature = "std",
427        doc = r##" # Examples
428```
429    use std::hash::BuildHasher;
430    use ahash::RandomState;
431
432    let hash_builder = RandomState::new();
433    let hash = hash_builder.hash_one("Some Data");
434```
435    "##
436    )]
437    /// This is similar to:
438    #[cfg_attr(
439        feature = "std",
440        doc = r##" # Examples
441```
442    use std::hash::{BuildHasher, Hash, Hasher};
443    use ahash::RandomState;
444
445    let hash_builder = RandomState::new();
446    let mut hasher = hash_builder.build_hasher();
447    "Some Data".hash(&mut hasher);
448    let hash = hasher.finish();
449```
450    "##
451    )]
452    /// (Note that these two ways to get a hash may not produce the same value for the same data)
453    ///
454    /// This is intended as a convenience for code which *consumes* hashes, such
455    /// as the implementation of a hash table or in unit tests that check
456    /// whether a custom [`Hash`] implementation behaves as expected.
457    ///
458    /// This must not be used in any code which *creates* hashes, such as in an
459    /// implementation of [`Hash`].  The way to create a combined hash of
460    /// multiple values is to call [`Hash::hash`] multiple times using the same
461    /// [`Hasher`], not to call this method repeatedly and combine the results.
462    // This is overridden wherever the compiler has the method (it was added in Rust 1.71), not only with
463    // specialization. Generic code, such as a `HashMap`, calls this one and not `RandomState::hash_one`.
464    #[cfg(build_hasher_hash_one)]
465    #[inline]
466    fn hash_one<T: Hash>(&self, x: T) -> u64 {
467        RandomState::hash_one(self, x)
468    }
469}
470
471#[cfg(specialize)]
472impl RandomState {
473    #[inline]
474    pub(crate) fn hash_as_u64<T: Hash + ?Sized>(&self, value: &T) -> u64 {
475        let mut hasher = AHasherU64 {
476            buffer: self.k1,
477            pad: self.k0,
478        };
479        value.hash(&mut hasher);
480        hasher.finish()
481    }
482
483    #[inline]
484    pub(crate) fn hash_as_fixed_length<T: Hash + ?Sized>(&self, value: &T) -> u64 {
485        let mut hasher = AHasherFixed(self.build_hasher());
486        value.hash(&mut hasher);
487        hasher.finish()
488    }
489
490    #[inline]
491    pub(crate) fn hash_as_str<T: Hash + ?Sized>(&self, value: &T) -> u64 {
492        let mut hasher = AHasherStr(self.build_hasher());
493        value.hash(&mut hasher);
494        hasher.finish()
495    }
496}
497
498#[cfg(test)]
499mod test {
500    use super::*;
501
502    #[test]
503    fn test_unique() {
504        let a = RandomState::generate_with(1, 2, 3, 4);
505        let b = RandomState::generate_with(1, 2, 3, 4);
506        assert_ne!(a.build_hasher().finish(), b.build_hasher().finish());
507    }
508
509    #[cfg(all(feature = "runtime-rng", not(all(feature = "compile-time-rng", test))))]
510    #[test]
511    fn test_not_pi() {
512        assert_ne!(PI_U64X4, get_fixed_seeds()[0]);
513    }
514
515    #[cfg(all(feature = "serde"))]
516    #[test]
517    fn test_serialize() {
518        let rs = RandomState::new();
519
520        let serialized = bincode::serialize(&rs).expect("failed to serialize");
521        let deserialized: RandomState = bincode::deserialize(&serialized).expect("failed to deserialize");
522
523        assert_eq!(rs.k0, deserialized.k0);
524        assert_eq!(rs.k1, deserialized.k1);
525        assert_eq!(rs.k2, deserialized.k2);
526        assert_eq!(rs.k3, deserialized.k3);
527    }
528
529    #[cfg(all(feature = "compile-time-rng", any(not(feature = "runtime-rng"), test)))]
530    #[test]
531    fn test_not_pi_const() {
532        assert_ne!(PI_U64X4, get_fixed_seeds()[0]);
533    }
534
535    #[cfg(all(not(feature = "runtime-rng"), not(feature = "compile-time-rng")))]
536    #[test]
537    fn test_pi() {
538        assert_eq!(PI_U64X4, get_fixed_seeds()[0]);
539    }
540
541    /// Generic code calls `BuildHasher::hash_one`. It has to agree with `RandomState::hash_one`.
542    #[cfg(build_hasher_hash_one)]
543    #[test]
544    fn test_trait_hash_one_is_own() {
545        fn through_trait<B: BuildHasher, T: Hash>(builder: &B, value: T) -> u64 {
546            builder.hash_one(value)
547        }
548        let state = RandomState::with_seeds(1, 2, 3, 4);
549        assert_eq!(through_trait(&state, 1234_u64), state.hash_one(1234_u64));
550        assert_eq!(through_trait(&state, &1234_u64), state.hash_one(&1234_u64));
551        assert_eq!(through_trait(&state, 1234_u128), state.hash_one(1234_u128));
552        assert_eq!(through_trait(&state, "Some Data"), state.hash_one("Some Data"));
553        assert_eq!(through_trait(&state, (1_u8, "tuple")), state.hash_one((1_u8, "tuple")));
554    }
555
556    #[test]
557    fn test_with_seeds_const() {
558        const _CONST_RANDOM_STATE: RandomState = RandomState::with_seeds(17, 19, 21, 23);
559    }
560}