1use serde::{Deserialize, Deserializer, Serialize, Serializer};
2use spin::{RwLock, RwLockReadGuard, RwLockWriteGuard};
3use std::borrow::Borrow;
4use std::cell::UnsafeCell;
5use std::collections::hash_map::{
6 IntoIter as MapIntoIter, Iter as MapIter, Keys,
7};
8use std::collections::HashMap;
9use std::fmt::{Debug, Formatter};
10use std::hash::{Hash, DefaultHasher, BuildHasherDefault};
11use std::ops::{Deref, DerefMut};
12use std::sync::Arc;
13
14pub type DefaultBuildHasher = BuildHasherDefault<DefaultHasher>;
24
25pub struct SyncHashMap<K, V> {
56 dirty: UnsafeCell<HashMap<K, RwLock<V>, DefaultBuildHasher>>,
59 lock: RwLock<()>,
62}
63
64unsafe impl<K, V> Send for SyncHashMap<K, V> {}
68
69unsafe impl<K, V> Sync for SyncHashMap<K, V> {}
73
74impl<K, V> SyncHashMap<K, V>
77where
78 K: Eq + Hash,
79{
80 pub fn new_arc() -> Arc<Self> {
83 Arc::new(Self::new())
84 }
85
86 pub const fn new() -> Self {
89 Self {
90 dirty: UnsafeCell::new(HashMap::with_hasher(DefaultBuildHasher::new())),
91 lock: RwLock::new(()),
92 }
93 }
94
95 pub fn with_capacity(capacity: usize) -> Self {
98 Self {
99 dirty: UnsafeCell::new(HashMap::with_capacity_and_hasher(
100 capacity,
101 std::hash::BuildHasherDefault::default(),
102 )),
103 lock: RwLock::new(()),
104 }
105 }
106
107 pub fn with_map(map: HashMap<K, V>) -> Self {
113 let mut wrapped = HashMap::with_capacity_and_hasher(
114 map.len(),
115 std::hash::BuildHasherDefault::default(),
116 );
117 for (k, v) in map {
118 wrapped.insert(k, RwLock::new(v));
119 }
120 Self {
121 dirty: UnsafeCell::new(wrapped),
122 lock: RwLock::new(()),
123 }
124 }
125
126 #[inline(always)]
132 pub fn insert(&self, k: K, v: V) -> Option<V> {
133 let _lock = self.lock.write();
134 let m = unsafe { &mut *self.dirty.get() };
135 m.insert(k, RwLock::new(v)).map(|old| old.into_inner())
136 }
137
138 #[inline(always)]
141 pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
142 let m = unsafe { &mut *self.dirty.get() };
143 m.insert(k, RwLock::new(v)).map(|old| old.into_inner())
144 }
145
146 #[inline(always)]
149 pub fn remove(&self, k: &K) -> Option<V> {
150 let _lock = self.lock.write();
151 let m = unsafe { &mut *self.dirty.get() };
152 m.remove(k).map(|v| v.into_inner())
153 }
154
155 #[inline(always)]
158 pub fn remove_mut(&mut self, k: &K) -> Option<V> {
159 let m = unsafe { &mut *self.dirty.get() };
160 m.remove(k).map(|v| v.into_inner())
161 }
162
163 #[inline(always)]
166 pub fn len(&self) -> usize {
167 let _lock = self.lock.read();
168 let m = unsafe { &*self.dirty.get() };
169 m.len()
170 }
171
172 #[inline(always)]
175 pub fn is_empty(&self) -> bool {
176 let _lock = self.lock.read();
177 let m = unsafe { &*self.dirty.get() };
178 m.is_empty()
179 }
180
181 #[inline(always)]
184 pub fn clear(&self) {
185 let _lock = self.lock.write();
186 let m = unsafe { &mut *self.dirty.get() };
187 m.clear();
188 }
189
190 #[inline(always)]
193 pub fn clear_mut(&mut self) {
194 let m = unsafe { &mut *self.dirty.get() };
195 m.clear();
196 }
197
198 #[inline(always)]
201 pub fn shrink_to_fit(&self) {
202 let _lock = self.lock.write();
203 let m = unsafe { &mut *self.dirty.get() };
204 m.shrink_to_fit();
205 }
206
207 #[inline(always)]
210 pub fn shrink_to_fit_mut(&mut self) {
211 let m = unsafe { &mut *self.dirty.get() };
212 m.shrink_to_fit();
213 }
214
215 pub fn from(map: HashMap<K, V>) -> Self {
218 Self::with_map(map)
219 }
220
221 #[inline]
245 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<MapReadGuard<'_, V>>
246 where
247 K: Borrow<Q>,
248 Q: Hash + Eq,
249 {
250 let map_lock = self.lock.read();
251 let m = unsafe { &*self.dirty.get() };
252 let value_lock_wrapper = m.get(k)?;
253 let value_ptr = unsafe {
255 let lock_ptr = value_lock_wrapper as *const RwLock<V> as *mut RwLock<V>;
256 &*(*lock_ptr).get_mut()
257 };
258 Some(MapReadGuard {
259 _map_lock: map_lock,
260 _value_ptr: value_ptr,
261 })
262 }
263
264 #[inline]
277 pub fn get_uncheck<Q: ?Sized>(&self, k: &Q) -> MapReadGuard<'_, V>
278 where
279 K: Borrow<Q>,
280 Q: Hash + Eq,
281 {
282 let map_lock = self.lock.read();
283 let m = unsafe { &*self.dirty.get() };
284 let value_lock_wrapper = m.get(k).expect("key not found");
285 let value_ptr = unsafe {
287 let lock_ptr = value_lock_wrapper as *const RwLock<V> as *mut RwLock<V>;
288 &*(*lock_ptr).get_mut()
289 };
290 MapReadGuard {
291 _map_lock: map_lock,
292 _value_ptr: value_ptr,
293 }
294 }
295
296 #[inline]
304 pub fn get_mut<Q: ?Sized>(&self, k: &Q) -> Option<WriteGuard<'_, V>>
305 where
306 K: Borrow<Q>,
307 Q: Hash + Eq,
308 {
309 let map_lock = self.lock.read();
310 let m = unsafe { &*self.dirty.get() };
311 let value_lock_wrapper = m.get(k)?;
312 let value_lock = value_lock_wrapper.write();
313 Some(WriteGuard {
314 _map_lock: map_lock,
315 _value_lock: value_lock,
316 })
317 }
318
319 #[inline]
322 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
323 where
324 K: Borrow<Q>,
325 Q: Hash + Eq,
326 {
327 let _lock = self.lock.read();
328 let m = unsafe { &*self.dirty.get() };
329 m.contains_key(k)
330 }
331
332 pub fn iter_mut(&self) -> IterMut<'_, K, V> {
338 let _lock = self.lock.read();
339 let m = unsafe { &*self.dirty.get() };
340 IterMut {
341 _lock,
342 inner: m.iter(),
343 }
344 }
345
346 pub fn iter_rlock(&self) -> IterRLock<'_, K, V> {
354 let _lock = self.lock.read();
355 let m = unsafe { &*self.dirty.get() };
356 IterRLock {
357 _lock,
358 inner: m.iter(),
359 }
360 }
361
362 pub fn iter(&self) -> IterNoLock<'_, K, V> {
371 let _lock = self.lock.read();
372 let m = unsafe { &*self.dirty.get() };
373 IterNoLock {
374 _lock,
375 inner: m.iter(),
376 }
377 }
378
379 pub fn dirty_ref(&self) -> ReadGuardMap<'_, K, V> {
387 let _lock = self.lock.read();
388 let v = unsafe { &*self.dirty.get() };
389 ReadGuardMap { _lock, v }
390 }
391
392 pub unsafe fn dirty_ref_unsafe(&self) -> &HashMap<K, RwLock<V>, DefaultBuildHasher> {
400 unsafe { &*self.dirty.get() }
401 }
402
403 pub fn into_inner(self) -> HashMap<K, V> {
406 self.dirty
407 .into_inner()
408 .into_iter()
409 .map(|(k, v)| (k, v.into_inner()))
410 .collect()
411 }
412
413 #[inline]
419 pub fn keys(&self) -> KeysGuard<'_, K, V> {
420 let _lock = self.lock.read();
421 let m = unsafe { &*self.dirty.get() };
422 KeysGuard {
423 _lock,
424 inner: m.keys(),
425 }
426 }
427
428 #[inline]
434 pub fn values(&self) -> ValuesGuard<'_, K, V> {
435 let _lock = self.lock.read();
436 let m = unsafe { &*self.dirty.get() };
437 ValuesGuard {
438 _lock,
439 inner: m.values(),
440 }
441 }
442
443 #[inline]
449 pub fn values_mut(&self) -> ValuesMutGuard<'_, K, V> {
450 let _lock = self.lock.write();
451 let m = unsafe { &*self.dirty.get() };
452 ValuesMutGuard {
453 _lock,
454 inner: m.values(),
455 }
456 }
457
458 #[inline]
461 pub fn retain<F>(&self, mut f: F)
462 where
463 F: FnMut(&K, &mut V) -> bool,
464 {
465 let _lock = self.lock.write();
466 let m = unsafe { &mut *self.dirty.get() };
467 m.retain(|k, v| f(k, v.get_mut()));
468 }
469
470 #[inline]
473 pub fn capacity(&self) -> usize {
474 let _lock = self.lock.read();
475 let m = unsafe { &*self.dirty.get() };
476 m.capacity()
477 }
478
479 #[inline]
482 pub fn reserve(&self, additional: usize) {
483 let _lock = self.lock.write();
484 let m = unsafe { &mut *self.dirty.get() };
485 m.reserve(additional);
486 }
487
488 #[inline]
491 pub fn remove_entry(&self, k: &K) -> Option<(K, V)> {
492 let _lock = self.lock.write();
493 let m = unsafe { &mut *self.dirty.get() };
494 m.remove_entry(k).map(|(k, v)| (k, v.into_inner()))
495 }
496
497 #[inline]
503 pub fn get_or_insert(&self, k: K, default: V) -> WriteGuardEntry<'_, V> {
504 let map_lock = self.lock.write();
505 let m = unsafe { &mut *self.dirty.get() };
506 let entry = m.entry(k).or_insert_with(|| RwLock::new(default));
507 let value_lock = entry.write();
508 WriteGuardEntry {
509 _map_lock: map_lock,
510 _value_lock: value_lock,
511 }
512 }
513
514 #[inline]
520 pub fn get_or_insert_with<F>(&self, k: K, default: F) -> WriteGuardEntry<'_, V>
521 where
522 F: FnOnce() -> V,
523 {
524 let map_lock = self.lock.write();
525 let m = unsafe { &mut *self.dirty.get() };
526 let entry = m.entry(k).or_insert_with(|| RwLock::new(default()));
527 let value_lock = entry.write();
528 WriteGuardEntry {
529 _map_lock: map_lock,
530 _value_lock: value_lock,
531 }
532 }
533
534 #[inline]
540 pub fn get_clone<Q: ?Sized>(&self, k: &Q) -> Option<V>
541 where
542 K: Borrow<Q>,
543 Q: Hash + Eq,
544 V: Clone,
545 {
546 let _map_lock = self.lock.read();
547 let m = unsafe { &*self.dirty.get() };
548 m.get(k).map(|v| v.read().clone())
549 }
550
551 #[inline]
557 pub fn take(&self, k: &K) -> Option<V> {
558 self.remove(k)
559 }
560}
561
562pub struct MapReadGuard<'a, V> {
570 _map_lock: RwLockReadGuard<'a, ()>,
573 _value_ptr: &'a V,
576}
577
578impl<'a, V> Deref for MapReadGuard<'a, V> {
579 type Target = V;
580
581 fn deref(&self) -> &Self::Target {
582 self._value_ptr
583 }
584}
585
586impl<'a, V> Debug for MapReadGuard<'a, V>
587where
588 V: Debug,
589{
590 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
591 write!(f, "{:?}", self._value_ptr)
592 }
593}
594
595impl<'a, V> PartialEq for MapReadGuard<'a, V>
596where
597 V: PartialEq,
598{
599 fn eq(&self, other: &Self) -> bool {
600 self._value_ptr.eq(other._value_ptr)
601 }
602}
603
604impl<'a, V> Eq for MapReadGuard<'a, V> where V: Eq {}
605
606impl<'a, V> std::fmt::Display for MapReadGuard<'a, V>
607where
608 V: std::fmt::Display,
609{
610 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
611 self._value_ptr.fmt(f)
612 }
613}
614
615impl<'a, V> AsRef<V> for MapReadGuard<'a, V> {
616 fn as_ref(&self) -> &V {
617 self._value_ptr
618 }
619}
620
621pub struct ReadGuard<'a, V> {
624 _map_lock: RwLockReadGuard<'a, ()>,
627 _value_lock: RwLockReadGuard<'a, V>,
630}
631
632impl<'a, V> Deref for ReadGuard<'a, V> {
633 type Target = V;
634
635 fn deref(&self) -> &Self::Target {
636 &*self._value_lock
637 }
638}
639
640impl<'a, V> Debug for ReadGuard<'a, V>
641where
642 V: Debug,
643{
644 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
645 write!(f, "{:?}", &*self._value_lock)
646 }
647}
648
649impl<'a, V> PartialEq for ReadGuard<'a, V>
650where
651 V: PartialEq,
652{
653 fn eq(&self, other: &Self) -> bool {
654 (*self._value_lock).eq(&*other._value_lock)
655 }
656}
657
658impl<'a, V> Eq for ReadGuard<'a, V> where V: Eq {}
659
660impl<'a, V> std::fmt::Display for ReadGuard<'a, V>
661where
662 V: std::fmt::Display,
663{
664 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
665 (*self._value_lock).fmt(f)
666 }
667}
668
669impl<'a, V> AsRef<V> for ReadGuard<'a, V> {
670 fn as_ref(&self) -> &V {
671 &*self._value_lock
672 }
673}
674
675pub struct ReadGuardMap<'a, K, V> {
681 _lock: RwLockReadGuard<'a, ()>,
684 v: &'a HashMap<K, RwLock<V>, DefaultBuildHasher>,
687}
688
689impl<'a, K, V> Deref for ReadGuardMap<'a, K, V> {
690 type Target = HashMap<K, RwLock<V>, DefaultBuildHasher>;
691
692 fn deref(&self) -> &Self::Target {
693 self.v
694 }
695}
696
697impl<'a, K, V> Debug for ReadGuardMap<'a, K, V>
698where
699 K: Debug,
700 V: Debug,
701{
702 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
703 let mut map = f.debug_map();
706 for (k, v) in self.v.iter() {
707 map.entry(k, &*v.read());
708 }
709 map.finish()
710 }
711}
712
713impl<'a, K, V> AsRef<HashMap<K, RwLock<V>, DefaultBuildHasher>> for ReadGuardMap<'a, K, V> {
714 fn as_ref(&self) -> &HashMap<K, RwLock<V>, DefaultBuildHasher> {
715 self.v
716 }
717}
718
719pub struct WriteGuard<'a, V> {
725 _map_lock: RwLockReadGuard<'a, ()>,
728 _value_lock: RwLockWriteGuard<'a, V>,
731}
732
733impl<'a, V> Deref for WriteGuard<'a, V> {
734 type Target = V;
735
736 fn deref(&self) -> &Self::Target {
737 &*self._value_lock
738 }
739}
740
741impl<'a, V> DerefMut for WriteGuard<'a, V> {
742 fn deref_mut(&mut self) -> &mut Self::Target {
743 &mut *self._value_lock
744 }
745}
746
747impl<'a, V> Debug for WriteGuard<'a, V>
748where
749 V: Debug,
750{
751 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
752 write!(f, "{:?}", &*self._value_lock)
753 }
754}
755
756impl<'a, V> PartialEq for WriteGuard<'a, V>
757where
758 V: PartialEq,
759{
760 fn eq(&self, other: &Self) -> bool {
761 (*self._value_lock).eq(&*other._value_lock)
762 }
763}
764
765impl<'a, V> Eq for WriteGuard<'a, V> where V: Eq {}
766
767impl<'a, V> std::fmt::Display for WriteGuard<'a, V>
768where
769 V: std::fmt::Display,
770{
771 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
772 (*self._value_lock).fmt(f)
773 }
774}
775
776impl<'a, V> AsRef<V> for WriteGuard<'a, V> {
777 fn as_ref(&self) -> &V {
778 &*self._value_lock
779 }
780}
781
782impl<'a, V> AsMut<V> for WriteGuard<'a, V> {
783 fn as_mut(&mut self) -> &mut V {
784 &mut *self._value_lock
785 }
786}
787
788pub struct WriteGuardEntry<'a, V> {
794 _map_lock: RwLockWriteGuard<'a, ()>,
797 _value_lock: RwLockWriteGuard<'a, V>,
800}
801
802impl<'a, V> Deref for WriteGuardEntry<'a, V> {
803 type Target = V;
804
805 fn deref(&self) -> &Self::Target {
806 &*self._value_lock
807 }
808}
809
810impl<'a, V> DerefMut for WriteGuardEntry<'a, V> {
811 fn deref_mut(&mut self) -> &mut Self::Target {
812 &mut *self._value_lock
813 }
814}
815
816impl<'a, V> Debug for WriteGuardEntry<'a, V>
817where
818 V: Debug,
819{
820 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
821 write!(f, "{:?}", &*self._value_lock)
822 }
823}
824
825impl<'a, V> std::fmt::Display for WriteGuardEntry<'a, V>
826where
827 V: std::fmt::Display,
828{
829 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
830 (*self._value_lock).fmt(f)
831 }
832}
833
834impl<'a, V> AsRef<V> for WriteGuardEntry<'a, V> {
835 fn as_ref(&self) -> &V {
836 &*self._value_lock
837 }
838}
839
840impl<'a, V> AsMut<V> for WriteGuardEntry<'a, V> {
841 fn as_mut(&mut self) -> &mut V {
842 &mut *self._value_lock
843 }
844}
845
846#[allow(dead_code)]
849#[deprecated(note = "Use ReadGuard instead")]
850pub type SyncMapRefMut<'a, V> = WriteGuard<'a, V>;
851
852pub struct IterRLock<'a, K, V> {
858 _lock: RwLockReadGuard<'a, ()>,
861 inner: MapIter<'a, K, RwLock<V>>,
864}
865
866impl<'a, K, V> Iterator for IterRLock<'a, K, V> {
867 type Item = (&'a K, RwLockReadGuard<'a, V>);
868
869 fn next(&mut self) -> Option<Self::Item> {
870 self.inner.next().map(|(k, v)| (k, v.read()))
871 }
872}
873
874pub type IterMy<'a, K, V> = IterRLock<'a, K, V>;
877
878pub struct IterMut<'a, K, V> {
884 _lock: RwLockReadGuard<'a, ()>,
887 inner: MapIter<'a, K, RwLock<V>>,
890}
891
892impl<'a, K, V> Iterator for IterMut<'a, K, V> {
893 type Item = (&'a K, RwLockWriteGuard<'a, V>);
894
895 fn next(&mut self) -> Option<Self::Item> {
896 self.inner.next().map(|(k, v)| (k, v.write()))
897 }
898}
899
900pub struct KeysGuard<'a, K, V> {
903 _lock: RwLockReadGuard<'a, ()>,
906 inner: Keys<'a, K, RwLock<V>>,
909}
910
911impl<'a, K, V> Deref for KeysGuard<'a, K, V> {
912 type Target = Keys<'a, K, RwLock<V>>;
913
914 fn deref(&self) -> &Self::Target {
915 &self.inner
916 }
917}
918
919impl<'a, K, V> DerefMut for KeysGuard<'a, K, V> {
920 fn deref_mut(&mut self) -> &mut Self::Target {
921 &mut self.inner
922 }
923}
924
925impl<'a, K, V> Iterator for KeysGuard<'a, K, V> {
926 type Item = &'a K;
927
928 fn next(&mut self) -> Option<Self::Item> {
929 self.inner.next()
930 }
931}
932
933pub struct ValuesGuard<'a, K, V> {
939 _lock: RwLockReadGuard<'a, ()>,
942 inner: std::collections::hash_map::Values<'a, K, RwLock<V>>,
945}
946
947impl<'a, K, V> Iterator for ValuesGuard<'a, K, V> {
948 type Item = RwLockReadGuard<'a, V>;
949
950 fn next(&mut self) -> Option<Self::Item> {
951 self.inner.next().map(|v| v.read())
952 }
953}
954
955pub struct ValuesMutGuard<'a, K, V> {
961 _lock: RwLockWriteGuard<'a, ()>,
964 inner: std::collections::hash_map::Values<'a, K, RwLock<V>>,
967}
968
969impl<'a, K, V> Iterator for ValuesMutGuard<'a, K, V> {
970 type Item = RwLockWriteGuard<'a, V>;
971
972 fn next(&mut self) -> Option<Self::Item> {
973 self.inner.next().map(|v| v.write())
974 }
975}
976
977pub struct IterNoLock<'a, K, V> {
980 _lock: RwLockReadGuard<'a, ()>,
983 inner: MapIter<'a, K, RwLock<V>>,
986}
987
988impl<'a, K, V> Iterator for IterNoLock<'a, K, V> {
989 type Item = (&'a K, &'a V);
990
991 fn next(&mut self) -> Option<Self::Item> {
992 self.inner.next().map(|(k, v)| {
993 unsafe {
995 let lock_ptr = v as *const RwLock<V> as *mut RwLock<V>;
996 (k, &*(*lock_ptr).get_mut())
997 }
998 })
999 }
1000}
1001
1002impl<'a, K, V> ExactSizeIterator for IterNoLock<'a, K, V> {
1003 fn len(&self) -> usize {
1004 self.inner.len()
1005 }
1006}
1007
1008impl<'a, K, V> IntoIterator for &'a SyncHashMap<K, V>
1009where
1010 K: Eq + Hash,
1011{
1012 type Item = (&'a K, &'a V);
1013 type IntoIter = IterNoLock<'a, K, V>;
1014
1015 fn into_iter(self) -> Self::IntoIter {
1016 self.iter()
1017 }
1018}
1019
1020impl<'a, K, V> IntoIterator for &'a mut SyncHashMap<K, V>
1021where
1022 K: Eq + Hash,
1023{
1024 type Item = (&'a K, RwLockWriteGuard<'a, V>);
1025 type IntoIter = IterMut<'a, K, V>;
1026
1027 fn into_iter(self) -> Self::IntoIter {
1028 self.iter_mut()
1029 }
1030}
1031
1032impl<K, V> IntoIterator for SyncHashMap<K, V>
1033where
1034 K: Eq + Hash,
1035{
1036 type Item = (K, V);
1037 type IntoIter = MapIntoIter<K, V>;
1038
1039 fn into_iter(self) -> Self::IntoIter {
1040 self.into_inner().into_iter()
1041 }
1042}
1043
1044impl<K, V> From<HashMap<K, V>> for SyncHashMap<K, V>
1045where
1046 K: Eq + Hash,
1047{
1048 fn from(map: HashMap<K, V>) -> Self {
1049 Self::with_map(map)
1050 }
1051}
1052
1053impl<K, V> Serialize for SyncHashMap<K, V>
1054where
1055 K: Eq + Hash + Serialize,
1056 V: Serialize,
1057{
1058 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1059 where
1060 S: Serializer,
1061 {
1062 use serde::ser::SerializeMap;
1063 let _lock = self.lock.read();
1064 let m = unsafe { &*self.dirty.get() };
1065 let mut map = serializer.serialize_map(Some(m.len()))?;
1066 for (k, v) in m.iter() {
1067 map.serialize_entry(k, &*v.read())?;
1068 }
1069 map.end()
1070 }
1071}
1072
1073impl<'de, K, V> Deserialize<'de> for SyncHashMap<K, V>
1074where
1075 K: Eq + Hash + Deserialize<'de>,
1076 V: Deserialize<'de>,
1077{
1078 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1079 where
1080 D: Deserializer<'de>,
1081 {
1082 let m = HashMap::deserialize(deserializer)?;
1083 Ok(Self::with_map(m))
1084 }
1085}
1086
1087impl<K, V> Debug for SyncHashMap<K, V>
1088where
1089 K: Eq + Hash + Debug,
1090 V: Debug,
1091{
1092 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1093 let _lock = self.lock.read();
1094 let m = unsafe { &*self.dirty.get() };
1095 let mut map = f.debug_map();
1096 for (k, v) in m.iter() {
1097 map.entry(k, &*v.read());
1098 }
1099 map.finish()
1100 }
1101}
1102
1103impl<K, V> Clone for SyncHashMap<K, V>
1104where
1105 K: Clone + Eq + Hash,
1106 V: Clone,
1107{
1108 fn clone(&self) -> Self {
1109 let _lock = self.lock.read();
1110 let m = unsafe { &*self.dirty.get() };
1111 let cloned: HashMap<K, V> = m
1112 .iter()
1113 .map(|(k, v)| (k.clone(), v.read().clone()))
1114 .collect();
1115 SyncHashMap::with_map(cloned)
1116 }
1117}
1118
1119impl<K, V> Default for SyncHashMap<K, V>
1120where
1121 K: Eq + Hash,
1122{
1123 fn default() -> Self {
1124 Self::new()
1125 }
1126}
1127
1128impl<K, V> PartialEq for SyncHashMap<K, V>
1129where
1130 K: Eq + Hash,
1131 V: PartialEq,
1132{
1133 fn eq(&self, other: &Self) -> bool {
1134 let _lock_self = self.lock.read();
1135 let _lock_other = other.lock.read();
1136 let self_map = unsafe { &*self.dirty.get() };
1137 let other_map = unsafe { &*other.dirty.get() };
1138
1139 if self_map.len() != other_map.len() {
1140 return false;
1141 }
1142
1143 for (k, v) in self_map.iter() {
1144 match other_map.get(k) {
1145 Some(other_v) => {
1146 if *v.read() != *other_v.read() {
1147 return false;
1148 }
1149 }
1150 None => return false,
1151 }
1152 }
1153 true
1154 }
1155}
1156
1157impl<K, V> Eq for SyncHashMap<K, V>
1158where
1159 K: Eq + Hash,
1160 V: Eq,
1161{
1162}
1163
1164pub mod buckets {
1167 use super::{ReadGuard, MapReadGuard, SyncHashMap, WriteGuard};
1168 use std::hash::{Hash, Hasher};
1169
1170 #[derive(Debug, Clone)]
1173 pub struct SyncHashMapB<K, V>
1174 where
1175 K: Eq + Hash,
1176 {
1177 inner: Vec<SyncHashMap<K, V>>,
1180 len: usize,
1183 }
1184
1185 impl<K, V> SyncHashMapB<K, V>
1186 where
1187 K: Eq + Hash,
1188 {
1189 pub fn new(bucket_count: Option<usize>) -> Self {
1208 let count = bucket_count.unwrap_or(10);
1209 let mut arr = Vec::with_capacity(count);
1210 for _ in 0..count {
1211 arr.push(SyncHashMap::new());
1212 }
1213 Self {
1214 inner: arr,
1215 len: count,
1216 }
1217 }
1218
1219 fn key_to_bucket_index(&self, k: &K) -> usize {
1222 let mut hasher = std::collections::hash_map::DefaultHasher::new();
1223 k.hash(&mut hasher);
1224 let hash = hasher.finish();
1225 (hash % self.len as u64) as usize
1226 }
1227
1228 #[inline]
1231 pub fn insert(&self, k: K, v: V) -> Option<V> {
1232 let index = self.key_to_bucket_index(&k);
1233 self.inner[index].insert(k, v)
1234 }
1235
1236 #[inline]
1239 pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
1240 let index = self.key_to_bucket_index(&k);
1241 self.inner[index].insert_mut(k, v)
1242 }
1243
1244 #[inline]
1247 pub fn remove(&self, k: &K) -> Option<V> {
1248 let index = self.key_to_bucket_index(k);
1249 self.inner[index].remove(k)
1250 }
1251
1252 #[inline]
1255 pub fn is_empty(&self) -> bool {
1256 self.inner.iter().all(|bucket| bucket.is_empty())
1257 }
1258
1259 #[inline]
1262 pub fn len(&self) -> usize {
1263 self.inner.iter().map(|bucket| bucket.len()).sum()
1264 }
1265
1266 #[inline]
1269 pub fn clear(&self) {
1270 self.inner.iter().for_each(|bucket| bucket.clear());
1271 }
1272
1273 #[inline]
1279 pub fn get(&self, k: &K) -> Option<MapReadGuard<'_, V>> {
1280 let index = self.key_to_bucket_index(k);
1281 self.inner[index].get(k)
1282 }
1283
1284 #[inline]
1290 pub fn get_mut(&self, k: &K) -> Option<WriteGuard<'_, V>> {
1291 let index = self.key_to_bucket_index(k);
1292 self.inner[index].get_mut(k)
1293 }
1294
1295 #[inline]
1298 pub fn bucket_count(&self) -> usize {
1299 self.len
1300 }
1301
1302 #[inline]
1305 pub fn keys(&self) -> impl Iterator<Item = &K> {
1306 self.inner.iter().flat_map(|bucket| bucket.keys())
1307 }
1308
1309 #[inline]
1312 pub fn get_clone(&self, k: &K) -> Option<V>
1313 where
1314 V: Clone,
1315 {
1316 let index = self.key_to_bucket_index(k);
1317 self.inner[index].get_clone(k)
1318 }
1319 }
1320
1321 impl<K, V> Default for SyncHashMapB<K, V>
1322 where
1323 K: Eq + Hash,
1324 {
1325 fn default() -> Self {
1326 Self::new(None)
1327 }
1328 }
1329}
1330
1331#[cfg(test)]
1332mod tests {
1333 use super::*;
1334 use std::collections::HashMap;
1335 use std::sync::Arc;
1336 use std::thread;
1337
1338 #[test]
1339 fn test_sync_hash_map_new() {
1340 let map: SyncHashMap<i32, String> = SyncHashMap::new();
1341 assert_eq!(map.len(), 0);
1342 assert!(map.is_empty());
1343 }
1344
1345 #[test]
1346 fn test_sync_hash_map_with_capacity() {
1347 let map = SyncHashMap::<i32, String>::with_capacity(100);
1348 assert!(map.capacity() >= 100);
1349 }
1350
1351 #[test]
1352 fn test_sync_hash_map_with_map() {
1353 let mut original = HashMap::new();
1354 original.insert(1, "one".to_string());
1355 original.insert(2, "two".to_string());
1356
1357 let map = SyncHashMap::with_map(original);
1358 assert_eq!(map.len(), 2);
1359 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1360 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1361 }
1362
1363 #[test]
1364 fn test_sync_hash_map_insert_and_get() {
1365 let map = SyncHashMap::new();
1366
1367 assert_eq!(map.insert(1, "one".to_string()), None);
1369 assert_eq!(map.insert(2, "two".to_string()), None);
1370 assert_eq!(map.len(), 2);
1371
1372 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1373 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1374 assert!(map.get(&3).is_none());
1375 }
1376
1377 #[test]
1378 fn test_sync_hash_map_insert_replace() {
1379 let map = SyncHashMap::new();
1380
1381 assert_eq!(map.insert(1, "one".to_string()), None);
1382 assert_eq!(map.insert(1, "updated".to_string()), Some("one".to_string()));
1383 assert_eq!(*map.get(&1).unwrap(), "updated".to_string());
1384 }
1385
1386 #[test]
1387 fn test_sync_hash_map_remove() {
1388 let map = SyncHashMap::new();
1389
1390 map.insert(1, "one".to_string());
1391 map.insert(2, "two".to_string());
1392
1393 assert_eq!(map.remove(&1), Some("one".to_string()));
1394 assert_eq!(map.remove(&1), None);
1395 assert_eq!(map.len(), 1);
1396 assert!(map.get(&1).is_none());
1397 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1398 }
1399
1400 #[test]
1401 fn test_sync_hash_map_contains_key() {
1402 let map = SyncHashMap::new();
1403
1404 map.insert(1, "one".to_string());
1405
1406 assert!(map.contains_key(&1));
1407 assert!(!map.contains_key(&2));
1408 }
1409
1410 #[test]
1411 fn test_sync_hash_map_clear() {
1412 let map = SyncHashMap::new();
1413
1414 map.insert(1, "one".to_string());
1415 map.insert(2, "two".to_string());
1416
1417 assert_eq!(map.len(), 2);
1418 map.clear();
1419 assert_eq!(map.len(), 0);
1420 assert!(map.is_empty());
1421 }
1422
1423 #[test]
1424 fn test_sync_hash_map_capacity_operations() {
1425 let map = SyncHashMap::new();
1426
1427 assert_eq!(map.capacity(), 0);
1428 map.reserve(100);
1429 assert!(map.capacity() >= 100);
1430
1431 map.insert(1, "one".to_string());
1432 map.insert(2, "two".to_string());
1433
1434 let old_capacity = map.capacity();
1435 map.shrink_to_fit();
1436 assert!(map.capacity() <= old_capacity);
1437 }
1438
1439 #[test]
1440 fn test_sync_hash_map_retain() {
1441 let map = SyncHashMap::new();
1442
1443 map.insert(1, "one".to_string());
1444 map.insert(2, "two".to_string());
1445 map.insert(3, "three".to_string());
1446
1447 map.retain(|&k, _| k % 2 == 1);
1448
1449 assert_eq!(map.len(), 2);
1450 assert!(map.contains_key(&1));
1451 assert!(!map.contains_key(&2));
1452 assert!(map.contains_key(&3));
1453 }
1454
1455 #[test]
1456 fn test_sync_hash_map_get_or_insert() {
1457 let map = SyncHashMap::new();
1458
1459 {
1461 let value = map.get_or_insert(1, "default".to_string());
1462 assert_eq!(*value, "default");
1463 }
1464 assert_eq!(map.len(), 1);
1465
1466 {
1468 let value = map.get_or_insert(1, "new_default".to_string());
1469 assert_eq!(*value, "default");
1470 }
1471 assert_eq!(map.len(), 1);
1472 }
1473
1474 #[test]
1475 fn test_sync_hash_map_get_or_insert_with() {
1476 let map = SyncHashMap::new();
1477
1478 {
1479 let value = map.get_or_insert_with(1, || "computed".to_string());
1480 assert_eq!(*value, "computed");
1481 }
1482 assert_eq!(map.len(), 1);
1483
1484 {
1485 let value = map.get_or_insert_with(1, || "new_computed".to_string());
1486 assert_eq!(*value, "computed");
1487 }
1488 }
1489
1490 #[test]
1491 fn test_sync_hash_map_remove_entry() {
1492 let map = SyncHashMap::new();
1493
1494 map.insert(1, "one".to_string());
1495 map.insert(2, "two".to_string());
1496
1497 let removed = map.remove_entry(&1);
1498 assert_eq!(removed, Some((1, "one".to_string())));
1499 assert_eq!(map.len(), 1);
1500 assert!(!map.contains_key(&1));
1501 }
1502
1503 #[test]
1504 fn test_sync_hash_map_iterators() {
1505 let map = SyncHashMap::new();
1506
1507 map.insert(1, "one".to_string());
1508 map.insert(2, "two".to_string());
1509 map.insert(3, "three".to_string());
1510
1511 let keys: Vec<_> = map.keys().collect();
1513 assert!(keys.contains(&&1));
1514 assert!(keys.contains(&&2));
1515 assert!(keys.contains(&&3));
1516
1517 assert_eq!(map.get_clone(&1), Some("one".to_string()));
1519 assert_eq!(map.get_clone(&2), Some("two".to_string()));
1520 assert_eq!(map.get_clone(&3), Some("three".to_string()));
1521
1522 let mut count = 0;
1524 for (k, v) in map.iter() {
1525 count += 1;
1526 assert!(map.contains_key(k));
1527 assert_eq!(*map.get(k).unwrap(), *v);
1528 }
1529 assert_eq!(count, 3);
1530 }
1531
1532 #[test]
1533 fn test_sync_hash_map_iter_mut() {
1534 let map = SyncHashMap::new();
1535
1536 map.insert(1, "one".to_string());
1537 map.insert(2, "two".to_string());
1538
1539 for (k, mut v) in map.iter_mut() {
1540 if *k == 1 {
1541 *v = "modified".to_string();
1542 }
1543 }
1544
1545 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1546 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1547 }
1548
1549 #[test]
1550 fn test_sync_hash_map_values_mut() {
1551 let map = SyncHashMap::new();
1552
1553 map.insert(1, "one".to_string());
1554 map.insert(2, "two".to_string());
1555
1556 for mut v in map.values_mut() {
1557 if *v == "one" {
1558 *v = "modified".to_string();
1559 }
1560 }
1561
1562 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1563 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1564 }
1565
1566 #[test]
1567 fn test_sync_hash_map_get_clone() {
1568 let map = SyncHashMap::new();
1569 map.insert(1, "one".to_string());
1570
1571 assert_eq!(map.get_clone(&1), Some("one".to_string()));
1573 assert_eq!(map.get_clone(&2), None);
1574 }
1575
1576 #[test]
1577 fn test_sync_hash_map_clone() {
1578 let map1 = SyncHashMap::new();
1579 map1.insert(1, "one".to_string());
1580 map1.insert(2, "two".to_string());
1581
1582 let map2 = map1.clone();
1583
1584 assert_eq!(map1.len(), map2.len());
1585 assert_eq!(*map1.get(&1).unwrap(), *map2.get(&1).unwrap());
1586 assert_eq!(*map1.get(&2).unwrap(), *map2.get(&2).unwrap());
1587
1588 map1.insert(3, "three".to_string());
1590 assert!(!map2.contains_key(&3));
1591 }
1592
1593 #[test]
1594 fn test_sync_hash_map_partial_eq() {
1595 let map1 = SyncHashMap::new();
1596 map1.insert(1, "one".to_string());
1597 map1.insert(2, "two".to_string());
1598
1599 let map2 = SyncHashMap::new();
1600 map2.insert(1, "one".to_string());
1601 map2.insert(2, "two".to_string());
1602
1603 let map3 = SyncHashMap::new();
1604 map3.insert(1, "different".to_string());
1605
1606 assert_eq!(map1, map2);
1607 assert_ne!(map1, map3);
1608 }
1609
1610 #[test]
1611 fn test_sync_hash_map_debug() {
1612 let map = SyncHashMap::new();
1613 map.insert(1, "one".to_string());
1614
1615 let debug_str = format!("{:?}", map);
1616 assert!(debug_str.contains("1"));
1617 assert!(debug_str.contains("one"));
1618 }
1619
1620 #[test]
1621 fn test_sync_hash_map_serialization() {
1622 let map = SyncHashMap::new();
1623 map.insert(1, "one".to_string());
1624 map.insert(2, "two".to_string());
1625
1626 let serialized = serde_json::to_string(&map).unwrap();
1628 assert!(serialized.contains("1"));
1629 assert!(serialized.contains("one"));
1630 assert!(serialized.contains("2"));
1631 assert!(serialized.contains("two"));
1632
1633 let deserialized: SyncHashMap<i32, String> = serde_json::from_str(&serialized).unwrap();
1635 assert_eq!(deserialized.len(), 2);
1636 assert_eq!(*deserialized.get(&1).unwrap(), "one".to_string());
1637 assert_eq!(*deserialized.get(&2).unwrap(), "two".to_string());
1638 }
1639
1640 #[test]
1641 fn test_sync_hash_map_from_hashmap() {
1642 let mut original = HashMap::new();
1643 original.insert(1, "one".to_string());
1644 original.insert(2, "two".to_string());
1645
1646 let map = SyncHashMap::from(original);
1647
1648 assert_eq!(map.len(), 2);
1649 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1650 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1651 }
1652
1653 #[test]
1654 fn test_sync_hash_map_into_iterator() {
1655 let map = SyncHashMap::new();
1656 map.insert(1, "one".to_string());
1657 map.insert(2, "two".to_string());
1658
1659 let mut count = 0;
1661 for (k, v) in &map {
1662 count += 1;
1663 assert!(map.contains_key(k));
1664 assert_eq!(*map.get(k).unwrap(), *v);
1665 }
1666 assert_eq!(count, 2);
1667
1668 let owned_pairs: Vec<_> = map.into_iter().collect();
1670 assert_eq!(owned_pairs.len(), 2);
1671 }
1672
1673 #[test]
1674 fn test_sync_hash_map_default() {
1675 let map: SyncHashMap<i32, String> = Default::default();
1676 assert_eq!(map.len(), 0);
1677 assert!(map.is_empty());
1678 }
1679
1680 #[test]
1681 fn test_sync_hash_map_arc() {
1682 let map = SyncHashMap::new_arc();
1683 map.insert(1, "one".to_string());
1684
1685 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1686
1687 let map2 = Arc::clone(&map);
1688 map2.insert(2, "two".to_string());
1689
1690 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1691 }
1692
1693 #[test]
1694 fn test_sync_hash_map_get_mut() {
1695 let map = SyncHashMap::new();
1696 map.insert(1, "one".to_string());
1697
1698 {
1699 let mut value = map.get_mut(&1).unwrap();
1700 *value = "modified".to_string();
1701 }
1702
1703 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1704 }
1705
1706 #[test]
1707 fn test_sync_hash_map_concurrent_access() {
1708 let map = Arc::new(SyncHashMap::new());
1709
1710 let handles: Vec<_> = (0..10).map(|i| {
1712 let map = Arc::clone(&map);
1713 thread::spawn(move || {
1714 map.insert(i, format!("value_{}", i));
1715 })
1716 }).collect();
1717
1718 for handle in handles {
1719 handle.join().unwrap();
1720 }
1721
1722 assert_eq!(map.len(), 10);
1724 for i in 0..10 {
1725 assert_eq!(*map.get(&i).unwrap(), format!("value_{}", i));
1726 }
1727
1728 let map_read = Arc::clone(&map);
1730 let handles: Vec<_> = (0..10).map(|i| {
1731 let map = Arc::clone(&map_read);
1732 thread::spawn(move || {
1733 let value = map.get(&i);
1734 assert_eq!(*value.unwrap(), format!("value_{}", i));
1735 })
1736 }).collect();
1737
1738 for handle in handles {
1739 handle.join().unwrap();
1740 }
1741 }
1742
1743 #[test]
1744 fn test_sync_hash_map_dirty_ref() {
1745 let map = SyncHashMap::new();
1746 map.insert(1, "one".to_string());
1747
1748 let dirty = map.dirty_ref();
1749 assert_eq!(dirty.len(), 1);
1750 assert_eq!(*dirty.get(&1).unwrap().read(), "one".to_string());
1752 }
1753
1754 #[test]
1755 fn test_sync_hash_map_into_inner() {
1756 let map = SyncHashMap::new();
1757 map.insert(1, "one".to_string());
1758 map.insert(2, "two".to_string());
1759
1760 let inner = map.into_inner();
1761 assert_eq!(inner.len(), 2);
1762 assert_eq!(inner.get(&1), Some(&"one".to_string()));
1763 assert_eq!(inner.get(&2), Some(&"two".to_string()));
1764 }
1765
1766 #[test]
1767 fn test_sync_hash_map_guard_debug() {
1768 let map = SyncHashMap::new();
1769 map.insert(1, "test".to_string());
1770
1771 let guard = map.get(&1).unwrap();
1772 let debug_str = format!("{:?}", guard);
1773 assert!(debug_str.contains("test"));
1774 }
1775
1776 #[test]
1777 fn test_sync_hash_map_guard_partial_eq() {
1778 let map = SyncHashMap::new();
1779 map.insert(1, "value".to_string());
1780
1781 let guard1 = map.get(&1).unwrap();
1782 let guard2 = map.get(&1).unwrap();
1783
1784 assert_eq!(guard1, guard2);
1785 }
1786
1787 mod buckets_tests {
1789 use super::*;
1790
1791 #[test]
1792 fn test_sync_hash_map_buckets_new() {
1793 let map = buckets::SyncHashMapB::<i32, String>::new(None);
1794 assert_eq!(map.len(), 0);
1795 assert!(map.is_empty());
1796 assert_eq!(map.bucket_count(), 10); }
1798
1799 #[test]
1800 fn test_sync_hash_map_buckets_with_custom_size() {
1801 let map = buckets::SyncHashMapB::<i32, String>::new(Some(5));
1802 assert_eq!(map.bucket_count(), 5);
1803 }
1804
1805 #[test]
1806 fn test_sync_hash_map_buckets_insert_and_get() {
1807 let map = buckets::SyncHashMapB::new(Some(3));
1808
1809 assert_eq!(map.insert(1, "one".to_string()), None);
1810 assert_eq!(map.insert(2, "two".to_string()), None);
1811 assert_eq!(map.len(), 2);
1812
1813 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1814 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1815 assert!(map.get(&3).is_none());
1816 }
1817
1818 #[test]
1819 fn test_sync_hash_map_buckets_remove() {
1820 let map = buckets::SyncHashMapB::new(Some(3));
1821
1822 map.insert(1, "one".to_string());
1823 map.insert(2, "two".to_string());
1824
1825 assert_eq!(map.remove(&1), Some("one".to_string()));
1826 assert_eq!(map.len(), 1);
1827 assert!(map.get(&1).is_none());
1828 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1829 }
1830
1831 #[test]
1832 fn test_sync_hash_map_buckets_clear() {
1833 let map = buckets::SyncHashMapB::new(Some(3));
1834
1835 map.insert(1, "one".to_string());
1836 map.insert(2, "two".to_string());
1837
1838 assert_eq!(map.len(), 2);
1839 map.clear();
1840 assert_eq!(map.len(), 0);
1841 assert!(map.is_empty());
1842 }
1843
1844 #[test]
1845 fn test_sync_hash_map_buckets_iterators() {
1846 let map = buckets::SyncHashMapB::new(Some(3));
1847
1848 map.insert(1, "one".to_string());
1849 map.insert(2, "two".to_string());
1850 map.insert(3, "three".to_string());
1851
1852 let keys: Vec<_> = map.keys().collect();
1854 assert!(keys.contains(&&1));
1855 assert!(keys.contains(&&2));
1856 assert!(keys.contains(&&3));
1857
1858 assert_eq!(map.get_clone(&1), Some("one".to_string()));
1860 assert_eq!(map.get_clone(&2), Some("two".to_string()));
1861 assert_eq!(map.get_clone(&3), Some("three".to_string()));
1862
1863 {
1865 let mut v = map.get_mut(&1).unwrap();
1866 *v = "modified".to_string();
1867 }
1868
1869 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1870 }
1871
1872 #[test]
1873 fn test_sync_hash_map_buckets_default() {
1874 let map: buckets::SyncHashMapB<i32, String> = Default::default();
1875 assert_eq!(map.len(), 0);
1876 assert!(map.is_empty());
1877 assert_eq!(map.bucket_count(), 10);
1878 }
1879
1880 #[test]
1881 fn test_sync_hash_map_buckets_debug() {
1882 let map = buckets::SyncHashMapB::new(Some(2));
1883 map.insert(1, "one".to_string());
1884
1885 let debug_str = format!("{:?}", map);
1886 assert!(debug_str.contains("1"));
1887 assert!(debug_str.contains("one"));
1888 }
1889 }
1890
1891 #[test]
1892 fn test_sync_hash_map_comprehensive() {
1893 let map = SyncHashMap::new();
1894
1895 map.insert("key1", 42);
1897 map.insert("key2", 24);
1898
1899 assert_eq!(map.len(), 2);
1900 assert!(!map.is_empty());
1901
1902 *map.get_mut("key1").unwrap() = 100;
1904 assert_eq!(*map.get(&"key1").unwrap(), 100);
1905
1906 map.insert("key3", 50);
1908 map.retain(|_, v| *v > 30);
1909
1910 assert_eq!(map.len(), 2);
1911 assert_eq!(*map.get(&"key1").unwrap(), 100);
1912 assert!(map.get(&"key2").is_none());
1913 assert_eq!(*map.get(&"key3").unwrap(), 50);
1914
1915 let map2 = map.clone();
1917 assert_eq!(map, map2);
1918
1919 let mut sum = 0;
1921 for (_, v) in map.iter() {
1922 sum += *v;
1923 }
1924 assert_eq!(sum, 150);
1925
1926 map.clear();
1928 assert_eq!(map.len(), 0);
1929 assert!(map.is_empty());
1930 }
1931
1932 #[test]
1933 fn test_sync_hash_map_iter_nlock() {
1934 let map = SyncHashMap::new();
1935 map.insert(1, "one".to_string());
1936 map.insert(2, "two".to_string());
1937 map.insert(3, "three".to_string());
1938
1939 let mut count = 0;
1941 for (k, v) in map.iter() {
1942 count += 1;
1943 match *k {
1944 1 => assert_eq!(v, "one"),
1945 2 => assert_eq!(v, "two"),
1946 3 => assert_eq!(v, "three"),
1947 _ => panic!("unexpected key"),
1948 }
1949 }
1950 assert_eq!(count, 3);
1951
1952 let iter = map.iter();
1954 assert_eq!(iter.len(), 3);
1955 }
1956
1957 #[test]
1958 fn test_sync_hash_map_into_iter_mut() {
1959 let mut map = SyncHashMap::new();
1960 map.insert(1, "one".to_string());
1961 map.insert(2, "two".to_string());
1962
1963 for (k, mut v) in &mut map {
1965 if *k == 1 {
1966 *v = "modified".to_string();
1967 }
1968 }
1969
1970 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1971 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1972 }
1973
1974 #[test]
1975 fn test_sync_hash_map_into_iter_ref() {
1976 let map = SyncHashMap::new();
1977 map.insert(1, 10);
1978 map.insert(2, 20);
1979 map.insert(3, 30);
1980
1981 let mut sum = 0;
1983 for (_, v) in &map {
1984 sum += *v;
1985 }
1986 assert_eq!(sum, 60);
1987
1988 assert_eq!(map.len(), 3);
1990 }
1991
1992 #[test]
1993 fn test_sync_hash_map_iter_nlock_empty() {
1994 let map: SyncHashMap<i32, String> = SyncHashMap::new();
1995
1996 let mut count = 0;
1997 for _ in map.iter() {
1998 count += 1;
1999 }
2000 assert_eq!(count, 0);
2001
2002 let iter = map.iter();
2003 assert_eq!(iter.len(), 0);
2004 }
2005}