Debian Codegraph @

debian/rust-vendor/rustc-hash/src/lib.rs

raw
1 //! A speedy, non-cryptographic hashing algorithm used by `rustc`.
2 //!
3 //! # Example
4 //!
5 //! ```rust
6 //! # #[cfg(feature = "std")]
7 //! # fn main() {
8 //! use rustc_hash::FxHashMap;
9 //!
10 //! let mut map: FxHashMap<u32, u32> = FxHashMap::default();
11 //! map.insert(22, 44);
12 //! # }
13 //! # #[cfg(not(feature = "std"))]
14 //! # fn main() { }
15 //! ```
16
17 #![no_std]
18 #![cfg_attr(feature = "nightly", feature(const_default))]
19 #![cfg_attr(feature = "nightly", feature(const_trait_impl))]
20 #![cfg_attr(feature = "nightly", feature(derive_const))]
21 #![cfg_attr(feature = "nightly", feature(hasher_prefixfree_extras))]
22 #![allow(rustc::default_hash_types)]
23
24 #[cfg(feature = "std")]
25 extern crate std;
26
27 #[cfg(feature = "rand")]
28 extern crate rand;
29
30 #[cfg(feature = "rand")]
31 mod random_state;
32
33 mod seeded_state;
34
35 use core::default::Default;
36 use core::hash::{BuildHasher, Hasher};
37 #[cfg(feature = "std")]
38 use std::collections::{HashMap, HashSet};
39
40 /// Type alias for a hash map that uses the Fx hashing algorithm.
41 #[cfg(feature = "std")]
42 pub type FxHashMap<K, V> = HashMap<K, V, FxBuildHasher>;
43
44 /// Type alias for a hash set that uses the Fx hashing algorithm.
45 #[cfg(feature = "std")]
46 pub type FxHashSet<V> = HashSet<V, FxBuildHasher>;
47
48 #[cfg(feature = "rand")]
49 pub use random_state::{FxHashMapRand, FxHashSetRand, FxRandomState};
50
51 pub use seeded_state::FxSeededState;
52 #[cfg(feature = "std")]
53 pub use seeded_state::{FxHashMapSeed, FxHashSetSeed};
54
55 /// A speedy hash algorithm for use within rustc. The hashmap in liballoc
56 /// by default uses SipHash which isn't quite as speedy as we want. In the
57 /// compiler we're not really worried about DOS attempts, so we use a fast
58 /// non-cryptographic hash.
59 ///
60 /// The current implementation is a fast polynomial hash with a single
61 /// bit rotation as a finishing step designed by Orson Peters.
62 #[derive(Clone)]
63 #[cfg_attr(not(feature = "nightly"), derive(Default))]
64 #[cfg_attr(feature = "nightly", derive_const(Default))]
65 pub struct FxHasher {
66 hash: usize,
67 }
68
69 // One might view a polynomial hash
70 // m[0] * k + m[1] * k^2 + m[2] * k^3 + ...
71 // as a multilinear hash with keystream k[..]
72 // m[0] * k[0] + m[1] * k[1] + m[2] * k[2] + ...
73 // where keystream k just happens to be generated using a multiplicative
74 // congruential pseudorandom number generator (MCG). For that reason we chose a
75 // constant that was found to be good for a MCG in:
76 // "Computationally Easy, Spectrally Good Multipliers for Congruential
77 // Pseudorandom Number Generators" by Guy Steele and Sebastiano Vigna.
78 #[cfg(target_pointer_width = "64")]
79 const K: usize = 0xf1357aea2e62a9c5;
80 #[cfg(target_pointer_width = "32")]
81 const K: usize = 0x93d765dd;
82
83 impl FxHasher {
84 /// Creates a `fx` hasher with a given seed.
85 pub const fn with_seed(seed: usize) -> FxHasher {
86 FxHasher { hash: seed }
87 }
88
89 /// Creates a default `fx` hasher.
90 pub const fn default() -> FxHasher {
91 FxHasher { hash: 0 }
92 }
93 }
94
95 impl FxHasher {
96 #[inline]
97 fn add_to_hash(&mut self, i: usize) {
98 self.hash = self.hash.wrapping_add(i).wrapping_mul(K);
99 }
100 }
101
102 impl Hasher for FxHasher {
103 #[inline]
104 fn write(&mut self, bytes: &[u8]) {
105 // Compress the byte string to a single u64 and add to our hash.
106 self.write_u64(hash_bytes(bytes));
107 }
108
109 #[inline]
110 fn write_u8(&mut self, i: u8) {
111 self.add_to_hash(i as usize);
112 }
113
114 #[inline]
115 fn write_u16(&mut self, i: u16) {
116 self.add_to_hash(i as usize);
117 }
118
119 #[inline]
120 fn write_u32(&mut self, i: u32) {
121 self.add_to_hash(i as usize);
122 }
123
124 #[inline]
125 fn write_u64(&mut self, i: u64) {
126 self.add_to_hash(i as usize);
127 #[cfg(target_pointer_width = "32")]
128 self.add_to_hash((i >> 32) as usize);
129 }
130
131 #[inline]
132 fn write_u128(&mut self, i: u128) {
133 self.add_to_hash(i as usize);
134 #[cfg(target_pointer_width = "32")]
135 self.add_to_hash((i >> 32) as usize);
136 self.add_to_hash((i >> 64) as usize);
137 #[cfg(target_pointer_width = "32")]
138 self.add_to_hash((i >> 96) as usize);
139 }
140
141 #[inline]
142 fn write_usize(&mut self, i: usize) {
143 self.add_to_hash(i);
144 }
145
146 #[cfg(feature = "nightly")]
147 #[inline]
148 fn write_length_prefix(&mut self, _len: usize) {
149 // Most cases will specialize hash_slice to call write(), which encodes
150 // the length already in a more efficient manner than we could here. For
151 // HashDoS-resistance you would still need to include this for the
152 // non-slice collection hashes, but for the purposes of rustc we do not
153 // care and do not wish to pay the performance penalty of mixing in len
154 // for those collections.
155 }
156
157 #[cfg(feature = "nightly")]
158 #[inline]
159 fn write_str(&mut self, s: &str) {
160 // Similarly here, write already encodes the length, so nothing special
161 // is needed.
162 self.write(s.as_bytes())
163 }
164
165 #[inline]
166 fn finish(&self) -> u64 {
167 // Since we used a multiplicative hash our top bits have the most
168 // entropy (with the top bit having the most, decreasing as you go).
169 // As most hash table implementations (including hashbrown) compute
170 // the bucket index from the bottom bits we want to move bits from the
171 // top to the bottom. Ideally we'd rotate left by exactly the hash table
172 // size, but as we don't know this we'll choose 26 bits, giving decent
173 // entropy up until 2^26 table sizes. On 32-bit hosts we'll dial it
174 // back down a bit to 15 bits.
175
176 #[cfg(target_pointer_width = "64")]
177 const ROTATE: u32 = 26;
178 #[cfg(target_pointer_width = "32")]
179 const ROTATE: u32 = 15;
180
181 self.hash.rotate_left(ROTATE) as u64
182
183 // A bit reversal would be even better, except hashbrown also expects
184 // good entropy in the top 7 bits and a bit reverse would fill those
185 // bits with low entropy. More importantly, bit reversals are very slow
186 // on x86-64. A byte reversal is relatively fast, but still has a 2
187 // cycle latency on x86-64 compared to the 1 cycle latency of a rotate.
188 // It also suffers from the hashbrown-top-7-bit-issue.
189 }
190 }
191
192 // Nothing special, digits of pi.
193 const SEED1: u64 = 0x243f6a8885a308d3;
194 const SEED2: u64 = 0x13198a2e03707344;
195 const PREVENT_TRIVIAL_ZERO_COLLAPSE: u64 = 0xa4093822299f31d0;
196
197 #[inline]
198 fn multiply_mix(x: u64, y: u64) -> u64 {
199 // The following code path is only fast if 64-bit to 128-bit widening
200 // multiplication is supported by the architecture. Most 64-bit
201 // architectures except SPARC64 and Wasm64 support it. However, the target
202 // pointer width doesn't always indicate that we are dealing with a 64-bit
203 // architecture, as there are ABIs that reduce the pointer width, especially
204 // on AArch64 and x86-64. WebAssembly (regardless of pointer width) supports
205 // 64-bit to 128-bit widening multiplication with the `wide-arithmetic`
206 // proposal.
207 if cfg!(any(
208 all(
209 target_pointer_width = "64",
210 not(any(target_arch = "sparc64", target_arch = "wasm64")),
211 ),
212 target_arch = "aarch64",
213 target_arch = "x86_64",
214 all(target_family = "wasm", target_feature = "wide-arithmetic"),
215 )) {
216 // We compute the full u64 x u64 -> u128 product, this is a single mul
217 // instruction on x86-64, one mul plus one mulhi on ARM64.
218 let full = (x as u128).wrapping_mul(y as u128);
219 let lo = full as u64;
220 let hi = (full >> 64) as u64;
221
222 // The middle bits of the full product fluctuate the most with small
223 // changes in the input. This is the top bits of lo and the bottom bits
224 // of hi. We can thus make the entire output fluctuate with small
225 // changes to the input by XOR'ing these two halves.
226 lo ^ hi
227
228 // Unfortunately both 2^64 + 1 and 2^64 - 1 have small prime factors,
229 // otherwise combining with + or - could result in a really strong hash, as:
230 // x * y = 2^64 * hi + lo = (-1) * hi + lo = lo - hi, (mod 2^64 + 1)
231 // x * y = 2^64 * hi + lo = 1 * hi + lo = lo + hi, (mod 2^64 - 1)
232 // Multiplicative hashing is universal in a field (like mod p).
233 } else {
234 // u64 x u64 -> u128 product is prohibitively expensive on 32-bit.
235 // Decompose into 32-bit parts.
236 let lx = x as u32;
237 let ly = y as u32;
238 let hx = (x >> 32) as u32;
239 let hy = (y >> 32) as u32;
240
241 // u32 x u32 -> u64 the low bits of one with the high bits of the other.
242 let afull = (lx as u64).wrapping_mul(hy as u64);
243 let bfull = (hx as u64).wrapping_mul(ly as u64);
244
245 // Combine, swapping low/high of one of them so the upper bits of the
246 // product of one combine with the lower bits of the other.
247 afull ^ bfull.rotate_right(32)
248 }
249 }
250
251 /// A wyhash-inspired non-collision-resistant hash for strings/slices designed
252 /// by Orson Peters, with a focus on small strings and small codesize.
253 ///
254 /// The 64-bit version of this hash passes the SMHasher3 test suite on the full
255 /// 64-bit output, that is, f(hash_bytes(b) ^ f(seed)) for some good avalanching
256 /// permutation f() passed all tests with zero failures. When using the 32-bit
257 /// version of multiply_mix this hash has a few non-catastrophic failures where
258 /// there are a handful more collisions than an optimal hash would give.
259 ///
260 /// We don't bother avalanching here as we'll feed this hash into a
261 /// multiplication after which we take the high bits, which avalanches for us.
262 #[inline]
263 fn hash_bytes(bytes: &[u8]) -> u64 {
264 let len = bytes.len();
265 let mut s0 = SEED1;
266 let mut s1 = SEED2;
267
268 if len <= 16 {
269 // XOR the input into s0, s1.
270 if len >= 8 {
271 s0 ^= u64::from_le_bytes(bytes[0..8].try_into().unwrap());
272 s1 ^= u64::from_le_bytes(bytes[len - 8..].try_into().unwrap());
273 } else if len >= 4 {
274 s0 ^= u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as u64;
275 s1 ^= u32::from_le_bytes(bytes[len - 4..].try_into().unwrap()) as u64;
276 } else if len > 0 {
277 let lo = bytes[0];
278 let mid = bytes[len / 2];
279 let hi = bytes[len - 1];
280 s0 ^= lo as u64;
281 s1 ^= ((hi as u64) << 8) | mid as u64;
282 }
283 } else {
284 // Handle bulk (can partially overlap with suffix).
285 let mut bulk = &bytes[..(len - 1)];
286 while let Some((chunk, rest)) = bulk.split_first_chunk::<16>() {
287 let x = u64::from_le_bytes((&chunk[..8]).try_into().unwrap());
288 let y = u64::from_le_bytes((&chunk[8..]).try_into().unwrap());
289
290 // Replace s1 with a mix of s0, x, and y, and s0 with s1.
291 // This ensures the compiler can unroll this loop into two
292 // independent streams, one operating on s0, the other on s1.
293 //
294 // Since zeroes are a common input we prevent an immediate trivial
295 // collapse of the hash function by XOR'ing a constant with y.
296 let t = multiply_mix(s0 ^ x, PREVENT_TRIVIAL_ZERO_COLLAPSE ^ y);
297 s0 = s1;
298 s1 = t;
299 bulk = rest;
300 }
301
302 let suffix = &bytes[len - 16..];
303 s0 ^= u64::from_le_bytes(suffix[0..8].try_into().unwrap());
304 s1 ^= u64::from_le_bytes(suffix[8..16].try_into().unwrap());
305 }
306
307 multiply_mix(s0, s1) ^ (len as u64)
308 }
309
310 /// An implementation of [`BuildHasher`] that produces [`FxHasher`]s.
311 ///
312 /// ```
313 /// use std::hash::BuildHasher;
314 /// use rustc_hash::FxBuildHasher;
315 /// assert_ne!(FxBuildHasher.hash_one(1), FxBuildHasher.hash_one(2));
316 /// ```
317 #[derive(Copy, Clone)]
318 #[cfg_attr(not(feature = "nightly"), derive(Default))]
319 #[cfg_attr(feature = "nightly", derive_const(Default))]
320 pub struct FxBuildHasher;
321
322 impl BuildHasher for FxBuildHasher {
323 type Hasher = FxHasher;
324 fn build_hasher(&self) -> FxHasher {
325 FxHasher::default()
326 }
327 }
328
329 #[cfg(test)]
330 mod tests {
331 #[cfg(not(any(target_pointer_width = "64", target_pointer_width = "32")))]
332 compile_error!("The test suite only supports 64 bit and 32 bit usize");
333
334 use crate::{FxBuildHasher, FxHasher};
335 use core::hash::{BuildHasher, Hash, Hasher};
336
337 macro_rules! test_hash {
338 (
339 $(
340 hash($value:expr) == $result:expr,
341 )*
342 ) => {
343 $(
344 assert_eq!(FxBuildHasher.hash_one($value), $result);
345 )*
346 };
347 }
348
349 const B32: bool = cfg!(target_pointer_width = "32");
350
351 #[test]
352 fn unsigned() {
353 test_hash! {
354 hash(0_u8) == 0,
355 hash(1_u8) == if B32 { 3001993707 } else { 12157901119326311915 },
356 hash(100_u8) == if B32 { 3844759569 } else { 16751747135202103309 },
357 hash(u8::MAX) == if B32 { 999399879 } else { 1211781028898739645 },
358
359 hash(0_u16) == 0,
360 hash(1_u16) == if B32 { 3001993707 } else { 12157901119326311915 },
361 hash(100_u16) == if B32 { 3844759569 } else { 16751747135202103309 },
362 hash(u16::MAX) == if B32 { 3440503042 } else { 16279819243059860173 },
363
364 hash(0_u32) == 0,
365 hash(1_u32) == if B32 { 3001993707 } else { 12157901119326311915 },
366 hash(100_u32) == if B32 { 3844759569 } else { 16751747135202103309 },
367 hash(u32::MAX) == if B32 { 1293006356 } else { 7729994835221066939 },
368
369 hash(0_u64) == 0,
370 hash(1_u64) == if B32 { 275023839 } else { 12157901119326311915 },
371 hash(100_u64) == if B32 { 1732383522 } else { 16751747135202103309 },
372 hash(u64::MAX) == if B32 { 1017982517 } else { 6288842954450348564 },
373
374 hash(0_u128) == 0,
375 hash(1_u128) == if B32 { 1860738631 } else { 13032756267696824044 },
376 hash(100_u128) == if B32 { 1389515751 } else { 12003541609544029302 },
377 hash(u128::MAX) == if B32 { 2156022013 } else { 11702830760530184999 },
378
379 hash(0_usize) == 0,
380 hash(1_usize) == if B32 { 3001993707 } else { 12157901119326311915 },
381 hash(100_usize) == if B32 { 3844759569 } else { 16751747135202103309 },
382 hash(usize::MAX) == if B32 { 1293006356 } else { 6288842954450348564 },
383 }
384 }
385
386 #[test]
387 fn signed() {
388 test_hash! {
389 hash(i8::MIN) == if B32 { 2000713177 } else { 6684841074112525780 },
390 hash(0_i8) == 0,
391 hash(1_i8) == if B32 { 3001993707 } else { 12157901119326311915 },
392 hash(100_i8) == if B32 { 3844759569 } else { 16751747135202103309 },
393 hash(i8::MAX) == if B32 { 3293686765 } else { 12973684028562874344 },
394
395 hash(i16::MIN) == if B32 { 1073764727 } else { 14218860181193086044 },
396 hash(0_i16) == 0,
397 hash(1_i16) == if B32 { 3001993707 } else { 12157901119326311915 },
398 hash(100_i16) == if B32 { 3844759569 } else { 16751747135202103309 },
399 hash(i16::MAX) == if B32 { 2366738315 } else { 2060959061933882993 },
400
401 hash(i32::MIN) == if B32 { 16384 } else { 9943947977240134995 },
402 hash(0_i32) == 0,
403 hash(1_i32) == if B32 { 3001993707 } else { 12157901119326311915 },
404 hash(100_i32) == if B32 { 3844759569 } else { 16751747135202103309 },
405 hash(i32::MAX) == if B32 { 1293022740 } else { 16232790931690483559 },
406
407 hash(i64::MIN) == if B32 { 16384 } else { 33554432 },
408 hash(0_i64) == 0,
409 hash(1_i64) == if B32 { 275023839 } else { 12157901119326311915 },
410 hash(100_i64) == if B32 { 1732383522 } else { 16751747135202103309 },
411 hash(i64::MAX) == if B32 { 1017998901 } else { 6288842954483902996 },
412
413 hash(i128::MIN) == if B32 { 16384 } else { 33554432 },
414 hash(0_i128) == 0,
415 hash(1_i128) == if B32 { 1860738631 } else { 13032756267696824044 },
416 hash(100_i128) == if B32 { 1389515751 } else { 12003541609544029302 },
417 hash(i128::MAX) == if B32 { 2156005629 } else { 11702830760496630567 },
418
419 hash(isize::MIN) == if B32 { 16384 } else { 33554432 },
420 hash(0_isize) == 0,
421 hash(1_isize) == if B32 { 3001993707 } else { 12157901119326311915 },
422 hash(100_isize) == if B32 { 3844759569 } else { 16751747135202103309 },
423 hash(isize::MAX) == if B32 { 1293022740 } else { 6288842954483902996 },
424 }
425 }
426
427 // Avoid relying on any `Hash` implementations in the standard library.
428 struct HashBytes(&'static [u8]);
429 impl Hash for HashBytes {
430 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
431 state.write(self.0);
432 }
433 }
434
435 #[test]
436 fn bytes() {
437 test_hash! {
438 hash(HashBytes(&[])) == if B32 { 2673204745 } else { 17606491139363777937 },
439 hash(HashBytes(&[0])) == if B32 { 2948228584 } else { 5448590020104574886 },
440 hash(HashBytes(&[0, 0, 0, 0, 0, 0])) == if B32 { 3223252423 } else { 16766921560080789783 },
441 hash(HashBytes(&[1])) == if B32 { 2943445104 } else { 5922447956811044110 },
442 hash(HashBytes(&[2])) == if B32 { 1055423297 } else { 5229781508510959783 },
443 hash(HashBytes(b"uwu")) == if B32 { 2699662140 } else { 7168164714682931527 },
444 hash(HashBytes(b"These are some bytes for testing rustc_hash.")) == if B32 { 2303640537 } else { 2349210501944688211 },
445 }
446 }
447
448 #[test]
449 fn with_seed_actually_different() {
450 let seeds = [
451 [1, 2],
452 [42, 17],
453 [124436707, 99237],
454 [usize::MIN, usize::MAX],
455 ];
456
457 for [a_seed, b_seed] in seeds {
458 let a = || FxHasher::with_seed(a_seed);
459 let b = || FxHasher::with_seed(b_seed);
460
461 for x in u8::MIN..=u8::MAX {
462 let mut a = a();
463 let mut b = b();
464
465 x.hash(&mut a);
466 x.hash(&mut b);
467
468 assert_ne!(a.finish(), b.finish())
469 }
470 }
471 }
472 }