1use serde::{Deserialize, Deserializer, Serialize, Serializer};
2use std::borrow::Borrow;
3use std::cell::UnsafeCell;
4use std::collections::hash_map::{
5 IntoIter as MapIntoIter, Iter as MapIter, IterMut as MapIterMut, Keys, Values, ValuesMut,
6};
7use std::collections::HashMap;
8use std::fmt::{Debug, Formatter};
9use std::hash::Hash;
10use std::ops::{Deref, DerefMut};
11use std::sync::{Arc, RwLock, RwLockWriteGuard};
12
13pub struct SyncHashMap<K, V> {
16 dirty: UnsafeCell<HashMap<K, V>>,
18 lock: RwLock<()>,
20}
21
22unsafe impl<K, V> Send for SyncHashMap<K, V> {}
25
26unsafe impl<K, V> Sync for SyncHashMap<K, V> {}
29
30impl<K, V> std::ops::Index<&K> for SyncHashMap<K, V>
32where
33 K: Eq + Hash,
34{
35 type Output = V;
36
37 fn index(&self, index: &K) -> &Self::Output {
38 unsafe { &(&*self.dirty.get())[index] }
39 }
40}
41
42impl<K, V> SyncHashMap<K, V>
43where
44 K: Eq + Hash,
45{
46 pub fn new_arc() -> Arc<Self> {
48 Arc::new(Self::new())
49 }
50
51 pub fn new() -> Self {
53 Self {
54 dirty: UnsafeCell::new(HashMap::new()),
55 lock: RwLock::new(()),
56 }
57 }
58
59 pub fn with_capacity(capacity: usize) -> Self {
61 Self {
62 dirty: UnsafeCell::new(HashMap::with_capacity(capacity)),
63 lock: RwLock::new(()),
64 }
65 }
66
67 pub const fn with_map(map: HashMap<K, V>) -> Self {
69 Self {
70 dirty: UnsafeCell::new(map),
71 lock: RwLock::new(()),
72 }
73 }
74
75 #[inline(always)]
77 pub fn insert(&self, k: K, v: V) -> Option<V> {
78 let _lock = self.lock.write();
79 let m = unsafe { &mut *self.dirty.get() };
80 m.insert(k, v)
81 }
82
83 #[inline(always)]
85 pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
86 let m = unsafe { &mut *self.dirty.get() };
87 m.insert(k, v)
88 }
89
90 #[inline(always)]
92 pub fn remove(&self, k: &K) -> Option<V> {
93 let _lock = self.lock.write();
94 let m = unsafe { &mut *self.dirty.get() };
95 m.remove(k)
96 }
97
98 #[inline(always)]
100 pub fn remove_mut(&mut self, k: &K) -> Option<V> {
101 let m = unsafe { &mut *self.dirty.get() };
102 m.remove(k)
103 }
104
105 #[inline(always)]
107 pub fn len(&self) -> usize {
108 let _lock = self.lock.read();
109 let m = unsafe { &*self.dirty.get() };
110 m.len()
111 }
112
113 #[inline(always)]
115 pub fn is_empty(&self) -> bool {
116 let _lock = self.lock.read();
117 let m = unsafe { &*self.dirty.get() };
118 m.is_empty()
119 }
120
121 #[inline(always)]
123 pub fn clear(&self) {
124 let _lock = self.lock.write();
125 let m = unsafe { &mut *self.dirty.get() };
126 m.clear();
127 }
128
129 #[inline(always)]
131 pub fn clear_mut(&mut self) {
132 let m = unsafe { &mut *self.dirty.get() };
133 m.clear();
134 }
135
136 #[inline(always)]
138 pub fn shrink_to_fit(&self) {
139 let _lock = self.lock.write();
140 let m = unsafe { &mut *self.dirty.get() };
141 m.shrink_to_fit();
142 }
143
144 #[inline(always)]
146 pub fn shrink_to_fit_mut(&mut self) {
147 let m = unsafe { &mut *self.dirty.get() };
148 m.shrink_to_fit();
149 }
150
151 pub fn from(map: HashMap<K, V>) -> Self {
153 Self::with_map(map)
154 }
155
156 #[inline]
171 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
172 where
173 K: Borrow<Q>,
174 Q: Hash + Eq,
175 {
176 let _lock = self.lock.read();
177 let m = unsafe { &*self.dirty.get() };
178 m.get(k)
179 }
180
181 #[inline]
183 pub fn get_mut<Q: ?Sized>(&self, k: &Q) -> Option<SyncMapRefMut<'_, K, V>>
184 where
185 K: Borrow<Q>,
186 Q: Hash + Eq,
187 {
188 let _lock = self.lock.write().expect("Lock poisoned");
189 let m = unsafe { &mut *self.dirty.get() };
190 let value = m.get_mut(k)?;
191 Some(SyncMapRefMut::<K, V> {
192 _lock,
193 value,
194 _phantom: std::marker::PhantomData,
195 })
196 }
197
198 #[inline]
200 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
201 where
202 K: Borrow<Q>,
203 Q: Hash + Eq,
204 {
205 let _lock = self.lock.read();
206 let m = unsafe { &*self.dirty.get() };
207 m.contains_key(k)
208 }
209
210 pub fn iter_mut(&self) -> IterMut<'_, K, V> {
212 let _lock = self.lock.write().expect("Lock poisoned");
213 let m = unsafe { &mut *self.dirty.get() };
214 IterMut {
215 _lock,
216 inner: m.iter_mut(),
217 }
218 }
219
220 pub fn iter(&self) -> MapIter<'_, K, V> {
222 let _lock = self.lock.read();
223 let m = unsafe { &*self.dirty.get() };
224 m.iter()
225 }
226
227 pub fn dirty_ref(&self) -> &HashMap<K, V> {
229 unsafe { &*self.dirty.get() }
230 }
231
232 pub fn into_inner(self) -> HashMap<K, V> {
234 self.dirty.into_inner()
235 }
236
237 #[inline]
239 pub fn keys(&self) -> Keys<'_, K, V> {
240 let _lock = self.lock.read();
241 let m = unsafe { &*self.dirty.get() };
242 m.keys()
243 }
244
245 #[inline]
247 pub fn values(&self) -> Values<'_, K, V> {
248 let _lock = self.lock.read();
249 let m = unsafe { &*self.dirty.get() };
250 m.values()
251 }
252
253 #[inline]
255 pub fn values_mut(&self) -> ValuesMut<'_, K, V> {
256 let _lock = self.lock.write();
257 let m = unsafe { &mut *self.dirty.get() };
258 m.values_mut()
259 }
260
261 #[inline]
263 pub fn retain<F>(&self, f: F)
264 where
265 F: FnMut(&K, &mut V) -> bool,
266 {
267 let _lock = self.lock.write();
268 let m = unsafe { &mut *self.dirty.get() };
269 m.retain(f);
270 }
271
272 #[inline]
274 pub fn capacity(&self) -> usize {
275 let _lock = self.lock.read();
276 let m = unsafe { &*self.dirty.get() };
277 m.capacity()
278 }
279
280 #[inline]
282 pub fn reserve(&self, additional: usize) {
283 let _lock = self.lock.write();
284 let m = unsafe { &mut *self.dirty.get() };
285 m.reserve(additional);
286 }
287
288 #[inline]
290 pub fn remove_entry(&self, k: &K) -> Option<(K, V)> {
291 let _lock = self.lock.write();
292 let m = unsafe { &mut *self.dirty.get() };
293 m.remove_entry(k)
294 }
295
296 #[inline]
298 pub fn get_or_insert(&self, k: K, default: V) -> &mut V {
299 let _lock = self.lock.write();
300 let m = unsafe { &mut *self.dirty.get() };
301 m.entry(k).or_insert(default)
302 }
303
304 #[inline]
306 pub fn get_or_insert_with<F>(&self, k: K, default: F) -> &mut V
307 where
308 F: FnOnce() -> V,
309 {
310 let _lock = self.lock.write();
311 let m = unsafe { &mut *self.dirty.get() };
312 m.entry(k).or_insert_with(default)
313 }
314}
315
316pub struct SyncMapRefMut<'a, K, V> {
318 _lock: RwLockWriteGuard<'a, ()>,
320 value: &'a mut V,
322 _phantom: std::marker::PhantomData<K>,
324}
325
326impl<'a, K, V> Deref for SyncMapRefMut<'a, K, V> {
327 type Target = V;
328
329 fn deref(&self) -> &Self::Target {
330 self.value
331 }
332}
333
334impl<'a, K, V> DerefMut for SyncMapRefMut<'a, K, V> {
335 fn deref_mut(&mut self) -> &mut Self::Target {
336 self.value
337 }
338}
339
340impl<'a, K, V> Debug for SyncMapRefMut<'a, K, V>
341where
342 V: Debug,
343{
344 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
345 self.value.fmt(f)
346 }
347}
348
349impl<'a, K, V> PartialEq for SyncMapRefMut<'a, K, V>
350where
351 V: PartialEq,
352{
353 fn eq(&self, other: &Self) -> bool {
354 (*self.value).eq(&*other.value)
356 }
357}
358
359impl<'a, K, V> Eq for SyncMapRefMut<'a, K, V> where V: Eq {}
360
361pub struct IterMy<'a, K, V> {
363 inner: MapIter<'a, K, V>,
365}
366
367impl<'a, K, V> Deref for IterMy<'a, K, V> {
368 type Target = MapIter<'a, K, V>;
369
370 fn deref(&self) -> &Self::Target {
371 &self.inner
372 }
373}
374
375impl<'a, K, V> Iterator for IterMy<'a, K, V> {
376 type Item = (&'a K, &'a V);
377
378 fn next(&mut self) -> Option<Self::Item> {
379 self.inner.next()
380 }
381}
382
383pub struct IterMut<'a, K, V> {
385 _lock: RwLockWriteGuard<'a, ()>,
387 inner: MapIterMut<'a, K, V>,
389}
390
391impl<'a, K, V> Deref for IterMut<'a, K, V> {
392 type Target = MapIterMut<'a, K, V>;
393
394 fn deref(&self) -> &Self::Target {
395 &self.inner
396 }
397}
398
399impl<'a, K, V> DerefMut for IterMut<'a, K, V> {
400 fn deref_mut(&mut self) -> &mut Self::Target {
401 &mut self.inner
402 }
403}
404
405impl<'a, K, V> Iterator for IterMut<'a, K, V> {
406 type Item = (&'a K, &'a mut V);
407
408 fn next(&mut self) -> Option<Self::Item> {
409 self.inner.next()
410 }
411}
412
413impl<'a, K, V> IntoIterator for &'a SyncHashMap<K, V>
414where
415 K: Eq + Hash,
416{
417 type Item = (&'a K, &'a V);
418 type IntoIter = MapIter<'a, K, V>;
419
420 fn into_iter(self) -> Self::IntoIter {
421 self.iter()
422 }
423}
424
425impl<K, V> IntoIterator for SyncHashMap<K, V>
426where
427 K: Eq + Hash,
428{
429 type Item = (K, V);
430 type IntoIter = MapIntoIter<K, V>;
431
432 fn into_iter(self) -> Self::IntoIter {
433 self.into_inner().into_iter()
434 }
435}
436
437impl<K, V> From<HashMap<K, V>> for SyncHashMap<K, V>
438where
439 K: Eq + Hash,
440{
441 fn from(map: HashMap<K, V>) -> Self {
442 Self::from(map)
443 }
444}
445
446impl<K, V> Serialize for SyncHashMap<K, V>
447where
448 K: Eq + Hash + Serialize,
449 V: Serialize,
450{
451 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
452 where
453 S: Serializer,
454 {
455 let _lock = self.lock.read();
456 let m = unsafe { &*self.dirty.get() };
457 m.serialize(serializer)
458 }
459}
460
461impl<'de, K, V> Deserialize<'de> for SyncHashMap<K, V>
462where
463 K: Eq + Hash + Deserialize<'de>,
464 V: Deserialize<'de>,
465{
466 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
467 where
468 D: Deserializer<'de>,
469 {
470 let m = HashMap::deserialize(deserializer)?;
471 Ok(Self::from(m))
472 }
473}
474
475impl<K, V> Debug for SyncHashMap<K, V>
476where
477 K: Eq + Hash + Debug,
478 V: Debug,
479{
480 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
481 let _lock = self.lock.read();
482 let m = unsafe { &*self.dirty.get() };
483 m.fmt(f)
484 }
485}
486
487impl<K, V> Clone for SyncHashMap<K, V>
488where
489 K: Clone + Eq + Hash,
490 V: Clone,
491{
492 fn clone(&self) -> Self {
493 let _lock = self.lock.read();
494 let c = unsafe { &*self.dirty.get() }.clone();
495 SyncHashMap::from(c)
496 }
497}
498
499impl<K, V> Default for SyncHashMap<K, V>
500where
501 K: Eq + Hash,
502{
503 fn default() -> Self {
504 Self::new()
505 }
506}
507
508impl<K, V> PartialEq for SyncHashMap<K, V>
509where
510 K: Eq + Hash,
511 V: PartialEq,
512{
513 fn eq(&self, other: &Self) -> bool {
514 let _lock_self = self.lock.read();
515 let _lock_other = other.lock.read();
516 let self_map = unsafe { &*self.dirty.get() };
517 let other_map = unsafe { &*other.dirty.get() };
518 self_map.eq(other_map)
519 }
520}
521
522impl<K, V> Eq for SyncHashMap<K, V>
523where
524 K: Eq + Hash,
525 V: Eq,
526{
527}
528
529pub mod buckets {
531 use super::{SyncHashMap, SyncMapRefMut};
532 use std::hash::{Hash, Hasher};
533
534 #[derive(Debug, Clone)]
536 pub struct SyncHashMapB<K, V>
537 where
538 K: Eq + Hash,
539 {
540 inner: Vec<SyncHashMap<K, V>>,
542 len: usize,
544 }
545
546 impl<K, V> SyncHashMapB<K, V>
547 where
548 K: Eq + Hash,
549 {
550 pub fn new(bucket_count: Option<usize>) -> Self {
567 let count = bucket_count.unwrap_or(10);
568 let mut arr = Vec::with_capacity(count);
569 for _ in 0..count {
570 arr.push(SyncHashMap::new());
571 }
572 Self {
573 inner: arr,
574 len: count,
575 }
576 }
577
578 fn key_to_bucket_index(&self, k: &K) -> usize {
580 let mut hasher = std::collections::hash_map::DefaultHasher::new();
581 k.hash(&mut hasher);
582 let hash = hasher.finish();
583 (hash % self.len as u64) as usize
584 }
585
586 #[inline]
588 pub fn insert(&self, k: K, v: V) -> Option<V> {
589 let index = self.key_to_bucket_index(&k);
590 self.inner[index].insert(k, v)
591 }
592
593 #[inline]
595 pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
596 let index = self.key_to_bucket_index(&k);
597 self.inner[index].insert_mut(k, v)
598 }
599
600 #[inline]
602 pub fn remove(&self, k: &K) -> Option<V> {
603 let index = self.key_to_bucket_index(k);
604 self.inner[index].remove(k)
605 }
606
607 #[inline]
609 pub fn is_empty(&self) -> bool {
610 self.inner.iter().all(|bucket| bucket.is_empty())
611 }
612
613 #[inline]
615 pub fn len(&self) -> usize {
616 self.inner.iter().map(|bucket| bucket.len()).sum()
617 }
618
619 #[inline]
621 pub fn clear(&self) {
622 self.inner.iter().for_each(|bucket| bucket.clear());
623 }
624
625 #[inline]
627 pub fn get(&self, k: &K) -> Option<&V> {
628 let index = self.key_to_bucket_index(k);
629 self.inner[index].get(k)
630 }
631
632 #[inline]
634 pub fn get_mut(&self, k: &K) -> Option<SyncMapRefMut<'_, K, V>> {
635 let index = self.key_to_bucket_index(k);
636 self.inner[index].get_mut(k)
637 }
638
639 #[inline]
641 pub fn bucket_count(&self) -> usize {
642 self.len
643 }
644
645 #[inline]
647 pub fn keys(&self) -> impl Iterator<Item = &K> {
648 self.inner.iter().flat_map(|bucket| bucket.keys())
649 }
650
651 #[inline]
653 pub fn values(&self) -> impl Iterator<Item = &V> {
654 self.inner.iter().flat_map(|bucket| bucket.values())
655 }
656
657 #[inline]
659 pub fn values_mut(&self) -> impl Iterator<Item = &mut V> {
660 self.inner.iter().flat_map(|bucket| bucket.values_mut())
661 }
662 }
663
664 impl<K, V> Default for SyncHashMapB<K, V>
665 where
666 K: Eq + Hash,
667 {
668 fn default() -> Self {
669 Self::new(None)
670 }
671 }
672}
673
674#[cfg(test)]
675mod tests {
676 use super::*;
677 use std::collections::HashMap;
678 use std::sync::Arc;
679 use std::thread;
680
681 #[test]
682 fn test_sync_hash_map_new() {
683 let map: SyncHashMap<i32, String> = SyncHashMap::new();
684 assert_eq!(map.len(), 0);
685 assert!(map.is_empty());
686 }
687
688 #[test]
689 fn test_sync_hash_map_with_capacity() {
690 let map = SyncHashMap::<i32, String>::with_capacity(100);
691 assert!(map.capacity() >= 100);
692 }
693
694 #[test]
695 fn test_sync_hash_map_with_map() {
696 let mut original = HashMap::new();
697 original.insert(1, "one".to_string());
698 original.insert(2, "two".to_string());
699
700 let map = SyncHashMap::with_map(original);
701 assert_eq!(map.len(), 2);
702 assert_eq!(map.get(&1), Some(&"one".to_string()));
703 assert_eq!(map.get(&2), Some(&"two".to_string()));
704 }
705
706 #[test]
707 fn test_sync_hash_map_insert_and_get() {
708 let map = SyncHashMap::new();
709
710 assert_eq!(map.insert(1, "one".to_string()), None);
712 assert_eq!(map.insert(2, "two".to_string()), None);
713 assert_eq!(map.len(), 2);
714
715 assert_eq!(map.get(&1), Some(&"one".to_string()));
716 assert_eq!(map.get(&2), Some(&"two".to_string()));
717 assert_eq!(map.get(&3), None);
718 }
719
720 #[test]
721 fn test_sync_hash_map_insert_replace() {
722 let map = SyncHashMap::new();
723
724 assert_eq!(map.insert(1, "one".to_string()), None);
725 assert_eq!(map.insert(1, "updated".to_string()), Some("one".to_string()));
726 assert_eq!(map.get(&1), Some(&"updated".to_string()));
727 }
728
729 #[test]
730 fn test_sync_hash_map_remove() {
731 let map = SyncHashMap::new();
732
733 map.insert(1, "one".to_string());
734 map.insert(2, "two".to_string());
735
736 assert_eq!(map.remove(&1), Some("one".to_string()));
737 assert_eq!(map.remove(&1), None);
738 assert_eq!(map.len(), 1);
739 assert_eq!(map.get(&1), None);
740 assert_eq!(map.get(&2), Some(&"two".to_string()));
741 }
742
743 #[test]
744 fn test_sync_hash_map_contains_key() {
745 let map = SyncHashMap::new();
746
747 map.insert(1, "one".to_string());
748
749 assert!(map.contains_key(&1));
750 assert!(!map.contains_key(&2));
751 }
752
753 #[test]
754 fn test_sync_hash_map_clear() {
755 let map = SyncHashMap::new();
756
757 map.insert(1, "one".to_string());
758 map.insert(2, "two".to_string());
759
760 assert_eq!(map.len(), 2);
761 map.clear();
762 assert_eq!(map.len(), 0);
763 assert!(map.is_empty());
764 }
765
766 #[test]
767 fn test_sync_hash_map_capacity_operations() {
768 let map = SyncHashMap::new();
769
770 assert_eq!(map.capacity(), 0);
771 map.reserve(100);
772 assert!(map.capacity() >= 100);
773
774 map.insert(1, "one".to_string());
775 map.insert(2, "two".to_string());
776
777 let old_capacity = map.capacity();
778 map.shrink_to_fit();
779 assert!(map.capacity() <= old_capacity);
780 }
781
782 #[test]
783 fn test_sync_hash_map_retain() {
784 let map = SyncHashMap::new();
785
786 map.insert(1, "one".to_string());
787 map.insert(2, "two".to_string());
788 map.insert(3, "three".to_string());
789
790 map.retain(|&k, _| k % 2 == 1);
791
792 assert_eq!(map.len(), 2);
793 assert!(map.contains_key(&1));
794 assert!(!map.contains_key(&2));
795 assert!(map.contains_key(&3));
796 }
797
798 #[test]
799 fn test_sync_hash_map_get_or_insert() {
800 let map = SyncHashMap::new();
801
802 let value = map.get_or_insert(1, "default".to_string());
804 assert_eq!(value, "default");
805 assert_eq!(map.len(), 1);
806
807 let value = map.get_or_insert(1, "new_default".to_string());
809 assert_eq!(value, "default");
810 assert_eq!(map.len(), 1);
811 }
812
813 #[test]
814 fn test_sync_hash_map_get_or_insert_with() {
815 let map = SyncHashMap::new();
816
817 let value = map.get_or_insert_with(1, || "computed".to_string());
818 assert_eq!(value, "computed");
819 assert_eq!(map.len(), 1);
820
821 let value = map.get_or_insert_with(1, || "new_computed".to_string());
822 assert_eq!(value, "computed");
823 }
824
825 #[test]
826 fn test_sync_hash_map_remove_entry() {
827 let map = SyncHashMap::new();
828
829 map.insert(1, "one".to_string());
830 map.insert(2, "two".to_string());
831
832 let removed = map.remove_entry(&1);
833 assert_eq!(removed, Some((1, "one".to_string())));
834 assert_eq!(map.len(), 1);
835 assert!(!map.contains_key(&1));
836 }
837
838 #[test]
839 fn test_sync_hash_map_iterators() {
840 let map = SyncHashMap::new();
841
842 map.insert(1, "one".to_string());
843 map.insert(2, "two".to_string());
844 map.insert(3, "three".to_string());
845
846 let keys: Vec<_> = map.keys().collect();
848 assert!(keys.contains(&&1));
849 assert!(keys.contains(&&2));
850 assert!(keys.contains(&&3));
851
852 let values: Vec<_> = map.values().collect();
854 assert!(values.contains(&&"one".to_string()));
855 assert!(values.contains(&&"two".to_string()));
856 assert!(values.contains(&&"three".to_string()));
857
858 let mut count = 0;
860 for (k, v) in map.iter() {
861 count += 1;
862 assert!(map.contains_key(k));
863 assert_eq!(map.get(k), Some(v));
864 }
865 assert_eq!(count, 3);
866 }
867
868 #[test]
869 fn test_sync_hash_map_iter_mut() {
870 let map = SyncHashMap::new();
871
872 map.insert(1, "one".to_string());
873 map.insert(2, "two".to_string());
874
875 for (k, v) in map.iter_mut() {
876 if *k == 1 {
877 *v = "modified".to_string();
878 }
879 }
880
881 assert_eq!(map.get(&1), Some(&"modified".to_string()));
882 assert_eq!(map.get(&2), Some(&"two".to_string()));
883 }
884
885 #[test]
886 fn test_sync_hash_map_values_mut() {
887 let map = SyncHashMap::new();
888
889 map.insert(1, "one".to_string());
890 map.insert(2, "two".to_string());
891
892 for v in map.values_mut() {
893 if v == "one" {
894 *v = "modified".to_string();
895 }
896 }
897
898 assert_eq!(map.get(&1), Some(&"modified".to_string()));
899 assert_eq!(map.get(&2), Some(&"two".to_string()));
900 }
901
902 #[test]
903 fn test_sync_hash_map_index() {
904 let map = SyncHashMap::new();
905 map.insert(1, "one".to_string());
906
907 assert_eq!(map[&1], "one");
909 }
910
911 #[test]
912 fn test_sync_hash_map_clone() {
913 let map1 = SyncHashMap::new();
914 map1.insert(1, "one".to_string());
915 map1.insert(2, "two".to_string());
916
917 let map2 = map1.clone();
918
919 assert_eq!(map1.len(), map2.len());
920 assert_eq!(map1.get(&1), map2.get(&1));
921 assert_eq!(map1.get(&2), map2.get(&2));
922
923 map1.insert(3, "three".to_string());
925 assert!(!map2.contains_key(&3));
926 }
927
928 #[test]
929 fn test_sync_hash_map_partial_eq() {
930 let map1 = SyncHashMap::new();
931 map1.insert(1, "one".to_string());
932 map1.insert(2, "two".to_string());
933
934 let map2 = SyncHashMap::new();
935 map2.insert(1, "one".to_string());
936 map2.insert(2, "two".to_string());
937
938 let map3 = SyncHashMap::new();
939 map3.insert(1, "different".to_string());
940
941 assert_eq!(map1, map2);
942 assert_ne!(map1, map3);
943 }
944
945 #[test]
946 fn test_sync_hash_map_debug() {
947 let map = SyncHashMap::new();
948 map.insert(1, "one".to_string());
949
950 let debug_str = format!("{:?}", map);
951 assert!(debug_str.contains("1"));
952 assert!(debug_str.contains("one"));
953 }
954
955 #[test]
956 fn test_sync_hash_map_serialization() {
957 let map = SyncHashMap::new();
958 map.insert(1, "one".to_string());
959 map.insert(2, "two".to_string());
960
961 let serialized = serde_json::to_string(&map).unwrap();
963 assert!(serialized.contains("1"));
964 assert!(serialized.contains("one"));
965 assert!(serialized.contains("2"));
966 assert!(serialized.contains("two"));
967
968 let deserialized: SyncHashMap<i32, String> = serde_json::from_str(&serialized).unwrap();
970 assert_eq!(deserialized.len(), 2);
971 assert_eq!(deserialized.get(&1), Some(&"one".to_string()));
972 assert_eq!(deserialized.get(&2), Some(&"two".to_string()));
973 }
974
975 #[test]
976 fn test_sync_hash_map_from_hashmap() {
977 let mut original = HashMap::new();
978 original.insert(1, "one".to_string());
979 original.insert(2, "two".to_string());
980
981 let map = SyncHashMap::from(original);
982
983 assert_eq!(map.len(), 2);
984 assert_eq!(map.get(&1), Some(&"one".to_string()));
985 assert_eq!(map.get(&2), Some(&"two".to_string()));
986 }
987
988 #[test]
989 fn test_sync_hash_map_into_iterator() {
990 let map = SyncHashMap::new();
991 map.insert(1, "one".to_string());
992 map.insert(2, "two".to_string());
993
994 let mut count = 0;
996 for (k, v) in &map {
997 count += 1;
998 assert!(map.contains_key(k));
999 assert_eq!(map.get(k), Some(v));
1000 }
1001 assert_eq!(count, 2);
1002
1003 let owned_pairs: Vec<_> = map.into_iter().collect();
1005 assert_eq!(owned_pairs.len(), 2);
1006 }
1007
1008 #[test]
1009 fn test_sync_hash_map_default() {
1010 let map: SyncHashMap<i32, String> = Default::default();
1011 assert_eq!(map.len(), 0);
1012 assert!(map.is_empty());
1013 }
1014
1015 #[test]
1016 fn test_sync_hash_map_arc() {
1017 let map = SyncHashMap::new_arc();
1018 map.insert(1, "one".to_string());
1019
1020 assert_eq!(map.get(&1), Some(&"one".to_string()));
1021
1022 let map2 = Arc::clone(&map);
1023 map2.insert(2, "two".to_string());
1024
1025 assert_eq!(map.get(&2), Some(&"two".to_string()));
1026 }
1027
1028 #[test]
1029 fn test_sync_hash_map_get_mut() {
1030 let map = SyncHashMap::new();
1031 map.insert(1, "one".to_string());
1032
1033 {
1034 let mut value = map.get_mut(&1).unwrap();
1035 *value = "modified".to_string();
1036 }
1037
1038 assert_eq!(map.get(&1), Some(&"modified".to_string()));
1039 }
1040
1041 #[test]
1042 fn test_sync_hash_map_concurrent_access() {
1043 let map = Arc::new(SyncHashMap::new());
1044
1045 let handles: Vec<_> = (0..10).map(|i| {
1047 let map = Arc::clone(&map);
1048 thread::spawn(move || {
1049 map.insert(i, format!("value_{}", i));
1050 })
1051 }).collect();
1052
1053 for handle in handles {
1054 handle.join().unwrap();
1055 }
1056
1057 assert_eq!(map.len(), 10);
1059 for i in 0..10 {
1060 assert_eq!(map.get(&i), Some(&format!("value_{}", i)));
1061 }
1062
1063 let map_read = Arc::clone(&map);
1065 let handles: Vec<_> = (0..10).map(|i| {
1066 let map = Arc::clone(&map_read);
1067 thread::spawn(move || {
1068 let value = map.get(&i);
1069 assert_eq!(value, Some(&format!("value_{}", i)));
1070 })
1071 }).collect();
1072
1073 for handle in handles {
1074 handle.join().unwrap();
1075 }
1076 }
1077
1078 #[test]
1079 fn test_sync_hash_map_dirty_ref() {
1080 let map = SyncHashMap::new();
1081 map.insert(1, "one".to_string());
1082
1083 let dirty = map.dirty_ref();
1084 assert_eq!(dirty.len(), 1);
1085 assert_eq!(dirty.get(&1), Some(&"one".to_string()));
1086 }
1087
1088 #[test]
1089 fn test_sync_hash_map_into_inner() {
1090 let map = SyncHashMap::new();
1091 map.insert(1, "one".to_string());
1092 map.insert(2, "two".to_string());
1093
1094 let inner = map.into_inner();
1095 assert_eq!(inner.len(), 2);
1096 assert_eq!(inner.get(&1), Some(&"one".to_string()));
1097 assert_eq!(inner.get(&2), Some(&"two".to_string()));
1098 }
1099
1100 #[test]
1101 fn test_sync_hash_map_guard_debug() {
1102 let map = SyncHashMap::new();
1103 map.insert(1, "test".to_string());
1104
1105 let guard = map.get(&1).unwrap();
1106 let debug_str = format!("{:?}", guard);
1107 assert!(debug_str.contains("test"));
1108 }
1109
1110 #[test]
1111 fn test_sync_hash_map_guard_partial_eq() {
1112 let map = SyncHashMap::new();
1113 map.insert(1, "value".to_string());
1114
1115 let guard1 = map.get(&1).unwrap();
1116 let guard2 = map.get(&1).unwrap();
1117
1118 assert_eq!(guard1, guard2);
1119 }
1120
1121 mod buckets_tests {
1123 use super::*;
1124
1125 #[test]
1126 fn test_sync_hash_map_buckets_new() {
1127 let map = buckets::SyncHashMapB::<i32, String>::new(None);
1128 assert_eq!(map.len(), 0);
1129 assert!(map.is_empty());
1130 assert_eq!(map.bucket_count(), 10); }
1132
1133 #[test]
1134 fn test_sync_hash_map_buckets_with_custom_size() {
1135 let map = buckets::SyncHashMapB::<i32, String>::new(Some(5));
1136 assert_eq!(map.bucket_count(), 5);
1137 }
1138
1139 #[test]
1140 fn test_sync_hash_map_buckets_insert_and_get() {
1141 let map = buckets::SyncHashMapB::new(Some(3));
1142
1143 assert_eq!(map.insert(1, "one".to_string()), None);
1144 assert_eq!(map.insert(2, "two".to_string()), None);
1145 assert_eq!(map.len(), 2);
1146
1147 assert_eq!(map.get(&1), Some(&"one".to_string()));
1148 assert_eq!(map.get(&2), Some(&"two".to_string()));
1149 assert_eq!(map.get(&3), None);
1150 }
1151
1152 #[test]
1153 fn test_sync_hash_map_buckets_remove() {
1154 let map = buckets::SyncHashMapB::new(Some(3));
1155
1156 map.insert(1, "one".to_string());
1157 map.insert(2, "two".to_string());
1158
1159 assert_eq!(map.remove(&1), Some("one".to_string()));
1160 assert_eq!(map.len(), 1);
1161 assert_eq!(map.get(&1), None);
1162 assert_eq!(map.get(&2), Some(&"two".to_string()));
1163 }
1164
1165 #[test]
1166 fn test_sync_hash_map_buckets_clear() {
1167 let map = buckets::SyncHashMapB::new(Some(3));
1168
1169 map.insert(1, "one".to_string());
1170 map.insert(2, "two".to_string());
1171
1172 assert_eq!(map.len(), 2);
1173 map.clear();
1174 assert_eq!(map.len(), 0);
1175 assert!(map.is_empty());
1176 }
1177
1178 #[test]
1179 fn test_sync_hash_map_buckets_iterators() {
1180 let map = buckets::SyncHashMapB::new(Some(3));
1181
1182 map.insert(1, "one".to_string());
1183 map.insert(2, "two".to_string());
1184 map.insert(3, "three".to_string());
1185
1186 let keys: Vec<_> = map.keys().collect();
1188 assert!(keys.contains(&&1));
1189 assert!(keys.contains(&&2));
1190 assert!(keys.contains(&&3));
1191
1192 let values: Vec<_> = map.values().collect();
1194 assert!(values.contains(&&"one".to_string()));
1195 assert!(values.contains(&&"two".to_string()));
1196 assert!(values.contains(&&"three".to_string()));
1197
1198 for v in map.values_mut() {
1200 if v == "one" {
1201 *v = "modified".to_string();
1202 }
1203 }
1204
1205 assert_eq!(map.get(&1), Some(&"modified".to_string()));
1206 }
1207
1208 #[test]
1209 fn test_sync_hash_map_buckets_default() {
1210 let map: buckets::SyncHashMapB<i32, String> = Default::default();
1211 assert_eq!(map.len(), 0);
1212 assert!(map.is_empty());
1213 assert_eq!(map.bucket_count(), 10);
1214 }
1215
1216 #[test]
1217 fn test_sync_hash_map_buckets_debug() {
1218 let map = buckets::SyncHashMapB::new(Some(2));
1219 map.insert(1, "one".to_string());
1220
1221 let debug_str = format!("{:?}", map);
1222 assert!(debug_str.contains("1"));
1223 assert!(debug_str.contains("one"));
1224 }
1225 }
1226
1227 #[test]
1228 fn test_sync_hash_map_comprehensive() {
1229 let map = SyncHashMap::new();
1230
1231 map.insert("key1", 42);
1233 map.insert("key2", 24);
1234
1235 assert_eq!(map.len(), 2);
1236 assert!(!map.is_empty());
1237
1238 *map.get_mut("key1").unwrap() = 100;
1240 assert_eq!(map.get(&"key1"), Some(&100));
1241
1242 map.insert("key3", 50);
1244 map.retain(|_, &mut v| v > 30);
1245
1246 assert_eq!(map.len(), 2);
1247 assert_eq!(map.get(&"key1"), Some(&100));
1248 assert_eq!(map.get(&"key2"), None);
1249 assert_eq!(map.get(&"key3"), Some(&50));
1250
1251 let map2 = map.clone();
1253 assert_eq!(map, map2);
1254
1255 let mut sum = 0;
1257 for (_, v) in map.iter() {
1258 sum += v;
1259 }
1260 assert_eq!(sum, 150);
1261
1262 map.clear();
1264 assert_eq!(map.len(), 0);
1265 assert!(map.is_empty());
1266 }
1267}