1use core::convert::TryInto;
27use core::default::Default;
28use core::hash::BuildHasherDefault;
29use core::hash::Hasher;
30use core::mem::size_of;
31use core::ops::BitXor;
32use std::collections::{HashMap, HashSet};
33
34pub type FxHashMap<K, V> = HashMap<K, V, BuildHasherDefault<FxHasher>>;
36
37pub type FxHashSet<V> = HashSet<V, BuildHasherDefault<FxHasher>>;
39
40#[derive(Default)]
52pub struct FxHasher {
53    hash: usize,
54}
55
56#[cfg(target_pointer_width = "32")]
57const K: usize = 0x9e3779b9;
58#[cfg(target_pointer_width = "64")]
59const K: usize = 0x517cc1b727220a95;
60
61impl FxHasher {
62    #[inline]
63    fn add_to_hash(&mut self, i: usize) {
64        self.hash = self.hash.rotate_left(5).bitxor(i).wrapping_mul(K);
65    }
66}
67
68impl Hasher for FxHasher {
69    #[inline]
70    fn write(&mut self, mut bytes: &[u8]) {
71        #[cfg(target_pointer_width = "32")]
72        let read_usize = |bytes: &[u8]| u32::from_ne_bytes(bytes[..4].try_into().unwrap());
73        #[cfg(target_pointer_width = "64")]
74        let read_usize = |bytes: &[u8]| u64::from_ne_bytes(bytes[..8].try_into().unwrap());
75
76        let mut hash = FxHasher { hash: self.hash };
77        assert!(size_of::<usize>() <= 8);
78        while bytes.len() >= size_of::<usize>() {
79            hash.add_to_hash(read_usize(bytes) as usize);
80            bytes = &bytes[size_of::<usize>()..];
81        }
82        if (size_of::<usize>() > 4) && (bytes.len() >= 4) {
83            hash.add_to_hash(u32::from_ne_bytes(bytes[..4].try_into().unwrap()) as usize);
84            bytes = &bytes[4..];
85        }
86        if (size_of::<usize>() > 2) && bytes.len() >= 2 {
87            hash.add_to_hash(u16::from_ne_bytes(bytes[..2].try_into().unwrap()) as usize);
88            bytes = &bytes[2..];
89        }
90        if (size_of::<usize>() > 1) && !bytes.is_empty() {
91            hash.add_to_hash(bytes[0] as usize);
92        }
93        self.hash = hash.hash;
94    }
95
96    #[inline]
97    fn write_u8(&mut self, i: u8) {
98        self.add_to_hash(i as usize);
99    }
100
101    #[inline]
102    fn write_u16(&mut self, i: u16) {
103        self.add_to_hash(i as usize);
104    }
105
106    #[inline]
107    fn write_u32(&mut self, i: u32) {
108        self.add_to_hash(i as usize);
109    }
110
111    #[cfg(target_pointer_width = "32")]
112    #[inline]
113    fn write_u64(&mut self, i: u64) {
114        self.add_to_hash(i as usize);
115        self.add_to_hash((i >> 32) as usize);
116    }
117
118    #[cfg(target_pointer_width = "64")]
119    #[inline]
120    fn write_u64(&mut self, i: u64) {
121        self.add_to_hash(i as usize);
122    }
123
124    #[inline]
125    fn write_usize(&mut self, i: usize) {
126        self.add_to_hash(i);
127    }
128
129    #[inline]
130    fn finish(&self) -> u64 {
131        self.hash as u64
132    }
133}