1use super::{HashMap, HashSet};
14use core::default::Default;
15use core::hash::{BuildHasherDefault, Hash, Hasher};
16use core::ops::BitXor;
17
18pub type FxHashMap<K, V> = HashMap<K, V, BuildHasherDefault<FxHasher>>;
19pub type FxHashSet<V> = HashSet<V, BuildHasherDefault<FxHasher>>;
20
21#[allow(non_snake_case)]
22pub fn FxHashMap<K: Hash + Eq, V>() -> FxHashMap<K, V> {
23 HashMap::default()
24}
25
26#[allow(non_snake_case)]
27pub fn FxHashSet<V: Hash + Eq>() -> FxHashSet<V> {
28 HashSet::default()
29}
30
31pub struct FxHasher {
43 hash: usize,
44}
45
46#[cfg(target_pointer_width = "32")]
47const K: usize = 0x9e3779b9;
48#[cfg(target_pointer_width = "64")]
49const K: usize = 0x517cc1b727220a95;
50
51impl Default for FxHasher {
52 #[inline]
53 fn default() -> Self {
54 Self { hash: 0 }
55 }
56}
57
58impl FxHasher {
59 #[inline]
60 fn add_to_hash(&mut self, i: usize) {
61 self.hash = self.hash.rotate_left(5).bitxor(i).wrapping_mul(K);
62 }
63}
64
65impl Hasher for FxHasher {
66 #[inline]
67 fn write(&mut self, bytes: &[u8]) {
68 for byte in bytes {
69 let i = *byte;
70 self.add_to_hash(i as usize);
71 }
72 }
73
74 #[inline]
75 fn write_u8(&mut self, i: u8) {
76 self.add_to_hash(i as usize);
77 }
78
79 #[inline]
80 fn write_u16(&mut self, i: u16) {
81 self.add_to_hash(i as usize);
82 }
83
84 #[inline]
85 fn write_u32(&mut self, i: u32) {
86 self.add_to_hash(i as usize);
87 }
88
89 #[cfg(target_pointer_width = "32")]
90 #[inline]
91 fn write_u64(&mut self, i: u64) {
92 self.add_to_hash(i as usize);
93 self.add_to_hash((i >> 32) as usize);
94 }
95
96 #[cfg(target_pointer_width = "64")]
97 #[inline]
98 fn write_u64(&mut self, i: u64) {
99 self.add_to_hash(i as usize);
100 }
101
102 #[inline]
103 fn write_usize(&mut self, i: usize) {
104 self.add_to_hash(i);
105 }
106
107 #[inline]
108 fn finish(&self) -> u64 {
109 self.hash as u64
110 }
111}