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