1 | use crate::HashFn; |
2 | use std::convert::TryInto; |
3 | |
4 | /// Implements the hash function from the rustc-hash crate. |
5 | #[derive (Eq, PartialEq)] |
6 | pub struct FxHashFn; |
7 | |
8 | impl HashFn for FxHashFn { |
9 | // This function is marked as #[inline] because that allows LLVM to know the |
10 | // actual size of `bytes` and thus eliminate all unneeded branches below. |
11 | #[inline ] |
12 | fn hash(mut bytes: &[u8]) -> u32 { |
13 | let mut hash_value = 0; |
14 | |
15 | while bytes.len() >= 8 { |
16 | hash_value = add_to_hash(hash_value, read_u64(bytes)); |
17 | bytes = &bytes[8..]; |
18 | } |
19 | |
20 | if bytes.len() >= 4 { |
21 | hash_value = add_to_hash( |
22 | hash_value, |
23 | u32::from_le_bytes(bytes[..4].try_into().unwrap()) as u64, |
24 | ); |
25 | bytes = &bytes[4..]; |
26 | } |
27 | |
28 | if bytes.len() >= 2 { |
29 | hash_value = add_to_hash( |
30 | hash_value, |
31 | u16::from_le_bytes(bytes[..2].try_into().unwrap()) as u64, |
32 | ); |
33 | bytes = &bytes[2..]; |
34 | } |
35 | |
36 | if bytes.len() >= 1 { |
37 | hash_value = add_to_hash(hash_value, bytes[0] as u64); |
38 | } |
39 | |
40 | return hash_value as u32; |
41 | |
42 | #[inline ] |
43 | fn add_to_hash(current_hash: u64, value: u64) -> u64 { |
44 | use std::ops::BitXor; |
45 | current_hash |
46 | .rotate_left(5) |
47 | .bitxor(value) |
48 | // This constant is part of FxHash's definition: |
49 | // https://github.com/rust-lang/rustc-hash/blob/5e09ea0a1/src/lib.rs#L67 |
50 | .wrapping_mul(0x517cc1b727220a95) |
51 | } |
52 | |
53 | #[inline ] |
54 | fn read_u64(bytes: &[u8]) -> u64 { |
55 | u64::from_le_bytes(bytes[..8].try_into().unwrap()) |
56 | } |
57 | } |
58 | } |
59 | |