1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
use std::borrow::Borrow;
use std::collections::hash_map::{Entry, IntoValues, Iter, IterMut, Keys, Values, ValuesMut};
use std::fmt::{self, Write};
use std::hash::{Hash, Hasher};
use std::iter::FromIterator;

use crate::fxhash::FxHashMap;

#[macro_export]
macro_rules! dict {
    () => { $crate::dict::Dict::new() };
    ($($k: expr => $v: expr),+ $(,)?) => {{
        let mut dict = $crate::dict::Dict::new();
        $(dict.insert($k, $v);)+
        dict
    }};
}

#[derive(Debug, Clone)]
pub struct Dict<K, V> {
    dict: FxHashMap<K, V>,
}

impl<K: Hash + Eq, V: Hash + Eq> PartialEq for Dict<K, V> {
    fn eq(&self, other: &Dict<K, V>) -> bool {
        self.dict == other.dict
    }
}

impl<K: Hash + Eq, V: Hash + Eq> Eq for Dict<K, V> {}

impl<K: Hash, V: Hash> Hash for Dict<K, V> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let keys = self.dict.keys().collect::<Vec<_>>();
        keys.hash(state);
        let vals = self.dict.values().collect::<Vec<_>>();
        vals.hash(state);
    }
}

impl<K: fmt::Display, V: fmt::Display> fmt::Display for Dict<K, V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = "".to_string();
        for (k, v) in self.dict.iter() {
            write!(s, "{k}: {v}, ")?;
        }
        s.pop();
        s.pop();
        write!(f, "{{{s}}}")
    }
}

impl<K: Hash + Eq, V> FromIterator<(K, V)> for Dict<K, V> {
    #[inline]
    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Dict<K, V> {
        let mut dict = Dict::new();
        dict.extend(iter);
        dict
    }
}

impl<K, V> Default for Dict<K, V> {
    fn default() -> Dict<K, V> {
        Dict::new()
    }
}

impl<K, V> Dict<K, V> {
    #[inline]
    pub fn new() -> Self {
        Self {
            dict: FxHashMap::default(),
        }
    }

    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            dict: FxHashMap::with_capacity_and_hasher(capacity, Default::default()),
        }
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.dict.len()
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.dict.is_empty()
    }

    #[inline]
    pub fn capacity(&self) -> usize {
        self.dict.capacity()
    }

    #[inline]
    pub fn keys(&self) -> Keys<K, V> {
        self.dict.keys()
    }

    #[inline]
    pub fn values(&self) -> Values<K, V> {
        self.dict.values()
    }

    #[inline]
    pub fn values_mut(&mut self) -> ValuesMut<K, V> {
        self.dict.values_mut()
    }

    #[inline]
    pub fn into_values(self) -> IntoValues<K, V> {
        self.dict.into_values()
    }

    #[inline]
    pub fn iter(&self) -> Iter<K, V> {
        self.dict.iter()
    }

    #[inline]
    pub fn iter_mut(&mut self) -> IterMut<K, V> {
        self.dict.iter_mut()
    }

    pub fn clear(&mut self) {
        self.dict.clear();
    }

    /// remove all elements for which the predicate returns false
    pub fn retain<F>(&mut self, f: F)
    where
        F: FnMut(&K, &mut V) -> bool,
    {
        self.dict.retain(f);
    }
}

impl<K, V> IntoIterator for Dict<K, V> {
    type Item = (K, V);
    type IntoIter = <FxHashMap<K, V> as IntoIterator>::IntoIter;
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.dict.into_iter()
    }
}

impl<K: Hash + Eq, V> Dict<K, V> {
    #[inline]
    pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq,
    {
        self.dict.get(k)
    }

    pub fn get_by(&self, k: &K, cmp: impl Fn(&K, &K) -> bool) -> Option<&V> {
        for (k_, v) in self.dict.iter() {
            if cmp(k, k_) {
                return Some(v);
            }
        }
        None
    }

    #[inline]
    pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq,
    {
        self.dict.get_mut(k)
    }

    pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
    where
        K: Borrow<Q>,
        Q: Hash + Eq,
    {
        self.dict.get_key_value(k)
    }

    #[inline]
    pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
    where
        K: Borrow<Q>,
        Q: Hash + Eq,
    {
        self.dict.contains_key(k)
    }

    #[inline]
    pub fn insert(&mut self, k: K, v: V) -> Option<V> {
        self.dict.insert(k, v)
    }

    #[inline]
    pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq,
    {
        self.dict.remove(k)
    }

    /// NOTE: This method does not consider pairing with values and keys. That is, a value may be paired with a different key (can be considered equal).
    /// If you need to consider the pairing of the keys and values, use `guaranteed_extend` instead.
    #[inline]
    pub fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
        self.dict.extend(iter);
    }

    #[inline]
    pub fn guaranteed_extend<I: IntoIterator<Item = (K, V)>>(&mut self, other: I) {
        for (k, v) in other {
            self.dict.entry(k).or_insert(v);
        }
    }

    #[inline]
    pub fn merge(&mut self, other: Self) {
        self.dict.extend(other.dict);
    }

    #[inline]
    pub fn concat(mut self, other: Self) -> Self {
        self.merge(other);
        self
    }

    #[inline]
    pub fn diff(mut self, other: &Self) -> Self {
        for k in other.dict.keys() {
            self.dict.remove(k);
        }
        self
    }

    pub fn entry(&mut self, k: K) -> Entry<K, V> {
        self.dict.entry(k)
    }
}