fast_able/
map_hash.rs

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, IterMut as MapIterMut, Keys, Values, ValuesMut,
7};
8use std::collections::HashMap;
9use std::fmt::{Debug, Formatter};
10use std::hash::Hash;
11use std::ops::{Deref, DerefMut};
12use std::sync::{Arc};
13
14/// 同步哈希映射,支持多读少写的场景
15/// this sync map used to many reader, writer less. space-for-time strategy
16pub struct SyncHashMap<K, V> {
17    /// 底层数据存储,使用UnsafeCell避免锁开销
18    dirty: UnsafeCell<HashMap<K, V>>,
19    /// 读写锁,用于保护并发访问
20    lock: RwLock<()>,
21}
22
23/// 标记为Send,因为使用了UnsafeCell但有锁保护
24/// this is safety, dirty mutex ensure
25unsafe impl<K, V> Send for SyncHashMap<K, V> {}
26
27/// 标记为Sync,因为使用了UnsafeCell但有锁保护
28/// this is safety, dirty mutex ensure
29unsafe impl<K, V> Sync for SyncHashMap<K, V> {}
30
31/// 索引操作,无锁访问
32/// 
33/// # Safety
34/// 
35/// 此操作不持有锁,仅应在确保没有并发写入时使用。
36/// 如需线程安全访问,请使用 `get` 方法。
37impl<K, V> std::ops::Index<&K> for SyncHashMap<K, V>
38where
39    K: Eq + Hash,
40{
41    type Output = V;
42
43    fn index(&self, index: &K) -> &Self::Output {
44        unsafe { &(&*self.dirty.get())[index] }
45    }
46}
47
48impl<K, V> SyncHashMap<K, V>
49where
50    K: Eq + Hash,
51{
52    /// 创建一个新的Arc包装的SyncHashMap
53    pub fn new_arc() -> Arc<Self> {
54        Arc::new(Self::new())
55    }
56
57    /// 创建一个新的空映射
58    pub fn new() -> Self {
59        Self {
60            dirty: UnsafeCell::new(HashMap::new()),
61            lock: RwLock::new(()),
62        }
63    }
64
65    /// 使用指定容量创建一个新的映射
66    pub fn with_capacity(capacity: usize) -> Self {
67        Self {
68            dirty: UnsafeCell::new(HashMap::with_capacity(capacity)),
69            lock: RwLock::new(()),
70        }
71    }
72
73    /// 使用现有的HashMap创建一个同步映射
74    pub const fn with_map(map: HashMap<K, V>) -> Self {
75        Self {
76            dirty: UnsafeCell::new(map),
77            lock: RwLock::new(()),
78        }
79    }
80
81    /// 插入键值对,使用写锁保护
82    #[inline(always)]
83    pub fn insert(&self, k: K, v: V) -> Option<V> {
84        let _lock = self.lock.write();
85        let m = unsafe { &mut *self.dirty.get() };
86        m.insert(k, v)
87    }
88
89    /// 可变引用下的插入操作,无锁保护(调用者需确保线程安全)
90    #[inline(always)]
91    pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
92        let m = unsafe { &mut *self.dirty.get() };
93        m.insert(k, v)
94    }
95
96    /// 移除键值对,使用写锁保护
97    #[inline(always)]
98    pub fn remove(&self, k: &K) -> Option<V> {
99        let _lock = self.lock.write();
100        let m = unsafe { &mut *self.dirty.get() };
101        m.remove(k)
102    }
103
104    /// 可变引用下的移除操作,无锁保护(调用者需确保线程安全)
105    #[inline(always)]
106    pub fn remove_mut(&mut self, k: &K) -> Option<V> {
107        let m = unsafe { &mut *self.dirty.get() };
108        m.remove(k)
109    }
110
111    /// 获取映射长度,使用读锁保护
112    #[inline(always)]
113    pub fn len(&self) -> usize {
114        let _lock = self.lock.read();
115        let m = unsafe { &*self.dirty.get() };
116        m.len()
117    }
118
119    /// 判断映射是否为空,使用读锁保护
120    #[inline(always)]
121    pub fn is_empty(&self) -> bool {
122        let _lock = self.lock.read();
123        let m = unsafe { &*self.dirty.get() };
124        m.is_empty()
125    }
126
127    /// 清空映射,使用写锁保护
128    #[inline(always)]
129    pub fn clear(&self) {
130        let _lock = self.lock.write();
131        let m = unsafe { &mut *self.dirty.get() };
132        m.clear();
133    }
134
135    /// 可变引用下的清空操作,无锁保护(调用者需确保线程安全)
136    #[inline(always)]
137    pub fn clear_mut(&mut self) {
138        let m = unsafe { &mut *self.dirty.get() };
139        m.clear();
140    }
141
142    /// 收缩容量以适应元素数量,使用写锁保护
143    #[inline(always)]
144    pub fn shrink_to_fit(&self) {
145        let _lock = self.lock.write();
146        let m = unsafe { &mut *self.dirty.get() };
147        m.shrink_to_fit();
148    }
149
150    /// 可变引用下的收缩容量操作,无锁保护(调用者需确保线程安全)
151    #[inline(always)]
152    pub fn shrink_to_fit_mut(&mut self) {
153        let m = unsafe { &mut *self.dirty.get() };
154        m.shrink_to_fit();
155    }
156
157    /// 从HashMap创建SyncHashMap的便捷方法
158    pub fn from(map: HashMap<K, V>) -> Self {
159        Self::with_map(map)
160    }
161
162    /// 获取键对应的值引用,使用读锁保护
163    ///
164    /// 返回一个 `ReadGuard`,在 guard 被释放前持有读锁,保证并发访问安全。
165    ///
166    /// 键可以是映射键类型的任何借用形式,但借用形式的 [`Hash`] 和 [`Eq`] 必须与键类型匹配。
167    ///
168    /// # Examples
169    ///
170    /// ```
171    /// use fast_able::SyncHashMap;
172    ///
173    /// let map = SyncHashMap::new();
174    /// map.insert(1, "a");
175    /// assert_eq!(*map.get(&1).unwrap(), "a");
176    /// assert!(map.get(&2).is_none());
177    /// ```
178    #[inline]
179    pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<ReadGuard<'_, V>>
180    where
181        K: Borrow<Q>,
182        Q: Hash + Eq,
183    {
184        let _lock = self.lock.read();
185        let m = unsafe { &*self.dirty.get() };
186        let v = m.get(k)?;
187        Some(ReadGuard { _lock, v })
188    }
189
190    /// 获取键对应的值引用(无检查版本),使用读锁保护
191    ///
192    /// # Panics
193    ///
194    /// 如果键不存在则 panic。
195    #[inline]
196    pub fn get_uncheck<Q: ?Sized>(&self, k: &Q) -> ReadGuard<'_, V>
197    where
198        K: Borrow<Q>,
199        Q: Hash + Eq,
200    {
201        let _lock = self.lock.read();
202        let m = unsafe { &*self.dirty.get() };
203        let v = m.get(k).expect("key not found");
204        ReadGuard { _lock, v }
205    }
206
207    /// 获取键对应的可变值引用,使用写锁保护
208    ///
209    /// 返回一个 `WriteGuard`,在 guard 被释放前持有写锁,保证并发访问安全。
210    #[inline]
211    pub fn get_mut<Q: ?Sized>(&self, k: &Q) -> Option<WriteGuard<'_, V>>
212    where
213        K: Borrow<Q>,
214        Q: Hash + Eq,
215    {
216        let _lock = self.lock.write();
217        let m = unsafe { &mut *self.dirty.get() };
218        let v = m.get_mut(k)?;
219        Some(WriteGuard { _lock, v })
220    }
221
222    /// 检查是否包含指定的键,使用读锁保护
223    #[inline]
224    pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
225    where
226        K: Borrow<Q>,
227        Q: Hash + Eq,
228    {
229        let _lock = self.lock.read();
230        let m = unsafe { &*self.dirty.get() };
231        m.contains_key(k)
232    }
233
234    /// 获取可变迭代器,使用写锁保护
235    pub fn iter_mut(&self) -> IterMut<'_, K, V> {
236        let _lock = self.lock.write();
237        let m = unsafe { &mut *self.dirty.get() };
238        IterMut {
239            _lock,
240            inner: m.iter_mut(),
241        }
242    }
243
244    /// 获取只读迭代器,使用读锁保护
245    ///
246    /// 返回的迭代器持有读锁,在迭代期间保证数据不被修改。
247    pub fn iter(&self) -> Iter<'_, K, V> {
248        let _lock = self.lock.read();
249        let m = unsafe { &*self.dirty.get() };
250        Iter {
251            _lock,
252            inner: m.iter(),
253        }
254    }
255
256    /// 获取底层HashMap的只读引用,使用读锁保护
257    ///
258    /// 返回一个 `ReadGuardMap`,在 guard 被释放前持有读锁。
259    pub fn dirty_ref(&self) -> ReadGuardMap<'_, K, V> {
260        let _lock = self.lock.read();
261        let v = unsafe { &*self.dirty.get() };
262        ReadGuardMap { _lock, v }
263    }
264
265    /// 获取底层HashMap的不安全引用(无锁保护)
266    ///
267    /// # Safety
268    ///
269    /// 调用者需确保没有并发写操作。
270    pub unsafe fn dirty_ref_unsafe(&self) -> &HashMap<K, V> {
271        unsafe { &*self.dirty.get() }
272    }
273
274    /// 消耗self并返回内部的HashMap
275    pub fn into_inner(self) -> HashMap<K, V> {
276        self.dirty.into_inner()
277    }
278
279    /// 获取键的迭代器,使用读锁保护
280    ///
281    /// 返回的迭代器持有读锁,在迭代期间保证数据不被修改。
282    #[inline]
283    pub fn keys(&self) -> KeysGuard<'_, K, V> {
284        let _lock = self.lock.read();
285        let m = unsafe { &*self.dirty.get() };
286        KeysGuard {
287            _lock,
288            inner: m.keys(),
289        }
290    }
291
292    /// 获取值的只读迭代器,使用读锁保护
293    ///
294    /// 返回的迭代器持有读锁,在迭代期间保证数据不被修改。
295    #[inline]
296    pub fn values(&self) -> ValuesGuard<'_, K, V> {
297        let _lock = self.lock.read();
298        let m = unsafe { &*self.dirty.get() };
299        ValuesGuard {
300            _lock,
301            inner: m.values(),
302        }
303    }
304
305    /// 获取值的可变迭代器,使用写锁保护
306    ///
307    /// 返回的迭代器持有写锁,在迭代期间保证独占访问。
308    #[inline]
309    pub fn values_mut(&self) -> ValuesMutGuard<'_, K, V> {
310        let _lock = self.lock.write();
311        let m = unsafe { &mut *self.dirty.get() };
312        ValuesMutGuard {
313            _lock,
314            inner: m.values_mut(),
315        }
316    }
317
318    /// 保留满足条件的元素,使用写锁保护
319    #[inline]
320    pub fn retain<F>(&self, f: F)
321    where
322        F: FnMut(&K, &mut V) -> bool,
323    {
324        let _lock = self.lock.write();
325        let m = unsafe { &mut *self.dirty.get() };
326        m.retain(f);
327    }
328
329    /// 获取映射的容量,使用读锁保护
330    #[inline]
331    pub fn capacity(&self) -> usize {
332        let _lock = self.lock.read();
333        let m = unsafe { &*self.dirty.get() };
334        m.capacity()
335    }
336
337    /// 预留指定容量,使用写锁保护
338    #[inline]
339    pub fn reserve(&self, additional: usize) {
340        let _lock = self.lock.write();
341        let m = unsafe { &mut *self.dirty.get() };
342        m.reserve(additional);
343    }
344
345    /// 尝试移除键值对,如果键存在则返回被移除的值,使用写锁保护
346    #[inline]
347    pub fn remove_entry(&self, k: &K) -> Option<(K, V)> {
348        let _lock = self.lock.write();
349        let m = unsafe { &mut *self.dirty.get() };
350        m.remove_entry(k)
351    }
352
353    /// 如果键存在则返回其可变引用,否则插入新值,使用写锁保护
354    ///
355    /// 返回一个 `WriteGuard`,在 guard 被释放前持有写锁,保证并发访问安全。
356    #[inline]
357    pub fn get_or_insert(&self, k: K, default: V) -> WriteGuard<'_, V> {
358        let _lock = self.lock.write();
359        let m = unsafe { &mut *self.dirty.get() };
360        let v = m.entry(k).or_insert(default);
361        WriteGuard { _lock, v }
362    }
363
364    /// 如果键存在则返回其可变引用,否则使用函数返回值插入,使用写锁保护
365    ///
366    /// 返回一个 `WriteGuard`,在 guard 被释放前持有写锁,保证并发访问安全。
367    #[inline]
368    pub fn get_or_insert_with<F>(&self, k: K, default: F) -> WriteGuard<'_, V>
369    where
370        F: FnOnce() -> V,
371    {
372        let _lock = self.lock.write();
373        let m = unsafe { &mut *self.dirty.get() };
374        let v = m.entry(k).or_insert_with(default);
375        WriteGuard { _lock, v }
376    }
377}
378
379/// 只读值引用的守护者,持有读锁
380pub struct ReadGuard<'a, V> {
381    /// 读锁守护者
382    _lock: RwLockReadGuard<'a, ()>,
383    /// 只读值引用
384    v: &'a V,
385}
386
387impl<'a, V> Deref for ReadGuard<'a, V> {
388    type Target = V;
389
390    fn deref(&self) -> &Self::Target {
391        self.v
392    }
393}
394
395impl<'a, V> Debug for ReadGuard<'a, V>
396where
397    V: Debug,
398{
399    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
400        write!(f, "{:?}", self.v)
401    }
402}
403
404impl<'a, V> PartialEq for ReadGuard<'a, V>
405where
406    V: PartialEq,
407{
408    fn eq(&self, other: &Self) -> bool {
409        self.v.eq(other.v)
410    }
411}
412
413impl<'a, V> Eq for ReadGuard<'a, V> where V: Eq {}
414
415impl<'a, V> std::fmt::Display for ReadGuard<'a, V>
416where
417    V: std::fmt::Display,
418{
419    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
420        self.v.fmt(f)
421    }
422}
423
424impl<'a, V> AsRef<V> for ReadGuard<'a, V> {
425    fn as_ref(&self) -> &V {
426        self.v
427    }
428}
429
430/// 只读HashMap引用的守护者,持有读锁
431pub struct ReadGuardMap<'a, K, V> {
432    /// 读锁守护者
433    _lock: RwLockReadGuard<'a, ()>,
434    /// 只读HashMap引用
435    v: &'a HashMap<K, V>,
436}
437
438impl<'a, K, V> Deref for ReadGuardMap<'a, K, V> {
439    type Target = HashMap<K, V>;
440
441    fn deref(&self) -> &Self::Target {
442        self.v
443    }
444}
445
446impl<'a, K, V> Debug for ReadGuardMap<'a, K, V>
447where
448    K: Debug,
449    V: Debug,
450{
451    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
452        write!(f, "{:?}", self.v)
453    }
454}
455
456impl<'a, K, V> PartialEq for ReadGuardMap<'a, K, V>
457where
458    K: Eq + Hash,
459    V: PartialEq,
460{
461    fn eq(&self, other: &Self) -> bool {
462        self.v.eq(other.v)
463    }
464}
465
466impl<'a, K, V> PartialEq<HashMap<K, V>> for ReadGuardMap<'a, K, V>
467where
468    K: Eq + Hash,
469    V: PartialEq,
470{
471    fn eq(&self, other: &HashMap<K, V>) -> bool {
472        self.v.eq(other)
473    }
474}
475
476impl<'a, K, V> AsRef<HashMap<K, V>> for ReadGuardMap<'a, K, V> {
477    fn as_ref(&self) -> &HashMap<K, V> {
478        self.v
479    }
480}
481
482/// 可变值引用的守护者,持有写锁
483pub struct WriteGuard<'a, V> {
484    /// 写锁守护者
485    _lock: RwLockWriteGuard<'a, ()>,
486    /// 可变值引用
487    v: &'a mut V,
488}
489
490impl<'a, V> Deref for WriteGuard<'a, V> {
491    type Target = V;
492
493    fn deref(&self) -> &Self::Target {
494        self.v
495    }
496}
497
498impl<'a, V> DerefMut for WriteGuard<'a, V> {
499    fn deref_mut(&mut self) -> &mut Self::Target {
500        self.v
501    }
502}
503
504impl<'a, V> Debug for WriteGuard<'a, V>
505where
506    V: Debug,
507{
508    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
509        write!(f, "{:?}", self.v)
510    }
511}
512
513impl<'a, V> PartialEq for WriteGuard<'a, V>
514where
515    V: PartialEq,
516{
517    fn eq(&self, other: &Self) -> bool {
518        (*self.v).eq(&*other.v)
519    }
520}
521
522impl<'a, V> Eq for WriteGuard<'a, V> where V: Eq {}
523
524impl<'a, V> std::fmt::Display for WriteGuard<'a, V>
525where
526    V: std::fmt::Display,
527{
528    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
529        self.v.fmt(f)
530    }
531}
532
533impl<'a, V> AsRef<V> for WriteGuard<'a, V> {
534    fn as_ref(&self) -> &V {
535        self.v
536    }
537}
538
539impl<'a, V> AsMut<V> for WriteGuard<'a, V> {
540    fn as_mut(&mut self) -> &mut V {
541        self.v
542    }
543}
544
545/// 类型别名,保持向后兼容
546#[allow(dead_code)]
547#[deprecated(note = "Use ReadGuard instead")]
548pub type SyncMapRefMut<'a, V> = WriteGuard<'a, V>;
549
550/// 只读迭代器的守护者,持有读锁
551pub struct Iter<'a, K, V> {
552    /// 读锁守护者
553    _lock: RwLockReadGuard<'a, ()>,
554    /// 内部迭代器
555    inner: MapIter<'a, K, V>,
556}
557
558impl<'a, K, V> Deref for Iter<'a, K, V> {
559    type Target = MapIter<'a, K, V>;
560
561    fn deref(&self) -> &Self::Target {
562        &self.inner
563    }
564}
565
566impl<'a, K, V> DerefMut for Iter<'a, K, V> {
567    fn deref_mut(&mut self) -> &mut Self::Target {
568        &mut self.inner
569    }
570}
571
572impl<'a, K, V> Iterator for Iter<'a, K, V> {
573    type Item = (&'a K, &'a V);
574
575    fn next(&mut self) -> Option<Self::Item> {
576        self.inner.next()
577    }
578}
579
580/// 类型别名,保持向后兼容
581pub type IterMy<'a, K, V> = Iter<'a, K, V>;
582
583/// 可变迭代器的守护者,持有写锁
584pub struct IterMut<'a, K, V> {
585    /// 写锁守护者
586    _lock: RwLockWriteGuard<'a, ()>,
587    /// 内部可变迭代器
588    inner: MapIterMut<'a, K, V>,
589}
590
591impl<'a, K, V> Deref for IterMut<'a, K, V> {
592    type Target = MapIterMut<'a, K, V>;
593
594    fn deref(&self) -> &Self::Target {
595        &self.inner
596    }
597}
598
599impl<'a, K, V> DerefMut for IterMut<'a, K, V> {
600    fn deref_mut(&mut self) -> &mut Self::Target {
601        &mut self.inner
602    }
603}
604
605impl<'a, K, V> Iterator for IterMut<'a, K, V> {
606    type Item = (&'a K, &'a mut V);
607
608    fn next(&mut self) -> Option<Self::Item> {
609        self.inner.next()
610    }
611}
612
613/// 键迭代器的守护者,持有读锁
614pub struct KeysGuard<'a, K, V> {
615    /// 读锁守护者
616    _lock: RwLockReadGuard<'a, ()>,
617    /// 内部迭代器
618    inner: Keys<'a, K, V>,
619}
620
621impl<'a, K, V> Deref for KeysGuard<'a, K, V> {
622    type Target = Keys<'a, K, V>;
623
624    fn deref(&self) -> &Self::Target {
625        &self.inner
626    }
627}
628
629impl<'a, K, V> DerefMut for KeysGuard<'a, K, V> {
630    fn deref_mut(&mut self) -> &mut Self::Target {
631        &mut self.inner
632    }
633}
634
635impl<'a, K, V> Iterator for KeysGuard<'a, K, V> {
636    type Item = &'a K;
637
638    fn next(&mut self) -> Option<Self::Item> {
639        self.inner.next()
640    }
641}
642
643/// 值只读迭代器的守护者,持有读锁
644pub struct ValuesGuard<'a, K, V> {
645    /// 读锁守护者
646    _lock: RwLockReadGuard<'a, ()>,
647    /// 内部迭代器
648    inner: Values<'a, K, V>,
649}
650
651impl<'a, K, V> Deref for ValuesGuard<'a, K, V> {
652    type Target = Values<'a, K, V>;
653
654    fn deref(&self) -> &Self::Target {
655        &self.inner
656    }
657}
658
659impl<'a, K, V> DerefMut for ValuesGuard<'a, K, V> {
660    fn deref_mut(&mut self) -> &mut Self::Target {
661        &mut self.inner
662    }
663}
664
665impl<'a, K, V> Iterator for ValuesGuard<'a, K, V> {
666    type Item = &'a V;
667
668    fn next(&mut self) -> Option<Self::Item> {
669        self.inner.next()
670    }
671}
672
673/// 值可变迭代器的守护者,持有写锁
674pub struct ValuesMutGuard<'a, K, V> {
675    /// 写锁守护者
676    _lock: RwLockWriteGuard<'a, ()>,
677    /// 内部迭代器
678    inner: ValuesMut<'a, K, V>,
679}
680
681impl<'a, K, V> Deref for ValuesMutGuard<'a, K, V> {
682    type Target = ValuesMut<'a, K, V>;
683
684    fn deref(&self) -> &Self::Target {
685        &self.inner
686    }
687}
688
689impl<'a, K, V> DerefMut for ValuesMutGuard<'a, K, V> {
690    fn deref_mut(&mut self) -> &mut Self::Target {
691        &mut self.inner
692    }
693}
694
695impl<'a, K, V> Iterator for ValuesMutGuard<'a, K, V> {
696    type Item = &'a mut V;
697
698    fn next(&mut self) -> Option<Self::Item> {
699        self.inner.next()
700    }
701}
702
703impl<'a, K, V> IntoIterator for &'a SyncHashMap<K, V>
704where
705    K: Eq + Hash,
706{
707    type Item = (&'a K, &'a V);
708    type IntoIter = Iter<'a, K, V>;
709
710    fn into_iter(self) -> Self::IntoIter {
711        self.iter()
712    }
713}
714
715impl<K, V> IntoIterator for SyncHashMap<K, V>
716where
717    K: Eq + Hash,
718{
719    type Item = (K, V);
720    type IntoIter = MapIntoIter<K, V>;
721
722    fn into_iter(self) -> Self::IntoIter {
723        self.into_inner().into_iter()
724    }
725}
726
727impl<K, V> From<HashMap<K, V>> for SyncHashMap<K, V>
728where
729    K: Eq + Hash,
730{
731    fn from(map: HashMap<K, V>) -> Self {
732        Self::from(map)
733    }
734}
735
736impl<K, V> Serialize for SyncHashMap<K, V>
737where
738    K: Eq + Hash + Serialize,
739    V: Serialize,
740{
741    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
742    where
743        S: Serializer,
744    {
745        let _lock = self.lock.read();
746        let m = unsafe { &*self.dirty.get() };
747        m.serialize(serializer)
748    }
749}
750
751impl<'de, K, V> Deserialize<'de> for SyncHashMap<K, V>
752where
753    K: Eq + Hash + Deserialize<'de>,
754    V: Deserialize<'de>,
755{
756    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
757    where
758        D: Deserializer<'de>,
759    {
760        let m = HashMap::deserialize(deserializer)?;
761        Ok(Self::from(m))
762    }
763}
764
765impl<K, V> Debug for SyncHashMap<K, V>
766where
767    K: Eq + Hash + Debug,
768    V: Debug,
769{
770    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
771        let _lock = self.lock.read();
772        let m = unsafe { &*self.dirty.get() };
773        m.fmt(f)
774    }
775}
776
777impl<K, V> Clone for SyncHashMap<K, V>
778where
779    K: Clone + Eq + Hash,
780    V: Clone,
781{
782    fn clone(&self) -> Self {
783        let _lock = self.lock.read();
784        let c = unsafe { &*self.dirty.get() }.clone();
785        SyncHashMap::from(c)
786    }
787}
788
789impl<K, V> Default for SyncHashMap<K, V>
790where
791    K: Eq + Hash,
792{
793    fn default() -> Self {
794        Self::new()
795    }
796}
797
798impl<K, V> PartialEq for SyncHashMap<K, V>
799where
800    K: Eq + Hash,
801    V: PartialEq,
802{
803    fn eq(&self, other: &Self) -> bool {
804        let _lock_self = self.lock.read();
805        let _lock_other = other.lock.read();
806        let self_map = unsafe { &*self.dirty.get() };
807        let other_map = unsafe { &*other.dirty.get() };
808        self_map.eq(other_map)
809    }
810}
811
812impl<K, V> Eq for SyncHashMap<K, V>
813where
814    K: Eq + Hash,
815    V: Eq,
816{
817}
818
819/// 分桶哈希映射模块,提供更高并发的哈希映射实现
820pub mod buckets {
821    use super::{ReadGuard, SyncHashMap, WriteGuard};
822    use std::hash::{Hash, Hasher};
823
824    /// 分桶哈希映射,将数据分散到多个子映射中以提高并发性能
825    #[derive(Debug, Clone)]
826    pub struct SyncHashMapB<K, V>
827    where
828        K: Eq + Hash,
829    {
830        /// 内部的子映射数组
831        inner: Vec<SyncHashMap<K, V>>,
832        /// 分桶数量
833        len: usize,
834    }
835
836    impl<K, V> SyncHashMapB<K, V>
837    where
838        K: Eq + Hash,
839    {
840        /// 创建新的分桶哈希映射
841        ///
842        /// # Arguments
843        /// * `bucket_count` - 分桶数量,如果为None则默认为10
844        ///
845        /// # Examples
846        /// ```
847        /// use fast_able::map_hash::buckets::SyncHashMapB;
848        ///
849        /// let map = SyncHashMapB::new(None);
850        /// map.insert(1, "a");
851        /// map.insert(2, "b");
852        /// assert_eq!(*map.get(&1).unwrap(), "a");
853        /// assert_eq!(*map.get(&2).unwrap(), "b");
854        /// assert!(map.get(&3).is_none());
855        /// ```
856        pub fn new(bucket_count: Option<usize>) -> Self {
857            let count = bucket_count.unwrap_or(10);
858            let mut arr = Vec::with_capacity(count);
859            for _ in 0..count {
860                arr.push(SyncHashMap::new());
861            }
862            Self {
863                inner: arr,
864                len: count,
865            }
866        }
867
868        /// 将键转换为桶索引
869        fn key_to_bucket_index(&self, k: &K) -> usize {
870            let mut hasher = std::collections::hash_map::DefaultHasher::new();
871            k.hash(&mut hasher);
872            let hash = hasher.finish();
873            (hash % self.len as u64) as usize
874        }
875
876        /// 插入键值对
877        #[inline]
878        pub fn insert(&self, k: K, v: V) -> Option<V> {
879            let index = self.key_to_bucket_index(&k);
880            self.inner[index].insert(k, v)
881        }
882
883        /// 可变引用下的插入操作
884        #[inline]
885        pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
886            let index = self.key_to_bucket_index(&k);
887            self.inner[index].insert_mut(k, v)
888        }
889
890        /// 移除键值对
891        #[inline]
892        pub fn remove(&self, k: &K) -> Option<V> {
893            let index = self.key_to_bucket_index(k);
894            self.inner[index].remove(k)
895        }
896
897        /// 检查是否为空
898        #[inline]
899        pub fn is_empty(&self) -> bool {
900            self.inner.iter().all(|bucket| bucket.is_empty())
901        }
902
903        /// 获取总长度
904        #[inline]
905        pub fn len(&self) -> usize {
906            self.inner.iter().map(|bucket| bucket.len()).sum()
907        }
908
909        /// 清空所有桶
910        #[inline]
911        pub fn clear(&self) {
912            self.inner.iter().for_each(|bucket| bucket.clear());
913        }
914
915        /// 获取键对应的值引用,使用读锁保护
916        ///
917        /// 返回一个 `ReadGuard`,在 guard 被释放前持有读锁,保证并发访问安全。
918        #[inline]
919        pub fn get(&self, k: &K) -> Option<ReadGuard<'_, V>> {
920            let index = self.key_to_bucket_index(k);
921            self.inner[index].get(k)
922        }
923
924        /// 获取键对应的可变值引用,使用写锁保护
925        ///
926        /// 返回一个 `WriteGuard`,在 guard 被释放前持有写锁,保证并发访问安全。
927        #[inline]
928        pub fn get_mut(&self, k: &K) -> Option<WriteGuard<'_, V>> {
929            let index = self.key_to_bucket_index(k);
930            self.inner[index].get_mut(k)
931        }
932
933        /// 获取桶数量
934        #[inline]
935        pub fn bucket_count(&self) -> usize {
936            self.len
937        }
938
939        /// 获取所有键的迭代器
940        #[inline]
941        pub fn keys(&self) -> impl Iterator<Item = &K> {
942            self.inner.iter().flat_map(|bucket| bucket.keys())
943        }
944
945        /// 获取所有值的只读迭代器
946        #[inline]
947        pub fn values(&self) -> impl Iterator<Item = &V> {
948            self.inner.iter().flat_map(|bucket| bucket.values())
949        }
950
951        /// 获取所有值的可变迭代器(注意:这是一个简化实现,返回值的锁可能不够严格)
952        #[inline]
953        pub fn values_mut(&self) -> impl Iterator<Item = &mut V> {
954            self.inner.iter().flat_map(|bucket| bucket.values_mut())
955        }
956    }
957
958    impl<K, V> Default for SyncHashMapB<K, V>
959    where
960        K: Eq + Hash,
961    {
962        fn default() -> Self {
963            Self::new(None)
964        }
965    }
966}
967
968#[cfg(test)]
969mod tests {
970    use super::*;
971    use std::collections::HashMap;
972    use std::sync::Arc;
973    use std::thread;
974
975    #[test]
976    fn test_sync_hash_map_new() {
977        let map: SyncHashMap<i32, String> = SyncHashMap::new();
978        assert_eq!(map.len(), 0);
979        assert!(map.is_empty());
980    }
981
982    #[test]
983    fn test_sync_hash_map_with_capacity() {
984        let map = SyncHashMap::<i32, String>::with_capacity(100);
985        assert!(map.capacity() >= 100);
986    }
987
988    #[test]
989    fn test_sync_hash_map_with_map() {
990        let mut original = HashMap::new();
991        original.insert(1, "one".to_string());
992        original.insert(2, "two".to_string());
993
994        let map = SyncHashMap::with_map(original);
995        assert_eq!(map.len(), 2);
996        assert_eq!(*map.get(&1).unwrap(), "one".to_string());
997        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
998    }
999
1000    #[test]
1001    fn test_sync_hash_map_insert_and_get() {
1002        let map = SyncHashMap::new();
1003
1004        // 测试插入和获取
1005        assert_eq!(map.insert(1, "one".to_string()), None);
1006        assert_eq!(map.insert(2, "two".to_string()), None);
1007        assert_eq!(map.len(), 2);
1008
1009        assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1010        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1011        assert!(map.get(&3).is_none());
1012    }
1013
1014    #[test]
1015    fn test_sync_hash_map_insert_replace() {
1016        let map = SyncHashMap::new();
1017
1018        assert_eq!(map.insert(1, "one".to_string()), None);
1019        assert_eq!(map.insert(1, "updated".to_string()), Some("one".to_string()));
1020        assert_eq!(*map.get(&1).unwrap(), "updated".to_string());
1021    }
1022
1023    #[test]
1024    fn test_sync_hash_map_remove() {
1025        let map = SyncHashMap::new();
1026
1027        map.insert(1, "one".to_string());
1028        map.insert(2, "two".to_string());
1029
1030        assert_eq!(map.remove(&1), Some("one".to_string()));
1031        assert_eq!(map.remove(&1), None);
1032        assert_eq!(map.len(), 1);
1033        assert!(map.get(&1).is_none());
1034        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1035    }
1036
1037    #[test]
1038    fn test_sync_hash_map_contains_key() {
1039        let map = SyncHashMap::new();
1040
1041        map.insert(1, "one".to_string());
1042
1043        assert!(map.contains_key(&1));
1044        assert!(!map.contains_key(&2));
1045    }
1046
1047    #[test]
1048    fn test_sync_hash_map_clear() {
1049        let map = SyncHashMap::new();
1050
1051        map.insert(1, "one".to_string());
1052        map.insert(2, "two".to_string());
1053
1054        assert_eq!(map.len(), 2);
1055        map.clear();
1056        assert_eq!(map.len(), 0);
1057        assert!(map.is_empty());
1058    }
1059
1060    #[test]
1061    fn test_sync_hash_map_capacity_operations() {
1062        let map = SyncHashMap::new();
1063
1064        assert_eq!(map.capacity(), 0);
1065        map.reserve(100);
1066        assert!(map.capacity() >= 100);
1067
1068        map.insert(1, "one".to_string());
1069        map.insert(2, "two".to_string());
1070
1071        let old_capacity = map.capacity();
1072        map.shrink_to_fit();
1073        assert!(map.capacity() <= old_capacity);
1074    }
1075
1076    #[test]
1077    fn test_sync_hash_map_retain() {
1078        let map = SyncHashMap::new();
1079
1080        map.insert(1, "one".to_string());
1081        map.insert(2, "two".to_string());
1082        map.insert(3, "three".to_string());
1083
1084        map.retain(|&k, _| k % 2 == 1);
1085
1086        assert_eq!(map.len(), 2);
1087        assert!(map.contains_key(&1));
1088        assert!(!map.contains_key(&2));
1089        assert!(map.contains_key(&3));
1090    }
1091
1092    #[test]
1093    fn test_sync_hash_map_get_or_insert() {
1094        let map = SyncHashMap::new();
1095
1096        // 键不存在时插入
1097        {
1098            let value = map.get_or_insert(1, "default".to_string());
1099            assert_eq!(*value, "default");
1100        }
1101        assert_eq!(map.len(), 1);
1102
1103        // 键存在时返回现有值
1104        {
1105            let value = map.get_or_insert(1, "new_default".to_string());
1106            assert_eq!(*value, "default");
1107        }
1108        assert_eq!(map.len(), 1);
1109    }
1110
1111    #[test]
1112    fn test_sync_hash_map_get_or_insert_with() {
1113        let map = SyncHashMap::new();
1114
1115        {
1116            let value = map.get_or_insert_with(1, || "computed".to_string());
1117            assert_eq!(*value, "computed");
1118        }
1119        assert_eq!(map.len(), 1);
1120
1121        {
1122            let value = map.get_or_insert_with(1, || "new_computed".to_string());
1123            assert_eq!(*value, "computed");
1124        }
1125    }
1126
1127    #[test]
1128    fn test_sync_hash_map_remove_entry() {
1129        let map = SyncHashMap::new();
1130
1131        map.insert(1, "one".to_string());
1132        map.insert(2, "two".to_string());
1133
1134        let removed = map.remove_entry(&1);
1135        assert_eq!(removed, Some((1, "one".to_string())));
1136        assert_eq!(map.len(), 1);
1137        assert!(!map.contains_key(&1));
1138    }
1139
1140    #[test]
1141    fn test_sync_hash_map_iterators() {
1142        let map = SyncHashMap::new();
1143
1144        map.insert(1, "one".to_string());
1145        map.insert(2, "two".to_string());
1146        map.insert(3, "three".to_string());
1147
1148        // 测试 keys 迭代器
1149        let keys: Vec<_> = map.keys().collect();
1150        assert!(keys.contains(&&1));
1151        assert!(keys.contains(&&2));
1152        assert!(keys.contains(&&3));
1153
1154        // 测试 values 迭代器
1155        let values: Vec<_> = map.values().collect();
1156        assert!(values.contains(&&"one".to_string()));
1157        assert!(values.contains(&&"two".to_string()));
1158        assert!(values.contains(&&"three".to_string()));
1159
1160        // 测试 iter 迭代器
1161        let mut count = 0;
1162        for (k, v) in map.iter() {
1163            count += 1;
1164            assert!(map.contains_key(k));
1165            assert_eq!(*map.get(k).unwrap(), *v);
1166        }
1167        assert_eq!(count, 3);
1168    }
1169
1170    #[test]
1171    fn test_sync_hash_map_iter_mut() {
1172        let map = SyncHashMap::new();
1173
1174        map.insert(1, "one".to_string());
1175        map.insert(2, "two".to_string());
1176
1177        for (k, v) in map.iter_mut() {
1178            if *k == 1 {
1179                *v = "modified".to_string();
1180            }
1181        }
1182
1183        assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1184        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1185    }
1186
1187    #[test]
1188    fn test_sync_hash_map_values_mut() {
1189        let map = SyncHashMap::new();
1190
1191        map.insert(1, "one".to_string());
1192        map.insert(2, "two".to_string());
1193
1194        for v in map.values_mut() {
1195            if v == "one" {
1196                *v = "modified".to_string();
1197            }
1198        }
1199
1200        assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1201        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1202    }
1203
1204    #[test]
1205    fn test_sync_hash_map_index() {
1206        let map = SyncHashMap::new();
1207        map.insert(1, "one".to_string());
1208
1209        // 测试索引访问
1210        assert_eq!(map[&1], "one");
1211    }
1212
1213    #[test]
1214    fn test_sync_hash_map_clone() {
1215        let map1 = SyncHashMap::new();
1216        map1.insert(1, "one".to_string());
1217        map1.insert(2, "two".to_string());
1218
1219        let map2 = map1.clone();
1220
1221        assert_eq!(map1.len(), map2.len());
1222        assert_eq!(*map1.get(&1).unwrap(), *map2.get(&1).unwrap());
1223        assert_eq!(*map1.get(&2).unwrap(), *map2.get(&2).unwrap());
1224
1225        // 修改原映射不影响克隆
1226        map1.insert(3, "three".to_string());
1227        assert!(!map2.contains_key(&3));
1228    }
1229
1230    #[test]
1231    fn test_sync_hash_map_partial_eq() {
1232        let map1 = SyncHashMap::new();
1233        map1.insert(1, "one".to_string());
1234        map1.insert(2, "two".to_string());
1235
1236        let map2 = SyncHashMap::new();
1237        map2.insert(1, "one".to_string());
1238        map2.insert(2, "two".to_string());
1239
1240        let map3 = SyncHashMap::new();
1241        map3.insert(1, "different".to_string());
1242
1243        assert_eq!(map1, map2);
1244        assert_ne!(map1, map3);
1245    }
1246
1247    #[test]
1248    fn test_sync_hash_map_debug() {
1249        let map = SyncHashMap::new();
1250        map.insert(1, "one".to_string());
1251
1252        let debug_str = format!("{:?}", map);
1253        assert!(debug_str.contains("1"));
1254        assert!(debug_str.contains("one"));
1255    }
1256
1257    #[test]
1258    fn test_sync_hash_map_serialization() {
1259        let map = SyncHashMap::new();
1260        map.insert(1, "one".to_string());
1261        map.insert(2, "two".to_string());
1262
1263        // 测试序列化
1264        let serialized = serde_json::to_string(&map).unwrap();
1265        assert!(serialized.contains("1"));
1266        assert!(serialized.contains("one"));
1267        assert!(serialized.contains("2"));
1268        assert!(serialized.contains("two"));
1269
1270        // 测试反序列化
1271        let deserialized: SyncHashMap<i32, String> = serde_json::from_str(&serialized).unwrap();
1272        assert_eq!(deserialized.len(), 2);
1273        assert_eq!(*deserialized.get(&1).unwrap(), "one".to_string());
1274        assert_eq!(*deserialized.get(&2).unwrap(), "two".to_string());
1275    }
1276
1277    #[test]
1278    fn test_sync_hash_map_from_hashmap() {
1279        let mut original = HashMap::new();
1280        original.insert(1, "one".to_string());
1281        original.insert(2, "two".to_string());
1282
1283        let map = SyncHashMap::from(original);
1284
1285        assert_eq!(map.len(), 2);
1286        assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1287        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1288    }
1289
1290    #[test]
1291    fn test_sync_hash_map_into_iterator() {
1292        let map = SyncHashMap::new();
1293        map.insert(1, "one".to_string());
1294        map.insert(2, "two".to_string());
1295
1296        // 测试 IntoIterator for &SyncHashMap
1297        let mut count = 0;
1298        for (k, v) in &map {
1299            count += 1;
1300            assert!(map.contains_key(k));
1301            assert_eq!(*map.get(k).unwrap(), *v);
1302        }
1303        assert_eq!(count, 2);
1304
1305        // 测试 IntoIterator for SyncHashMap
1306        let owned_pairs: Vec<_> = map.into_iter().collect();
1307        assert_eq!(owned_pairs.len(), 2);
1308    }
1309
1310    #[test]
1311    fn test_sync_hash_map_default() {
1312        let map: SyncHashMap<i32, String> = Default::default();
1313        assert_eq!(map.len(), 0);
1314        assert!(map.is_empty());
1315    }
1316
1317    #[test]
1318    fn test_sync_hash_map_arc() {
1319        let map = SyncHashMap::new_arc();
1320        map.insert(1, "one".to_string());
1321
1322        assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1323
1324        let map2 = Arc::clone(&map);
1325        map2.insert(2, "two".to_string());
1326
1327        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1328    }
1329
1330    #[test]
1331    fn test_sync_hash_map_get_mut() {
1332        let map = SyncHashMap::new();
1333        map.insert(1, "one".to_string());
1334
1335        {
1336            let mut value = map.get_mut(&1).unwrap();
1337            *value = "modified".to_string();
1338        }
1339
1340        assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1341    }
1342
1343    #[test]
1344    fn test_sync_hash_map_concurrent_access() {
1345        let map = Arc::new(SyncHashMap::new());
1346
1347        // 并发写入测试
1348        let handles: Vec<_> = (0..10).map(|i| {
1349            let map = Arc::clone(&map);
1350            thread::spawn(move || {
1351                map.insert(i, format!("value_{}", i));
1352            })
1353        }).collect();
1354
1355        for handle in handles {
1356            handle.join().unwrap();
1357        }
1358
1359        // 验证所有值都被插入
1360        assert_eq!(map.len(), 10);
1361        for i in 0..10 {
1362            assert_eq!(*map.get(&i).unwrap(), format!("value_{}", i));
1363        }
1364
1365        // 并发读取测试
1366        let map_read = Arc::clone(&map);
1367        let handles: Vec<_> = (0..10).map(|i| {
1368            let map = Arc::clone(&map_read);
1369            thread::spawn(move || {
1370                let value = map.get(&i);
1371                assert_eq!(*value.unwrap(), format!("value_{}", i));
1372            })
1373        }).collect();
1374
1375        for handle in handles {
1376            handle.join().unwrap();
1377        }
1378    }
1379
1380    #[test]
1381    fn test_sync_hash_map_dirty_ref() {
1382        let map = SyncHashMap::new();
1383        map.insert(1, "one".to_string());
1384
1385        let dirty = map.dirty_ref();
1386        assert_eq!(dirty.len(), 1);
1387        assert_eq!(dirty.get(&1), Some(&"one".to_string()));
1388    }
1389
1390    #[test]
1391    fn test_sync_hash_map_into_inner() {
1392        let map = SyncHashMap::new();
1393        map.insert(1, "one".to_string());
1394        map.insert(2, "two".to_string());
1395
1396        let inner = map.into_inner();
1397        assert_eq!(inner.len(), 2);
1398        assert_eq!(inner.get(&1), Some(&"one".to_string()));
1399        assert_eq!(inner.get(&2), Some(&"two".to_string()));
1400    }
1401
1402    #[test]
1403    fn test_sync_hash_map_guard_debug() {
1404        let map = SyncHashMap::new();
1405        map.insert(1, "test".to_string());
1406
1407        let guard = map.get(&1).unwrap();
1408        let debug_str = format!("{:?}", guard);
1409        assert!(debug_str.contains("test"));
1410    }
1411
1412    #[test]
1413    fn test_sync_hash_map_guard_partial_eq() {
1414        let map = SyncHashMap::new();
1415        map.insert(1, "value".to_string());
1416
1417        let guard1 = map.get(&1).unwrap();
1418        let guard2 = map.get(&1).unwrap();
1419
1420        assert_eq!(guard1, guard2);
1421    }
1422
1423    // 分桶映射测试
1424    mod buckets_tests {
1425        use super::*;
1426
1427        #[test]
1428        fn test_sync_hash_map_buckets_new() {
1429            let map = buckets::SyncHashMapB::<i32, String>::new(None);
1430            assert_eq!(map.len(), 0);
1431            assert!(map.is_empty());
1432            assert_eq!(map.bucket_count(), 10); // 默认桶数量
1433        }
1434
1435        #[test]
1436        fn test_sync_hash_map_buckets_with_custom_size() {
1437            let map = buckets::SyncHashMapB::<i32, String>::new(Some(5));
1438            assert_eq!(map.bucket_count(), 5);
1439        }
1440
1441        #[test]
1442        fn test_sync_hash_map_buckets_insert_and_get() {
1443            let map = buckets::SyncHashMapB::new(Some(3));
1444
1445            assert_eq!(map.insert(1, "one".to_string()), None);
1446            assert_eq!(map.insert(2, "two".to_string()), None);
1447            assert_eq!(map.len(), 2);
1448
1449            assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1450            assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1451            assert!(map.get(&3).is_none());
1452        }
1453
1454        #[test]
1455        fn test_sync_hash_map_buckets_remove() {
1456            let map = buckets::SyncHashMapB::new(Some(3));
1457
1458            map.insert(1, "one".to_string());
1459            map.insert(2, "two".to_string());
1460
1461            assert_eq!(map.remove(&1), Some("one".to_string()));
1462            assert_eq!(map.len(), 1);
1463            assert!(map.get(&1).is_none());
1464            assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1465        }
1466
1467        #[test]
1468        fn test_sync_hash_map_buckets_clear() {
1469            let map = buckets::SyncHashMapB::new(Some(3));
1470
1471            map.insert(1, "one".to_string());
1472            map.insert(2, "two".to_string());
1473
1474            assert_eq!(map.len(), 2);
1475            map.clear();
1476            assert_eq!(map.len(), 0);
1477            assert!(map.is_empty());
1478        }
1479
1480        #[test]
1481        fn test_sync_hash_map_buckets_iterators() {
1482            let map = buckets::SyncHashMapB::new(Some(3));
1483
1484            map.insert(1, "one".to_string());
1485            map.insert(2, "two".to_string());
1486            map.insert(3, "three".to_string());
1487
1488            // 测试 keys 迭代器
1489            let keys: Vec<_> = map.keys().collect();
1490            assert!(keys.contains(&&1));
1491            assert!(keys.contains(&&2));
1492            assert!(keys.contains(&&3));
1493
1494            // 测试 values 迭代器
1495            let values: Vec<_> = map.values().collect();
1496            assert!(values.contains(&&"one".to_string()));
1497            assert!(values.contains(&&"two".to_string()));
1498            assert!(values.contains(&&"three".to_string()));
1499
1500            // 测试 values_mut 迭代器
1501            for v in map.values_mut() {
1502                if v == "one" {
1503                    *v = "modified".to_string();
1504                }
1505            }
1506
1507            assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1508        }
1509
1510        #[test]
1511        fn test_sync_hash_map_buckets_default() {
1512            let map: buckets::SyncHashMapB<i32, String> = Default::default();
1513            assert_eq!(map.len(), 0);
1514            assert!(map.is_empty());
1515            assert_eq!(map.bucket_count(), 10);
1516        }
1517
1518        #[test]
1519        fn test_sync_hash_map_buckets_debug() {
1520            let map = buckets::SyncHashMapB::new(Some(2));
1521            map.insert(1, "one".to_string());
1522
1523            let debug_str = format!("{:?}", map);
1524            assert!(debug_str.contains("1"));
1525            assert!(debug_str.contains("one"));
1526        }
1527    }
1528
1529    #[test]
1530    fn test_sync_hash_map_comprehensive() {
1531        let map = SyncHashMap::new();
1532
1533        // 测试各种操作的组合
1534        map.insert("key1", 42);
1535        map.insert("key2", 24);
1536
1537        assert_eq!(map.len(), 2);
1538        assert!(!map.is_empty());
1539
1540        // 测试修改操作
1541        *map.get_mut("key1").unwrap() = 100;
1542        assert_eq!(*map.get(&"key1").unwrap(), 100);
1543
1544        // 测试条件保留
1545        map.insert("key3", 50);
1546        map.retain(|_, &mut v| v > 30);
1547
1548        assert_eq!(map.len(), 2);
1549        assert_eq!(*map.get(&"key1").unwrap(), 100);
1550        assert!(map.get(&"key2").is_none());
1551        assert_eq!(*map.get(&"key3").unwrap(), 50);
1552
1553        // 测试克隆和比较
1554        let map2 = map.clone();
1555        assert_eq!(map, map2);
1556
1557        // 测试迭代
1558        let mut sum = 0;
1559        for (_, v) in map.iter() {
1560            sum += v;
1561        }
1562        assert_eq!(sum, 150);
1563
1564        // 测试清空
1565        map.clear();
1566        assert_eq!(map.len(), 0);
1567        assert!(map.is_empty());
1568    }
1569}