1use serde::{Deserialize, Deserializer, Serialize, Serializer};
2use spin::{RwLock, RwLockReadGuard, RwLockWriteGuard};
3use std::borrow::Borrow;
4use std::cell::UnsafeCell;
5use std::collections::HashMap;
6use std::collections::hash_map::{IntoIter as MapIntoIter, Iter as MapIter, Keys};
7use std::fmt::{Debug, Formatter};
8use std::hash::{BuildHasherDefault, DefaultHasher, Hash};
9use std::ops::{Deref, DerefMut};
10use std::sync::Arc;
11
12pub type DefaultBuildHasher = BuildHasherDefault<DefaultHasher>;
22
23pub struct SyncHashMap<K, V> {
54 dirty: UnsafeCell<HashMap<K, RwLock<V>, DefaultBuildHasher>>,
57 lock: RwLock<()>,
60}
61
62unsafe impl<K, V> Send for SyncHashMap<K, V> {}
66
67unsafe impl<K, V> Sync for SyncHashMap<K, V> {}
71
72impl<K, V> SyncHashMap<K, V>
75where
76 K: Eq + Hash,
77{
78 pub fn new_arc() -> Arc<Self> {
81 Arc::new(Self::new())
82 }
83
84 pub const fn new() -> Self {
87 Self {
88 dirty: UnsafeCell::new(HashMap::with_hasher(DefaultBuildHasher::new())),
89 lock: RwLock::new(()),
90 }
91 }
92
93 pub fn with_capacity(capacity: usize) -> Self {
96 Self {
97 dirty: UnsafeCell::new(HashMap::with_capacity_and_hasher(
98 capacity,
99 std::hash::BuildHasherDefault::default(),
100 )),
101 lock: RwLock::new(()),
102 }
103 }
104
105 pub fn with_map(map: HashMap<K, V>) -> Self {
111 let mut wrapped =
112 HashMap::with_capacity_and_hasher(map.len(), std::hash::BuildHasherDefault::default());
113 for (k, v) in map {
114 wrapped.insert(k, RwLock::new(v));
115 }
116 Self {
117 dirty: UnsafeCell::new(wrapped),
118 lock: RwLock::new(()),
119 }
120 }
121
122 #[inline(always)]
128 pub fn insert(&self, k: K, v: V) -> Option<V> {
129 let _lock = self.lock.write();
130 let m = unsafe { &mut *self.dirty.get() };
131 m.insert(k, RwLock::new(v)).map(|old| old.into_inner())
132 }
133
134 #[inline(always)]
137 pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
138 let m = unsafe { &mut *self.dirty.get() };
139 m.insert(k, RwLock::new(v)).map(|old| old.into_inner())
140 }
141
142 #[inline(always)]
145 pub fn remove(&self, k: &K) -> Option<V> {
146 let _lock = self.lock.write();
147 let m = unsafe { &mut *self.dirty.get() };
148 m.remove(k).map(|v| v.into_inner())
149 }
150
151 #[inline(always)]
154 pub fn remove_mut(&mut self, k: &K) -> Option<V> {
155 let m = unsafe { &mut *self.dirty.get() };
156 m.remove(k).map(|v| v.into_inner())
157 }
158
159 #[inline(always)]
162 pub fn len(&self) -> usize {
163 let _lock = self.lock.read();
164 let m = unsafe { &*self.dirty.get() };
165 m.len()
166 }
167
168 #[inline(always)]
171 pub fn is_empty(&self) -> bool {
172 let _lock = self.lock.read();
173 let m = unsafe { &*self.dirty.get() };
174 m.is_empty()
175 }
176
177 #[inline(always)]
180 pub fn clear(&self) {
181 let _lock = self.lock.write();
182 let m = unsafe { &mut *self.dirty.get() };
183 m.clear();
184 }
185
186 #[inline(always)]
189 pub fn clear_mut(&mut self) {
190 let m = unsafe { &mut *self.dirty.get() };
191 m.clear();
192 }
193
194 #[inline(always)]
197 pub fn shrink_to_fit(&self) {
198 let _lock = self.lock.write();
199 let m = unsafe { &mut *self.dirty.get() };
200 m.shrink_to_fit();
201 }
202
203 #[inline(always)]
206 pub fn shrink_to_fit_mut(&mut self) {
207 let m = unsafe { &mut *self.dirty.get() };
208 m.shrink_to_fit();
209 }
210
211 pub fn from(map: HashMap<K, V>) -> Self {
214 Self::with_map(map)
215 }
216
217 #[inline]
241 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<MapReadGuard<'_, V>>
242 where
243 K: Borrow<Q>,
244 Q: Hash + Eq,
245 {
246 let map_lock = self.lock.read();
247 let m = unsafe { &*self.dirty.get() };
248 let value_lock_wrapper = m.get(k)?;
249 let value_ptr = unsafe {
251 let lock_ptr = value_lock_wrapper as *const RwLock<V> as *mut RwLock<V>;
252 &*(*lock_ptr).get_mut()
253 };
254 Some(MapReadGuard {
255 _map_lock: map_lock,
256 _value_ptr: value_ptr,
257 })
258 }
259
260 pub fn get_rlock<Q: ?Sized>(&self, k: &Q) -> Option<ReadGuard<'_, V>>
265 where
266 K: Borrow<Q>,
267 Q: Hash + Eq,
268 {
269 let map_lock = self.lock.read();
270 let m = unsafe { &*self.dirty.get() };
271 let value_lock_wrapper = m.get(k)?;
272 let value_lock = value_lock_wrapper.read();
273 Some(ReadGuard {
274 _map_lock: map_lock,
275 _value_lock: value_lock,
276 })
277 }
278
279 #[inline]
292 pub fn get_uncheck<Q: ?Sized>(&self, k: &Q) -> MapReadGuard<'_, V>
293 where
294 K: Borrow<Q>,
295 Q: Hash + Eq,
296 {
297 let map_lock = self.lock.read();
298 let m = unsafe { &*self.dirty.get() };
299 let value_lock_wrapper = m.get(k).expect("key not found");
300 let value_ptr = unsafe {
302 let lock_ptr = value_lock_wrapper as *const RwLock<V> as *mut RwLock<V>;
303 &*(*lock_ptr).get_mut()
304 };
305 MapReadGuard {
306 _map_lock: map_lock,
307 _value_ptr: value_ptr,
308 }
309 }
310
311 #[inline]
319 pub fn get_mut<Q: ?Sized>(&self, k: &Q) -> Option<WriteGuard<'_, V>>
320 where
321 K: Borrow<Q>,
322 Q: Hash + Eq,
323 {
324 let map_lock = self.lock.read();
325 let m = unsafe { &*self.dirty.get() };
326 let value_lock_wrapper = m.get(k)?;
327 let value_lock = value_lock_wrapper.write();
328 Some(WriteGuard {
329 _map_lock: map_lock,
330 _value_lock: value_lock,
331 })
332 }
333
334 #[inline]
337 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
338 where
339 K: Borrow<Q>,
340 Q: Hash + Eq,
341 {
342 let _lock = self.lock.read();
343 let m = unsafe { &*self.dirty.get() };
344 m.contains_key(k)
345 }
346
347 pub fn iter_mut(&self) -> IterMut<'_, K, V> {
353 let _lock = self.lock.read();
354 let m = unsafe { &*self.dirty.get() };
355 IterMut {
356 _lock,
357 inner: m.iter(),
358 }
359 }
360
361 pub fn iter_rlock(&self) -> IterRLock<'_, K, V> {
369 let _lock = self.lock.read();
370 let m = unsafe { &*self.dirty.get() };
371 IterRLock {
372 _lock,
373 inner: m.iter(),
374 }
375 }
376
377 pub fn iter(&self) -> IterNoLock<'_, K, V> {
386 let _lock = self.lock.read();
387 let m = unsafe { &*self.dirty.get() };
388 IterNoLock {
389 _lock,
390 inner: m.iter(),
391 }
392 }
393
394 pub fn dirty_ref(&self) -> ReadGuardMap<'_, K, V> {
402 let _lock = self.lock.read();
403 let v = unsafe { &*self.dirty.get() };
404 ReadGuardMap { _lock, v }
405 }
406
407 pub unsafe fn dirty_ref_unsafe(&self) -> &HashMap<K, RwLock<V>, DefaultBuildHasher> {
415 unsafe { &*self.dirty.get() }
416 }
417
418 pub fn into_inner(self) -> HashMap<K, V> {
421 self.dirty
422 .into_inner()
423 .into_iter()
424 .map(|(k, v)| (k, v.into_inner()))
425 .collect()
426 }
427
428 #[inline]
434 pub fn keys(&self) -> KeysGuard<'_, K, V> {
435 let _lock = self.lock.read();
436 let m = unsafe { &*self.dirty.get() };
437 KeysGuard {
438 _lock,
439 inner: m.keys(),
440 }
441 }
442
443 #[inline]
449 pub fn values(&self) -> ValuesGuard<'_, K, V> {
450 let _lock = self.lock.read();
451 let m = unsafe { &*self.dirty.get() };
452 ValuesGuard {
453 _lock,
454 inner: m.values(),
455 }
456 }
457
458 #[inline]
464 pub fn values_mut(&self) -> ValuesMutGuard<'_, K, V> {
465 let _lock = self.lock.write();
466 let m = unsafe { &*self.dirty.get() };
467 ValuesMutGuard {
468 _lock,
469 inner: m.values(),
470 }
471 }
472
473 #[inline]
476 pub fn retain<F>(&self, mut f: F)
477 where
478 F: FnMut(&K, &mut V) -> bool,
479 {
480 let _lock = self.lock.write();
481 let m = unsafe { &mut *self.dirty.get() };
482 m.retain(|k, v| f(k, v.get_mut()));
483 }
484
485 #[inline]
488 pub fn capacity(&self) -> usize {
489 let _lock = self.lock.read();
490 let m = unsafe { &*self.dirty.get() };
491 m.capacity()
492 }
493
494 #[inline]
497 pub fn reserve(&self, additional: usize) {
498 let _lock = self.lock.write();
499 let m = unsafe { &mut *self.dirty.get() };
500 m.reserve(additional);
501 }
502
503 #[inline]
506 pub fn remove_entry(&self, k: &K) -> Option<(K, V)> {
507 let _lock = self.lock.write();
508 let m = unsafe { &mut *self.dirty.get() };
509 m.remove_entry(k).map(|(k, v)| (k, v.into_inner()))
510 }
511
512 #[inline]
518 pub fn get_or_insert(&self, k: K, default: V) -> WriteGuardEntry<'_, V> {
519 let map_lock = self.lock.write();
520 let m = unsafe { &mut *self.dirty.get() };
521 let entry = m.entry(k).or_insert_with(|| RwLock::new(default));
522 let value_lock = entry.write();
523 WriteGuardEntry {
524 _map_lock: map_lock,
525 _value_lock: value_lock,
526 }
527 }
528
529 #[inline]
535 pub fn get_or_insert_with<F>(&self, k: K, default: F) -> WriteGuardEntry<'_, V>
536 where
537 F: FnOnce() -> V,
538 {
539 let map_lock = self.lock.write();
540 let m = unsafe { &mut *self.dirty.get() };
541 let entry = m.entry(k).or_insert_with(|| RwLock::new(default()));
542 let value_lock = entry.write();
543 WriteGuardEntry {
544 _map_lock: map_lock,
545 _value_lock: value_lock,
546 }
547 }
548
549 #[inline]
555 pub fn get_clone<Q: ?Sized>(&self, k: &Q) -> Option<V>
556 where
557 K: Borrow<Q>,
558 Q: Hash + Eq,
559 V: Clone,
560 {
561 let _map_lock = self.lock.read();
562 let m = unsafe { &*self.dirty.get() };
563 m.get(k).map(|v| v.read().clone())
564 }
565
566 #[inline]
572 pub fn take(&self, k: &K) -> Option<V> {
573 self.remove(k)
574 }
575}
576
577pub struct MapReadGuard<'a, V> {
585 _map_lock: RwLockReadGuard<'a, ()>,
588 _value_ptr: &'a V,
591}
592
593impl<'a, V> Deref for MapReadGuard<'a, V> {
594 type Target = V;
595
596 fn deref(&self) -> &Self::Target {
597 self._value_ptr
598 }
599}
600
601impl<'a, V> Debug for MapReadGuard<'a, V>
602where
603 V: Debug,
604{
605 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
606 write!(f, "{:?}", self._value_ptr)
607 }
608}
609
610impl<'a, V> PartialEq for MapReadGuard<'a, V>
611where
612 V: PartialEq,
613{
614 fn eq(&self, other: &Self) -> bool {
615 self._value_ptr.eq(other._value_ptr)
616 }
617}
618
619impl<'a, V> Eq for MapReadGuard<'a, V> where V: Eq {}
620
621impl<'a, V> std::fmt::Display for MapReadGuard<'a, V>
622where
623 V: std::fmt::Display,
624{
625 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
626 self._value_ptr.fmt(f)
627 }
628}
629
630impl<'a, V> AsRef<V> for MapReadGuard<'a, V> {
631 fn as_ref(&self) -> &V {
632 self._value_ptr
633 }
634}
635
636pub struct ReadGuard<'a, V> {
639 _map_lock: RwLockReadGuard<'a, ()>,
642 _value_lock: RwLockReadGuard<'a, V>,
645}
646
647impl<'a, V> Deref for ReadGuard<'a, V> {
648 type Target = V;
649
650 fn deref(&self) -> &Self::Target {
651 &*self._value_lock
652 }
653}
654
655impl<'a, V> Debug for ReadGuard<'a, V>
656where
657 V: Debug,
658{
659 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
660 write!(f, "{:?}", &*self._value_lock)
661 }
662}
663
664impl<'a, V> PartialEq for ReadGuard<'a, V>
665where
666 V: PartialEq,
667{
668 fn eq(&self, other: &Self) -> bool {
669 (*self._value_lock).eq(&*other._value_lock)
670 }
671}
672
673impl<'a, V> Eq for ReadGuard<'a, V> where V: Eq {}
674
675impl<'a, V> std::fmt::Display for ReadGuard<'a, V>
676where
677 V: std::fmt::Display,
678{
679 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
680 (*self._value_lock).fmt(f)
681 }
682}
683
684impl<'a, V> AsRef<V> for ReadGuard<'a, V> {
685 fn as_ref(&self) -> &V {
686 &*self._value_lock
687 }
688}
689
690pub struct ReadGuardMap<'a, K, V> {
696 _lock: RwLockReadGuard<'a, ()>,
699 v: &'a HashMap<K, RwLock<V>, DefaultBuildHasher>,
702}
703
704impl<'a, K, V> Deref for ReadGuardMap<'a, K, V> {
705 type Target = HashMap<K, RwLock<V>, DefaultBuildHasher>;
706
707 fn deref(&self) -> &Self::Target {
708 self.v
709 }
710}
711
712impl<'a, K, V> Debug for ReadGuardMap<'a, K, V>
713where
714 K: Debug,
715 V: Debug,
716{
717 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
718 let mut map = f.debug_map();
721 for (k, v) in self.v.iter() {
722 map.entry(k, &*v.read());
723 }
724 map.finish()
725 }
726}
727
728impl<'a, K, V> AsRef<HashMap<K, RwLock<V>, DefaultBuildHasher>> for ReadGuardMap<'a, K, V> {
729 fn as_ref(&self) -> &HashMap<K, RwLock<V>, DefaultBuildHasher> {
730 self.v
731 }
732}
733
734pub struct WriteGuard<'a, V> {
740 _map_lock: RwLockReadGuard<'a, ()>,
743 _value_lock: RwLockWriteGuard<'a, V>,
746}
747
748impl<'a, V> Deref for WriteGuard<'a, V> {
749 type Target = V;
750
751 fn deref(&self) -> &Self::Target {
752 &*self._value_lock
753 }
754}
755
756impl<'a, V> DerefMut for WriteGuard<'a, V> {
757 fn deref_mut(&mut self) -> &mut Self::Target {
758 &mut *self._value_lock
759 }
760}
761
762impl<'a, V> Debug for WriteGuard<'a, V>
763where
764 V: Debug,
765{
766 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
767 write!(f, "{:?}", &*self._value_lock)
768 }
769}
770
771impl<'a, V> PartialEq for WriteGuard<'a, V>
772where
773 V: PartialEq,
774{
775 fn eq(&self, other: &Self) -> bool {
776 (*self._value_lock).eq(&*other._value_lock)
777 }
778}
779
780impl<'a, V> Eq for WriteGuard<'a, V> where V: Eq {}
781
782impl<'a, V> std::fmt::Display for WriteGuard<'a, V>
783where
784 V: std::fmt::Display,
785{
786 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
787 (*self._value_lock).fmt(f)
788 }
789}
790
791impl<'a, V> AsRef<V> for WriteGuard<'a, V> {
792 fn as_ref(&self) -> &V {
793 &*self._value_lock
794 }
795}
796
797impl<'a, V> AsMut<V> for WriteGuard<'a, V> {
798 fn as_mut(&mut self) -> &mut V {
799 &mut *self._value_lock
800 }
801}
802
803pub struct WriteGuardEntry<'a, V> {
809 _map_lock: RwLockWriteGuard<'a, ()>,
812 _value_lock: RwLockWriteGuard<'a, V>,
815}
816
817impl<'a, V> Deref for WriteGuardEntry<'a, V> {
818 type Target = V;
819
820 fn deref(&self) -> &Self::Target {
821 &*self._value_lock
822 }
823}
824
825impl<'a, V> DerefMut for WriteGuardEntry<'a, V> {
826 fn deref_mut(&mut self) -> &mut Self::Target {
827 &mut *self._value_lock
828 }
829}
830
831impl<'a, V> Debug for WriteGuardEntry<'a, V>
832where
833 V: Debug,
834{
835 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
836 write!(f, "{:?}", &*self._value_lock)
837 }
838}
839
840impl<'a, V> std::fmt::Display for WriteGuardEntry<'a, V>
841where
842 V: std::fmt::Display,
843{
844 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
845 (*self._value_lock).fmt(f)
846 }
847}
848
849impl<'a, V> AsRef<V> for WriteGuardEntry<'a, V> {
850 fn as_ref(&self) -> &V {
851 &*self._value_lock
852 }
853}
854
855impl<'a, V> AsMut<V> for WriteGuardEntry<'a, V> {
856 fn as_mut(&mut self) -> &mut V {
857 &mut *self._value_lock
858 }
859}
860
861#[allow(dead_code)]
864#[deprecated(note = "Use ReadGuard instead")]
865pub type SyncMapRefMut<'a, V> = WriteGuard<'a, V>;
866
867pub struct IterRLock<'a, K, V> {
873 _lock: RwLockReadGuard<'a, ()>,
876 inner: MapIter<'a, K, RwLock<V>>,
879}
880
881impl<'a, K, V> Iterator for IterRLock<'a, K, V> {
882 type Item = (&'a K, RwLockReadGuard<'a, V>);
883
884 fn next(&mut self) -> Option<Self::Item> {
885 self.inner.next().map(|(k, v)| (k, v.read()))
886 }
887}
888
889pub type IterMy<'a, K, V> = IterRLock<'a, K, V>;
892
893pub struct IterMut<'a, K, V> {
899 _lock: RwLockReadGuard<'a, ()>,
902 inner: MapIter<'a, K, RwLock<V>>,
905}
906
907impl<'a, K, V> Iterator for IterMut<'a, K, V> {
908 type Item = (&'a K, RwLockWriteGuard<'a, V>);
909
910 fn next(&mut self) -> Option<Self::Item> {
911 self.inner.next().map(|(k, v)| (k, v.write()))
912 }
913}
914
915pub struct KeysGuard<'a, K, V> {
918 _lock: RwLockReadGuard<'a, ()>,
921 inner: Keys<'a, K, RwLock<V>>,
924}
925
926impl<'a, K, V> Deref for KeysGuard<'a, K, V> {
927 type Target = Keys<'a, K, RwLock<V>>;
928
929 fn deref(&self) -> &Self::Target {
930 &self.inner
931 }
932}
933
934impl<'a, K, V> DerefMut for KeysGuard<'a, K, V> {
935 fn deref_mut(&mut self) -> &mut Self::Target {
936 &mut self.inner
937 }
938}
939
940impl<'a, K, V> Iterator for KeysGuard<'a, K, V> {
941 type Item = &'a K;
942
943 fn next(&mut self) -> Option<Self::Item> {
944 self.inner.next()
945 }
946}
947
948pub struct ValuesGuard<'a, K, V> {
954 _lock: RwLockReadGuard<'a, ()>,
957 inner: std::collections::hash_map::Values<'a, K, RwLock<V>>,
960}
961
962impl<'a, K, V> Iterator for ValuesGuard<'a, K, V> {
963 type Item = RwLockReadGuard<'a, V>;
964
965 fn next(&mut self) -> Option<Self::Item> {
966 self.inner.next().map(|v| v.read())
967 }
968}
969
970pub struct ValuesMutGuard<'a, K, V> {
976 _lock: RwLockWriteGuard<'a, ()>,
979 inner: std::collections::hash_map::Values<'a, K, RwLock<V>>,
982}
983
984impl<'a, K, V> Iterator for ValuesMutGuard<'a, K, V> {
985 type Item = RwLockWriteGuard<'a, V>;
986
987 fn next(&mut self) -> Option<Self::Item> {
988 self.inner.next().map(|v| v.write())
989 }
990}
991
992pub struct IterNoLock<'a, K, V> {
995 _lock: RwLockReadGuard<'a, ()>,
998 inner: MapIter<'a, K, RwLock<V>>,
1001}
1002
1003impl<'a, K, V> Iterator for IterNoLock<'a, K, V> {
1004 type Item = (&'a K, &'a V);
1005
1006 fn next(&mut self) -> Option<Self::Item> {
1007 self.inner.next().map(|(k, v)| {
1008 unsafe {
1010 let lock_ptr = v as *const RwLock<V> as *mut RwLock<V>;
1011 (k, &*(*lock_ptr).get_mut())
1012 }
1013 })
1014 }
1015}
1016
1017impl<'a, K, V> ExactSizeIterator for IterNoLock<'a, K, V> {
1018 fn len(&self) -> usize {
1019 self.inner.len()
1020 }
1021}
1022
1023impl<'a, K, V> IntoIterator for &'a SyncHashMap<K, V>
1024where
1025 K: Eq + Hash,
1026{
1027 type Item = (&'a K, &'a V);
1028 type IntoIter = IterNoLock<'a, K, V>;
1029
1030 fn into_iter(self) -> Self::IntoIter {
1031 self.iter()
1032 }
1033}
1034
1035impl<'a, K, V> IntoIterator for &'a mut SyncHashMap<K, V>
1036where
1037 K: Eq + Hash,
1038{
1039 type Item = (&'a K, RwLockWriteGuard<'a, V>);
1040 type IntoIter = IterMut<'a, K, V>;
1041
1042 fn into_iter(self) -> Self::IntoIter {
1043 self.iter_mut()
1044 }
1045}
1046
1047impl<K, V> IntoIterator for SyncHashMap<K, V>
1048where
1049 K: Eq + Hash,
1050{
1051 type Item = (K, V);
1052 type IntoIter = MapIntoIter<K, V>;
1053
1054 fn into_iter(self) -> Self::IntoIter {
1055 self.into_inner().into_iter()
1056 }
1057}
1058
1059impl<K, V> From<HashMap<K, V>> for SyncHashMap<K, V>
1060where
1061 K: Eq + Hash,
1062{
1063 fn from(map: HashMap<K, V>) -> Self {
1064 Self::with_map(map)
1065 }
1066}
1067
1068impl<K, V> Serialize for SyncHashMap<K, V>
1069where
1070 K: Eq + Hash + Serialize,
1071 V: Serialize,
1072{
1073 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1074 where
1075 S: Serializer,
1076 {
1077 use serde::ser::SerializeMap;
1078 let _lock = self.lock.read();
1079 let m = unsafe { &*self.dirty.get() };
1080 let mut map = serializer.serialize_map(Some(m.len()))?;
1081 for (k, v) in m.iter() {
1082 map.serialize_entry(k, &*v.read())?;
1083 }
1084 map.end()
1085 }
1086}
1087
1088impl<'de, K, V> Deserialize<'de> for SyncHashMap<K, V>
1089where
1090 K: Eq + Hash + Deserialize<'de>,
1091 V: Deserialize<'de>,
1092{
1093 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1094 where
1095 D: Deserializer<'de>,
1096 {
1097 let m = HashMap::deserialize(deserializer)?;
1098 Ok(Self::with_map(m))
1099 }
1100}
1101
1102impl<K, V> Debug for SyncHashMap<K, V>
1103where
1104 K: Eq + Hash + Debug,
1105 V: Debug,
1106{
1107 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1108 let _lock = self.lock.read();
1109 let m = unsafe { &*self.dirty.get() };
1110 let mut map = f.debug_map();
1111 for (k, v) in m.iter() {
1112 map.entry(k, &*v.read());
1113 }
1114 map.finish()
1115 }
1116}
1117
1118impl<K, V> Clone for SyncHashMap<K, V>
1119where
1120 K: Clone + Eq + Hash,
1121 V: Clone,
1122{
1123 fn clone(&self) -> Self {
1124 let _lock = self.lock.read();
1125 let m = unsafe { &*self.dirty.get() };
1126 let cloned: HashMap<K, V> = m
1127 .iter()
1128 .map(|(k, v)| (k.clone(), v.read().clone()))
1129 .collect();
1130 SyncHashMap::with_map(cloned)
1131 }
1132}
1133
1134impl<K, V> Default for SyncHashMap<K, V>
1135where
1136 K: Eq + Hash,
1137{
1138 fn default() -> Self {
1139 Self::new()
1140 }
1141}
1142
1143impl<K, V> PartialEq for SyncHashMap<K, V>
1144where
1145 K: Eq + Hash,
1146 V: PartialEq,
1147{
1148 fn eq(&self, other: &Self) -> bool {
1149 let _lock_self = self.lock.read();
1150 let _lock_other = other.lock.read();
1151 let self_map = unsafe { &*self.dirty.get() };
1152 let other_map = unsafe { &*other.dirty.get() };
1153
1154 if self_map.len() != other_map.len() {
1155 return false;
1156 }
1157
1158 for (k, v) in self_map.iter() {
1159 match other_map.get(k) {
1160 Some(other_v) => {
1161 if *v.read() != *other_v.read() {
1162 return false;
1163 }
1164 }
1165 None => return false,
1166 }
1167 }
1168 true
1169 }
1170}
1171
1172impl<K, V> Eq for SyncHashMap<K, V>
1173where
1174 K: Eq + Hash,
1175 V: Eq,
1176{
1177}
1178
1179pub mod buckets {
1182 use super::{MapReadGuard, ReadGuard, SyncHashMap, WriteGuard};
1183 use std::hash::{Hash, Hasher};
1184
1185 #[derive(Debug, Clone)]
1188 pub struct SyncHashMapB<K, V>
1189 where
1190 K: Eq + Hash,
1191 {
1192 inner: Vec<SyncHashMap<K, V>>,
1195 len: usize,
1198 }
1199
1200 impl<K, V> SyncHashMapB<K, V>
1201 where
1202 K: Eq + Hash,
1203 {
1204 pub fn new(bucket_count: Option<usize>) -> Self {
1223 let count = bucket_count.unwrap_or(10);
1224 let mut arr = Vec::with_capacity(count);
1225 for _ in 0..count {
1226 arr.push(SyncHashMap::new());
1227 }
1228 Self {
1229 inner: arr,
1230 len: count,
1231 }
1232 }
1233
1234 fn key_to_bucket_index(&self, k: &K) -> usize {
1237 let mut hasher = std::collections::hash_map::DefaultHasher::new();
1238 k.hash(&mut hasher);
1239 let hash = hasher.finish();
1240 (hash % self.len as u64) as usize
1241 }
1242
1243 #[inline]
1246 pub fn insert(&self, k: K, v: V) -> Option<V> {
1247 let index = self.key_to_bucket_index(&k);
1248 self.inner[index].insert(k, v)
1249 }
1250
1251 #[inline]
1254 pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
1255 let index = self.key_to_bucket_index(&k);
1256 self.inner[index].insert_mut(k, v)
1257 }
1258
1259 #[inline]
1262 pub fn remove(&self, k: &K) -> Option<V> {
1263 let index = self.key_to_bucket_index(k);
1264 self.inner[index].remove(k)
1265 }
1266
1267 #[inline]
1270 pub fn is_empty(&self) -> bool {
1271 self.inner.iter().all(|bucket| bucket.is_empty())
1272 }
1273
1274 #[inline]
1277 pub fn len(&self) -> usize {
1278 self.inner.iter().map(|bucket| bucket.len()).sum()
1279 }
1280
1281 #[inline]
1284 pub fn clear(&self) {
1285 self.inner.iter().for_each(|bucket| bucket.clear());
1286 }
1287
1288 #[inline]
1294 pub fn get(&self, k: &K) -> Option<MapReadGuard<'_, V>> {
1295 let index = self.key_to_bucket_index(k);
1296 self.inner[index].get(k)
1297 }
1298
1299 #[inline]
1305 pub fn get_mut(&self, k: &K) -> Option<WriteGuard<'_, V>> {
1306 let index = self.key_to_bucket_index(k);
1307 self.inner[index].get_mut(k)
1308 }
1309
1310 #[inline]
1313 pub fn bucket_count(&self) -> usize {
1314 self.len
1315 }
1316
1317 #[inline]
1320 pub fn keys(&self) -> impl Iterator<Item = &K> {
1321 self.inner.iter().flat_map(|bucket| bucket.keys())
1322 }
1323
1324 #[inline]
1327 pub fn get_clone(&self, k: &K) -> Option<V>
1328 where
1329 V: Clone,
1330 {
1331 let index = self.key_to_bucket_index(k);
1332 self.inner[index].get_clone(k)
1333 }
1334 }
1335
1336 impl<K, V> Default for SyncHashMapB<K, V>
1337 where
1338 K: Eq + Hash,
1339 {
1340 fn default() -> Self {
1341 Self::new(None)
1342 }
1343 }
1344}
1345
1346#[cfg(test)]
1347mod tests {
1348 use super::*;
1349 use std::collections::HashMap;
1350 use std::sync::Arc;
1351 use std::thread;
1352
1353 #[test]
1354 fn test_sync_hash_map_new() {
1355 let map: SyncHashMap<i32, String> = SyncHashMap::new();
1356 assert_eq!(map.len(), 0);
1357 assert!(map.is_empty());
1358 }
1359
1360 #[test]
1361 fn test_sync_hash_map_with_capacity() {
1362 let map = SyncHashMap::<i32, String>::with_capacity(100);
1363 assert!(map.capacity() >= 100);
1364 }
1365
1366 #[test]
1367 fn test_sync_hash_map_with_map() {
1368 let mut original = HashMap::new();
1369 original.insert(1, "one".to_string());
1370 original.insert(2, "two".to_string());
1371
1372 let map = SyncHashMap::with_map(original);
1373 assert_eq!(map.len(), 2);
1374 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1375 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1376 }
1377
1378 #[test]
1379 fn test_sync_hash_map_insert_and_get() {
1380 let map = SyncHashMap::new();
1381
1382 assert_eq!(map.insert(1, "one".to_string()), None);
1384 assert_eq!(map.insert(2, "two".to_string()), None);
1385 assert_eq!(map.len(), 2);
1386
1387 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1388 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1389 assert!(map.get(&3).is_none());
1390 }
1391
1392 #[test]
1393 fn test_sync_hash_map_insert_replace() {
1394 let map = SyncHashMap::new();
1395
1396 assert_eq!(map.insert(1, "one".to_string()), None);
1397 assert_eq!(
1398 map.insert(1, "updated".to_string()),
1399 Some("one".to_string())
1400 );
1401 assert_eq!(*map.get(&1).unwrap(), "updated".to_string());
1402 }
1403
1404 #[test]
1405 fn test_sync_hash_map_remove() {
1406 let map = SyncHashMap::new();
1407
1408 map.insert(1, "one".to_string());
1409 map.insert(2, "two".to_string());
1410
1411 assert_eq!(map.remove(&1), Some("one".to_string()));
1412 assert_eq!(map.remove(&1), None);
1413 assert_eq!(map.len(), 1);
1414 assert!(map.get(&1).is_none());
1415 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1416 }
1417
1418 #[test]
1419 fn test_sync_hash_map_contains_key() {
1420 let map = SyncHashMap::new();
1421
1422 map.insert(1, "one".to_string());
1423
1424 assert!(map.contains_key(&1));
1425 assert!(!map.contains_key(&2));
1426 }
1427
1428 #[test]
1429 fn test_sync_hash_map_clear() {
1430 let map = SyncHashMap::new();
1431
1432 map.insert(1, "one".to_string());
1433 map.insert(2, "two".to_string());
1434
1435 assert_eq!(map.len(), 2);
1436 map.clear();
1437 assert_eq!(map.len(), 0);
1438 assert!(map.is_empty());
1439 }
1440
1441 #[test]
1442 fn test_sync_hash_map_capacity_operations() {
1443 let map = SyncHashMap::new();
1444
1445 assert_eq!(map.capacity(), 0);
1446 map.reserve(100);
1447 assert!(map.capacity() >= 100);
1448
1449 map.insert(1, "one".to_string());
1450 map.insert(2, "two".to_string());
1451
1452 let old_capacity = map.capacity();
1453 map.shrink_to_fit();
1454 assert!(map.capacity() <= old_capacity);
1455 }
1456
1457 #[test]
1458 fn test_sync_hash_map_retain() {
1459 let map = SyncHashMap::new();
1460
1461 map.insert(1, "one".to_string());
1462 map.insert(2, "two".to_string());
1463 map.insert(3, "three".to_string());
1464
1465 map.retain(|&k, _| k % 2 == 1);
1466
1467 assert_eq!(map.len(), 2);
1468 assert!(map.contains_key(&1));
1469 assert!(!map.contains_key(&2));
1470 assert!(map.contains_key(&3));
1471 }
1472
1473 #[test]
1474 fn test_sync_hash_map_get_or_insert() {
1475 let map = SyncHashMap::new();
1476
1477 {
1479 let value = map.get_or_insert(1, "default".to_string());
1480 assert_eq!(*value, "default");
1481 }
1482 assert_eq!(map.len(), 1);
1483
1484 {
1486 let value = map.get_or_insert(1, "new_default".to_string());
1487 assert_eq!(*value, "default");
1488 }
1489 assert_eq!(map.len(), 1);
1490 }
1491
1492 #[test]
1493 fn test_sync_hash_map_get_or_insert_with() {
1494 let map = SyncHashMap::new();
1495
1496 {
1497 let value = map.get_or_insert_with(1, || "computed".to_string());
1498 assert_eq!(*value, "computed");
1499 }
1500 assert_eq!(map.len(), 1);
1501
1502 {
1503 let value = map.get_or_insert_with(1, || "new_computed".to_string());
1504 assert_eq!(*value, "computed");
1505 }
1506 }
1507
1508 #[test]
1509 fn test_sync_hash_map_remove_entry() {
1510 let map = SyncHashMap::new();
1511
1512 map.insert(1, "one".to_string());
1513 map.insert(2, "two".to_string());
1514
1515 let removed = map.remove_entry(&1);
1516 assert_eq!(removed, Some((1, "one".to_string())));
1517 assert_eq!(map.len(), 1);
1518 assert!(!map.contains_key(&1));
1519 }
1520
1521 #[test]
1522 fn test_sync_hash_map_iterators() {
1523 let map = SyncHashMap::new();
1524
1525 map.insert(1, "one".to_string());
1526 map.insert(2, "two".to_string());
1527 map.insert(3, "three".to_string());
1528
1529 let keys: Vec<_> = map.keys().collect();
1531 assert!(keys.contains(&&1));
1532 assert!(keys.contains(&&2));
1533 assert!(keys.contains(&&3));
1534
1535 assert_eq!(map.get_clone(&1), Some("one".to_string()));
1537 assert_eq!(map.get_clone(&2), Some("two".to_string()));
1538 assert_eq!(map.get_clone(&3), Some("three".to_string()));
1539
1540 let mut count = 0;
1542 for (k, v) in map.iter() {
1543 count += 1;
1544 assert!(map.contains_key(k));
1545 assert_eq!(*map.get(k).unwrap(), *v);
1546 }
1547 assert_eq!(count, 3);
1548 }
1549
1550 #[test]
1551 fn test_sync_hash_map_iter_mut() {
1552 let map = SyncHashMap::new();
1553
1554 map.insert(1, "one".to_string());
1555 map.insert(2, "two".to_string());
1556
1557 for (k, mut v) in map.iter_mut() {
1558 if *k == 1 {
1559 *v = "modified".to_string();
1560 }
1561 }
1562
1563 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1564 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1565 }
1566
1567 #[test]
1568 fn test_sync_hash_map_values_mut() {
1569 let map = SyncHashMap::new();
1570
1571 map.insert(1, "one".to_string());
1572 map.insert(2, "two".to_string());
1573
1574 for mut v in map.values_mut() {
1575 if *v == "one" {
1576 *v = "modified".to_string();
1577 }
1578 }
1579
1580 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1581 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1582 }
1583
1584 #[test]
1585 fn test_sync_hash_map_get_clone() {
1586 let map = SyncHashMap::new();
1587 map.insert(1, "one".to_string());
1588
1589 assert_eq!(map.get_clone(&1), Some("one".to_string()));
1591 assert_eq!(map.get_clone(&2), None);
1592 }
1593
1594 #[test]
1595 fn test_sync_hash_map_clone() {
1596 let map1 = SyncHashMap::new();
1597 map1.insert(1, "one".to_string());
1598 map1.insert(2, "two".to_string());
1599
1600 let map2 = map1.clone();
1601
1602 assert_eq!(map1.len(), map2.len());
1603 assert_eq!(*map1.get(&1).unwrap(), *map2.get(&1).unwrap());
1604 assert_eq!(*map1.get(&2).unwrap(), *map2.get(&2).unwrap());
1605
1606 map1.insert(3, "three".to_string());
1608 assert!(!map2.contains_key(&3));
1609 }
1610
1611 #[test]
1612 fn test_sync_hash_map_partial_eq() {
1613 let map1 = SyncHashMap::new();
1614 map1.insert(1, "one".to_string());
1615 map1.insert(2, "two".to_string());
1616
1617 let map2 = SyncHashMap::new();
1618 map2.insert(1, "one".to_string());
1619 map2.insert(2, "two".to_string());
1620
1621 let map3 = SyncHashMap::new();
1622 map3.insert(1, "different".to_string());
1623
1624 assert_eq!(map1, map2);
1625 assert_ne!(map1, map3);
1626 }
1627
1628 #[test]
1629 fn test_sync_hash_map_debug() {
1630 let map = SyncHashMap::new();
1631 map.insert(1, "one".to_string());
1632
1633 let debug_str = format!("{:?}", map);
1634 assert!(debug_str.contains("1"));
1635 assert!(debug_str.contains("one"));
1636 }
1637
1638 #[test]
1639 fn test_sync_hash_map_serialization() {
1640 let map = SyncHashMap::new();
1641 map.insert(1, "one".to_string());
1642 map.insert(2, "two".to_string());
1643
1644 let serialized = serde_json::to_string(&map).unwrap();
1646 assert!(serialized.contains("1"));
1647 assert!(serialized.contains("one"));
1648 assert!(serialized.contains("2"));
1649 assert!(serialized.contains("two"));
1650
1651 let deserialized: SyncHashMap<i32, String> = serde_json::from_str(&serialized).unwrap();
1653 assert_eq!(deserialized.len(), 2);
1654 assert_eq!(*deserialized.get(&1).unwrap(), "one".to_string());
1655 assert_eq!(*deserialized.get(&2).unwrap(), "two".to_string());
1656 }
1657
1658 #[test]
1659 fn test_sync_hash_map_from_hashmap() {
1660 let mut original = HashMap::new();
1661 original.insert(1, "one".to_string());
1662 original.insert(2, "two".to_string());
1663
1664 let map = SyncHashMap::from(original);
1665
1666 assert_eq!(map.len(), 2);
1667 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1668 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1669 }
1670
1671 #[test]
1672 fn test_sync_hash_map_into_iterator() {
1673 let map = SyncHashMap::new();
1674 map.insert(1, "one".to_string());
1675 map.insert(2, "two".to_string());
1676
1677 let mut count = 0;
1679 for (k, v) in &map {
1680 count += 1;
1681 assert!(map.contains_key(k));
1682 assert_eq!(*map.get(k).unwrap(), *v);
1683 }
1684 assert_eq!(count, 2);
1685
1686 let owned_pairs: Vec<_> = map.into_iter().collect();
1688 assert_eq!(owned_pairs.len(), 2);
1689 }
1690
1691 #[test]
1692 fn test_sync_hash_map_default() {
1693 let map: SyncHashMap<i32, String> = Default::default();
1694 assert_eq!(map.len(), 0);
1695 assert!(map.is_empty());
1696 }
1697
1698 #[test]
1699 fn test_sync_hash_map_arc() {
1700 let map = SyncHashMap::new_arc();
1701 map.insert(1, "one".to_string());
1702
1703 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1704
1705 let map2 = Arc::clone(&map);
1706 map2.insert(2, "two".to_string());
1707
1708 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1709 }
1710
1711 #[test]
1712 fn test_sync_hash_map_get_mut() {
1713 let map = SyncHashMap::new();
1714 map.insert(1, "one".to_string());
1715
1716 {
1717 let mut value = map.get_mut(&1).unwrap();
1718 *value = "modified".to_string();
1719 }
1720
1721 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1722 }
1723
1724 #[test]
1725 fn test_sync_hash_map_concurrent_access() {
1726 let map = Arc::new(SyncHashMap::new());
1727
1728 let handles: Vec<_> = (0..10)
1730 .map(|i| {
1731 let map = Arc::clone(&map);
1732 thread::spawn(move || {
1733 map.insert(i, format!("value_{}", i));
1734 })
1735 })
1736 .collect();
1737
1738 for handle in handles {
1739 handle.join().unwrap();
1740 }
1741
1742 assert_eq!(map.len(), 10);
1744 for i in 0..10 {
1745 assert_eq!(*map.get(&i).unwrap(), format!("value_{}", i));
1746 }
1747
1748 let map_read = Arc::clone(&map);
1750 let handles: Vec<_> = (0..10)
1751 .map(|i| {
1752 let map = Arc::clone(&map_read);
1753 thread::spawn(move || {
1754 let value = map.get(&i);
1755 assert_eq!(*value.unwrap(), format!("value_{}", i));
1756 })
1757 })
1758 .collect();
1759
1760 for handle in handles {
1761 handle.join().unwrap();
1762 }
1763 }
1764
1765 #[test]
1766 fn test_sync_hash_map_dirty_ref() {
1767 let map = SyncHashMap::new();
1768 map.insert(1, "one".to_string());
1769
1770 let dirty = map.dirty_ref();
1771 assert_eq!(dirty.len(), 1);
1772 assert_eq!(*dirty.get(&1).unwrap().read(), "one".to_string());
1774 }
1775
1776 #[test]
1777 fn test_sync_hash_map_into_inner() {
1778 let map = SyncHashMap::new();
1779 map.insert(1, "one".to_string());
1780 map.insert(2, "two".to_string());
1781
1782 let inner = map.into_inner();
1783 assert_eq!(inner.len(), 2);
1784 assert_eq!(inner.get(&1), Some(&"one".to_string()));
1785 assert_eq!(inner.get(&2), Some(&"two".to_string()));
1786 }
1787
1788 #[test]
1789 fn test_sync_hash_map_guard_debug() {
1790 let map = SyncHashMap::new();
1791 map.insert(1, "test".to_string());
1792
1793 let guard = map.get(&1).unwrap();
1794 let debug_str = format!("{:?}", guard);
1795 assert!(debug_str.contains("test"));
1796 }
1797
1798 #[test]
1799 fn test_sync_hash_map_guard_partial_eq() {
1800 let map = SyncHashMap::new();
1801 map.insert(1, "value".to_string());
1802
1803 let guard1 = map.get(&1).unwrap();
1804 let guard2 = map.get(&1).unwrap();
1805
1806 assert_eq!(guard1, guard2);
1807 }
1808
1809 mod buckets_tests {
1811 use super::*;
1812
1813 #[test]
1814 fn test_sync_hash_map_buckets_new() {
1815 let map = buckets::SyncHashMapB::<i32, String>::new(None);
1816 assert_eq!(map.len(), 0);
1817 assert!(map.is_empty());
1818 assert_eq!(map.bucket_count(), 10); }
1820
1821 #[test]
1822 fn test_sync_hash_map_buckets_with_custom_size() {
1823 let map = buckets::SyncHashMapB::<i32, String>::new(Some(5));
1824 assert_eq!(map.bucket_count(), 5);
1825 }
1826
1827 #[test]
1828 fn test_sync_hash_map_buckets_insert_and_get() {
1829 let map = buckets::SyncHashMapB::new(Some(3));
1830
1831 assert_eq!(map.insert(1, "one".to_string()), None);
1832 assert_eq!(map.insert(2, "two".to_string()), None);
1833 assert_eq!(map.len(), 2);
1834
1835 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1836 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1837 assert!(map.get(&3).is_none());
1838 }
1839
1840 #[test]
1841 fn test_sync_hash_map_buckets_remove() {
1842 let map = buckets::SyncHashMapB::new(Some(3));
1843
1844 map.insert(1, "one".to_string());
1845 map.insert(2, "two".to_string());
1846
1847 assert_eq!(map.remove(&1), Some("one".to_string()));
1848 assert_eq!(map.len(), 1);
1849 assert!(map.get(&1).is_none());
1850 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1851 }
1852
1853 #[test]
1854 fn test_sync_hash_map_buckets_clear() {
1855 let map = buckets::SyncHashMapB::new(Some(3));
1856
1857 map.insert(1, "one".to_string());
1858 map.insert(2, "two".to_string());
1859
1860 assert_eq!(map.len(), 2);
1861 map.clear();
1862 assert_eq!(map.len(), 0);
1863 assert!(map.is_empty());
1864 }
1865
1866 #[test]
1867 fn test_sync_hash_map_buckets_iterators() {
1868 let map = buckets::SyncHashMapB::new(Some(3));
1869
1870 map.insert(1, "one".to_string());
1871 map.insert(2, "two".to_string());
1872 map.insert(3, "three".to_string());
1873
1874 let keys: Vec<_> = map.keys().collect();
1876 assert!(keys.contains(&&1));
1877 assert!(keys.contains(&&2));
1878 assert!(keys.contains(&&3));
1879
1880 assert_eq!(map.get_clone(&1), Some("one".to_string()));
1882 assert_eq!(map.get_clone(&2), Some("two".to_string()));
1883 assert_eq!(map.get_clone(&3), Some("three".to_string()));
1884
1885 {
1887 let mut v = map.get_mut(&1).unwrap();
1888 *v = "modified".to_string();
1889 }
1890
1891 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1892 }
1893
1894 #[test]
1895 fn test_sync_hash_map_buckets_default() {
1896 let map: buckets::SyncHashMapB<i32, String> = Default::default();
1897 assert_eq!(map.len(), 0);
1898 assert!(map.is_empty());
1899 assert_eq!(map.bucket_count(), 10);
1900 }
1901
1902 #[test]
1903 fn test_sync_hash_map_buckets_debug() {
1904 let map = buckets::SyncHashMapB::new(Some(2));
1905 map.insert(1, "one".to_string());
1906
1907 let debug_str = format!("{:?}", map);
1908 assert!(debug_str.contains("1"));
1909 assert!(debug_str.contains("one"));
1910 }
1911 }
1912
1913 #[test]
1914 fn test_sync_hash_map_comprehensive() {
1915 let map = SyncHashMap::new();
1916
1917 map.insert("key1", 42);
1919 map.insert("key2", 24);
1920
1921 assert_eq!(map.len(), 2);
1922 assert!(!map.is_empty());
1923
1924 *map.get_mut("key1").unwrap() = 100;
1926 assert_eq!(*map.get(&"key1").unwrap(), 100);
1927
1928 map.insert("key3", 50);
1930 map.retain(|_, v| *v > 30);
1931
1932 assert_eq!(map.len(), 2);
1933 assert_eq!(*map.get(&"key1").unwrap(), 100);
1934 assert!(map.get(&"key2").is_none());
1935 assert_eq!(*map.get(&"key3").unwrap(), 50);
1936
1937 let map2 = map.clone();
1939 assert_eq!(map, map2);
1940
1941 let mut sum = 0;
1943 for (_, v) in map.iter() {
1944 sum += *v;
1945 }
1946 assert_eq!(sum, 150);
1947
1948 map.clear();
1950 assert_eq!(map.len(), 0);
1951 assert!(map.is_empty());
1952 }
1953
1954 #[test]
1955 fn test_sync_hash_map_iter_nlock() {
1956 let map = SyncHashMap::new();
1957 map.insert(1, "one".to_string());
1958 map.insert(2, "two".to_string());
1959 map.insert(3, "three".to_string());
1960
1961 let mut count = 0;
1963 for (k, v) in map.iter() {
1964 count += 1;
1965 match *k {
1966 1 => assert_eq!(v, "one"),
1967 2 => assert_eq!(v, "two"),
1968 3 => assert_eq!(v, "three"),
1969 _ => panic!("unexpected key"),
1970 }
1971 }
1972 assert_eq!(count, 3);
1973
1974 let iter = map.iter();
1976 assert_eq!(iter.len(), 3);
1977 }
1978
1979 #[test]
1980 fn test_sync_hash_map_into_iter_mut() {
1981 let mut map = SyncHashMap::new();
1982 map.insert(1, "one".to_string());
1983 map.insert(2, "two".to_string());
1984
1985 for (k, mut v) in &mut map {
1987 if *k == 1 {
1988 *v = "modified".to_string();
1989 }
1990 }
1991
1992 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1993 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1994 }
1995
1996 #[test]
1997 fn test_sync_hash_map_into_iter_ref() {
1998 let map = SyncHashMap::new();
1999 map.insert(1, 10);
2000 map.insert(2, 20);
2001 map.insert(3, 30);
2002
2003 let mut sum = 0;
2005 for (_, v) in &map {
2006 sum += *v;
2007 }
2008 assert_eq!(sum, 60);
2009
2010 assert_eq!(map.len(), 3);
2012 }
2013
2014 #[test]
2015 fn test_sync_hash_map_iter_nlock_empty() {
2016 let map: SyncHashMap<i32, String> = SyncHashMap::new();
2017
2018 let mut count = 0;
2019 for _ in map.iter() {
2020 count += 1;
2021 }
2022 assert_eq!(count, 0);
2023
2024 let iter = map.iter();
2025 assert_eq!(iter.len(), 0);
2026 }
2027}