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(&self) -> Iter<'_, K, V> {
336 let _lock = self.lock.read();
337 let m = unsafe { &*self.dirty.get() };
338 Iter {
339 _lock,
340 inner: m.iter(),
341 }
342 }
343
344 pub fn dirty_ref(&self) -> ReadGuardMap<'_, K, V> {
352 let _lock = self.lock.read();
353 let v = unsafe { &*self.dirty.get() };
354 ReadGuardMap { _lock, v }
355 }
356
357 pub unsafe fn dirty_ref_unsafe(&self) -> &HashMap<K, RwLock<V>, DefaultBuildHasher> {
365 unsafe { &*self.dirty.get() }
366 }
367
368 pub fn into_inner(self) -> HashMap<K, V> {
371 self.dirty
372 .into_inner()
373 .into_iter()
374 .map(|(k, v)| (k, v.into_inner()))
375 .collect()
376 }
377
378 #[inline]
384 pub fn keys(&self) -> KeysGuard<'_, K, V> {
385 let _lock = self.lock.read();
386 let m = unsafe { &*self.dirty.get() };
387 KeysGuard {
388 _lock,
389 inner: m.keys(),
390 }
391 }
392
393 #[inline]
399 pub fn values(&self) -> ValuesGuard<'_, K, V> {
400 let _lock = self.lock.read();
401 let m = unsafe { &*self.dirty.get() };
402 ValuesGuard {
403 _lock,
404 inner: m.values(),
405 }
406 }
407
408 #[inline]
414 pub fn values_mut(&self) -> ValuesMutGuard<'_, K, V> {
415 let _lock = self.lock.write();
416 let m = unsafe { &*self.dirty.get() };
417 ValuesMutGuard {
418 _lock,
419 inner: m.values(),
420 }
421 }
422
423 #[inline]
426 pub fn retain<F>(&self, mut f: F)
427 where
428 F: FnMut(&K, &mut V) -> bool,
429 {
430 let _lock = self.lock.write();
431 let m = unsafe { &mut *self.dirty.get() };
432 m.retain(|k, v| f(k, v.get_mut()));
433 }
434
435 #[inline]
438 pub fn capacity(&self) -> usize {
439 let _lock = self.lock.read();
440 let m = unsafe { &*self.dirty.get() };
441 m.capacity()
442 }
443
444 #[inline]
447 pub fn reserve(&self, additional: usize) {
448 let _lock = self.lock.write();
449 let m = unsafe { &mut *self.dirty.get() };
450 m.reserve(additional);
451 }
452
453 #[inline]
456 pub fn remove_entry(&self, k: &K) -> Option<(K, V)> {
457 let _lock = self.lock.write();
458 let m = unsafe { &mut *self.dirty.get() };
459 m.remove_entry(k).map(|(k, v)| (k, v.into_inner()))
460 }
461
462 #[inline]
468 pub fn get_or_insert(&self, k: K, default: V) -> WriteGuardEntry<'_, V> {
469 let map_lock = self.lock.write();
470 let m = unsafe { &mut *self.dirty.get() };
471 let entry = m.entry(k).or_insert_with(|| RwLock::new(default));
472 let value_lock = entry.write();
473 WriteGuardEntry {
474 _map_lock: map_lock,
475 _value_lock: value_lock,
476 }
477 }
478
479 #[inline]
485 pub fn get_or_insert_with<F>(&self, k: K, default: F) -> WriteGuardEntry<'_, V>
486 where
487 F: FnOnce() -> V,
488 {
489 let map_lock = self.lock.write();
490 let m = unsafe { &mut *self.dirty.get() };
491 let entry = m.entry(k).or_insert_with(|| RwLock::new(default()));
492 let value_lock = entry.write();
493 WriteGuardEntry {
494 _map_lock: map_lock,
495 _value_lock: value_lock,
496 }
497 }
498
499 #[inline]
505 pub fn get_clone<Q: ?Sized>(&self, k: &Q) -> Option<V>
506 where
507 K: Borrow<Q>,
508 Q: Hash + Eq,
509 V: Clone,
510 {
511 let _map_lock = self.lock.read();
512 let m = unsafe { &*self.dirty.get() };
513 m.get(k).map(|v| v.read().clone())
514 }
515
516 #[inline]
522 pub fn take(&self, k: &K) -> Option<V> {
523 self.remove(k)
524 }
525}
526
527pub struct ReadGuard<'a, V> {
530 _map_lock: RwLockReadGuard<'a, ()>,
533 _value_lock: RwLockReadGuard<'a, V>,
536}
537
538impl<'a, V> Deref for ReadGuard<'a, V> {
539 type Target = V;
540
541 fn deref(&self) -> &Self::Target {
542 &*self._value_lock
543 }
544}
545
546impl<'a, V> Debug for ReadGuard<'a, V>
547where
548 V: Debug,
549{
550 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
551 write!(f, "{:?}", &*self._value_lock)
552 }
553}
554
555impl<'a, V> PartialEq for ReadGuard<'a, V>
556where
557 V: PartialEq,
558{
559 fn eq(&self, other: &Self) -> bool {
560 (*self._value_lock).eq(&*other._value_lock)
561 }
562}
563
564impl<'a, V> Eq for ReadGuard<'a, V> where V: Eq {}
565
566impl<'a, V> std::fmt::Display for ReadGuard<'a, V>
567where
568 V: std::fmt::Display,
569{
570 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
571 (*self._value_lock).fmt(f)
572 }
573}
574
575impl<'a, V> AsRef<V> for ReadGuard<'a, V> {
576 fn as_ref(&self) -> &V {
577 &*self._value_lock
578 }
579}
580
581pub struct ReadGuardMap<'a, K, V> {
587 _lock: RwLockReadGuard<'a, ()>,
590 v: &'a HashMap<K, RwLock<V>, DefaultBuildHasher>,
593}
594
595impl<'a, K, V> Deref for ReadGuardMap<'a, K, V> {
596 type Target = HashMap<K, RwLock<V>, DefaultBuildHasher>;
597
598 fn deref(&self) -> &Self::Target {
599 self.v
600 }
601}
602
603impl<'a, K, V> Debug for ReadGuardMap<'a, K, V>
604where
605 K: Debug,
606 V: Debug,
607{
608 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
609 let mut map = f.debug_map();
612 for (k, v) in self.v.iter() {
613 map.entry(k, &*v.read());
614 }
615 map.finish()
616 }
617}
618
619impl<'a, K, V> AsRef<HashMap<K, RwLock<V>, DefaultBuildHasher>> for ReadGuardMap<'a, K, V> {
620 fn as_ref(&self) -> &HashMap<K, RwLock<V>, DefaultBuildHasher> {
621 self.v
622 }
623}
624
625pub struct WriteGuard<'a, V> {
631 _map_lock: RwLockReadGuard<'a, ()>,
634 _value_lock: RwLockWriteGuard<'a, V>,
637}
638
639impl<'a, V> Deref for WriteGuard<'a, V> {
640 type Target = V;
641
642 fn deref(&self) -> &Self::Target {
643 &*self._value_lock
644 }
645}
646
647impl<'a, V> DerefMut for WriteGuard<'a, V> {
648 fn deref_mut(&mut self) -> &mut Self::Target {
649 &mut *self._value_lock
650 }
651}
652
653impl<'a, V> Debug for WriteGuard<'a, V>
654where
655 V: Debug,
656{
657 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
658 write!(f, "{:?}", &*self._value_lock)
659 }
660}
661
662impl<'a, V> PartialEq for WriteGuard<'a, V>
663where
664 V: PartialEq,
665{
666 fn eq(&self, other: &Self) -> bool {
667 (*self._value_lock).eq(&*other._value_lock)
668 }
669}
670
671impl<'a, V> Eq for WriteGuard<'a, V> where V: Eq {}
672
673impl<'a, V> std::fmt::Display for WriteGuard<'a, V>
674where
675 V: std::fmt::Display,
676{
677 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
678 (*self._value_lock).fmt(f)
679 }
680}
681
682impl<'a, V> AsRef<V> for WriteGuard<'a, V> {
683 fn as_ref(&self) -> &V {
684 &*self._value_lock
685 }
686}
687
688impl<'a, V> AsMut<V> for WriteGuard<'a, V> {
689 fn as_mut(&mut self) -> &mut V {
690 &mut *self._value_lock
691 }
692}
693
694pub struct WriteGuardEntry<'a, V> {
700 _map_lock: RwLockWriteGuard<'a, ()>,
703 _value_lock: RwLockWriteGuard<'a, V>,
706}
707
708impl<'a, V> Deref for WriteGuardEntry<'a, V> {
709 type Target = V;
710
711 fn deref(&self) -> &Self::Target {
712 &*self._value_lock
713 }
714}
715
716impl<'a, V> DerefMut for WriteGuardEntry<'a, V> {
717 fn deref_mut(&mut self) -> &mut Self::Target {
718 &mut *self._value_lock
719 }
720}
721
722impl<'a, V> Debug for WriteGuardEntry<'a, V>
723where
724 V: Debug,
725{
726 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
727 write!(f, "{:?}", &*self._value_lock)
728 }
729}
730
731impl<'a, V> std::fmt::Display for WriteGuardEntry<'a, V>
732where
733 V: std::fmt::Display,
734{
735 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
736 (*self._value_lock).fmt(f)
737 }
738}
739
740impl<'a, V> AsRef<V> for WriteGuardEntry<'a, V> {
741 fn as_ref(&self) -> &V {
742 &*self._value_lock
743 }
744}
745
746impl<'a, V> AsMut<V> for WriteGuardEntry<'a, V> {
747 fn as_mut(&mut self) -> &mut V {
748 &mut *self._value_lock
749 }
750}
751
752#[allow(dead_code)]
755#[deprecated(note = "Use ReadGuard instead")]
756pub type SyncMapRefMut<'a, V> = WriteGuard<'a, V>;
757
758pub struct Iter<'a, K, V> {
764 _lock: RwLockReadGuard<'a, ()>,
767 inner: MapIter<'a, K, RwLock<V>>,
770}
771
772impl<'a, K, V> Iterator for Iter<'a, K, V> {
773 type Item = (&'a K, RwLockReadGuard<'a, V>);
774
775 fn next(&mut self) -> Option<Self::Item> {
776 self.inner.next().map(|(k, v)| (k, v.read()))
777 }
778}
779
780pub type IterMy<'a, K, V> = Iter<'a, K, V>;
783
784pub struct IterMut<'a, K, V> {
790 _lock: RwLockReadGuard<'a, ()>,
793 inner: MapIter<'a, K, RwLock<V>>,
796}
797
798impl<'a, K, V> Iterator for IterMut<'a, K, V> {
799 type Item = (&'a K, RwLockWriteGuard<'a, V>);
800
801 fn next(&mut self) -> Option<Self::Item> {
802 self.inner.next().map(|(k, v)| (k, v.write()))
803 }
804}
805
806pub struct KeysGuard<'a, K, V> {
809 _lock: RwLockReadGuard<'a, ()>,
812 inner: Keys<'a, K, RwLock<V>>,
815}
816
817impl<'a, K, V> Deref for KeysGuard<'a, K, V> {
818 type Target = Keys<'a, K, RwLock<V>>;
819
820 fn deref(&self) -> &Self::Target {
821 &self.inner
822 }
823}
824
825impl<'a, K, V> DerefMut for KeysGuard<'a, K, V> {
826 fn deref_mut(&mut self) -> &mut Self::Target {
827 &mut self.inner
828 }
829}
830
831impl<'a, K, V> Iterator for KeysGuard<'a, K, V> {
832 type Item = &'a K;
833
834 fn next(&mut self) -> Option<Self::Item> {
835 self.inner.next()
836 }
837}
838
839pub struct ValuesGuard<'a, K, V> {
845 _lock: RwLockReadGuard<'a, ()>,
848 inner: std::collections::hash_map::Values<'a, K, RwLock<V>>,
851}
852
853impl<'a, K, V> Iterator for ValuesGuard<'a, K, V> {
854 type Item = RwLockReadGuard<'a, V>;
855
856 fn next(&mut self) -> Option<Self::Item> {
857 self.inner.next().map(|v| v.read())
858 }
859}
860
861pub struct ValuesMutGuard<'a, K, V> {
867 _lock: RwLockWriteGuard<'a, ()>,
870 inner: std::collections::hash_map::Values<'a, K, RwLock<V>>,
873}
874
875impl<'a, K, V> Iterator for ValuesMutGuard<'a, K, V> {
876 type Item = RwLockWriteGuard<'a, V>;
877
878 fn next(&mut self) -> Option<Self::Item> {
879 self.inner.next().map(|v| v.write())
880 }
881}
882
883impl<'a, K, V> IntoIterator for &'a SyncHashMap<K, V>
884where
885 K: Eq + Hash,
886{
887 type Item = (&'a K, RwLockReadGuard<'a, V>);
888 type IntoIter = Iter<'a, K, V>;
889
890 fn into_iter(self) -> Self::IntoIter {
891 self.iter()
892 }
893}
894
895impl<K, V> IntoIterator for SyncHashMap<K, V>
896where
897 K: Eq + Hash,
898{
899 type Item = (K, V);
900 type IntoIter = MapIntoIter<K, V>;
901
902 fn into_iter(self) -> Self::IntoIter {
903 self.into_inner().into_iter()
904 }
905}
906
907impl<K, V> From<HashMap<K, V>> for SyncHashMap<K, V>
908where
909 K: Eq + Hash,
910{
911 fn from(map: HashMap<K, V>) -> Self {
912 Self::with_map(map)
913 }
914}
915
916impl<K, V> Serialize for SyncHashMap<K, V>
917where
918 K: Eq + Hash + Serialize,
919 V: Serialize,
920{
921 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
922 where
923 S: Serializer,
924 {
925 use serde::ser::SerializeMap;
926 let _lock = self.lock.read();
927 let m = unsafe { &*self.dirty.get() };
928 let mut map = serializer.serialize_map(Some(m.len()))?;
929 for (k, v) in m.iter() {
930 map.serialize_entry(k, &*v.read())?;
931 }
932 map.end()
933 }
934}
935
936impl<'de, K, V> Deserialize<'de> for SyncHashMap<K, V>
937where
938 K: Eq + Hash + Deserialize<'de>,
939 V: Deserialize<'de>,
940{
941 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
942 where
943 D: Deserializer<'de>,
944 {
945 let m = HashMap::deserialize(deserializer)?;
946 Ok(Self::with_map(m))
947 }
948}
949
950impl<K, V> Debug for SyncHashMap<K, V>
951where
952 K: Eq + Hash + Debug,
953 V: Debug,
954{
955 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
956 let _lock = self.lock.read();
957 let m = unsafe { &*self.dirty.get() };
958 let mut map = f.debug_map();
959 for (k, v) in m.iter() {
960 map.entry(k, &*v.read());
961 }
962 map.finish()
963 }
964}
965
966impl<K, V> Clone for SyncHashMap<K, V>
967where
968 K: Clone + Eq + Hash,
969 V: Clone,
970{
971 fn clone(&self) -> Self {
972 let _lock = self.lock.read();
973 let m = unsafe { &*self.dirty.get() };
974 let cloned: HashMap<K, V> = m
975 .iter()
976 .map(|(k, v)| (k.clone(), v.read().clone()))
977 .collect();
978 SyncHashMap::with_map(cloned)
979 }
980}
981
982impl<K, V> Default for SyncHashMap<K, V>
983where
984 K: Eq + Hash,
985{
986 fn default() -> Self {
987 Self::new()
988 }
989}
990
991impl<K, V> PartialEq for SyncHashMap<K, V>
992where
993 K: Eq + Hash,
994 V: PartialEq,
995{
996 fn eq(&self, other: &Self) -> bool {
997 let _lock_self = self.lock.read();
998 let _lock_other = other.lock.read();
999 let self_map = unsafe { &*self.dirty.get() };
1000 let other_map = unsafe { &*other.dirty.get() };
1001
1002 if self_map.len() != other_map.len() {
1003 return false;
1004 }
1005
1006 for (k, v) in self_map.iter() {
1007 match other_map.get(k) {
1008 Some(other_v) => {
1009 if *v.read() != *other_v.read() {
1010 return false;
1011 }
1012 }
1013 None => return false,
1014 }
1015 }
1016 true
1017 }
1018}
1019
1020impl<K, V> Eq for SyncHashMap<K, V>
1021where
1022 K: Eq + Hash,
1023 V: Eq,
1024{
1025}
1026
1027pub mod buckets {
1030 use super::{ReadGuard, SyncHashMap, WriteGuard};
1031 use std::hash::{Hash, Hasher};
1032
1033 #[derive(Debug, Clone)]
1036 pub struct SyncHashMapB<K, V>
1037 where
1038 K: Eq + Hash,
1039 {
1040 inner: Vec<SyncHashMap<K, V>>,
1043 len: usize,
1046 }
1047
1048 impl<K, V> SyncHashMapB<K, V>
1049 where
1050 K: Eq + Hash,
1051 {
1052 pub fn new(bucket_count: Option<usize>) -> Self {
1071 let count = bucket_count.unwrap_or(10);
1072 let mut arr = Vec::with_capacity(count);
1073 for _ in 0..count {
1074 arr.push(SyncHashMap::new());
1075 }
1076 Self {
1077 inner: arr,
1078 len: count,
1079 }
1080 }
1081
1082 fn key_to_bucket_index(&self, k: &K) -> usize {
1085 let mut hasher = std::collections::hash_map::DefaultHasher::new();
1086 k.hash(&mut hasher);
1087 let hash = hasher.finish();
1088 (hash % self.len as u64) as usize
1089 }
1090
1091 #[inline]
1094 pub fn insert(&self, k: K, v: V) -> Option<V> {
1095 let index = self.key_to_bucket_index(&k);
1096 self.inner[index].insert(k, v)
1097 }
1098
1099 #[inline]
1102 pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
1103 let index = self.key_to_bucket_index(&k);
1104 self.inner[index].insert_mut(k, v)
1105 }
1106
1107 #[inline]
1110 pub fn remove(&self, k: &K) -> Option<V> {
1111 let index = self.key_to_bucket_index(k);
1112 self.inner[index].remove(k)
1113 }
1114
1115 #[inline]
1118 pub fn is_empty(&self) -> bool {
1119 self.inner.iter().all(|bucket| bucket.is_empty())
1120 }
1121
1122 #[inline]
1125 pub fn len(&self) -> usize {
1126 self.inner.iter().map(|bucket| bucket.len()).sum()
1127 }
1128
1129 #[inline]
1132 pub fn clear(&self) {
1133 self.inner.iter().for_each(|bucket| bucket.clear());
1134 }
1135
1136 #[inline]
1142 pub fn get(&self, k: &K) -> Option<ReadGuard<'_, V>> {
1143 let index = self.key_to_bucket_index(k);
1144 self.inner[index].get(k)
1145 }
1146
1147 #[inline]
1153 pub fn get_mut(&self, k: &K) -> Option<WriteGuard<'_, V>> {
1154 let index = self.key_to_bucket_index(k);
1155 self.inner[index].get_mut(k)
1156 }
1157
1158 #[inline]
1161 pub fn bucket_count(&self) -> usize {
1162 self.len
1163 }
1164
1165 #[inline]
1168 pub fn keys(&self) -> impl Iterator<Item = &K> {
1169 self.inner.iter().flat_map(|bucket| bucket.keys())
1170 }
1171
1172 #[inline]
1175 pub fn get_clone(&self, k: &K) -> Option<V>
1176 where
1177 V: Clone,
1178 {
1179 let index = self.key_to_bucket_index(k);
1180 self.inner[index].get_clone(k)
1181 }
1182 }
1183
1184 impl<K, V> Default for SyncHashMapB<K, V>
1185 where
1186 K: Eq + Hash,
1187 {
1188 fn default() -> Self {
1189 Self::new(None)
1190 }
1191 }
1192}
1193
1194#[cfg(test)]
1195mod tests {
1196 use super::*;
1197 use std::collections::HashMap;
1198 use std::sync::Arc;
1199 use std::thread;
1200
1201 #[test]
1202 fn test_sync_hash_map_new() {
1203 let map: SyncHashMap<i32, String> = SyncHashMap::new();
1204 assert_eq!(map.len(), 0);
1205 assert!(map.is_empty());
1206 }
1207
1208 #[test]
1209 fn test_sync_hash_map_with_capacity() {
1210 let map = SyncHashMap::<i32, String>::with_capacity(100);
1211 assert!(map.capacity() >= 100);
1212 }
1213
1214 #[test]
1215 fn test_sync_hash_map_with_map() {
1216 let mut original = HashMap::new();
1217 original.insert(1, "one".to_string());
1218 original.insert(2, "two".to_string());
1219
1220 let map = SyncHashMap::with_map(original);
1221 assert_eq!(map.len(), 2);
1222 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1223 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1224 }
1225
1226 #[test]
1227 fn test_sync_hash_map_insert_and_get() {
1228 let map = SyncHashMap::new();
1229
1230 assert_eq!(map.insert(1, "one".to_string()), None);
1232 assert_eq!(map.insert(2, "two".to_string()), None);
1233 assert_eq!(map.len(), 2);
1234
1235 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1236 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1237 assert!(map.get(&3).is_none());
1238 }
1239
1240 #[test]
1241 fn test_sync_hash_map_insert_replace() {
1242 let map = SyncHashMap::new();
1243
1244 assert_eq!(map.insert(1, "one".to_string()), None);
1245 assert_eq!(map.insert(1, "updated".to_string()), Some("one".to_string()));
1246 assert_eq!(*map.get(&1).unwrap(), "updated".to_string());
1247 }
1248
1249 #[test]
1250 fn test_sync_hash_map_remove() {
1251 let map = SyncHashMap::new();
1252
1253 map.insert(1, "one".to_string());
1254 map.insert(2, "two".to_string());
1255
1256 assert_eq!(map.remove(&1), Some("one".to_string()));
1257 assert_eq!(map.remove(&1), None);
1258 assert_eq!(map.len(), 1);
1259 assert!(map.get(&1).is_none());
1260 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1261 }
1262
1263 #[test]
1264 fn test_sync_hash_map_contains_key() {
1265 let map = SyncHashMap::new();
1266
1267 map.insert(1, "one".to_string());
1268
1269 assert!(map.contains_key(&1));
1270 assert!(!map.contains_key(&2));
1271 }
1272
1273 #[test]
1274 fn test_sync_hash_map_clear() {
1275 let map = SyncHashMap::new();
1276
1277 map.insert(1, "one".to_string());
1278 map.insert(2, "two".to_string());
1279
1280 assert_eq!(map.len(), 2);
1281 map.clear();
1282 assert_eq!(map.len(), 0);
1283 assert!(map.is_empty());
1284 }
1285
1286 #[test]
1287 fn test_sync_hash_map_capacity_operations() {
1288 let map = SyncHashMap::new();
1289
1290 assert_eq!(map.capacity(), 0);
1291 map.reserve(100);
1292 assert!(map.capacity() >= 100);
1293
1294 map.insert(1, "one".to_string());
1295 map.insert(2, "two".to_string());
1296
1297 let old_capacity = map.capacity();
1298 map.shrink_to_fit();
1299 assert!(map.capacity() <= old_capacity);
1300 }
1301
1302 #[test]
1303 fn test_sync_hash_map_retain() {
1304 let map = SyncHashMap::new();
1305
1306 map.insert(1, "one".to_string());
1307 map.insert(2, "two".to_string());
1308 map.insert(3, "three".to_string());
1309
1310 map.retain(|&k, _| k % 2 == 1);
1311
1312 assert_eq!(map.len(), 2);
1313 assert!(map.contains_key(&1));
1314 assert!(!map.contains_key(&2));
1315 assert!(map.contains_key(&3));
1316 }
1317
1318 #[test]
1319 fn test_sync_hash_map_get_or_insert() {
1320 let map = SyncHashMap::new();
1321
1322 {
1324 let value = map.get_or_insert(1, "default".to_string());
1325 assert_eq!(*value, "default");
1326 }
1327 assert_eq!(map.len(), 1);
1328
1329 {
1331 let value = map.get_or_insert(1, "new_default".to_string());
1332 assert_eq!(*value, "default");
1333 }
1334 assert_eq!(map.len(), 1);
1335 }
1336
1337 #[test]
1338 fn test_sync_hash_map_get_or_insert_with() {
1339 let map = SyncHashMap::new();
1340
1341 {
1342 let value = map.get_or_insert_with(1, || "computed".to_string());
1343 assert_eq!(*value, "computed");
1344 }
1345 assert_eq!(map.len(), 1);
1346
1347 {
1348 let value = map.get_or_insert_with(1, || "new_computed".to_string());
1349 assert_eq!(*value, "computed");
1350 }
1351 }
1352
1353 #[test]
1354 fn test_sync_hash_map_remove_entry() {
1355 let map = SyncHashMap::new();
1356
1357 map.insert(1, "one".to_string());
1358 map.insert(2, "two".to_string());
1359
1360 let removed = map.remove_entry(&1);
1361 assert_eq!(removed, Some((1, "one".to_string())));
1362 assert_eq!(map.len(), 1);
1363 assert!(!map.contains_key(&1));
1364 }
1365
1366 #[test]
1367 fn test_sync_hash_map_iterators() {
1368 let map = SyncHashMap::new();
1369
1370 map.insert(1, "one".to_string());
1371 map.insert(2, "two".to_string());
1372 map.insert(3, "three".to_string());
1373
1374 let keys: Vec<_> = map.keys().collect();
1376 assert!(keys.contains(&&1));
1377 assert!(keys.contains(&&2));
1378 assert!(keys.contains(&&3));
1379
1380 assert_eq!(map.get_clone(&1), Some("one".to_string()));
1382 assert_eq!(map.get_clone(&2), Some("two".to_string()));
1383 assert_eq!(map.get_clone(&3), Some("three".to_string()));
1384
1385 let mut count = 0;
1387 for (k, v) in map.iter() {
1388 count += 1;
1389 assert!(map.contains_key(k));
1390 assert_eq!(*map.get(k).unwrap(), *v);
1391 }
1392 assert_eq!(count, 3);
1393 }
1394
1395 #[test]
1396 fn test_sync_hash_map_iter_mut() {
1397 let map = SyncHashMap::new();
1398
1399 map.insert(1, "one".to_string());
1400 map.insert(2, "two".to_string());
1401
1402 for (k, mut v) in map.iter_mut() {
1403 if *k == 1 {
1404 *v = "modified".to_string();
1405 }
1406 }
1407
1408 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1409 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1410 }
1411
1412 #[test]
1413 fn test_sync_hash_map_values_mut() {
1414 let map = SyncHashMap::new();
1415
1416 map.insert(1, "one".to_string());
1417 map.insert(2, "two".to_string());
1418
1419 for mut v in map.values_mut() {
1420 if *v == "one" {
1421 *v = "modified".to_string();
1422 }
1423 }
1424
1425 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1426 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1427 }
1428
1429 #[test]
1430 fn test_sync_hash_map_get_clone() {
1431 let map = SyncHashMap::new();
1432 map.insert(1, "one".to_string());
1433
1434 assert_eq!(map.get_clone(&1), Some("one".to_string()));
1436 assert_eq!(map.get_clone(&2), None);
1437 }
1438
1439 #[test]
1440 fn test_sync_hash_map_clone() {
1441 let map1 = SyncHashMap::new();
1442 map1.insert(1, "one".to_string());
1443 map1.insert(2, "two".to_string());
1444
1445 let map2 = map1.clone();
1446
1447 assert_eq!(map1.len(), map2.len());
1448 assert_eq!(*map1.get(&1).unwrap(), *map2.get(&1).unwrap());
1449 assert_eq!(*map1.get(&2).unwrap(), *map2.get(&2).unwrap());
1450
1451 map1.insert(3, "three".to_string());
1453 assert!(!map2.contains_key(&3));
1454 }
1455
1456 #[test]
1457 fn test_sync_hash_map_partial_eq() {
1458 let map1 = SyncHashMap::new();
1459 map1.insert(1, "one".to_string());
1460 map1.insert(2, "two".to_string());
1461
1462 let map2 = SyncHashMap::new();
1463 map2.insert(1, "one".to_string());
1464 map2.insert(2, "two".to_string());
1465
1466 let map3 = SyncHashMap::new();
1467 map3.insert(1, "different".to_string());
1468
1469 assert_eq!(map1, map2);
1470 assert_ne!(map1, map3);
1471 }
1472
1473 #[test]
1474 fn test_sync_hash_map_debug() {
1475 let map = SyncHashMap::new();
1476 map.insert(1, "one".to_string());
1477
1478 let debug_str = format!("{:?}", map);
1479 assert!(debug_str.contains("1"));
1480 assert!(debug_str.contains("one"));
1481 }
1482
1483 #[test]
1484 fn test_sync_hash_map_serialization() {
1485 let map = SyncHashMap::new();
1486 map.insert(1, "one".to_string());
1487 map.insert(2, "two".to_string());
1488
1489 let serialized = serde_json::to_string(&map).unwrap();
1491 assert!(serialized.contains("1"));
1492 assert!(serialized.contains("one"));
1493 assert!(serialized.contains("2"));
1494 assert!(serialized.contains("two"));
1495
1496 let deserialized: SyncHashMap<i32, String> = serde_json::from_str(&serialized).unwrap();
1498 assert_eq!(deserialized.len(), 2);
1499 assert_eq!(*deserialized.get(&1).unwrap(), "one".to_string());
1500 assert_eq!(*deserialized.get(&2).unwrap(), "two".to_string());
1501 }
1502
1503 #[test]
1504 fn test_sync_hash_map_from_hashmap() {
1505 let mut original = HashMap::new();
1506 original.insert(1, "one".to_string());
1507 original.insert(2, "two".to_string());
1508
1509 let map = SyncHashMap::from(original);
1510
1511 assert_eq!(map.len(), 2);
1512 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1513 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1514 }
1515
1516 #[test]
1517 fn test_sync_hash_map_into_iterator() {
1518 let map = SyncHashMap::new();
1519 map.insert(1, "one".to_string());
1520 map.insert(2, "two".to_string());
1521
1522 let mut count = 0;
1524 for (k, v) in &map {
1525 count += 1;
1526 assert!(map.contains_key(k));
1527 assert_eq!(*map.get(k).unwrap(), *v);
1528 }
1529 assert_eq!(count, 2);
1530
1531 let owned_pairs: Vec<_> = map.into_iter().collect();
1533 assert_eq!(owned_pairs.len(), 2);
1534 }
1535
1536 #[test]
1537 fn test_sync_hash_map_default() {
1538 let map: SyncHashMap<i32, String> = Default::default();
1539 assert_eq!(map.len(), 0);
1540 assert!(map.is_empty());
1541 }
1542
1543 #[test]
1544 fn test_sync_hash_map_arc() {
1545 let map = SyncHashMap::new_arc();
1546 map.insert(1, "one".to_string());
1547
1548 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1549
1550 let map2 = Arc::clone(&map);
1551 map2.insert(2, "two".to_string());
1552
1553 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1554 }
1555
1556 #[test]
1557 fn test_sync_hash_map_get_mut() {
1558 let map = SyncHashMap::new();
1559 map.insert(1, "one".to_string());
1560
1561 {
1562 let mut value = map.get_mut(&1).unwrap();
1563 *value = "modified".to_string();
1564 }
1565
1566 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1567 }
1568
1569 #[test]
1570 fn test_sync_hash_map_concurrent_access() {
1571 let map = Arc::new(SyncHashMap::new());
1572
1573 let handles: Vec<_> = (0..10).map(|i| {
1575 let map = Arc::clone(&map);
1576 thread::spawn(move || {
1577 map.insert(i, format!("value_{}", i));
1578 })
1579 }).collect();
1580
1581 for handle in handles {
1582 handle.join().unwrap();
1583 }
1584
1585 assert_eq!(map.len(), 10);
1587 for i in 0..10 {
1588 assert_eq!(*map.get(&i).unwrap(), format!("value_{}", i));
1589 }
1590
1591 let map_read = Arc::clone(&map);
1593 let handles: Vec<_> = (0..10).map(|i| {
1594 let map = Arc::clone(&map_read);
1595 thread::spawn(move || {
1596 let value = map.get(&i);
1597 assert_eq!(*value.unwrap(), format!("value_{}", i));
1598 })
1599 }).collect();
1600
1601 for handle in handles {
1602 handle.join().unwrap();
1603 }
1604 }
1605
1606 #[test]
1607 fn test_sync_hash_map_dirty_ref() {
1608 let map = SyncHashMap::new();
1609 map.insert(1, "one".to_string());
1610
1611 let dirty = map.dirty_ref();
1612 assert_eq!(dirty.len(), 1);
1613 assert_eq!(*dirty.get(&1).unwrap().read(), "one".to_string());
1615 }
1616
1617 #[test]
1618 fn test_sync_hash_map_into_inner() {
1619 let map = SyncHashMap::new();
1620 map.insert(1, "one".to_string());
1621 map.insert(2, "two".to_string());
1622
1623 let inner = map.into_inner();
1624 assert_eq!(inner.len(), 2);
1625 assert_eq!(inner.get(&1), Some(&"one".to_string()));
1626 assert_eq!(inner.get(&2), Some(&"two".to_string()));
1627 }
1628
1629 #[test]
1630 fn test_sync_hash_map_guard_debug() {
1631 let map = SyncHashMap::new();
1632 map.insert(1, "test".to_string());
1633
1634 let guard = map.get(&1).unwrap();
1635 let debug_str = format!("{:?}", guard);
1636 assert!(debug_str.contains("test"));
1637 }
1638
1639 #[test]
1640 fn test_sync_hash_map_guard_partial_eq() {
1641 let map = SyncHashMap::new();
1642 map.insert(1, "value".to_string());
1643
1644 let guard1 = map.get(&1).unwrap();
1645 let guard2 = map.get(&1).unwrap();
1646
1647 assert_eq!(guard1, guard2);
1648 }
1649
1650 mod buckets_tests {
1652 use super::*;
1653
1654 #[test]
1655 fn test_sync_hash_map_buckets_new() {
1656 let map = buckets::SyncHashMapB::<i32, String>::new(None);
1657 assert_eq!(map.len(), 0);
1658 assert!(map.is_empty());
1659 assert_eq!(map.bucket_count(), 10); }
1661
1662 #[test]
1663 fn test_sync_hash_map_buckets_with_custom_size() {
1664 let map = buckets::SyncHashMapB::<i32, String>::new(Some(5));
1665 assert_eq!(map.bucket_count(), 5);
1666 }
1667
1668 #[test]
1669 fn test_sync_hash_map_buckets_insert_and_get() {
1670 let map = buckets::SyncHashMapB::new(Some(3));
1671
1672 assert_eq!(map.insert(1, "one".to_string()), None);
1673 assert_eq!(map.insert(2, "two".to_string()), None);
1674 assert_eq!(map.len(), 2);
1675
1676 assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1677 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1678 assert!(map.get(&3).is_none());
1679 }
1680
1681 #[test]
1682 fn test_sync_hash_map_buckets_remove() {
1683 let map = buckets::SyncHashMapB::new(Some(3));
1684
1685 map.insert(1, "one".to_string());
1686 map.insert(2, "two".to_string());
1687
1688 assert_eq!(map.remove(&1), Some("one".to_string()));
1689 assert_eq!(map.len(), 1);
1690 assert!(map.get(&1).is_none());
1691 assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1692 }
1693
1694 #[test]
1695 fn test_sync_hash_map_buckets_clear() {
1696 let map = buckets::SyncHashMapB::new(Some(3));
1697
1698 map.insert(1, "one".to_string());
1699 map.insert(2, "two".to_string());
1700
1701 assert_eq!(map.len(), 2);
1702 map.clear();
1703 assert_eq!(map.len(), 0);
1704 assert!(map.is_empty());
1705 }
1706
1707 #[test]
1708 fn test_sync_hash_map_buckets_iterators() {
1709 let map = buckets::SyncHashMapB::new(Some(3));
1710
1711 map.insert(1, "one".to_string());
1712 map.insert(2, "two".to_string());
1713 map.insert(3, "three".to_string());
1714
1715 let keys: Vec<_> = map.keys().collect();
1717 assert!(keys.contains(&&1));
1718 assert!(keys.contains(&&2));
1719 assert!(keys.contains(&&3));
1720
1721 assert_eq!(map.get_clone(&1), Some("one".to_string()));
1723 assert_eq!(map.get_clone(&2), Some("two".to_string()));
1724 assert_eq!(map.get_clone(&3), Some("three".to_string()));
1725
1726 {
1728 let mut v = map.get_mut(&1).unwrap();
1729 *v = "modified".to_string();
1730 }
1731
1732 assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1733 }
1734
1735 #[test]
1736 fn test_sync_hash_map_buckets_default() {
1737 let map: buckets::SyncHashMapB<i32, String> = Default::default();
1738 assert_eq!(map.len(), 0);
1739 assert!(map.is_empty());
1740 assert_eq!(map.bucket_count(), 10);
1741 }
1742
1743 #[test]
1744 fn test_sync_hash_map_buckets_debug() {
1745 let map = buckets::SyncHashMapB::new(Some(2));
1746 map.insert(1, "one".to_string());
1747
1748 let debug_str = format!("{:?}", map);
1749 assert!(debug_str.contains("1"));
1750 assert!(debug_str.contains("one"));
1751 }
1752 }
1753
1754 #[test]
1755 fn test_sync_hash_map_comprehensive() {
1756 let map = SyncHashMap::new();
1757
1758 map.insert("key1", 42);
1760 map.insert("key2", 24);
1761
1762 assert_eq!(map.len(), 2);
1763 assert!(!map.is_empty());
1764
1765 *map.get_mut("key1").unwrap() = 100;
1767 assert_eq!(*map.get(&"key1").unwrap(), 100);
1768
1769 map.insert("key3", 50);
1771 map.retain(|_, v| *v > 30);
1772
1773 assert_eq!(map.len(), 2);
1774 assert_eq!(*map.get(&"key1").unwrap(), 100);
1775 assert!(map.get(&"key2").is_none());
1776 assert_eq!(*map.get(&"key3").unwrap(), 50);
1777
1778 let map2 = map.clone();
1780 assert_eq!(map, map2);
1781
1782 let mut sum = 0;
1784 for (_, v) in map.iter() {
1785 sum += *v;
1786 }
1787 assert_eq!(sum, 150);
1788
1789 map.clear();
1791 assert_eq!(map.len(), 0);
1792 assert!(map.is_empty());
1793 }
1794}