1use std::collections::{HashMap, HashSet};
9use std::hash::{BuildHasher, Hash, Hasher};
10
11const K: u64 = 0x517cc1b727220a95;
12
13pub type FastSet<T> = HashSet<T, BuildFxHasher>;
15
16pub type FastMap<K, V> = HashMap<K, V, BuildFxHasher>;
18
19pub trait FastSetExt<T> {
21 #[must_use]
22 fn new() -> Self;
23 #[must_use]
24 fn with_capacity(capacity: usize) -> Self;
25 #[must_use]
26 fn build<const N: usize>(array: [T; N]) -> Self;
27}
28
29impl<T: Eq + Hash> FastSetExt<T> for FastSet<T> {
30 fn new() -> Self {
31 Self::with_hasher(BuildFxHasher)
32 }
33
34 fn with_capacity(capacity: usize) -> Self {
35 Self::with_capacity_and_hasher(capacity, BuildFxHasher)
36 }
37
38 fn build<const N: usize>(array: [T; N]) -> Self {
39 Self::from_iter(array)
40 }
41}
42
43pub trait FastMapExt<K, V> {
45 #[must_use]
46 fn new() -> Self;
47 #[must_use]
48 fn with_capacity(capacity: usize) -> Self;
49 #[must_use]
50 fn build<const N: usize>(array: [(K, V); N]) -> Self;
51}
52
53impl<K: Eq + Hash, V> FastMapExt<K, V> for FastMap<K, V> {
54 fn new() -> Self {
55 Self::with_hasher(BuildFxHasher)
56 }
57
58 fn with_capacity(capacity: usize) -> Self {
59 Self::with_capacity_and_hasher(capacity, BuildFxHasher)
60 }
61
62 fn build<const N: usize>(array: [(K, V); N]) -> Self {
63 Self::from_iter(array)
64 }
65}
66
67#[derive(Clone, Copy, Default)]
69pub struct BuildFxHasher;
70
71impl BuildHasher for BuildFxHasher {
72 type Hasher = FxHasher;
73
74 #[inline]
75 fn build_hasher(&self) -> Self::Hasher {
76 FxHasher { hash: 0 }
77 }
78}
79
80pub struct FxHasher {
85 hash: u64,
86}
87
88impl FxHasher {
89 #[inline]
90 fn add(&mut self, i: u64) {
91 self.hash = (self.hash.rotate_left(5) ^ i).wrapping_mul(K);
92 }
93}
94
95impl Hasher for FxHasher {
96 #[inline]
97 fn write(&mut self, mut bytes: &[u8]) {
98 while let Some((&head, tail)) = bytes.split_first_chunk() {
99 self.add(u64::from_ne_bytes(head));
100 bytes = tail;
101 }
102 if let Some((&head, tail)) = bytes.split_first_chunk() {
103 self.add(u32::from_ne_bytes(head) as u64);
104 bytes = tail;
105 }
106 if let Some((&head, tail)) = bytes.split_first_chunk() {
107 self.add(u16::from_ne_bytes(head) as u64);
108 bytes = tail;
109 }
110 if !bytes.is_empty() {
111 self.add(bytes[0] as u64);
112 }
113 }
114
115 #[inline]
116 fn write_u8(&mut self, i: u8) {
117 self.add(i as u64);
118 }
119
120 #[inline]
121 fn write_u16(&mut self, i: u16) {
122 self.add(i as u64);
123 }
124
125 #[inline]
126 fn write_u32(&mut self, i: u32) {
127 self.add(i as u64);
128 }
129
130 #[inline]
131 fn write_u64(&mut self, i: u64) {
132 self.add(i);
133 }
134
135 #[inline]
136 fn write_usize(&mut self, i: usize) {
137 self.add(i as u64);
138 }
139
140 #[inline]
141 fn finish(&self) -> u64 {
142 self.hash
143 }
144}