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]
240 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<ReadGuard<'_, V>>
241 where
242 K: Borrow<Q>,
243 Q: Hash + Eq,
244 {
245 let map_lock = self.lock.read();
246 let m = unsafe { &*self.dirty.get() };
247 let value_lock_wrapper = m.get(k)?;
248 let value_lock = value_lock_wrapper.read();
249 Some(ReadGuard {
250 _map_lock: map_lock,
251 _value_lock: value_lock,
252 })
253 }
254
255 #[inline]
263 pub fn get_uncheck<Q: ?Sized>(&self, k: &Q) -> ReadGuard<'_, V>
264 where
265 K: Borrow<Q>,
266 Q: Hash + Eq,
267 {
268 let map_lock = self.lock.read();
269 let m = unsafe { &*self.dirty.get() };
270 let value_lock_wrapper = m.get(k).expect("key not found");
271 let value_lock = value_lock_wrapper.read();
272 ReadGuard {
273 _map_lock: map_lock,
274 _value_lock: value_lock,
275 }
276 }
277
278 #[inline]
286 pub fn get_mut<Q: ?Sized>(&self, k: &Q) -> Option<WriteGuard<'_, V>>
287 where
288 K: Borrow<Q>,
289 Q: Hash + Eq,
290 {
291 let map_lock = self.lock.read();
292 let m = unsafe { &*self.dirty.get() };
293 let value_lock_wrapper = m.get(k)?;
294 let value_lock = value_lock_wrapper.write();
295 Some(WriteGuard {
296 _map_lock: map_lock,
297 _value_lock: value_lock,
298 })
299 }
300
301 #[inline]
304 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
305 where
306 K: Borrow<Q>,
307 Q: Hash + Eq,
308 {
309 let _lock = self.lock.read();
310 let m = unsafe { &*self.dirty.get() };
311 m.contains_key(k)
312 }
313
314 pub fn iter_mut(&self) -> IterMut<'_, K, V> {
320 let _lock = self.lock.read();
321 let m = unsafe { &*self.dirty.get() };
322 IterMut {
323 _lock,
324 inner: m.iter(),
325 }
326 }
327
328 pub fn iter_rlock(&self) -> IterRLock<'_, K, V> {
336 let _lock = self.lock.read();
337 let m = unsafe { &*self.dirty.get() };
338 IterRLock {
339 _lock,
340 inner: m.iter(),
341 }
342 }
343
344 pub fn iter(&self) -> IterNoLock<'_, K, V> {
353 let _lock = self.lock.read();
354 let m = unsafe { &*self.dirty.get() };
355 IterNoLock {
356 _lock,
357 inner: m.iter(),
358 }
359 }
360
361 pub fn dirty_ref(&self) -> ReadGuardMap<'_, K, V> {
369 let _lock = self.lock.read();
370 let v = unsafe { &*self.dirty.get() };
371 ReadGuardMap { _lock, v }
372 }
373
374 pub unsafe fn dirty_ref_unsafe(&self) -> &HashMap<K, RwLock<V>, DefaultBuildHasher> {
382 unsafe { &*self.dirty.get() }
383 }
384
385 pub fn into_inner(self) -> HashMap<K, V> {
388 self.dirty
389 .into_inner()
390 .into_iter()
391 .map(|(k, v)| (k, v.into_inner()))
392 .collect()
393 }
394
395 #[inline]
401 pub fn keys(&self) -> KeysGuard<'_, K, V> {
402 let _lock = self.lock.read();
403 let m = unsafe { &*self.dirty.get() };
404 KeysGuard {
405 _lock,
406 inner: m.keys(),
407 }
408 }
409
410 #[inline]
416 pub fn values(&self) -> ValuesGuard<'_, K, V> {
417 let _lock = self.lock.read();
418 let m = unsafe { &*self.dirty.get() };
419 ValuesGuard {
420 _lock,
421 inner: m.values(),
422 }
423 }
424
425 #[inline]
431 pub fn values_mut(&self) -> ValuesMutGuard<'_, K, V> {
432 let _lock = self.lock.write();
433 let m = unsafe { &*self.dirty.get() };
434 ValuesMutGuard {
435 _lock,
436 inner: m.values(),
437 }
438 }
439
440 #[inline]
443 pub fn retain<F>(&self, mut f: F)
444 where
445 F: FnMut(&K, &mut V) -> bool,
446 {
447 let _lock = self.lock.write();
448 let m = unsafe { &mut *self.dirty.get() };
449 m.retain(|k, v| f(k, v.get_mut()));
450 }
451
452 #[inline]
455 pub fn capacity(&self) -> usize {
456 let _lock = self.lock.read();
457 let m = unsafe { &*self.dirty.get() };
458 m.capacity()
459 }
460
461 #[inline]
464 pub fn reserve(&self, additional: usize) {
465 let _lock = self.lock.write();
466 let m = unsafe { &mut *self.dirty.get() };
467 m.reserve(additional);
468 }
469
470 #[inline]
473 pub fn remove_entry(&self, k: &K) -> Option<(K, V)> {
474 let _lock = self.lock.write();
475 let m = unsafe { &mut *self.dirty.get() };
476 m.remove_entry(k).map(|(k, v)| (k, v.into_inner()))
477 }
478
479 #[inline]
485 pub fn get_or_insert(&self, k: K, default: V) -> WriteGuardEntry<'_, V> {
486 let map_lock = self.lock.write();
487 let m = unsafe { &mut *self.dirty.get() };
488 let entry = m.entry(k).or_insert_with(|| RwLock::new(default));
489 let value_lock = entry.write();
490 WriteGuardEntry {
491 _map_lock: map_lock,
492 _value_lock: value_lock,
493 }
494 }
495
496 #[inline]
502 pub fn get_or_insert_with<F>(&self, k: K, default: F) -> WriteGuardEntry<'_, V>
503 where
504 F: FnOnce() -> V,
505 {
506 let map_lock = self.lock.write();
507 let m = unsafe { &mut *self.dirty.get() };
508 let entry = m.entry(k).or_insert_with(|| RwLock::new(default()));
509 let value_lock = entry.write();
510 WriteGuardEntry {
511 _map_lock: map_lock,
512 _value_lock: value_lock,
513 }
514 }
515
516 #[inline]
522 pub fn get_clone<Q: ?Sized>(&self, k: &Q) -> Option<V>
523 where
524 K: Borrow<Q>,
525 Q: Hash + Eq,
526 V: Clone,
527 {
528 let _map_lock = self.lock.read();
529 let m = unsafe { &*self.dirty.get() };
530 m.get(k).map(|v| v.read().clone())
531 }
532
533 #[inline]
539 pub fn take(&self, k: &K) -> Option<V> {
540 self.remove(k)
541 }
542}
543
544pub struct ReadGuard<'a, V> {
547 _map_lock: RwLockReadGuard<'a, ()>,
550 _value_lock: RwLockReadGuard<'a, V>,
553}
554
555impl<'a, V> Deref for ReadGuard<'a, V> {
556 type Target = V;
557
558 fn deref(&self) -> &Self::Target {
559 &*self._value_lock
560 }
561}
562
563impl<'a, V> Debug for ReadGuard<'a, V>
564where
565 V: Debug,
566{
567 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
568 write!(f, "{:?}", &*self._value_lock)
569 }
570}
571
572impl<'a, V> PartialEq for ReadGuard<'a, V>
573where
574 V: PartialEq,
575{
576 fn eq(&self, other: &Self) -> bool {
577 (*self._value_lock).eq(&*other._value_lock)
578 }
579}
580
581impl<'a, V> Eq for ReadGuard<'a, V> where V: Eq {}
582
583impl<'a, V> std::fmt::Display for ReadGuard<'a, V>
584where
585 V: std::fmt::Display,
586{
587 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
588 (*self._value_lock).fmt(f)
589 }
590}
591
592impl<'a, V> AsRef<V> for ReadGuard<'a, V> {
593 fn as_ref(&self) -> &V {
594 &*self._value_lock
595 }
596}
597
598pub struct ReadGuardMap<'a, K, V> {
604 _lock: RwLockReadGuard<'a, ()>,
607 v: &'a HashMap<K, RwLock<V>, DefaultBuildHasher>,
610}
611
612impl<'a, K, V> Deref for ReadGuardMap<'a, K, V> {
613 type Target = HashMap<K, RwLock<V>, DefaultBuildHasher>;
614
615 fn deref(&self) -> &Self::Target {
616 self.v
617 }
618}
619
620impl<'a, K, V> Debug for ReadGuardMap<'a, K, V>
621where
622 K: Debug,
623 V: Debug,
624{
625 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
626 let mut map = f.debug_map();
629 for (k, v) in self.v.iter() {
630 map.entry(k, &*v.read());
631 }
632 map.finish()
633 }
634}
635
636impl<'a, K, V> AsRef<HashMap<K, RwLock<V>, DefaultBuildHasher>> for ReadGuardMap<'a, K, V> {
637 fn as_ref(&self) -> &HashMap<K, RwLock<V>, DefaultBuildHasher> {
638 self.v
639 }
640}
641
642pub struct WriteGuard<'a, V> {
648 _map_lock: RwLockReadGuard<'a, ()>,
651 _value_lock: RwLockWriteGuard<'a, V>,
654}
655
656impl<'a, V> Deref for WriteGuard<'a, V> {
657 type Target = V;
658
659 fn deref(&self) -> &Self::Target {
660 &*self._value_lock
661 }
662}
663
664impl<'a, V> DerefMut for WriteGuard<'a, V> {
665 fn deref_mut(&mut self) -> &mut Self::Target {
666 &mut *self._value_lock
667 }
668}
669
670impl<'a, V> Debug for WriteGuard<'a, V>
671where
672 V: Debug,
673{
674 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
675 write!(f, "{:?}", &*self._value_lock)
676 }
677}
678
679impl<'a, V> PartialEq for WriteGuard<'a, V>
680where
681 V: PartialEq,
682{
683 fn eq(&self, other: &Self) -> bool {
684 (*self._value_lock).eq(&*other._value_lock)
685 }
686}
687
688impl<'a, V> Eq for WriteGuard<'a, V> where V: Eq {}
689
690impl<'a, V> std::fmt::Display for WriteGuard<'a, V>
691where
692 V: std::fmt::Display,
693{
694 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
695 (*self._value_lock).fmt(f)
696 }
697}
698
699impl<'a, V> AsRef<V> for WriteGuard<'a, V> {
700 fn as_ref(&self) -> &V {
701 &*self._value_lock
702 }
703}
704
705impl<'a, V> AsMut<V> for WriteGuard<'a, V> {
706 fn as_mut(&mut self) -> &mut V {
707 &mut *self._value_lock
708 }
709}
710
711pub struct WriteGuardEntry<'a, V> {
717 _map_lock: RwLockWriteGuard<'a, ()>,
720 _value_lock: RwLockWriteGuard<'a, V>,
723}
724
725impl<'a, V> Deref for WriteGuardEntry<'a, V> {
726 type Target = V;
727
728 fn deref(&self) -> &Self::Target {
729 &*self._value_lock
730 }
731}
732
733impl<'a, V> DerefMut for WriteGuardEntry<'a, V> {
734 fn deref_mut(&mut self) -> &mut Self::Target {
735 &mut *self._value_lock
736 }
737}
738
739impl<'a, V> Debug for WriteGuardEntry<'a, V>
740where
741 V: Debug,
742{
743 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
744 write!(f, "{:?}", &*self._value_lock)
745 }
746}
747
748impl<'a, V> std::fmt::Display for WriteGuardEntry<'a, V>
749where
750 V: std::fmt::Display,
751{
752 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
753 (*self._value_lock).fmt(f)
754 }
755}
756
757impl<'a, V> AsRef<V> for WriteGuardEntry<'a, V> {
758 fn as_ref(&self) -> &V {
759 &*self._value_lock
760 }
761}
762
763impl<'a, V> AsMut<V> for WriteGuardEntry<'a, V> {
764 fn as_mut(&mut self) -> &mut V {
765 &mut *self._value_lock
766 }
767}
768
769#[allow(dead_code)]
772#[deprecated(note = "Use ReadGuard instead")]
773pub type SyncMapRefMut<'a, V> = WriteGuard<'a, V>;
774
775pub struct IterRLock<'a, K, V> {
781 _lock: RwLockReadGuard<'a, ()>,
784 inner: MapIter<'a, K, RwLock<V>>,
787}
788
789impl<'a, K, V> Iterator for IterRLock<'a, K, V> {
790 type Item = (&'a K, RwLockReadGuard<'a, V>);
791
792 fn next(&mut self) -> Option<Self::Item> {
793 self.inner.next().map(|(k, v)| (k, v.read()))
794 }
795}
796
797pub type IterMy<'a, K, V> = IterRLock<'a, K, V>;
800
801pub struct IterMut<'a, K, V> {
807 _lock: RwLockReadGuard<'a, ()>,
810 inner: MapIter<'a, K, RwLock<V>>,
813}
814
815impl<'a, K, V> Iterator for IterMut<'a, K, V> {
816 type Item = (&'a K, RwLockWriteGuard<'a, V>);
817
818 fn next(&mut self) -> Option<Self::Item> {
819 self.inner.next().map(|(k, v)| (k, v.write()))
820 }
821}
822
823pub struct KeysGuard<'a, K, V> {
826 _lock: RwLockReadGuard<'a, ()>,
829 inner: Keys<'a, K, RwLock<V>>,
832}
833
834impl<'a, K, V> Deref for KeysGuard<'a, K, V> {
835 type Target = Keys<'a, K, RwLock<V>>;
836
837 fn deref(&self) -> &Self::Target {
838 &self.inner
839 }
840}
841
842impl<'a, K, V> DerefMut for KeysGuard<'a, K, V> {
843 fn deref_mut(&mut self) -> &mut Self::Target {
844 &mut self.inner
845 }
846}
847
848impl<'a, K, V> Iterator for KeysGuard<'a, K, V> {
849 type Item = &'a K;
850
851 fn next(&mut self) -> Option<Self::Item> {
852 self.inner.next()
853 }
854}
855
856pub struct ValuesGuard<'a, K, V> {
862 _lock: RwLockReadGuard<'a, ()>,
865 inner: std::collections::hash_map::Values<'a, K, RwLock<V>>,
868}
869
870impl<'a, K, V> Iterator for ValuesGuard<'a, K, V> {
871 type Item = RwLockReadGuard<'a, V>;
872
873 fn next(&mut self) -> Option<Self::Item> {
874 self.inner.next().map(|v| v.read())
875 }
876}
877
878pub struct ValuesMutGuard<'a, K, V> {
884 _lock: RwLockWriteGuard<'a, ()>,
887 inner: std::collections::hash_map::Values<'a, K, RwLock<V>>,
890}
891
892impl<'a, K, V> Iterator for ValuesMutGuard<'a, K, V> {
893 type Item = RwLockWriteGuard<'a, V>;
894
895 fn next(&mut self) -> Option<Self::Item> {
896 self.inner.next().map(|v| v.write())
897 }
898}
899
900pub struct IterNoLock<'a, K, V> {
903 _lock: RwLockReadGuard<'a, ()>,
906 inner: MapIter<'a, K, RwLock<V>>,
909}
910
911impl<'a, K, V> Iterator for IterNoLock<'a, K, V> {
912 type Item = (&'a K, &'a V);
913
914 fn next(&mut self) -> Option<Self::Item> {
915 self.inner.next().map(|(k, v)| {
916 unsafe {
918 let lock_ptr = v as *const RwLock<V> as *mut RwLock<V>;
919 (k, &*(*lock_ptr).get_mut())
920 }
921 })
922 }
923}
924
925impl<'a, K, V> ExactSizeIterator for IterNoLock<'a, K, V> {
926 fn len(&self) -> usize {
927 self.inner.len()
928 }
929}
930
931impl<'a, K, V> IntoIterator for &'a SyncHashMap<K, V>
932where
933 K: Eq + Hash,
934{
935 type Item = (&'a K, &'a V);
936 type IntoIter = IterNoLock<'a, K, V>;
937
938 fn into_iter(self) -> Self::IntoIter {
939 self.iter()
940 }
941}
942
943impl<'a, K, V> IntoIterator for &'a mut SyncHashMap<K, V>
944where
945 K: Eq + Hash,
946{
947 type Item = (&'a K, RwLockWriteGuard<'a, V>);
948 type IntoIter = IterMut<'a, K, V>;
949
950 fn into_iter(self) -> Self::IntoIter {
951 self.iter_mut()
952 }
953}
954
955impl<K, V> IntoIterator for SyncHashMap<K, V>
956where
957 K: Eq + Hash,
958{
959 type Item = (K, V);
960 type IntoIter = MapIntoIter<K, V>;
961
962 fn into_iter(self) -> Self::IntoIter {
963 self.into_inner().into_iter()
964 }
965}
966
967impl<K, V> From<HashMap<K, V>> for SyncHashMap<K, V>
968where
969 K: Eq + Hash,
970{
971 fn from(map: HashMap<K, V>) -> Self {
972 Self::with_map(map)
973 }
974}
975
976impl<K, V> Serialize for SyncHashMap<K, V>
977where
978 K: Eq + Hash + Serialize,
979 V: Serialize,
980{
981 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
982 where
983 S: Serializer,
984 {
985 use serde::ser::SerializeMap;
986 let _lock = self.lock.read();
987 let m = unsafe { &*self.dirty.get() };
988 let mut map = serializer.serialize_map(Some(m.len()))?;
989 for (k, v) in m.iter() {
990 map.serialize_entry(k, &*v.read())?;
991 }
992 map.end()
993 }
994}
995
996impl<'de, K, V> Deserialize<'de> for SyncHashMap<K, V>
997where
998 K: Eq + Hash + Deserialize<'de>,
999 V: Deserialize<'de>,
1000{
1001 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1002 where
1003 D: Deserializer<'de>,
1004 {
1005 let m = HashMap::deserialize(deserializer)?;
1006 Ok(Self::with_map(m))
1007 }
1008}
1009
1010impl<K, V> Debug for SyncHashMap<K, V>
1011where
1012 K: Eq + Hash + Debug,
1013 V: Debug,
1014{
1015 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1016 let _lock = self.lock.read();
1017 let m = unsafe { &*self.dirty.get() };
1018 let mut map = f.debug_map();
1019 for (k, v) in m.iter() {
1020 map.entry(k, &*v.read());
1021 }
1022 map.finish()
1023 }
1024}
1025
1026impl<K, V> Clone for SyncHashMap<K, V>
1027where
1028 K: Clone + Eq + Hash,
1029 V: Clone,
1030{
1031 fn clone(&self) -> Self {
1032 let _lock = self.lock.read();
1033 let m = unsafe { &*self.dirty.get() };
1034 let cloned: HashMap<K, V> = m
1035 .iter()
1036 .map(|(k, v)| (k.clone(), v.read().clone()))
1037 .collect();
1038 SyncHashMap::with_map(cloned)
1039 }
1040}
1041
1042impl<K, V> Default for SyncHashMap<K, V>
1043where
1044 K: Eq + Hash,
1045{
1046 fn default() -> Self {
1047 Self::new()
1048 }
1049}
1050
1051impl<K, V> PartialEq for SyncHashMap<K, V>
1052where
1053 K: Eq + Hash,
1054 V: PartialEq,
1055{
1056 fn eq(&self, other: &Self) -> bool {
1057 let _lock_self = self.lock.read();
1058 let _lock_other = other.lock.read();
1059 let self_map = unsafe { &*self.dirty.get() };
1060 let other_map = unsafe { &*other.dirty.get() };
1061
1062 if self_map.len() != other_map.len() {
1063 return false;
1064 }
1065
1066 for (k, v) in self_map.iter() {
1067 match other_map.get(k) {
1068 Some(other_v) => {
1069 if *v.read() != *other_v.read() {
1070 return false;
1071 }
1072 }
1073 None => return false,
1074 }
1075 }
1076 true
1077 }
1078}
1079
1080impl<K, V> Eq for SyncHashMap<K, V>
1081where
1082 K: Eq + Hash,
1083 V: Eq,
1084{
1085}
1086
1087pub mod buckets {
1090 use super::{ReadGuard, SyncHashMap, WriteGuard};
1091 use std::hash::{Hash, Hasher};
1092
1093 #[derive(Debug, Clone)]
1096 pub struct SyncHashMapB<K, V>
1097 where
1098 K: Eq + Hash,
1099 {
1100 inner: Vec<SyncHashMap<K, V>>,
1103 len: usize,
1106 }
1107
1108 impl<K, V> SyncHashMapB<K, V>
1109 where
1110 K: Eq + Hash,
1111 {
1112 pub fn new(bucket_count: Option<usize>) -> Self {
1131 let count = bucket_count.unwrap_or(10);
1132 let mut arr = Vec::with_capacity(count);
1133 for _ in 0..count {
1134 arr.push(SyncHashMap::new());
1135 }
1136 Self {
1137 inner: arr,
1138 len: count,
1139 }
1140 }
1141
1142 fn key_to_bucket_index(&self, k: &K) -> usize {
1145 let mut hasher = std::collections::hash_map::DefaultHasher::new();
1146 k.hash(&mut hasher);
1147 let hash = hasher.finish();
1148 (hash % self.len as u64) as usize
1149 }
1150
1151 #[inline]
1154 pub fn insert(&self, k: K, v: V) -> Option<V> {
1155 let index = self.key_to_bucket_index(&k);
1156 self.inner[index].insert(k, v)
1157 }
1158
1159 #[inline]
1162 pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
1163 let index = self.key_to_bucket_index(&k);
1164 self.inner[index].insert_mut(k, v)
1165 }
1166
1167 #[inline]
1170 pub fn remove(&self, k: &K) -> Option<V> {
1171 let index = self.key_to_bucket_index(k);
1172 self.inner[index].remove(k)
1173 }
1174
1175 #[inline]
1178 pub fn is_empty(&self) -> bool {
1179 self.inner.iter().all(|bucket| bucket.is_empty())
1180 }
1181
1182 #[inline]
1185 pub fn len(&self) -> usize {
1186 self.inner.iter().map(|bucket| bucket.len()).sum()
1187 }
1188
1189 #[inline]
1192 pub fn clear(&self) {
1193 self.inner.iter().for_each(|bucket| bucket.clear());
1194 }
1195
1196 #[inline]
1202 pub fn get(&self, k: &K) -> Option<ReadGuard<'_, V>> {
1203 let index = self.key_to_bucket_index(k);
1204 self.inner[index].get(k)
1205 }
1206
1207 #[inline]
1213 pub fn get_mut(&self, k: &K) -> Option<WriteGuard<'_, V>> {
1214 let index = self.key_to_bucket_index(k);
1215 self.inner[index].get_mut(k)
1216 }
1217
1218 #[inline]
1221 pub fn bucket_count(&self) -> usize {
1222 self.len
1223 }
1224
1225 #[inline]
1228 pub fn keys(&self) -> impl Iterator<Item = &K> {
1229 self.inner.iter().flat_map(|bucket| bucket.keys())
1230 }
1231
1232 #[inline]
1235 pub fn get_clone(&self, k: &K) -> Option<V>
1236 where
1237 V: Clone,
1238 {
1239 let index = self.key_to_bucket_index(k);
1240 self.inner[index].get_clone(k)
1241 }
1242 }
1243
1244 impl<K, V> Default for SyncHashMapB<K, V>
1245 where
1246 K: Eq + Hash,
1247 {
1248 fn default() -> Self {
1249 Self::new(None)
1250 }
1251 }
1252}
1253
1254#[cfg(test)]
1255mod tests {
1256 use super::*;
1257 use std::collections::HashMap;
1258 use std::sync::Arc;
1259 use std::thread;
1260
1261 #[test]
1262 fn test_sync_hash_map_new() {
1263 let map: SyncHashMap<i32, String> = SyncHashMap::new();
1264 assert_eq!(map.len(), 0);
1265 assert!(map.is_empty());
1266 }
1267
1268 #[test]
1269 fn test_sync_hash_map_with_capacity() {
1270 let map = SyncHashMap::<i32, String>::with_capacity(100);
1271 assert!(map.capacity() >= 100);
1272 }
1273
1274 #[test]
1275 fn test_sync_hash_map_with_map() {
1276 let mut original = HashMap::new();
1277 original.insert(1, "one".to_string());
1278 original.insert(2, "two".to_string());
1279
1280 let map = SyncHashMap::with_map(original);
1281 assert_eq!(map.len(), 2);
1282 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1283 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1284 }
1285
1286 #[test]
1287 fn test_sync_hash_map_insert_and_get() {
1288 let map = SyncHashMap::new();
1289
1290 assert_eq!(map.insert(1, "one".to_string()), None);
1292 assert_eq!(map.insert(2, "two".to_string()), None);
1293 assert_eq!(map.len(), 2);
1294
1295 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1296 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1297 assert!(map.get(&3).is_none());
1298 }
1299
1300 #[test]
1301 fn test_sync_hash_map_insert_replace() {
1302 let map = SyncHashMap::new();
1303
1304 assert_eq!(map.insert(1, "one".to_string()), None);
1305 assert_eq!(map.insert(1, "updated".to_string()), Some("one".to_string()));
1306 assert_eq!(*map.get(&1).unwrap(), "updated".to_string());
1307 }
1308
1309 #[test]
1310 fn test_sync_hash_map_remove() {
1311 let map = SyncHashMap::new();
1312
1313 map.insert(1, "one".to_string());
1314 map.insert(2, "two".to_string());
1315
1316 assert_eq!(map.remove(&1), Some("one".to_string()));
1317 assert_eq!(map.remove(&1), None);
1318 assert_eq!(map.len(), 1);
1319 assert!(map.get(&1).is_none());
1320 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1321 }
1322
1323 #[test]
1324 fn test_sync_hash_map_contains_key() {
1325 let map = SyncHashMap::new();
1326
1327 map.insert(1, "one".to_string());
1328
1329 assert!(map.contains_key(&1));
1330 assert!(!map.contains_key(&2));
1331 }
1332
1333 #[test]
1334 fn test_sync_hash_map_clear() {
1335 let map = SyncHashMap::new();
1336
1337 map.insert(1, "one".to_string());
1338 map.insert(2, "two".to_string());
1339
1340 assert_eq!(map.len(), 2);
1341 map.clear();
1342 assert_eq!(map.len(), 0);
1343 assert!(map.is_empty());
1344 }
1345
1346 #[test]
1347 fn test_sync_hash_map_capacity_operations() {
1348 let map = SyncHashMap::new();
1349
1350 assert_eq!(map.capacity(), 0);
1351 map.reserve(100);
1352 assert!(map.capacity() >= 100);
1353
1354 map.insert(1, "one".to_string());
1355 map.insert(2, "two".to_string());
1356
1357 let old_capacity = map.capacity();
1358 map.shrink_to_fit();
1359 assert!(map.capacity() <= old_capacity);
1360 }
1361
1362 #[test]
1363 fn test_sync_hash_map_retain() {
1364 let map = SyncHashMap::new();
1365
1366 map.insert(1, "one".to_string());
1367 map.insert(2, "two".to_string());
1368 map.insert(3, "three".to_string());
1369
1370 map.retain(|&k, _| k % 2 == 1);
1371
1372 assert_eq!(map.len(), 2);
1373 assert!(map.contains_key(&1));
1374 assert!(!map.contains_key(&2));
1375 assert!(map.contains_key(&3));
1376 }
1377
1378 #[test]
1379 fn test_sync_hash_map_get_or_insert() {
1380 let map = SyncHashMap::new();
1381
1382 {
1384 let value = map.get_or_insert(1, "default".to_string());
1385 assert_eq!(*value, "default");
1386 }
1387 assert_eq!(map.len(), 1);
1388
1389 {
1391 let value = map.get_or_insert(1, "new_default".to_string());
1392 assert_eq!(*value, "default");
1393 }
1394 assert_eq!(map.len(), 1);
1395 }
1396
1397 #[test]
1398 fn test_sync_hash_map_get_or_insert_with() {
1399 let map = SyncHashMap::new();
1400
1401 {
1402 let value = map.get_or_insert_with(1, || "computed".to_string());
1403 assert_eq!(*value, "computed");
1404 }
1405 assert_eq!(map.len(), 1);
1406
1407 {
1408 let value = map.get_or_insert_with(1, || "new_computed".to_string());
1409 assert_eq!(*value, "computed");
1410 }
1411 }
1412
1413 #[test]
1414 fn test_sync_hash_map_remove_entry() {
1415 let map = SyncHashMap::new();
1416
1417 map.insert(1, "one".to_string());
1418 map.insert(2, "two".to_string());
1419
1420 let removed = map.remove_entry(&1);
1421 assert_eq!(removed, Some((1, "one".to_string())));
1422 assert_eq!(map.len(), 1);
1423 assert!(!map.contains_key(&1));
1424 }
1425
1426 #[test]
1427 fn test_sync_hash_map_iterators() {
1428 let map = SyncHashMap::new();
1429
1430 map.insert(1, "one".to_string());
1431 map.insert(2, "two".to_string());
1432 map.insert(3, "three".to_string());
1433
1434 let keys: Vec<_> = map.keys().collect();
1436 assert!(keys.contains(&&1));
1437 assert!(keys.contains(&&2));
1438 assert!(keys.contains(&&3));
1439
1440 assert_eq!(map.get_clone(&1), Some("one".to_string()));
1442 assert_eq!(map.get_clone(&2), Some("two".to_string()));
1443 assert_eq!(map.get_clone(&3), Some("three".to_string()));
1444
1445 let mut count = 0;
1447 for (k, v) in map.iter() {
1448 count += 1;
1449 assert!(map.contains_key(k));
1450 assert_eq!(*map.get(k).unwrap(), *v);
1451 }
1452 assert_eq!(count, 3);
1453 }
1454
1455 #[test]
1456 fn test_sync_hash_map_iter_mut() {
1457 let map = SyncHashMap::new();
1458
1459 map.insert(1, "one".to_string());
1460 map.insert(2, "two".to_string());
1461
1462 for (k, mut v) in map.iter_mut() {
1463 if *k == 1 {
1464 *v = "modified".to_string();
1465 }
1466 }
1467
1468 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1469 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1470 }
1471
1472 #[test]
1473 fn test_sync_hash_map_values_mut() {
1474 let map = SyncHashMap::new();
1475
1476 map.insert(1, "one".to_string());
1477 map.insert(2, "two".to_string());
1478
1479 for mut v in map.values_mut() {
1480 if *v == "one" {
1481 *v = "modified".to_string();
1482 }
1483 }
1484
1485 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1486 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1487 }
1488
1489 #[test]
1490 fn test_sync_hash_map_get_clone() {
1491 let map = SyncHashMap::new();
1492 map.insert(1, "one".to_string());
1493
1494 assert_eq!(map.get_clone(&1), Some("one".to_string()));
1496 assert_eq!(map.get_clone(&2), None);
1497 }
1498
1499 #[test]
1500 fn test_sync_hash_map_clone() {
1501 let map1 = SyncHashMap::new();
1502 map1.insert(1, "one".to_string());
1503 map1.insert(2, "two".to_string());
1504
1505 let map2 = map1.clone();
1506
1507 assert_eq!(map1.len(), map2.len());
1508 assert_eq!(*map1.get(&1).unwrap(), *map2.get(&1).unwrap());
1509 assert_eq!(*map1.get(&2).unwrap(), *map2.get(&2).unwrap());
1510
1511 map1.insert(3, "three".to_string());
1513 assert!(!map2.contains_key(&3));
1514 }
1515
1516 #[test]
1517 fn test_sync_hash_map_partial_eq() {
1518 let map1 = SyncHashMap::new();
1519 map1.insert(1, "one".to_string());
1520 map1.insert(2, "two".to_string());
1521
1522 let map2 = SyncHashMap::new();
1523 map2.insert(1, "one".to_string());
1524 map2.insert(2, "two".to_string());
1525
1526 let map3 = SyncHashMap::new();
1527 map3.insert(1, "different".to_string());
1528
1529 assert_eq!(map1, map2);
1530 assert_ne!(map1, map3);
1531 }
1532
1533 #[test]
1534 fn test_sync_hash_map_debug() {
1535 let map = SyncHashMap::new();
1536 map.insert(1, "one".to_string());
1537
1538 let debug_str = format!("{:?}", map);
1539 assert!(debug_str.contains("1"));
1540 assert!(debug_str.contains("one"));
1541 }
1542
1543 #[test]
1544 fn test_sync_hash_map_serialization() {
1545 let map = SyncHashMap::new();
1546 map.insert(1, "one".to_string());
1547 map.insert(2, "two".to_string());
1548
1549 let serialized = serde_json::to_string(&map).unwrap();
1551 assert!(serialized.contains("1"));
1552 assert!(serialized.contains("one"));
1553 assert!(serialized.contains("2"));
1554 assert!(serialized.contains("two"));
1555
1556 let deserialized: SyncHashMap<i32, String> = serde_json::from_str(&serialized).unwrap();
1558 assert_eq!(deserialized.len(), 2);
1559 assert_eq!(*deserialized.get(&1).unwrap(), "one".to_string());
1560 assert_eq!(*deserialized.get(&2).unwrap(), "two".to_string());
1561 }
1562
1563 #[test]
1564 fn test_sync_hash_map_from_hashmap() {
1565 let mut original = HashMap::new();
1566 original.insert(1, "one".to_string());
1567 original.insert(2, "two".to_string());
1568
1569 let map = SyncHashMap::from(original);
1570
1571 assert_eq!(map.len(), 2);
1572 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1573 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1574 }
1575
1576 #[test]
1577 fn test_sync_hash_map_into_iterator() {
1578 let map = SyncHashMap::new();
1579 map.insert(1, "one".to_string());
1580 map.insert(2, "two".to_string());
1581
1582 let mut count = 0;
1584 for (k, v) in &map {
1585 count += 1;
1586 assert!(map.contains_key(k));
1587 assert_eq!(*map.get(k).unwrap(), *v);
1588 }
1589 assert_eq!(count, 2);
1590
1591 let owned_pairs: Vec<_> = map.into_iter().collect();
1593 assert_eq!(owned_pairs.len(), 2);
1594 }
1595
1596 #[test]
1597 fn test_sync_hash_map_default() {
1598 let map: SyncHashMap<i32, String> = Default::default();
1599 assert_eq!(map.len(), 0);
1600 assert!(map.is_empty());
1601 }
1602
1603 #[test]
1604 fn test_sync_hash_map_arc() {
1605 let map = SyncHashMap::new_arc();
1606 map.insert(1, "one".to_string());
1607
1608 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1609
1610 let map2 = Arc::clone(&map);
1611 map2.insert(2, "two".to_string());
1612
1613 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1614 }
1615
1616 #[test]
1617 fn test_sync_hash_map_get_mut() {
1618 let map = SyncHashMap::new();
1619 map.insert(1, "one".to_string());
1620
1621 {
1622 let mut value = map.get_mut(&1).unwrap();
1623 *value = "modified".to_string();
1624 }
1625
1626 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1627 }
1628
1629 #[test]
1630 fn test_sync_hash_map_concurrent_access() {
1631 let map = Arc::new(SyncHashMap::new());
1632
1633 let handles: Vec<_> = (0..10).map(|i| {
1635 let map = Arc::clone(&map);
1636 thread::spawn(move || {
1637 map.insert(i, format!("value_{}", i));
1638 })
1639 }).collect();
1640
1641 for handle in handles {
1642 handle.join().unwrap();
1643 }
1644
1645 assert_eq!(map.len(), 10);
1647 for i in 0..10 {
1648 assert_eq!(*map.get(&i).unwrap(), format!("value_{}", i));
1649 }
1650
1651 let map_read = Arc::clone(&map);
1653 let handles: Vec<_> = (0..10).map(|i| {
1654 let map = Arc::clone(&map_read);
1655 thread::spawn(move || {
1656 let value = map.get(&i);
1657 assert_eq!(*value.unwrap(), format!("value_{}", i));
1658 })
1659 }).collect();
1660
1661 for handle in handles {
1662 handle.join().unwrap();
1663 }
1664 }
1665
1666 #[test]
1667 fn test_sync_hash_map_dirty_ref() {
1668 let map = SyncHashMap::new();
1669 map.insert(1, "one".to_string());
1670
1671 let dirty = map.dirty_ref();
1672 assert_eq!(dirty.len(), 1);
1673 assert_eq!(*dirty.get(&1).unwrap().read(), "one".to_string());
1675 }
1676
1677 #[test]
1678 fn test_sync_hash_map_into_inner() {
1679 let map = SyncHashMap::new();
1680 map.insert(1, "one".to_string());
1681 map.insert(2, "two".to_string());
1682
1683 let inner = map.into_inner();
1684 assert_eq!(inner.len(), 2);
1685 assert_eq!(inner.get(&1), Some(&"one".to_string()));
1686 assert_eq!(inner.get(&2), Some(&"two".to_string()));
1687 }
1688
1689 #[test]
1690 fn test_sync_hash_map_guard_debug() {
1691 let map = SyncHashMap::new();
1692 map.insert(1, "test".to_string());
1693
1694 let guard = map.get(&1).unwrap();
1695 let debug_str = format!("{:?}", guard);
1696 assert!(debug_str.contains("test"));
1697 }
1698
1699 #[test]
1700 fn test_sync_hash_map_guard_partial_eq() {
1701 let map = SyncHashMap::new();
1702 map.insert(1, "value".to_string());
1703
1704 let guard1 = map.get(&1).unwrap();
1705 let guard2 = map.get(&1).unwrap();
1706
1707 assert_eq!(guard1, guard2);
1708 }
1709
1710 mod buckets_tests {
1712 use super::*;
1713
1714 #[test]
1715 fn test_sync_hash_map_buckets_new() {
1716 let map = buckets::SyncHashMapB::<i32, String>::new(None);
1717 assert_eq!(map.len(), 0);
1718 assert!(map.is_empty());
1719 assert_eq!(map.bucket_count(), 10); }
1721
1722 #[test]
1723 fn test_sync_hash_map_buckets_with_custom_size() {
1724 let map = buckets::SyncHashMapB::<i32, String>::new(Some(5));
1725 assert_eq!(map.bucket_count(), 5);
1726 }
1727
1728 #[test]
1729 fn test_sync_hash_map_buckets_insert_and_get() {
1730 let map = buckets::SyncHashMapB::new(Some(3));
1731
1732 assert_eq!(map.insert(1, "one".to_string()), None);
1733 assert_eq!(map.insert(2, "two".to_string()), None);
1734 assert_eq!(map.len(), 2);
1735
1736 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1737 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1738 assert!(map.get(&3).is_none());
1739 }
1740
1741 #[test]
1742 fn test_sync_hash_map_buckets_remove() {
1743 let map = buckets::SyncHashMapB::new(Some(3));
1744
1745 map.insert(1, "one".to_string());
1746 map.insert(2, "two".to_string());
1747
1748 assert_eq!(map.remove(&1), Some("one".to_string()));
1749 assert_eq!(map.len(), 1);
1750 assert!(map.get(&1).is_none());
1751 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1752 }
1753
1754 #[test]
1755 fn test_sync_hash_map_buckets_clear() {
1756 let map = buckets::SyncHashMapB::new(Some(3));
1757
1758 map.insert(1, "one".to_string());
1759 map.insert(2, "two".to_string());
1760
1761 assert_eq!(map.len(), 2);
1762 map.clear();
1763 assert_eq!(map.len(), 0);
1764 assert!(map.is_empty());
1765 }
1766
1767 #[test]
1768 fn test_sync_hash_map_buckets_iterators() {
1769 let map = buckets::SyncHashMapB::new(Some(3));
1770
1771 map.insert(1, "one".to_string());
1772 map.insert(2, "two".to_string());
1773 map.insert(3, "three".to_string());
1774
1775 let keys: Vec<_> = map.keys().collect();
1777 assert!(keys.contains(&&1));
1778 assert!(keys.contains(&&2));
1779 assert!(keys.contains(&&3));
1780
1781 assert_eq!(map.get_clone(&1), Some("one".to_string()));
1783 assert_eq!(map.get_clone(&2), Some("two".to_string()));
1784 assert_eq!(map.get_clone(&3), Some("three".to_string()));
1785
1786 {
1788 let mut v = map.get_mut(&1).unwrap();
1789 *v = "modified".to_string();
1790 }
1791
1792 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1793 }
1794
1795 #[test]
1796 fn test_sync_hash_map_buckets_default() {
1797 let map: buckets::SyncHashMapB<i32, String> = Default::default();
1798 assert_eq!(map.len(), 0);
1799 assert!(map.is_empty());
1800 assert_eq!(map.bucket_count(), 10);
1801 }
1802
1803 #[test]
1804 fn test_sync_hash_map_buckets_debug() {
1805 let map = buckets::SyncHashMapB::new(Some(2));
1806 map.insert(1, "one".to_string());
1807
1808 let debug_str = format!("{:?}", map);
1809 assert!(debug_str.contains("1"));
1810 assert!(debug_str.contains("one"));
1811 }
1812 }
1813
1814 #[test]
1815 fn test_sync_hash_map_comprehensive() {
1816 let map = SyncHashMap::new();
1817
1818 map.insert("key1", 42);
1820 map.insert("key2", 24);
1821
1822 assert_eq!(map.len(), 2);
1823 assert!(!map.is_empty());
1824
1825 *map.get_mut("key1").unwrap() = 100;
1827 assert_eq!(*map.get(&"key1").unwrap(), 100);
1828
1829 map.insert("key3", 50);
1831 map.retain(|_, v| *v > 30);
1832
1833 assert_eq!(map.len(), 2);
1834 assert_eq!(*map.get(&"key1").unwrap(), 100);
1835 assert!(map.get(&"key2").is_none());
1836 assert_eq!(*map.get(&"key3").unwrap(), 50);
1837
1838 let map2 = map.clone();
1840 assert_eq!(map, map2);
1841
1842 let mut sum = 0;
1844 for (_, v) in map.iter() {
1845 sum += *v;
1846 }
1847 assert_eq!(sum, 150);
1848
1849 map.clear();
1851 assert_eq!(map.len(), 0);
1852 assert!(map.is_empty());
1853 }
1854
1855 #[test]
1856 fn test_sync_hash_map_iter_nlock() {
1857 let map = SyncHashMap::new();
1858 map.insert(1, "one".to_string());
1859 map.insert(2, "two".to_string());
1860 map.insert(3, "three".to_string());
1861
1862 let mut count = 0;
1864 for (k, v) in map.iter() {
1865 count += 1;
1866 match *k {
1867 1 => assert_eq!(v, "one"),
1868 2 => assert_eq!(v, "two"),
1869 3 => assert_eq!(v, "three"),
1870 _ => panic!("unexpected key"),
1871 }
1872 }
1873 assert_eq!(count, 3);
1874
1875 let iter = map.iter();
1877 assert_eq!(iter.len(), 3);
1878 }
1879
1880 #[test]
1881 fn test_sync_hash_map_into_iter_mut() {
1882 let mut map = SyncHashMap::new();
1883 map.insert(1, "one".to_string());
1884 map.insert(2, "two".to_string());
1885
1886 for (k, mut v) in &mut map {
1888 if *k == 1 {
1889 *v = "modified".to_string();
1890 }
1891 }
1892
1893 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1894 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1895 }
1896
1897 #[test]
1898 fn test_sync_hash_map_into_iter_ref() {
1899 let map = SyncHashMap::new();
1900 map.insert(1, 10);
1901 map.insert(2, 20);
1902 map.insert(3, 30);
1903
1904 let mut sum = 0;
1906 for (_, v) in &map {
1907 sum += *v;
1908 }
1909 assert_eq!(sum, 60);
1910
1911 assert_eq!(map.len(), 3);
1913 }
1914
1915 #[test]
1916 fn test_sync_hash_map_iter_nlock_empty() {
1917 let map: SyncHashMap<i32, String> = SyncHashMap::new();
1918
1919 let mut count = 0;
1920 for _ in map.iter() {
1921 count += 1;
1922 }
1923 assert_eq!(count, 0);
1924
1925 let iter = map.iter();
1926 assert_eq!(iter.len(), 0);
1927 }
1928}