fast_able/
map_hash.rs

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
13/// 同步哈希映射,支持多读少写的场景
14/// this sync map used to many reader, writer less. space-for-time strategy
15pub struct SyncHashMap<K, V> {
16    /// 底层数据存储,使用UnsafeCell避免锁开销
17    dirty: UnsafeCell<HashMap<K, V>>,
18    /// 读写锁,用于保护并发访问
19    lock: RwLock<()>,
20}
21
22/// 标记为Send,因为使用了UnsafeCell但有锁保护
23/// this is safety, dirty mutex ensure
24unsafe impl<K, V> Send for SyncHashMap<K, V> {}
25
26/// 标记为Sync,因为使用了UnsafeCell但有锁保护
27/// this is safety, dirty mutex ensure
28unsafe impl<K, V> Sync for SyncHashMap<K, V> {}
29
30/// 索引操作,无锁访问(unsafe但在单线程场景下高效)
31impl<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    /// 创建一个新的Arc包装的SyncHashMap
47    pub fn new_arc() -> Arc<Self> {
48        Arc::new(Self::new())
49    }
50
51    /// 创建一个新的空映射
52    pub fn new() -> Self {
53        Self {
54            dirty: UnsafeCell::new(HashMap::new()),
55            lock: RwLock::new(()),
56        }
57    }
58
59    /// 使用指定容量创建一个新的映射
60    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    /// 使用现有的HashMap创建一个同步映射
68    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    /// 插入键值对,使用写锁保护
76    #[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    /// 可变引用下的插入操作,无锁保护(调用者需确保线程安全)
84    #[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    /// 移除键值对,使用写锁保护
91    #[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    /// 可变引用下的移除操作,无锁保护(调用者需确保线程安全)
99    #[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    /// 获取映射长度,使用读锁保护
106    #[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    /// 判断映射是否为空,使用读锁保护
114    #[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    /// 清空映射,使用写锁保护
122    #[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    /// 可变引用下的清空操作,无锁保护(调用者需确保线程安全)
130    #[inline(always)]
131    pub fn clear_mut(&mut self) {
132        let m = unsafe { &mut *self.dirty.get() };
133        m.clear();
134    }
135
136    /// 收缩容量以适应元素数量,使用写锁保护
137    #[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    /// 可变引用下的收缩容量操作,无锁保护(调用者需确保线程安全)
145    #[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    /// 从HashMap创建SyncHashMap的便捷方法
152    pub fn from(map: HashMap<K, V>) -> Self {
153        Self::with_map(map)
154    }
155
156    /// 获取键对应的值引用,使用读锁保护
157    ///
158    /// 键可以是映射键类型的任何借用形式,但借用形式的 [`Hash`] 和 [`Eq`] 必须与键类型匹配。
159    ///
160    /// # Examples
161    ///
162    /// ```
163    /// use fast_able::SyncHashMap;
164    ///
165    /// let map = SyncHashMap::new();
166    /// map.insert(1, "a");
167    /// assert_eq!(map.get(&1), Some(&"a"));
168    /// assert_eq!(map.get(&2), None);
169    /// ```
170    #[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    /// 获取键对应的可变值引用,使用写锁保护
182    #[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    /// 检查是否包含指定的键,使用读锁保护
199    #[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    /// 获取可变迭代器,使用写锁保护
211    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    /// 获取只读迭代器,使用读锁保护
221    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    /// 获取底层HashMap的引用(unsafe,调用者需确保无其他写操作)
228    pub fn dirty_ref(&self) -> &HashMap<K, V> {
229        unsafe { &*self.dirty.get() }
230    }
231
232    /// 消耗self并返回内部的HashMap
233    pub fn into_inner(self) -> HashMap<K, V> {
234        self.dirty.into_inner()
235    }
236
237    /// 获取键的迭代器,使用读锁保护
238    #[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    /// 获取值的只读迭代器,使用读锁保护
246    #[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    /// 获取值的可变迭代器,使用写锁保护
254    #[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    /// 保留满足条件的元素,使用写锁保护
262    #[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    /// 获取映射的容量,使用读锁保护
273    #[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    /// 预留指定容量,使用写锁保护
281    #[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    /// 尝试移除键值对,如果键存在则返回被移除的值,使用写锁保护
289    #[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    /// 如果键存在则返回其可变引用,否则插入新值,使用写锁保护
297    #[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    /// 如果键存在则返回其可变引用,否则使用函数返回值插入,使用写锁保护
305    #[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
316/// 可变值引用的守护者,持有写锁
317pub struct SyncMapRefMut<'a, K, V> {
318    /// 写锁守护者
319    _lock: RwLockWriteGuard<'a, ()>,
320    /// 可变值引用
321    value: &'a mut V,
322    /// 用于标记键类型(编译时使用)
323    _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        // 避免直接比较可变引用,改用引用比较
355        (*self.value).eq(&*other.value)
356    }
357}
358
359impl<'a, K, V> Eq for SyncMapRefMut<'a, K, V> where V: Eq {}
360
361/// 自定义迭代器包装器(主要用于兼容性)
362pub struct IterMy<'a, K, V> {
363    /// 内部迭代器
364    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
383/// 可变迭代器的守护者,持有写锁
384pub struct IterMut<'a, K, V> {
385    /// 写锁守护者
386    _lock: RwLockWriteGuard<'a, ()>,
387    /// 内部可变迭代器
388    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
529/// 分桶哈希映射模块,提供更高并发的哈希映射实现
530pub mod buckets {
531    use super::{SyncHashMap, SyncMapRefMut};
532    use std::hash::{Hash, Hasher};
533
534    /// 分桶哈希映射,将数据分散到多个子映射中以提高并发性能
535    #[derive(Debug, Clone)]
536    pub struct SyncHashMapB<K, V>
537    where
538        K: Eq + Hash,
539    {
540        /// 内部的子映射数组
541        inner: Vec<SyncHashMap<K, V>>,
542        /// 分桶数量
543        len: usize,
544    }
545
546    impl<K, V> SyncHashMapB<K, V>
547    where
548        K: Eq + Hash,
549    {
550        /// 创建新的分桶哈希映射
551        ///
552        /// # Arguments
553        /// * `bucket_count` - 分桶数量,如果为None则默认为10
554        ///
555        /// # Examples
556        /// ```
557        /// use fast_able::map_hash::buckets::SyncHashMapB;
558        ///
559        /// let map = SyncHashMapB::new(None);
560        /// map.insert(1, "a");
561        /// map.insert(2, "b");
562        /// assert_eq!(map.get(&1), Some(&"a"));
563        /// assert_eq!(map.get(&2), Some(&"b"));
564        /// assert_eq!(map.get(&3), None);
565        /// ```
566        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        /// 将键转换为桶索引
579        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        /// 插入键值对
587        #[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        /// 可变引用下的插入操作
594        #[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        /// 移除键值对
601        #[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        /// 检查是否为空
608        #[inline]
609        pub fn is_empty(&self) -> bool {
610            self.inner.iter().all(|bucket| bucket.is_empty())
611        }
612
613        /// 获取总长度
614        #[inline]
615        pub fn len(&self) -> usize {
616            self.inner.iter().map(|bucket| bucket.len()).sum()
617        }
618
619        /// 清空所有桶
620        #[inline]
621        pub fn clear(&self) {
622            self.inner.iter().for_each(|bucket| bucket.clear());
623        }
624
625        /// 获取键对应的值引用
626        #[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        /// 获取键对应的可变值引用
633        #[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        /// 获取桶数量
640        #[inline]
641        pub fn bucket_count(&self) -> usize {
642            self.len
643        }
644
645        /// 获取所有键的迭代器
646        #[inline]
647        pub fn keys(&self) -> impl Iterator<Item = &K> {
648            self.inner.iter().flat_map(|bucket| bucket.keys())
649        }
650
651        /// 获取所有值的只读迭代器
652        #[inline]
653        pub fn values(&self) -> impl Iterator<Item = &V> {
654            self.inner.iter().flat_map(|bucket| bucket.values())
655        }
656
657        /// 获取所有值的可变迭代器(注意:这是一个简化实现,返回值的锁可能不够严格)
658        #[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        // 测试插入和获取
711        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        // 键不存在时插入
803        let value = map.get_or_insert(1, "default".to_string());
804        assert_eq!(value, "default");
805        assert_eq!(map.len(), 1);
806
807        // 键存在时返回现有值
808        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        // 测试 keys 迭代器
847        let keys: Vec<_> = map.keys().collect();
848        assert!(keys.contains(&&1));
849        assert!(keys.contains(&&2));
850        assert!(keys.contains(&&3));
851
852        // 测试 values 迭代器
853        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        // 测试 iter 迭代器
859        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        // 测试索引访问
908        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        // 修改原映射不影响克隆
924        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        // 测试序列化
962        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        // 测试反序列化
969        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        // 测试 IntoIterator for &SyncHashMap
995        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        // 测试 IntoIterator for SyncHashMap
1004        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        // 并发写入测试
1046        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        // 验证所有值都被插入
1058        assert_eq!(map.len(), 10);
1059        for i in 0..10 {
1060            assert_eq!(map.get(&i), Some(&format!("value_{}", i)));
1061        }
1062
1063        // 并发读取测试
1064        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    // 分桶映射测试
1122    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); // 默认桶数量
1131        }
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            // 测试 keys 迭代器
1187            let keys: Vec<_> = map.keys().collect();
1188            assert!(keys.contains(&&1));
1189            assert!(keys.contains(&&2));
1190            assert!(keys.contains(&&3));
1191
1192            // 测试 values 迭代器
1193            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            // 测试 values_mut 迭代器
1199            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        // 测试各种操作的组合
1232        map.insert("key1", 42);
1233        map.insert("key2", 24);
1234
1235        assert_eq!(map.len(), 2);
1236        assert!(!map.is_empty());
1237
1238        // 测试修改操作
1239        *map.get_mut("key1").unwrap() = 100;
1240        assert_eq!(map.get(&"key1"), Some(&100));
1241
1242        // 测试条件保留
1243        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        // 测试克隆和比较
1252        let map2 = map.clone();
1253        assert_eq!(map, map2);
1254
1255        // 测试迭代
1256        let mut sum = 0;
1257        for (_, v) in map.iter() {
1258            sum += v;
1259        }
1260        assert_eq!(sum, 150);
1261
1262        // 测试清空
1263        map.clear();
1264        assert_eq!(map.len(), 0);
1265        assert!(map.is_empty());
1266    }
1267}