• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #[cfg(all(feature = "runtime-rng", not(all(feature = "compile-time-rng", test))))]
2 use crate::convert::Convert;
3 use crate::{AHasher};
4 #[cfg(all(feature = "compile-time-rng", any(not(feature = "runtime-rng"), test)))]
5 use const_random::const_random;
6 use core::fmt;
7 use core::hash::BuildHasher;
8 use core::hash::Hasher;
9 #[cfg(all(feature = "runtime-rng", not(all(feature = "compile-time-rng", test))))]
10 use lazy_static::*;
11 use core::sync::atomic::{AtomicUsize, Ordering};
12 
13 #[cfg(all(feature = "runtime-rng", not(all(feature = "compile-time-rng", test))))]
read_urandom(dest: &mut [u8]) -> Result<(), std::io::Error>14 fn read_urandom(dest: &mut [u8]) -> Result<(), std::io::Error> {
15     use std::fs::File;
16     use std::io::Read;
17 
18     let mut f = File::open("/dev/urandom")?;
19     f.read_exact(dest)
20 }
21 
22 #[cfg(all(feature = "runtime-rng", not(all(feature = "compile-time-rng", test))))]
23 lazy_static! {
24     static ref SEEDS: [[u64; 4]; 2] = {
25         let mut result: [u8; 64] = [0; 64];
26         if read_urandom(&mut result).is_err() {
27             getrandom::getrandom(&mut result).expect("getrandom::getrandom() failed.")
28         }
29         result.convert()
30     };
31 }
32 
33 static COUNTER: AtomicUsize = AtomicUsize::new(0);
34 
35 pub(crate) const PI: [u64; 4] = [
36     0x243f_6a88_85a3_08d3,
37     0x1319_8a2e_0370_7344,
38     0xa409_3822_299f_31d0,
39     0x082e_fa98_ec4e_6c89,
40 ];
41 
42 #[cfg(all(not(feature = "runtime-rng"), not(feature = "compile-time-rng")))]
43 const PI2: [u64; 4] = [
44     0x4528_21e6_38d0_1377,
45     0xbe54_66cf_34e9_0c6c,
46     0xc0ac_29b7_c97c_50dd,
47     0x3f84_d5b5_b547_0917,
48 ];
49 
50 #[inline]
seeds() -> [u64; 4]51 pub(crate) fn seeds() -> [u64; 4] {
52     #[cfg(all(feature = "runtime-rng", not(all(feature = "compile-time-rng", test))))]
53     { SEEDS[1] }
54     #[cfg(all(feature = "compile-time-rng", any(not(feature = "runtime-rng"), test)))]
55     { [const_random!(u64), const_random!(u64), const_random!(u64), const_random!(u64)] }
56     #[cfg(all(not(feature = "runtime-rng"), not(feature = "compile-time-rng")))]
57     { PI }
58 }
59 
60 
61 /// Provides a [Hasher] factory. This is typically used (e.g. by [HashMap]) to create
62 /// [AHasher]s in order to hash the keys of the map. See `build_hasher` below.
63 ///
64 /// [build_hasher]: ahash::
65 /// [Hasher]: std::hash::Hasher
66 /// [BuildHasher]: std::hash::BuildHasher
67 /// [HashMap]: std::collections::HashMap
68 #[derive(Clone)]
69 pub struct RandomState {
70     pub(crate) k0: u64,
71     pub(crate) k1: u64,
72     pub(crate) k2: u64,
73     pub(crate) k3: u64,
74 }
75 
76 impl fmt::Debug for RandomState {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result77     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78         f.pad("RandomState { .. }")
79     }
80 }
81 
82 impl RandomState {
83     /// Use randomly generated keys
84     #[inline]
new() -> RandomState85     pub fn new() -> RandomState {
86         #[cfg(all(feature = "runtime-rng", not(all(feature = "compile-time-rng", test))))]
87         {
88             let seeds = *SEEDS;
89             RandomState::from_keys(seeds[0], seeds[1])
90         }
91         #[cfg(all(feature = "compile-time-rng", any(not(feature = "runtime-rng"), test)))]
92         {
93             RandomState::from_keys(
94                 [const_random!(u64), const_random!(u64), const_random!(u64), const_random!(u64)],
95                 [const_random!(u64), const_random!(u64), const_random!(u64), const_random!(u64)],
96             )
97         }
98         #[cfg(all(not(feature = "runtime-rng"), not(feature = "compile-time-rng")))]
99         {
100             RandomState::from_keys(PI, PI2)
101         }
102     }
103 
104     /// Allows for supplying seeds, but each time it is called the resulting state will be different.
105     /// This is done using a static counter, so it can safely be used with a fixed keys.
106     #[inline]
generate_with(k0: u64, k1: u64, k2: u64, k3: u64) -> RandomState107     pub fn generate_with(k0: u64, k1: u64, k2: u64, k3: u64) -> RandomState {
108         RandomState::from_keys(seeds(), [k0, k1, k2, k3])
109     }
110 
from_keys(a: [u64; 4], b: [u64; 4]) -> RandomState111     fn from_keys(a: [u64; 4], b: [u64; 4]) -> RandomState {
112         let [k0, k1, k2, k3] = a;
113         let mut hasher = AHasher::from_random_state(&RandomState { k0, k1, k2, k3 });
114 
115         let stack_mem_loc = &hasher as *const _ as usize;
116         #[cfg(not(all(target_arch="arm", target_os="none")))]
117         {
118             hasher.write_usize(COUNTER.fetch_add(stack_mem_loc, Ordering::Relaxed));
119         }
120         #[cfg(all(target_arch="arm", target_os="none"))]
121         {
122             let previous = COUNTER.load(Ordering::Relaxed);
123             let new = previous.wrapping_add(stack_mem_loc);
124             COUNTER.store(new, Ordering::Relaxed);
125             hasher.write_usize(new);
126         }
127         #[cfg(all(not(feature = "runtime-rng"), not(feature = "compile-time-rng")))]
128         hasher.write_usize(&PI as *const _ as usize);
129         let mix = |k: u64| {
130             let mut h = hasher.clone();
131             h.write_u64(k);
132             h.finish()
133         };
134 
135         RandomState { k0: mix(b[0]), k1: mix(b[1]), k2: mix(b[2]), k3: mix(b[3]) }
136     }
137 
138     /// Internal. Used by Default.
139     #[inline]
with_fixed_keys() -> RandomState140     pub(crate) fn with_fixed_keys() -> RandomState {
141         let [k0, k1, k2, k3] = seeds();
142         RandomState { k0, k1, k2, k3 }
143     }
144 
145     /// Allows for explicitly setting the seeds to used.
146     #[inline]
with_seeds(k0: u64, k1: u64, k2: u64, k3: u64) -> RandomState147     pub const fn with_seeds(k0: u64, k1: u64, k2: u64, k3: u64) -> RandomState {
148         RandomState { k0, k1, k2, k3 }
149     }
150 }
151 
152 impl Default for RandomState {
153     #[inline]
default() -> Self154     fn default() -> Self {
155         Self::new()
156     }
157 }
158 
159 impl BuildHasher for RandomState {
160     type Hasher = AHasher;
161 
162     /// Constructs a new [AHasher] with keys based on this [RandomState] object.
163     /// This means that two different [RandomState]s will will generate
164     /// [AHasher]s that will return different hashcodes, but [Hasher]s created from the same [BuildHasher]
165     /// will generate the same hashes for the same input data.
166     ///
167     /// # Examples
168     ///
169     /// ```
170     /// use ahash::{AHasher, RandomState};
171     /// use std::hash::{Hasher, BuildHasher};
172     ///
173     /// let build_hasher = RandomState::new();
174     /// let mut hasher_1 = build_hasher.build_hasher();
175     /// let mut hasher_2 = build_hasher.build_hasher();
176     ///
177     /// hasher_1.write_u32(1234);
178     /// hasher_2.write_u32(1234);
179     ///
180     /// assert_eq!(hasher_1.finish(), hasher_2.finish());
181     ///
182     /// let other_build_hasher = RandomState::new();
183     /// let mut different_hasher = other_build_hasher.build_hasher();
184     /// different_hasher.write_u32(1234);
185     /// assert_ne!(different_hasher.finish(), hasher_1.finish());
186     /// ```
187     /// [Hasher]: std::hash::Hasher
188     /// [BuildHasher]: std::hash::BuildHasher
189     /// [HashMap]: std::collections::HashMap
190     #[inline]
build_hasher(&self) -> AHasher191     fn build_hasher(&self) -> AHasher {
192         AHasher::from_random_state(self)
193     }
194 }
195 
196 #[cfg(test)]
197 mod test {
198     use super::*;
199 
200     #[test]
test_unique()201     fn test_unique() {
202         let a = RandomState::new();
203         let b = RandomState::new();
204         assert_ne!(a.build_hasher().finish(), b.build_hasher().finish());
205     }
206 
207     #[cfg(all(feature = "runtime-rng", not(all(feature = "compile-time-rng", test))))]
208     #[test]
test_not_pi()209     fn test_not_pi() {
210         assert_ne!(PI, seeds());
211     }
212 
213     #[cfg(all(feature = "compile-time-rng", any(not(feature = "runtime-rng"), test)))]
214     #[test]
test_not_pi_const()215     fn test_not_pi_const() {
216         assert_ne!(PI, seeds());
217     }
218 
219     #[cfg(all(not(feature = "runtime-rng"), not(feature = "compile-time-rng")))]
220     #[test]
test_pi()221     fn test_pi() {
222         assert_eq!(PI, seeds());
223     }
224 
225     #[test]
test_with_seeds_const()226     fn test_with_seeds_const() {
227         const _CONST_RANDOM_STATE: RandomState = RandomState::with_seeds(17, 19, 21, 23);
228     }
229 }
230