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 use crate::guard_common::{EntryGuard, MutRefGuard, ReadGuard, RefGuard, WriteGuard};
14
15pub type DefaultBuildHasher = BuildHasherDefault<DefaultHasher>;
25
26pub struct SyncHashMap<K, V> {
57 dirty: UnsafeCell<HashMap<K, RwLock<V>, DefaultBuildHasher>>,
60 lock: RwLock<()>,
63}
64
65unsafe impl<K, V> Send for SyncHashMap<K, V> {}
69
70unsafe impl<K, V> Sync for SyncHashMap<K, V> {}
74
75impl<K, V> SyncHashMap<K, V>
78where
79 K: Eq + Hash,
80{
81 pub fn new_arc() -> Arc<Self> {
84 Arc::new(Self::new())
85 }
86
87 pub const fn new() -> Self {
90 Self {
91 dirty: UnsafeCell::new(HashMap::with_hasher(DefaultBuildHasher::new())),
92 lock: RwLock::new(()),
93 }
94 }
95
96 pub fn with_capacity(capacity: usize) -> Self {
99 Self {
100 dirty: UnsafeCell::new(HashMap::with_capacity_and_hasher(
101 capacity,
102 std::hash::BuildHasherDefault::default(),
103 )),
104 lock: RwLock::new(()),
105 }
106 }
107
108 pub fn with_map(map: HashMap<K, V>) -> Self {
114 let mut wrapped =
115 HashMap::with_capacity_and_hasher(map.len(), std::hash::BuildHasherDefault::default());
116 for (k, v) in map {
117 wrapped.insert(k, RwLock::new(v));
118 }
119 Self {
120 dirty: UnsafeCell::new(wrapped),
121 lock: RwLock::new(()),
122 }
123 }
124
125 #[inline(always)]
131 pub fn insert(&self, k: K, v: V) -> Option<V> {
132 let _lock = self.lock.write();
133 let m = unsafe { &mut *self.dirty.get() };
134 m.insert(k, RwLock::new(v)).map(|old| old.into_inner())
135 }
136
137 #[inline(always)]
140 pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
141 let m = unsafe { &mut *self.dirty.get() };
142 m.insert(k, RwLock::new(v)).map(|old| old.into_inner())
143 }
144
145 #[inline(always)]
148 pub fn remove(&self, k: &K) -> Option<V> {
149 let _lock = self.lock.write();
150 let m = unsafe { &mut *self.dirty.get() };
151 m.remove(k).map(|v| v.into_inner())
152 }
153
154 #[inline(always)]
157 pub fn remove_mut(&mut self, k: &K) -> Option<V> {
158 let m = unsafe { &mut *self.dirty.get() };
159 m.remove(k).map(|v| v.into_inner())
160 }
161
162 #[inline(always)]
165 pub fn len(&self) -> usize {
166 let _lock = self.lock.read();
167 let m = unsafe { &*self.dirty.get() };
168 m.len()
169 }
170
171 #[inline(always)]
174 pub fn is_empty(&self) -> bool {
175 let _lock = self.lock.read();
176 let m = unsafe { &*self.dirty.get() };
177 m.is_empty()
178 }
179
180 #[inline(always)]
183 pub fn clear(&self) {
184 let _lock = self.lock.write();
185 let m = unsafe { &mut *self.dirty.get() };
186 m.clear();
187 }
188
189 #[inline(always)]
192 pub fn clear_mut(&mut self) {
193 let m = unsafe { &mut *self.dirty.get() };
194 m.clear();
195 }
196
197 #[inline(always)]
200 pub fn shrink_to_fit(&self) {
201 let _lock = self.lock.write();
202 let m = unsafe { &mut *self.dirty.get() };
203 m.shrink_to_fit();
204 }
205
206 #[inline(always)]
209 pub fn shrink_to_fit_mut(&mut self) {
210 let m = unsafe { &mut *self.dirty.get() };
211 m.shrink_to_fit();
212 }
213
214 pub fn from(map: HashMap<K, V>) -> Self {
217 Self::with_map(map)
218 }
219
220 #[inline]
244 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<RefGuard<'_, V>>
245 where
246 K: Borrow<Q>,
247 Q: Hash + Eq,
248 {
249 let map_lock = self.lock.read();
250 let m = unsafe { &*self.dirty.get() };
251 let value_lock_wrapper = m.get(k)?;
252 let value_ptr = unsafe {
254 let lock_ptr = value_lock_wrapper as *const RwLock<V> as *mut RwLock<V>;
255 &*(*lock_ptr).get_mut()
256 };
257 Some(RefGuard {
258 _lock: map_lock,
259 _value: value_ptr,
260 })
261 }
262
263 pub fn get_rlock<Q: ?Sized>(&self, k: &Q) -> Option<ReadGuard<'_, V>>
268 where
269 K: Borrow<Q>,
270 Q: Hash + Eq,
271 {
272 let map_lock = self.lock.read();
273 let m = unsafe { &*self.dirty.get() };
274 let value_lock_wrapper = m.get(k)?;
275 let value_lock = value_lock_wrapper.read();
276 Some(ReadGuard {
277 _lock: map_lock,
278 _value_lock: value_lock,
279 })
280 }
281
282 #[inline]
295 pub fn get_uncheck<Q: ?Sized>(&self, k: &Q) -> RefGuard<'_, V>
296 where
297 K: Borrow<Q>,
298 Q: Hash + Eq,
299 {
300 let map_lock = self.lock.read();
301 let m = unsafe { &*self.dirty.get() };
302 let value_lock_wrapper = m.get(k).expect("key not found");
303 let value_ptr = unsafe {
305 let lock_ptr = value_lock_wrapper as *const RwLock<V> as *mut RwLock<V>;
306 &*(*lock_ptr).get_mut()
307 };
308 RefGuard {
309 _lock: map_lock,
310 _value: value_ptr,
311 }
312 }
313
314 #[inline]
322 pub fn get_mut<Q: ?Sized>(&self, k: &Q) -> Option<MutRefGuard<'_, V>>
323 where
324 K: Borrow<Q>,
325 Q: Hash + Eq,
326 {
327 let map_lock = self.lock.read();
328 let m = unsafe { &*self.dirty.get() };
329 let value_lock_wrapper = m.get(k)?;
330 let value_ptr = unsafe {
332 let lock_ptr = value_lock_wrapper as *const RwLock<V> as *mut RwLock<V>;
333 &mut *(*lock_ptr).get_mut()
334 };
335 Some(MutRefGuard {
336 _lock: map_lock,
337 _value: value_ptr,
338 })
339 }
340
341 #[inline]
349 pub fn get_mut_lock<Q: ?Sized>(&self, k: &Q) -> Option<WriteGuard<'_, V>>
350 where
351 K: Borrow<Q>,
352 Q: Hash + Eq,
353 {
354 let map_lock = self.lock.read();
355 let m = unsafe { &*self.dirty.get() };
356 let value_lock_wrapper = m.get(k)?;
357 let value_lock = value_lock_wrapper.write();
358 Some(WriteGuard {
359 _lock: map_lock,
360 _value_lock: value_lock,
361 })
362 }
363
364 #[inline]
367 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
368 where
369 K: Borrow<Q>,
370 Q: Hash + Eq,
371 {
372 let _lock = self.lock.read();
373 let m = unsafe { &*self.dirty.get() };
374 m.contains_key(k)
375 }
376
377 pub fn iter_mut_lock(&self) -> IterLock<'_, K, V> {
380 let _lock = self.lock.read();
381 let m = unsafe { &*self.dirty.get() };
382 IterLock {
383 _lock,
384 inner: m.iter(),
385 }
386 }
387
388 pub fn iter_mut(&self) -> IterMut<'_, K, V> {
398 let _lock = self.lock.read();
399 let m = unsafe { &*self.dirty.get() };
400 IterMut {
401 _lock,
402 inner: m.iter(),
403 }
404 }
405
406 pub fn iter_rlock(&self) -> IterRLock<'_, K, V> {
414 let _lock = self.lock.read();
415 let m = unsafe { &*self.dirty.get() };
416 IterRLock {
417 _lock,
418 inner: m.iter(),
419 }
420 }
421
422 pub fn iter(&self) -> Iter<'_, K, V> {
431 let _lock = self.lock.read();
432 let m = unsafe { &*self.dirty.get() };
433 Iter {
434 _lock,
435 inner: m.iter(),
436 }
437 }
438
439 pub fn dirty_ref(&self) -> ReadGuardMap<'_, K, V> {
447 let _lock = self.lock.read();
448 let v = unsafe { &*self.dirty.get() };
449 ReadGuardMap { _lock, v }
450 }
451
452 pub unsafe fn dirty_ref_unsafe(&self) -> &HashMap<K, RwLock<V>, DefaultBuildHasher> {
460 unsafe { &*self.dirty.get() }
461 }
462
463 pub fn into_inner(self) -> HashMap<K, V> {
466 self.dirty
467 .into_inner()
468 .into_iter()
469 .map(|(k, v)| (k, v.into_inner()))
470 .collect()
471 }
472
473 #[inline]
479 pub fn keys(&self) -> KeysGuard<'_, K, V> {
480 let _lock = self.lock.read();
481 let m = unsafe { &*self.dirty.get() };
482 KeysGuard {
483 _lock,
484 inner: m.keys(),
485 }
486 }
487
488 #[inline]
494 pub fn values(&self) -> ValuesGuard<'_, K, V> {
495 let _lock = self.lock.read();
496 let m = unsafe { &*self.dirty.get() };
497 ValuesGuard {
498 _lock,
499 inner: m.values(),
500 }
501 }
502
503 #[inline]
509 pub fn values_mut(&self) -> ValuesMutGuard<'_, K, V> {
510 let _lock = self.lock.write();
511 let m = unsafe { &*self.dirty.get() };
512 ValuesMutGuard {
513 _lock,
514 inner: m.values(),
515 }
516 }
517
518 #[inline]
521 pub fn retain<F>(&self, mut f: F)
522 where
523 F: FnMut(&K, &mut V) -> bool,
524 {
525 let _lock = self.lock.write();
526 let m = unsafe { &mut *self.dirty.get() };
527 m.retain(|k, v| f(k, v.get_mut()));
528 }
529
530 #[inline]
533 pub fn capacity(&self) -> usize {
534 let _lock = self.lock.read();
535 let m = unsafe { &*self.dirty.get() };
536 m.capacity()
537 }
538
539 #[inline]
542 pub fn reserve(&self, additional: usize) {
543 let _lock = self.lock.write();
544 let m = unsafe { &mut *self.dirty.get() };
545 m.reserve(additional);
546 }
547
548 #[inline]
551 pub fn remove_entry(&self, k: &K) -> Option<(K, V)> {
552 let _lock = self.lock.write();
553 let m = unsafe { &mut *self.dirty.get() };
554 m.remove_entry(k).map(|(k, v)| (k, v.into_inner()))
555 }
556
557 #[inline]
563 pub fn get_or_insert(&self, k: K, default: V) -> EntryGuard<'_, V> {
564 let map_lock = self.lock.write();
565 let m = unsafe { &mut *self.dirty.get() };
566 let entry = m.entry(k).or_insert_with(|| RwLock::new(default));
567 let value_lock = entry.write();
568 EntryGuard {
569 _lock: map_lock,
570 _value_lock: value_lock,
571 }
572 }
573
574 #[inline]
580 pub fn get_or_insert_with<F>(&self, k: K, default: F) -> EntryGuard<'_, V>
581 where
582 F: FnOnce() -> V,
583 {
584 let map_lock = self.lock.write();
585 let m = unsafe { &mut *self.dirty.get() };
586 let entry = m.entry(k).or_insert_with(|| RwLock::new(default()));
587 let value_lock = entry.write();
588 EntryGuard {
589 _lock: map_lock,
590 _value_lock: value_lock,
591 }
592 }
593
594 #[inline]
600 pub fn get_clone<Q: ?Sized>(&self, k: &Q) -> Option<V>
601 where
602 K: Borrow<Q>,
603 Q: Hash + Eq,
604 V: Clone,
605 {
606 let _map_lock = self.lock.read();
607 let m = unsafe { &*self.dirty.get() };
608 m.get(k).map(|v| v.read().clone())
609 }
610
611 #[inline]
617 pub fn take(&self, k: &K) -> Option<V> {
618 self.remove(k)
619 }
620}
621
622pub struct ReadGuardMap<'a, K, V> {
628 _lock: RwLockReadGuard<'a, ()>,
631 v: &'a HashMap<K, RwLock<V>, DefaultBuildHasher>,
634}
635
636impl<'a, K, V> Deref for ReadGuardMap<'a, K, V> {
637 type Target = HashMap<K, RwLock<V>, DefaultBuildHasher>;
638
639 fn deref(&self) -> &Self::Target {
640 self.v
641 }
642}
643
644impl<'a, K, V> Debug for ReadGuardMap<'a, K, V>
645where
646 K: Debug,
647 V: Debug,
648{
649 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
650 let mut map = f.debug_map();
653 for (k, v) in self.v.iter() {
654 map.entry(k, &*v.read());
655 }
656 map.finish()
657 }
658}
659
660impl<'a, K, V> AsRef<HashMap<K, RwLock<V>, DefaultBuildHasher>> for ReadGuardMap<'a, K, V> {
661 fn as_ref(&self) -> &HashMap<K, RwLock<V>, DefaultBuildHasher> {
662 self.v
663 }
664}
665
666#[allow(dead_code)]
669#[deprecated(note = "Use WriteGuard instead")]
670pub type SyncMapRefMut<'a, V> = WriteGuard<'a, V>;
671
672pub struct IterRLock<'a, K, V> {
678 _lock: RwLockReadGuard<'a, ()>,
681 inner: MapIter<'a, K, RwLock<V>>,
684}
685
686impl<'a, K, V> Iterator for IterRLock<'a, K, V> {
687 type Item = (&'a K, RwLockReadGuard<'a, V>);
688
689 fn next(&mut self) -> Option<Self::Item> {
690 self.inner.next().map(|(k, v)| (k, v.read()))
691 }
692}
693
694pub type IterMy<'a, K, V> = IterRLock<'a, K, V>;
697
698pub struct IterLock<'a, K, V> {
704 _lock: RwLockReadGuard<'a, ()>,
707 inner: MapIter<'a, K, RwLock<V>>,
710}
711
712impl<'a, K, V> Iterator for IterLock<'a, K, V> {
713 type Item = (&'a K, RwLockWriteGuard<'a, V>);
714
715 fn next(&mut self) -> Option<Self::Item> {
716 self.inner.next().map(|(k, v)| (k, v.write()))
717 }
718}
719
720pub struct IterMut<'a, K, V> {
723 _lock: RwLockReadGuard<'a, ()>,
726 inner: MapIter<'a, K, RwLock<V>>,
729}
730
731impl<'a, K, V> Iterator for IterMut<'a, K, V> {
732 type Item = (&'a K, &'a mut V);
733
734 fn next(&mut self) -> Option<Self::Item> {
735 self.inner.next().map(|(k, v)| {
736 let value_ptr = unsafe {
738 let lock_ptr = v as *const RwLock<V> as *mut RwLock<V>;
739 &mut *(*lock_ptr).get_mut()
740 };
741 (k, value_ptr)
742 })
743 }
744}
745
746pub struct KeysGuard<'a, K, V> {
749 _lock: RwLockReadGuard<'a, ()>,
752 inner: Keys<'a, K, RwLock<V>>,
755}
756
757impl<'a, K, V> Deref for KeysGuard<'a, K, V> {
758 type Target = Keys<'a, K, RwLock<V>>;
759
760 fn deref(&self) -> &Self::Target {
761 &self.inner
762 }
763}
764
765impl<'a, K, V> DerefMut for KeysGuard<'a, K, V> {
766 fn deref_mut(&mut self) -> &mut Self::Target {
767 &mut self.inner
768 }
769}
770
771impl<'a, K, V> Iterator for KeysGuard<'a, K, V> {
772 type Item = &'a K;
773
774 fn next(&mut self) -> Option<Self::Item> {
775 self.inner.next()
776 }
777}
778
779pub struct ValuesGuard<'a, K, V> {
785 _lock: RwLockReadGuard<'a, ()>,
788 inner: std::collections::hash_map::Values<'a, K, RwLock<V>>,
791}
792
793impl<'a, K, V> Iterator for ValuesGuard<'a, K, V> {
794 type Item = RwLockReadGuard<'a, V>;
795
796 fn next(&mut self) -> Option<Self::Item> {
797 self.inner.next().map(|v| v.read())
798 }
799}
800
801pub struct ValuesMutGuard<'a, K, V> {
807 _lock: RwLockWriteGuard<'a, ()>,
810 inner: std::collections::hash_map::Values<'a, K, RwLock<V>>,
813}
814
815impl<'a, K, V> Iterator for ValuesMutGuard<'a, K, V> {
816 type Item = RwLockWriteGuard<'a, V>;
817
818 fn next(&mut self) -> Option<Self::Item> {
819 self.inner.next().map(|v| v.write())
820 }
821}
822
823pub struct Iter<'a, K, V> {
826 _lock: RwLockReadGuard<'a, ()>,
829 inner: MapIter<'a, K, RwLock<V>>,
832}
833
834impl<'a, K, V> Iterator for Iter<'a, K, V> {
835 type Item = (&'a K, &'a V);
836
837 fn next(&mut self) -> Option<Self::Item> {
838 self.inner.next().map(|(k, v)| {
839 unsafe {
841 let lock_ptr = v as *const RwLock<V> as *mut RwLock<V>;
842 (k, &*(*lock_ptr).get_mut())
843 }
844 })
845 }
846}
847
848impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
849 fn len(&self) -> usize {
850 self.inner.len()
851 }
852}
853
854impl<'a, K, V> IntoIterator for &'a SyncHashMap<K, V>
855where
856 K: Eq + Hash,
857{
858 type Item = (&'a K, &'a V);
859 type IntoIter = Iter<'a, K, V>;
860
861 fn into_iter(self) -> Self::IntoIter {
862 self.iter()
863 }
864}
865
866impl<'a, K, V> IntoIterator for &'a mut SyncHashMap<K, V>
867where
868 K: Eq + Hash,
869{
870 type Item = (&'a K, &'a mut V);
871 type IntoIter = IterMut<'a, K, V>;
872
873 fn into_iter(self) -> Self::IntoIter {
874 self.iter_mut()
875 }
876}
877
878impl<K, V> IntoIterator for SyncHashMap<K, V>
879where
880 K: Eq + Hash,
881{
882 type Item = (K, V);
883 type IntoIter = MapIntoIter<K, V>;
884
885 fn into_iter(self) -> Self::IntoIter {
886 self.into_inner().into_iter()
887 }
888}
889
890impl<K, V> From<HashMap<K, V>> for SyncHashMap<K, V>
891where
892 K: Eq + Hash,
893{
894 fn from(map: HashMap<K, V>) -> Self {
895 Self::with_map(map)
896 }
897}
898
899impl<K, V> Serialize for SyncHashMap<K, V>
900where
901 K: Eq + Hash + Serialize,
902 V: Serialize,
903{
904 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
905 where
906 S: Serializer,
907 {
908 use serde::ser::SerializeMap;
909 let _lock = self.lock.read();
910 let m = unsafe { &*self.dirty.get() };
911 let mut map = serializer.serialize_map(Some(m.len()))?;
912 for (k, v) in m.iter() {
913 map.serialize_entry(k, &*v.read())?;
914 }
915 map.end()
916 }
917}
918
919impl<'de, K, V> Deserialize<'de> for SyncHashMap<K, V>
920where
921 K: Eq + Hash + Deserialize<'de>,
922 V: Deserialize<'de>,
923{
924 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
925 where
926 D: Deserializer<'de>,
927 {
928 let m = HashMap::deserialize(deserializer)?;
929 Ok(Self::with_map(m))
930 }
931}
932
933impl<K, V> Debug for SyncHashMap<K, V>
934where
935 K: Eq + Hash + Debug,
936 V: Debug,
937{
938 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
939 let _lock = self.lock.read();
940 let m = unsafe { &*self.dirty.get() };
941 let mut map = f.debug_map();
942 for (k, v) in m.iter() {
943 map.entry(k, &*v.read());
944 }
945 map.finish()
946 }
947}
948
949impl<K, V> Clone for SyncHashMap<K, V>
950where
951 K: Clone + Eq + Hash,
952 V: Clone,
953{
954 fn clone(&self) -> Self {
955 let _lock = self.lock.read();
956 let m = unsafe { &*self.dirty.get() };
957 let cloned: HashMap<K, V> = m
958 .iter()
959 .map(|(k, v)| (k.clone(), v.read().clone()))
960 .collect();
961 SyncHashMap::with_map(cloned)
962 }
963}
964
965impl<K, V> Default for SyncHashMap<K, V>
966where
967 K: Eq + Hash,
968{
969 fn default() -> Self {
970 Self::new()
971 }
972}
973
974impl<K, V> PartialEq for SyncHashMap<K, V>
975where
976 K: Eq + Hash,
977 V: PartialEq,
978{
979 fn eq(&self, other: &Self) -> bool {
980 let _lock_self = self.lock.read();
981 let _lock_other = other.lock.read();
982 let self_map = unsafe { &*self.dirty.get() };
983 let other_map = unsafe { &*other.dirty.get() };
984
985 if self_map.len() != other_map.len() {
986 return false;
987 }
988
989 for (k, v) in self_map.iter() {
990 match other_map.get(k) {
991 Some(other_v) => {
992 if *v.read() != *other_v.read() {
993 return false;
994 }
995 }
996 None => return false,
997 }
998 }
999 true
1000 }
1001}
1002
1003impl<K, V> Eq for SyncHashMap<K, V>
1004where
1005 K: Eq + Hash,
1006 V: Eq,
1007{
1008}
1009
1010pub mod buckets {
1013 use super::{MutRefGuard, RefGuard, SyncHashMap, WriteGuard};
1014 use std::hash::{Hash, Hasher};
1015
1016 #[derive(Debug, Clone)]
1019 pub struct SyncHashMapB<K, V>
1020 where
1021 K: Eq + Hash,
1022 {
1023 inner: Vec<SyncHashMap<K, V>>,
1026 len: usize,
1029 }
1030
1031 impl<K, V> SyncHashMapB<K, V>
1032 where
1033 K: Eq + Hash,
1034 {
1035 pub fn new(bucket_count: Option<usize>) -> Self {
1054 let count = bucket_count.unwrap_or(10);
1055 let mut arr = Vec::with_capacity(count);
1056 for _ in 0..count {
1057 arr.push(SyncHashMap::new());
1058 }
1059 Self {
1060 inner: arr,
1061 len: count,
1062 }
1063 }
1064
1065 fn key_to_bucket_index(&self, k: &K) -> usize {
1068 let mut hasher = std::collections::hash_map::DefaultHasher::new();
1069 k.hash(&mut hasher);
1070 let hash = hasher.finish();
1071 (hash % self.len as u64) as usize
1072 }
1073
1074 #[inline]
1077 pub fn insert(&self, k: K, v: V) -> Option<V> {
1078 let index = self.key_to_bucket_index(&k);
1079 self.inner[index].insert(k, v)
1080 }
1081
1082 #[inline]
1085 pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
1086 let index = self.key_to_bucket_index(&k);
1087 self.inner[index].insert_mut(k, v)
1088 }
1089
1090 #[inline]
1093 pub fn remove(&self, k: &K) -> Option<V> {
1094 let index = self.key_to_bucket_index(k);
1095 self.inner[index].remove(k)
1096 }
1097
1098 #[inline]
1101 pub fn is_empty(&self) -> bool {
1102 self.inner.iter().all(|bucket| bucket.is_empty())
1103 }
1104
1105 #[inline]
1108 pub fn len(&self) -> usize {
1109 self.inner.iter().map(|bucket| bucket.len()).sum()
1110 }
1111
1112 #[inline]
1115 pub fn clear(&self) {
1116 self.inner.iter().for_each(|bucket| bucket.clear());
1117 }
1118
1119 #[inline]
1125 pub fn get(&self, k: &K) -> Option<RefGuard<'_, V>> {
1126 let index = self.key_to_bucket_index(k);
1127 self.inner[index].get(k)
1128 }
1129
1130 #[inline]
1133 pub fn get_mut(&self, k: &K) -> Option<MutRefGuard<'_, V>> {
1134 let index = self.key_to_bucket_index(k);
1135 self.inner[index].get_mut(k)
1136 }
1137
1138 #[inline]
1144 pub fn get_mut_lock(&self, k: &K) -> Option<WriteGuard<'_, V>> {
1145 let index = self.key_to_bucket_index(k);
1146 self.inner[index].get_mut_lock(k)
1147 }
1148
1149 #[inline]
1152 pub fn bucket_count(&self) -> usize {
1153 self.len
1154 }
1155
1156 #[inline]
1159 pub fn keys(&self) -> impl Iterator<Item = &K> {
1160 self.inner.iter().flat_map(|bucket| bucket.keys())
1161 }
1162
1163 #[inline]
1166 pub fn get_clone(&self, k: &K) -> Option<V>
1167 where
1168 V: Clone,
1169 {
1170 let index = self.key_to_bucket_index(k);
1171 self.inner[index].get_clone(k)
1172 }
1173 }
1174
1175 impl<K, V> Default for SyncHashMapB<K, V>
1176 where
1177 K: Eq + Hash,
1178 {
1179 fn default() -> Self {
1180 Self::new(None)
1181 }
1182 }
1183}
1184
1185#[cfg(test)]
1186mod tests {
1187 use super::*;
1188 use std::collections::HashMap;
1189 use std::sync::Arc;
1190 use std::thread;
1191
1192 #[test]
1193 fn test_sync_hash_map_new() {
1194 let map: SyncHashMap<i32, String> = SyncHashMap::new();
1195 assert_eq!(map.len(), 0);
1196 assert!(map.is_empty());
1197 }
1198
1199 #[test]
1200 fn test_sync_hash_map_with_capacity() {
1201 let map = SyncHashMap::<i32, String>::with_capacity(100);
1202 assert!(map.capacity() >= 100);
1203 }
1204
1205 #[test]
1206 fn test_sync_hash_map_with_map() {
1207 let mut original = HashMap::new();
1208 original.insert(1, "one".to_string());
1209 original.insert(2, "two".to_string());
1210
1211 let map = SyncHashMap::with_map(original);
1212 assert_eq!(map.len(), 2);
1213 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1214 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1215 }
1216
1217 #[test]
1218 fn test_sync_hash_map_insert_and_get() {
1219 let map = SyncHashMap::new();
1220
1221 assert_eq!(map.insert(1, "one".to_string()), None);
1223 assert_eq!(map.insert(2, "two".to_string()), None);
1224 assert_eq!(map.len(), 2);
1225
1226 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1227 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1228 assert!(map.get(&3).is_none());
1229 }
1230
1231 #[test]
1232 fn test_sync_hash_map_insert_replace() {
1233 let map = SyncHashMap::new();
1234
1235 assert_eq!(map.insert(1, "one".to_string()), None);
1236 assert_eq!(
1237 map.insert(1, "updated".to_string()),
1238 Some("one".to_string())
1239 );
1240 assert_eq!(*map.get(&1).unwrap(), "updated".to_string());
1241 }
1242
1243 #[test]
1244 fn test_sync_hash_map_remove() {
1245 let map = SyncHashMap::new();
1246
1247 map.insert(1, "one".to_string());
1248 map.insert(2, "two".to_string());
1249
1250 assert_eq!(map.remove(&1), Some("one".to_string()));
1251 assert_eq!(map.remove(&1), None);
1252 assert_eq!(map.len(), 1);
1253 assert!(map.get(&1).is_none());
1254 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1255 }
1256
1257 #[test]
1258 fn test_sync_hash_map_contains_key() {
1259 let map = SyncHashMap::new();
1260
1261 map.insert(1, "one".to_string());
1262
1263 assert!(map.contains_key(&1));
1264 assert!(!map.contains_key(&2));
1265 }
1266
1267 #[test]
1268 fn test_sync_hash_map_clear() {
1269 let map = SyncHashMap::new();
1270
1271 map.insert(1, "one".to_string());
1272 map.insert(2, "two".to_string());
1273
1274 assert_eq!(map.len(), 2);
1275 map.clear();
1276 assert_eq!(map.len(), 0);
1277 assert!(map.is_empty());
1278 }
1279
1280 #[test]
1281 fn test_sync_hash_map_capacity_operations() {
1282 let map = SyncHashMap::new();
1283
1284 assert_eq!(map.capacity(), 0);
1285 map.reserve(100);
1286 assert!(map.capacity() >= 100);
1287
1288 map.insert(1, "one".to_string());
1289 map.insert(2, "two".to_string());
1290
1291 let old_capacity = map.capacity();
1292 map.shrink_to_fit();
1293 assert!(map.capacity() <= old_capacity);
1294 }
1295
1296 #[test]
1297 fn test_sync_hash_map_retain() {
1298 let map = SyncHashMap::new();
1299
1300 map.insert(1, "one".to_string());
1301 map.insert(2, "two".to_string());
1302 map.insert(3, "three".to_string());
1303
1304 map.retain(|&k, _| k % 2 == 1);
1305
1306 assert_eq!(map.len(), 2);
1307 assert!(map.contains_key(&1));
1308 assert!(!map.contains_key(&2));
1309 assert!(map.contains_key(&3));
1310 }
1311
1312 #[test]
1313 fn test_sync_hash_map_get_or_insert() {
1314 let map = SyncHashMap::new();
1315
1316 {
1318 let value = map.get_or_insert(1, "default".to_string());
1319 assert_eq!(*value, "default");
1320 }
1321 assert_eq!(map.len(), 1);
1322
1323 {
1325 let value = map.get_or_insert(1, "new_default".to_string());
1326 assert_eq!(*value, "default");
1327 }
1328 assert_eq!(map.len(), 1);
1329 }
1330
1331 #[test]
1332 fn test_sync_hash_map_get_or_insert_with() {
1333 let map = SyncHashMap::new();
1334
1335 {
1336 let value = map.get_or_insert_with(1, || "computed".to_string());
1337 assert_eq!(*value, "computed");
1338 }
1339 assert_eq!(map.len(), 1);
1340
1341 {
1342 let value = map.get_or_insert_with(1, || "new_computed".to_string());
1343 assert_eq!(*value, "computed");
1344 }
1345 }
1346
1347 #[test]
1348 fn test_sync_hash_map_remove_entry() {
1349 let map = SyncHashMap::new();
1350
1351 map.insert(1, "one".to_string());
1352 map.insert(2, "two".to_string());
1353
1354 let removed = map.remove_entry(&1);
1355 assert_eq!(removed, Some((1, "one".to_string())));
1356 assert_eq!(map.len(), 1);
1357 assert!(!map.contains_key(&1));
1358 }
1359
1360 #[test]
1361 fn test_sync_hash_map_iterators() {
1362 let map = SyncHashMap::new();
1363
1364 map.insert(1, "one".to_string());
1365 map.insert(2, "two".to_string());
1366 map.insert(3, "three".to_string());
1367
1368 let keys: Vec<_> = map.keys().collect();
1370 assert!(keys.contains(&&1));
1371 assert!(keys.contains(&&2));
1372 assert!(keys.contains(&&3));
1373
1374 assert_eq!(map.get_clone(&1), Some("one".to_string()));
1376 assert_eq!(map.get_clone(&2), Some("two".to_string()));
1377 assert_eq!(map.get_clone(&3), Some("three".to_string()));
1378
1379 let mut count = 0;
1381 for (k, v) in map.iter() {
1382 count += 1;
1383 assert!(map.contains_key(k));
1384 assert_eq!(*map.get(k).unwrap(), *v);
1385 }
1386
1387 let mut count_rlock = 0;
1389 for (k, v) in map.iter_rlock() {
1390 count_rlock += 1;
1391 assert!(map.contains_key(k));
1392 assert_eq!(*map.get(k).unwrap(), *v);
1393
1394 for (k, v) in map.iter_rlock() {
1395 count_rlock += 1;
1396 assert!(map.contains_key(k));
1397 assert_eq!(*map.get(k).unwrap(), *v);
1398 }
1399 }
1400 assert_eq!(count_rlock, 12);
1401
1402 assert_eq!(count, 3);
1403 }
1404
1405 #[test]
1406 fn test_sync_hash_map_iter_mut() {
1407 let map = SyncHashMap::new();
1408
1409 map.insert(1, "one".to_string());
1410 map.insert(2, "two".to_string());
1411
1412 for (k, v) in map.iter_mut() {
1413 if *k == 1 {
1414 *v = "modified".to_string();
1415 }
1416 }
1417
1418 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1419 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1420
1421 for (k, mut v) in map.iter_mut_lock() {
1422 if *k == 1 {
1423 *v = "modified2".to_string();
1424 }
1425 if *k == 2 {
1426 *v = "modified3".to_string();
1427 }
1428 }
1429 assert_eq!(*map.get(&1).unwrap(), "modified2".to_string());
1430 assert_eq!(*map.get(&2).unwrap(), "modified3".to_string());
1431
1432 }
1433
1434 #[test]
1435 fn test_sync_hash_map_values_mut() {
1436 let map = SyncHashMap::new();
1437
1438 map.insert(1, "one".to_string());
1439 map.insert(2, "two".to_string());
1440
1441 for mut v in map.values_mut() {
1442 if *v == "one" {
1443 *v = "modified".to_string();
1444 }
1445 }
1446
1447 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1448 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1449 }
1450
1451 #[test]
1452 fn test_sync_hash_map_get_clone() {
1453 let map = SyncHashMap::new();
1454 map.insert(1, "one".to_string());
1455
1456 assert_eq!(map.get_clone(&1), Some("one".to_string()));
1458 assert_eq!(map.get_clone(&2), None);
1459 }
1460
1461 #[test]
1462 fn test_sync_hash_map_clone() {
1463 let map1 = SyncHashMap::new();
1464 map1.insert(1, "one".to_string());
1465 map1.insert(2, "two".to_string());
1466
1467 let map2 = map1.clone();
1468
1469 assert_eq!(map1.len(), map2.len());
1470 assert_eq!(*map1.get(&1).unwrap(), *map2.get(&1).unwrap());
1471 assert_eq!(*map1.get(&2).unwrap(), *map2.get(&2).unwrap());
1472
1473 map1.insert(3, "three".to_string());
1475 assert!(!map2.contains_key(&3));
1476 }
1477
1478 #[test]
1479 fn test_sync_hash_map_partial_eq() {
1480 let map1 = SyncHashMap::new();
1481 map1.insert(1, "one".to_string());
1482 map1.insert(2, "two".to_string());
1483
1484 let map2 = SyncHashMap::new();
1485 map2.insert(1, "one".to_string());
1486 map2.insert(2, "two".to_string());
1487
1488 let map3 = SyncHashMap::new();
1489 map3.insert(1, "different".to_string());
1490
1491 assert_eq!(map1, map2);
1492 assert_ne!(map1, map3);
1493 }
1494
1495 #[test]
1496 fn test_sync_hash_map_debug() {
1497 let map = SyncHashMap::new();
1498 map.insert(1, "one".to_string());
1499
1500 let debug_str = format!("{:?}", map);
1501 assert!(debug_str.contains("1"));
1502 assert!(debug_str.contains("one"));
1503 }
1504
1505 #[test]
1506 fn test_sync_hash_map_serialization() {
1507 let map = SyncHashMap::new();
1508 map.insert(1, "one".to_string());
1509 map.insert(2, "two".to_string());
1510
1511 let serialized = serde_json::to_string(&map).unwrap();
1513 assert!(serialized.contains("1"));
1514 assert!(serialized.contains("one"));
1515 assert!(serialized.contains("2"));
1516 assert!(serialized.contains("two"));
1517
1518 let deserialized: SyncHashMap<i32, String> = serde_json::from_str(&serialized).unwrap();
1520 assert_eq!(deserialized.len(), 2);
1521 assert_eq!(*deserialized.get(&1).unwrap(), "one".to_string());
1522 assert_eq!(*deserialized.get(&2).unwrap(), "two".to_string());
1523 }
1524
1525 #[test]
1526 fn test_sync_hash_map_from_hashmap() {
1527 let mut original = HashMap::new();
1528 original.insert(1, "one".to_string());
1529 original.insert(2, "two".to_string());
1530
1531 let map = SyncHashMap::from(original);
1532
1533 assert_eq!(map.len(), 2);
1534 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1535 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1536 }
1537
1538 #[test]
1539 fn test_sync_hash_map_into_iterator() {
1540 let map = SyncHashMap::new();
1541 map.insert(1, "one".to_string());
1542 map.insert(2, "two".to_string());
1543
1544 let mut count = 0;
1546 for (k, v) in &map {
1547 count += 1;
1548 assert!(map.contains_key(k));
1549 assert_eq!(*map.get(k).unwrap(), *v);
1550 }
1551 assert_eq!(count, 2);
1552
1553 let owned_pairs: Vec<_> = map.into_iter().collect();
1555 assert_eq!(owned_pairs.len(), 2);
1556 }
1557
1558 #[test]
1559 fn test_sync_hash_map_default() {
1560 let map: SyncHashMap<i32, String> = Default::default();
1561 assert_eq!(map.len(), 0);
1562 assert!(map.is_empty());
1563 }
1564
1565 #[test]
1566 fn test_sync_hash_map_arc() {
1567 let map = SyncHashMap::new_arc();
1568 map.insert(1, "one".to_string());
1569
1570 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1571
1572 let map2 = Arc::clone(&map);
1573 map2.insert(2, "two".to_string());
1574
1575 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1576 }
1577
1578 #[test]
1579 fn test_sync_hash_map_get_mut() {
1580 let map = SyncHashMap::new();
1581 map.insert(1, "one".to_string());
1582
1583 {
1584 let mut value = map.get_mut(&1).unwrap();
1585 *value = "modified".to_string();
1586 }
1587
1588 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1589 }
1590
1591 #[test]
1592 fn test_sync_hash_map_concurrent_access() {
1593 let map = Arc::new(SyncHashMap::new());
1594
1595 let handles: Vec<_> = (0..10)
1597 .map(|i| {
1598 let map = Arc::clone(&map);
1599 thread::spawn(move || {
1600 map.insert(i, format!("value_{}", i));
1601 })
1602 })
1603 .collect();
1604
1605 for handle in handles {
1606 handle.join().unwrap();
1607 }
1608
1609 assert_eq!(map.len(), 10);
1611 for i in 0..10 {
1612 assert_eq!(*map.get(&i).unwrap(), format!("value_{}", i));
1613 }
1614
1615 let map_read = Arc::clone(&map);
1617 let handles: Vec<_> = (0..10)
1618 .map(|i| {
1619 let map = Arc::clone(&map_read);
1620 thread::spawn(move || {
1621 let value = map.get(&i);
1622 assert_eq!(*value.unwrap(), format!("value_{}", i));
1623 })
1624 })
1625 .collect();
1626
1627 for handle in handles {
1628 handle.join().unwrap();
1629 }
1630 }
1631
1632 #[test]
1633 fn test_sync_hash_map_dirty_ref() {
1634 let map = SyncHashMap::new();
1635 map.insert(1, "one".to_string());
1636
1637 let dirty = map.dirty_ref();
1638 assert_eq!(dirty.len(), 1);
1639 assert_eq!(*dirty.get(&1).unwrap().read(), "one".to_string());
1641 }
1642
1643 #[test]
1644 fn test_sync_hash_map_into_inner() {
1645 let map = SyncHashMap::new();
1646 map.insert(1, "one".to_string());
1647 map.insert(2, "two".to_string());
1648
1649 let inner = map.into_inner();
1650 assert_eq!(inner.len(), 2);
1651 assert_eq!(inner.get(&1), Some(&"one".to_string()));
1652 assert_eq!(inner.get(&2), Some(&"two".to_string()));
1653 }
1654
1655 #[test]
1656 fn test_sync_hash_map_guard_debug() {
1657 let map = SyncHashMap::new();
1658 map.insert(1, "test".to_string());
1659
1660 let guard = map.get(&1).unwrap();
1661 let debug_str = format!("{:?}", guard);
1662 assert!(debug_str.contains("test"));
1663 }
1664
1665 #[test]
1666 fn test_sync_hash_map_guard_partial_eq() {
1667 let map = SyncHashMap::new();
1668 map.insert(1, "value".to_string());
1669
1670 let guard1 = map.get(&1).unwrap();
1671 let guard2 = map.get(&1).unwrap();
1672
1673 assert_eq!(guard1, guard2);
1674 }
1675
1676 mod buckets_tests {
1678 use super::*;
1679
1680 #[test]
1681 fn test_sync_hash_map_buckets_new() {
1682 let map = buckets::SyncHashMapB::<i32, String>::new(None);
1683 assert_eq!(map.len(), 0);
1684 assert!(map.is_empty());
1685 assert_eq!(map.bucket_count(), 10); }
1687
1688 #[test]
1689 fn test_sync_hash_map_buckets_with_custom_size() {
1690 let map = buckets::SyncHashMapB::<i32, String>::new(Some(5));
1691 assert_eq!(map.bucket_count(), 5);
1692 }
1693
1694 #[test]
1695 fn test_sync_hash_map_buckets_insert_and_get() {
1696 let map = buckets::SyncHashMapB::new(Some(3));
1697
1698 assert_eq!(map.insert(1, "one".to_string()), None);
1699 assert_eq!(map.insert(2, "two".to_string()), None);
1700 assert_eq!(map.len(), 2);
1701
1702 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1703 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1704 assert!(map.get(&3).is_none());
1705 }
1706
1707 #[test]
1708 fn test_sync_hash_map_buckets_remove() {
1709 let map = buckets::SyncHashMapB::new(Some(3));
1710
1711 map.insert(1, "one".to_string());
1712 map.insert(2, "two".to_string());
1713
1714 assert_eq!(map.remove(&1), Some("one".to_string()));
1715 assert_eq!(map.len(), 1);
1716 assert!(map.get(&1).is_none());
1717 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1718 }
1719
1720 #[test]
1721 fn test_sync_hash_map_buckets_clear() {
1722 let map = buckets::SyncHashMapB::new(Some(3));
1723
1724 map.insert(1, "one".to_string());
1725 map.insert(2, "two".to_string());
1726
1727 assert_eq!(map.len(), 2);
1728 map.clear();
1729 assert_eq!(map.len(), 0);
1730 assert!(map.is_empty());
1731 }
1732
1733 #[test]
1734 fn test_sync_hash_map_buckets_iterators() {
1735 let map = buckets::SyncHashMapB::new(Some(3));
1736
1737 map.insert(1, "one".to_string());
1738 map.insert(2, "two".to_string());
1739 map.insert(3, "three".to_string());
1740
1741 let keys: Vec<_> = map.keys().collect();
1743 assert!(keys.contains(&&1));
1744 assert!(keys.contains(&&2));
1745 assert!(keys.contains(&&3));
1746
1747 assert_eq!(map.get_clone(&1), Some("one".to_string()));
1749 assert_eq!(map.get_clone(&2), Some("two".to_string()));
1750 assert_eq!(map.get_clone(&3), Some("three".to_string()));
1751
1752 {
1754 let mut v = map.get_mut(&1).unwrap();
1755 *v = "modified".to_string();
1756 }
1757
1758 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1759 }
1760
1761 #[test]
1762 fn test_sync_hash_map_buckets_default() {
1763 let map: buckets::SyncHashMapB<i32, String> = Default::default();
1764 assert_eq!(map.len(), 0);
1765 assert!(map.is_empty());
1766 assert_eq!(map.bucket_count(), 10);
1767 }
1768
1769 #[test]
1770 fn test_sync_hash_map_buckets_debug() {
1771 let map = buckets::SyncHashMapB::new(Some(2));
1772 map.insert(1, "one".to_string());
1773
1774 let debug_str = format!("{:?}", map);
1775 assert!(debug_str.contains("1"));
1776 assert!(debug_str.contains("one"));
1777 }
1778 }
1779
1780 #[test]
1781 fn test_sync_hash_map_comprehensive() {
1782 let map = SyncHashMap::new();
1783
1784 map.insert("key1", 42);
1786 map.insert("key2", 24);
1787
1788 assert_eq!(map.len(), 2);
1789 assert!(!map.is_empty());
1790
1791 *map.get_mut("key1").unwrap() = 100;
1793 assert_eq!(*map.get(&"key1").unwrap(), 100);
1794
1795 map.insert("key3", 50);
1797 map.retain(|_, v| *v > 30);
1798
1799 assert_eq!(map.len(), 2);
1800 assert_eq!(*map.get(&"key1").unwrap(), 100);
1801 assert!(map.get(&"key2").is_none());
1802 assert_eq!(*map.get(&"key3").unwrap(), 50);
1803
1804 let map2 = map.clone();
1806 assert_eq!(map, map2);
1807
1808 let mut sum = 0;
1810 for (_, v) in map.iter() {
1811 sum += *v;
1812 }
1813 assert_eq!(sum, 150);
1814
1815 map.clear();
1817 assert_eq!(map.len(), 0);
1818 assert!(map.is_empty());
1819 }
1820
1821 #[test]
1822 fn test_sync_hash_map_iter_nlock() {
1823 let map = SyncHashMap::new();
1824 map.insert(1, "one".to_string());
1825 map.insert(2, "two".to_string());
1826 map.insert(3, "three".to_string());
1827
1828 let mut count = 0;
1830 for (k, v) in map.iter() {
1831 count += 1;
1832 match *k {
1833 1 => assert_eq!(v, "one"),
1834 2 => assert_eq!(v, "two"),
1835 3 => assert_eq!(v, "three"),
1836 _ => panic!("unexpected key"),
1837 }
1838 }
1839 assert_eq!(count, 3);
1840
1841 let iter = map.iter();
1843 assert_eq!(iter.len(), 3);
1844 }
1845
1846 #[test]
1847 fn test_sync_hash_map_into_iter_mut() {
1848 let mut map = SyncHashMap::new();
1849 map.insert(1, "one".to_string());
1850 map.insert(2, "two".to_string());
1851
1852 for (k, mut v) in &mut map {
1854 if *k == 1 {
1855 *v = "modified".to_string();
1856 }
1857 }
1858
1859 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1860 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1861 }
1862
1863 #[test]
1864 fn test_sync_hash_map_into_iter_ref() {
1865 let map = SyncHashMap::new();
1866 map.insert(1, 10);
1867 map.insert(2, 20);
1868 map.insert(3, 30);
1869
1870 let mut sum = 0;
1872 for (_, v) in &map {
1873 sum += *v;
1874 }
1875 assert_eq!(sum, 60);
1876
1877 assert_eq!(map.len(), 3);
1879 }
1880
1881 #[test]
1882 fn test_sync_hash_map_iter_nlock_empty() {
1883 let map: SyncHashMap<i32, String> = SyncHashMap::new();
1884
1885 let mut count = 0;
1886 for _ in map.iter() {
1887 count += 1;
1888 }
1889 assert_eq!(count, 0);
1890
1891 let iter = map.iter();
1892 assert_eq!(iter.len(), 0);
1893 }
1894}