proc_macro/bridge/
fxhash.rs1use std::collections::HashMap;
8use std::hash::{BuildHasherDefault, Hasher};
9use std::ops::BitXor;
10
11pub(super) type FxHashMap<K, V> = HashMap<K, V, BuildHasherDefault<FxHasher>>;
13
14#[derive(Default)]
26pub(super) struct FxHasher {
27 hash: usize,
28}
29
30impl FxHasher {
31 #[inline]
32 fn add_to_hash(&mut self, i: usize) {
33 const K: usize = cfg_select! {
34 target_pointer_width = "64" => 0x517cc1b727220a95,
35 target_pointer_width = "32" => 0x9e3779b9,
36 _ => 0, };
38 self.hash = self.hash.rotate_left(5).bitxor(i).wrapping_mul(K);
39 }
40}
41
42impl Hasher for FxHasher {
43 #[inline]
44 fn write(&mut self, mut bytes: &[u8]) {
45 let mut hash = FxHasher { hash: self.hash };
46 assert!(size_of::<usize>() <= 8);
47 while bytes.len() >= size_of::<usize>() {
48 hash.add_to_hash(usize::from_ne_bytes(bytes[..size_of::<usize>()].try_into().unwrap()));
49 bytes = &bytes[size_of::<usize>()..];
50 }
51 if (size_of::<usize>() > 4) && (bytes.len() >= 4) {
52 hash.add_to_hash(u32::from_ne_bytes(bytes[..4].try_into().unwrap()) as usize);
53 bytes = &bytes[4..];
54 }
55 if (size_of::<usize>() > 2) && bytes.len() >= 2 {
56 hash.add_to_hash(u16::from_ne_bytes(bytes[..2].try_into().unwrap()) as usize);
57 bytes = &bytes[2..];
58 }
59 if (size_of::<usize>() > 1) && !bytes.is_empty() {
60 hash.add_to_hash(bytes[0] as usize);
61 }
62 self.hash = hash.hash;
63 }
64
65 #[inline]
66 fn write_u8(&mut self, i: u8) {
67 self.add_to_hash(i as usize);
68 }
69
70 #[inline]
71 fn write_u16(&mut self, i: u16) {
72 self.add_to_hash(i as usize);
73 }
74
75 #[inline]
76 fn write_u32(&mut self, i: u32) {
77 self.add_to_hash(i as usize);
78 }
79
80 #[cfg(target_pointer_width = "32")]
81 #[inline]
82 fn write_u64(&mut self, i: u64) {
83 self.add_to_hash(i as usize);
84 self.add_to_hash((i >> 32) as usize);
85 }
86
87 #[cfg(target_pointer_width = "64")]
88 #[inline]
89 fn write_u64(&mut self, i: u64) {
90 self.add_to_hash(i as usize);
91 }
92
93 #[inline]
94 fn write_usize(&mut self, i: usize) {
95 self.add_to_hash(i);
96 }
97
98 #[inline]
99 fn finish(&self) -> u64 {
100 self.hash as u64
101 }
102}