1use parking_lot::{ReentrantMutex, ReentrantMutexGuard};
2use serde::{Deserializer, Serialize, Serializer};
3use std::borrow::Borrow;
4use std::cell::UnsafeCell;
5use std::collections::{
6 hash_map::IntoIter as MapIntoIter, hash_map::Iter as MapIter, hash_map::IterMut as MapIterMut,
7 HashMap as Map,
8};
9use std::fmt::{Debug, Display, Formatter};
10use std::hash::Hash;
11use std::ops::{Deref, DerefMut};
12use std::sync::Arc;
13
14pub struct SyncHashMap<K: Eq + Hash, V> {
16 locks: UnsafeCell<Map<K, ReentrantMutex<()>>>,
17 dirty: UnsafeCell<Map<K, V>>,
18 lock: ReentrantMutex<()>,
19}
20
21unsafe impl<K: Eq + Hash, V> Send for SyncHashMap<K, V> {}
23
24unsafe impl<K: Eq + Hash, V> Sync for SyncHashMap<K, V> {}
26
27impl<K, V> std::ops::Index<&K> for SyncHashMap<K, V>
28where
29 K: Eq + Hash,
30{
31 type Output = V;
32
33 fn index(&self, index: &K) -> &Self::Output {
34 unsafe { &(&*self.dirty.get())[index] }
35 }
36}
37
38impl<K, V> SyncHashMap<K, V>
39where
40 K: Eq + Hash,
41{
42 pub fn new_arc() -> Arc<Self> {
43 Arc::new(Self::new())
44 }
45
46 pub fn new() -> Self {
47 Self {
48 locks: UnsafeCell::new(Map::new()),
49 dirty: UnsafeCell::new(Map::new()),
50 lock: Default::default(),
51 }
52 }
53
54 pub fn with_capacity(capacity: usize) -> Self {
55 Self {
56 locks: UnsafeCell::new(Map::new()),
57 dirty: UnsafeCell::new(Map::with_capacity(capacity)),
58 lock: Default::default(),
59 }
60 }
61
62 pub fn with_map(map: Map<K, V>) -> Self {
63 Self {
64 locks: UnsafeCell::new(Map::new()),
65 dirty: UnsafeCell::new(map),
66 lock: Default::default(),
67 }
68 }
69
70 pub fn insert(&self, k: K, v: V) -> Option<V> {
71 let g = self.lock.lock();
72 let m = unsafe { &mut *self.dirty.get() };
73 let r = m.insert(k, v);
74 drop(g);
75 r
76 }
77
78 pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
79 let m = unsafe { &mut *self.dirty.get() };
80 m.insert(k, v)
81 }
82
83 pub fn remove(&self, k: &K) -> Option<V> {
84 let g = self.lock.lock();
85 let m = unsafe { &mut *self.dirty.get() };
86 let r = m.remove(k);
87 drop(g);
88 r
89 }
90
91 pub fn remove_mut(&mut self, k: &K) -> Option<V> {
92 let m = unsafe { &mut *self.dirty.get() };
93 m.remove(k)
94 }
95
96 pub fn len(&self) -> usize {
97 unsafe { (&*self.dirty.get()).len() }
98 }
99
100 pub fn is_empty(&self) -> bool {
101 unsafe { (&*self.dirty.get()).is_empty() }
102 }
103
104 pub fn clear(&self) {
105 let g = self.lock.lock();
106 let m = unsafe { &mut *self.dirty.get() };
107 m.clear();
108 drop(g);
109 }
110
111 pub fn clear_mut(&mut self) {
112 let m = unsafe { &mut *self.dirty.get() };
113 m.clear();
114 }
115
116 pub fn shrink_to_fit(&self) {
117 let g = self.lock.lock();
118 let m = unsafe { &mut *self.dirty.get() };
119 m.shrink_to_fit();
120 drop(g);
121 }
122
123 pub fn shrink_to_fit_mut(&mut self) {
124 let m = unsafe { &mut *self.dirty.get() };
125 m.shrink_to_fit()
126 }
127
128 pub fn from(map: Map<K, V>) -> Self
129 where
130 K: Eq + Hash,
131 {
132 let s = Self::with_map(map);
133 s
134 }
135
136 #[inline]
156 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
157 where
158 K: Borrow<Q>,
159 Q: Hash + Eq,
160 {
161 unsafe { (&*self.dirty.get()).get(k) }
162 }
163
164 #[inline]
165 pub fn get_mut(&self, k: &K) -> Option<HashMapRefMut<'_, K, V>>
166 where
167 K: Hash + Eq + Clone,
168 {
169 let get_mut_lock = self.lock.lock();
170 let m = unsafe { &mut *self.locks.get() };
171 if m.contains_key(k) == false {
172 let g = ReentrantMutex::new(());
173 m.insert(k.clone(), g);
174 }
175 let g = m.get(k).unwrap();
176 let v = HashMapRefMut {
177 k: unsafe { std::mem::transmute(&k) },
178 m: self,
179 _g: g.lock(),
180 value: {
181 let m = unsafe { &mut *self.dirty.get() };
182 m.get_mut(k)?
183 },
184 };
185 drop(get_mut_lock);
186 Some(v)
187 }
188
189 #[inline]
190 pub fn contains_key(&self, x: &K) -> bool
191 where
192 K: PartialEq,
193 {
194 let m = unsafe { &mut *self.dirty.get() };
195 m.contains_key(x)
196 }
197
198 pub fn iter(&self) -> MapIter<'_, K, V> {
199 unsafe { (&*self.dirty.get()).iter() }
200 }
201
202 pub fn iter_mut(&self) -> HashIterMut<'_, K, V> {
203 return HashIterMut {
204 _g: self.lock.lock(),
205 inner: {
206 let m = unsafe { &mut *self.dirty.get() };
207 m.iter_mut()
208 },
209 };
210 }
211
212 pub fn into_iter(self) -> MapIntoIter<K, V> {
213 self.dirty.into_inner().into_iter()
214 }
215
216 pub fn dirty_ref(&self) -> &Map<K, V> {
217 unsafe { &*self.dirty.get() }
218 }
219
220 pub fn into_inner(self) -> Map<K, V> {
221 self.dirty.into_inner()
222 }
223}
224
225pub struct HashMapRefMut<'a, K: Eq + Hash, V> {
226 k: &'a K,
227 m: &'a SyncHashMap<K, V>,
228 _g: ReentrantMutexGuard<'a, ()>,
229 value: &'a mut V,
230}
231
232impl<'a, K: Eq + Hash, V> Drop for HashMapRefMut<'a, K, V> {
233 fn drop(&mut self) {
234 let m = unsafe { &mut *self.m.locks.get() };
235 _ = m.remove(self.k);
236 }
237}
238
239impl<'a, K: Eq + Hash, V> Deref for HashMapRefMut<'_, K, V> {
240 type Target = V;
241
242 fn deref(&self) -> &Self::Target {
243 self.value
244 }
245}
246
247impl<'a, K: Eq + Hash, V> DerefMut for HashMapRefMut<'_, K, V> {
248 fn deref_mut(&mut self) -> &mut Self::Target {
249 self.value
250 }
251}
252
253impl<'a, K: Eq + Hash, V> Debug for HashMapRefMut<'_, K, V>
254where
255 V: Debug,
256{
257 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
258 self.value.fmt(f)
259 }
260}
261
262impl<'a, K: Eq + Hash, V> Display for HashMapRefMut<'_, K, V>
263where
264 V: Display,
265{
266 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
267 self.value.fmt(f)
268 }
269}
270
271impl<'a, K: Eq + Hash, V> PartialEq<Self> for HashMapRefMut<'_, K, V>
272where
273 V: Eq,
274{
275 fn eq(&self, other: &Self) -> bool {
276 self.value.eq(&other.value)
277 }
278}
279
280impl<'a, K: Eq + Hash, V> Eq for HashMapRefMut<'_, K, V> where V: Eq {}
281
282pub struct HashIterMut<'a, K, V> {
283 _g: ReentrantMutexGuard<'a, ()>,
284 inner: MapIterMut<'a, K, V>,
285}
286
287impl<'a, K, V> Deref for HashIterMut<'a, K, V> {
288 type Target = MapIterMut<'a, K, V>;
289
290 fn deref(&self) -> &Self::Target {
291 &self.inner
292 }
293}
294
295impl<'a, K, V> DerefMut for HashIterMut<'a, K, V> {
296 fn deref_mut(&mut self) -> &mut Self::Target {
297 &mut self.inner
298 }
299}
300
301impl<'a, K, V> Iterator for HashIterMut<'a, K, V> {
302 type Item = (&'a K, &'a mut V);
303
304 fn next(&mut self) -> Option<Self::Item> {
305 self.inner.next()
306 }
307}
308
309impl<'a, K, V> IntoIterator for &'a SyncHashMap<K, V>
310where
311 K: Eq + Hash,
312{
313 type Item = (&'a K, &'a V);
314 type IntoIter = MapIter<'a, K, V>;
315
316 fn into_iter(self) -> Self::IntoIter {
317 self.iter()
318 }
319}
320
321impl<K, V> IntoIterator for SyncHashMap<K, V>
322where
323 K: Eq + Hash,
324{
325 type Item = (K, V);
326 type IntoIter = MapIntoIter<K, V>;
327
328 fn into_iter(self) -> Self::IntoIter {
329 self.into_iter()
330 }
331}
332
333impl<K: Eq + Hash, V> From<Map<K, V>> for SyncHashMap<K, V> {
334 fn from(arg: Map<K, V>) -> Self {
335 Self::from(arg)
336 }
337}
338
339impl<K, V> serde::Serialize for SyncHashMap<K, V>
340where
341 K: Eq + Hash + Serialize,
342 V: Serialize,
343{
344 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
345 where
346 S: Serializer,
347 {
348 self.dirty_ref().serialize(serializer)
349 }
350}
351
352impl<'de, K, V> serde::Deserialize<'de> for SyncHashMap<K, V>
353where
354 K: Eq + Hash + serde::Deserialize<'de>,
355 V: serde::Deserialize<'de>,
356{
357 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
358 where
359 D: Deserializer<'de>,
360 {
361 let m = Map::deserialize(deserializer)?;
362 Ok(Self::from(m))
363 }
364}
365
366impl<K, V> Debug for SyncHashMap<K, V>
367where
368 K: Eq + Hash + Debug,
369 V: Debug,
370{
371 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
372 self.dirty_ref().fmt(f)
373 }
374}
375
376impl<K, V> Display for SyncHashMap<K, V>
377where
378 K: Eq + Hash + Display,
379 V: Display,
380{
381 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
382 use std::fmt::Pointer;
383 self.dirty_ref().fmt(f)
384 }
385}
386
387impl<K: Clone + Eq + Hash, V: Clone> Clone for SyncHashMap<K, V> {
388 fn clone(&self) -> Self {
389 let c = (*self.dirty_ref()).clone();
390 SyncHashMap::from(c)
391 }
392}
393
394impl<K: Eq + Hash, V> Default for SyncHashMap<K, V> {
395 fn default() -> Self {
396 SyncHashMap::new()
397 }
398}