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::HashMap;
6use std::collections::hash_map::{IntoIter as MapIntoIter, Iter as MapIter, Keys};
7use std::fmt::{Debug, Formatter};
8use std::hash::{BuildHasherDefault, DefaultHasher, Hash};
9use std::ops::{Deref, DerefMut};
10use std::sync::Arc;
11
12/// Default hasher type alias
13/// 默认哈希器类型别名
14///
15/// Use `BuildHasherDefault<DefaultHasher>` to support `const fn new()`.
16/// Note: This hasher has no random seed. If untrusted external input is accepted as a key,
17/// it may be subject to hash collision attacks (HashDoS).
18/// 使用 `BuildHasherDefault<DefaultHasher>` 以支持 `const fn new()`。
19/// 注意:此哈希器没有随机种子,如果接受不可信的外部输入作为 key,
20/// 可能会受到哈希碰撞攻击(HashDoS)。
21pub type DefaultBuildHasher = BuildHasherDefault<DefaultHasher>;
22
23/// Synchronous hash map supporting fine-grained lock control
24/// 同步哈希映射,支持细粒度锁控制
25///
26/// Locking strategy:
27/// - Read operations like `get`: HashMap read lock + value read lock
28/// - Value modification operations like `get_mut`: HashMap read lock + value write lock
29/// - Structure modification operations like `insert`/`remove`: HashMap write lock
30/// 锁策略:
31/// - get 等读取操作: HashMap读锁 + 值的读锁
32/// - get_mut 等修改值操作: HashMap读锁 + 值的写锁
33/// - insert/remove 等修改结构操作: HashMap写锁
34///
35/// This allows:
36/// - Multiple threads can read different values simultaneously
37/// - When one thread modifies a value, other threads can still read other values
38/// - Exclusive access when modifying the HashMap structure
39/// 这样可以实现:
40/// - 多个线程可以同时读取不同的值
41/// - 一个线程修改某个值时,其他线程仍可读取其他值
42/// - 修改HashMap结构时独占访问
43///
44/// ## Note
45/// ## 注意
46///
47/// Use `BuildHasherDefault<DefaultHasher>` hasher to support `const fn new()`.
48/// This hasher has no random seed. If the HashMap accepts untrusted external input as a key,
49/// it may be subject to hash collision attacks (HashDoS).
50/// 使用 `BuildHasherDefault<DefaultHasher>` 哈希器以支持 `const fn new()`。
51/// 此哈希器没有随机种子,如果 HashMap 接受不可信的外部输入作为 key,
52/// 可能会受到哈希碰撞攻击(HashDoS)。
53pub struct SyncHashMap<K, V> {
54    /// Underlying data storage, each value has an independent read-write lock
55    /// 底层数据存储,每个值都有独立的读写锁
56    dirty: UnsafeCell<HashMap<K, RwLock<V>, DefaultBuildHasher>>,
57    /// HashMap-level read-write lock, used to protect the HashMap structure
58    /// HashMap级别的读写锁,用于保护HashMap结构
59    lock: RwLock<()>,
60}
61
62/// Marked as Send because UnsafeCell is used but protected by a lock
63/// 标记为Send,因为使用了UnsafeCell但有锁保护
64/// this is safety, dirty mutex ensure
65unsafe impl<K, V> Send for SyncHashMap<K, V> {}
66
67/// Marked as Sync because UnsafeCell is used but protected by a lock
68/// 标记为Sync,因为使用了UnsafeCell但有锁保护
69/// this is safety, dirty mutex ensure
70unsafe impl<K, V> Sync for SyncHashMap<K, V> {}
71
72// const NONRANDOM_EMPTY_MAP: HashMap<String, Vec<i32>, std::hash::BuildHasherDefault<std::hash::DefaultHasher>> = HashMap::with_hasher(std::hash::BuildHasherDefault::new());
73
74impl<K, V> SyncHashMap<K, V>
75where
76    K: Eq + Hash,
77{
78    /// Create a new Arc-wrapped SyncHashMap
79    /// 创建一个新的Arc包装的SyncHashMap
80    pub fn new_arc() -> Arc<Self> {
81        Arc::new(Self::new())
82    }
83
84    /// Create a new empty map
85    /// 创建一个新的空映射
86    pub const fn new() -> Self {
87        Self {
88            dirty: UnsafeCell::new(HashMap::with_hasher(DefaultBuildHasher::new())),
89            lock: RwLock::new(()),
90        }
91    }
92
93    /// Create a new map with the specified capacity
94    /// 使用指定容量创建一个新的映射
95    pub fn with_capacity(capacity: usize) -> Self {
96        Self {
97            dirty: UnsafeCell::new(HashMap::with_capacity_and_hasher(
98                capacity,
99                std::hash::BuildHasherDefault::default(),
100            )),
101            lock: RwLock::new(()),
102        }
103    }
104
105    /// Create a synchronous map using an existing HashMap
106    /// 使用现有的HashMap创建一个同步映射
107    ///
108    /// Note: Values in the passed HashMap will be wrapped in RwLock
109    /// 注意:传入的HashMap中的值会被包装在RwLock中
110    pub fn with_map(map: HashMap<K, V>) -> Self {
111        let mut wrapped =
112            HashMap::with_capacity_and_hasher(map.len(), std::hash::BuildHasherDefault::default());
113        for (k, v) in map {
114            wrapped.insert(k, RwLock::new(v));
115        }
116        Self {
117            dirty: UnsafeCell::new(wrapped),
118            lock: RwLock::new(()),
119        }
120    }
121
122    /// Insert a key-value pair, protected by HashMap write lock
123    /// 插入键值对,使用HashMap写锁保护
124    ///
125    /// If the key already exists, return the old value
126    /// 如果键已存在,返回旧值
127    #[inline(always)]
128    pub fn insert(&self, k: K, v: V) -> Option<V> {
129        let _lock = self.lock.write();
130        let m = unsafe { &mut *self.dirty.get() };
131        m.insert(k, RwLock::new(v)).map(|old| old.into_inner())
132    }
133
134    /// Insert operation under mutable reference, no lock protection (caller must ensure thread safety)
135    /// 可变引用下的插入操作,无锁保护(调用者需确保线程安全)
136    #[inline(always)]
137    pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
138        let m = unsafe { &mut *self.dirty.get() };
139        m.insert(k, RwLock::new(v)).map(|old| old.into_inner())
140    }
141
142    /// Remove a key-value pair, protected by HashMap write lock
143    /// 移除键值对,使用HashMap写锁保护
144    #[inline(always)]
145    pub fn remove(&self, k: &K) -> Option<V> {
146        let _lock = self.lock.write();
147        let m = unsafe { &mut *self.dirty.get() };
148        m.remove(k).map(|v| v.into_inner())
149    }
150
151    /// Remove operation under mutable reference, no lock protection (caller must ensure thread safety)
152    /// 可变引用下的移除操作,无锁保护(调用者需确保线程安全)
153    #[inline(always)]
154    pub fn remove_mut(&mut self, k: &K) -> Option<V> {
155        let m = unsafe { &mut *self.dirty.get() };
156        m.remove(k).map(|v| v.into_inner())
157    }
158
159    /// Get the length of the map, protected by HashMap read lock
160    /// 获取映射长度,使用HashMap读锁保护
161    #[inline(always)]
162    pub fn len(&self) -> usize {
163        let _lock = self.lock.read();
164        let m = unsafe { &*self.dirty.get() };
165        m.len()
166    }
167
168    /// Check if the map is empty, protected by HashMap read lock
169    /// 判断映射是否为空,使用HashMap读锁保护
170    #[inline(always)]
171    pub fn is_empty(&self) -> bool {
172        let _lock = self.lock.read();
173        let m = unsafe { &*self.dirty.get() };
174        m.is_empty()
175    }
176
177    /// Clear the map, protected by HashMap write lock
178    /// 清空映射,使用HashMap写锁保护
179    #[inline(always)]
180    pub fn clear(&self) {
181        let _lock = self.lock.write();
182        let m = unsafe { &mut *self.dirty.get() };
183        m.clear();
184    }
185
186    /// Clear operation under mutable reference, no lock protection (caller must ensure thread safety)
187    /// 可变引用下的清空操作,无锁保护(调用者需确保线程安全)
188    #[inline(always)]
189    pub fn clear_mut(&mut self) {
190        let m = unsafe { &mut *self.dirty.get() };
191        m.clear();
192    }
193
194    /// Shrink capacity to fit the number of elements, protected by HashMap write lock
195    /// 收缩容量以适应元素数量,使用HashMap写锁保护
196    #[inline(always)]
197    pub fn shrink_to_fit(&self) {
198        let _lock = self.lock.write();
199        let m = unsafe { &mut *self.dirty.get() };
200        m.shrink_to_fit();
201    }
202
203    /// Shrink capacity operation under mutable reference, no lock protection (caller must ensure thread safety)
204    /// 可变引用下的收缩容量操作,无锁保护(调用者需确保线程安全)
205    #[inline(always)]
206    pub fn shrink_to_fit_mut(&mut self) {
207        let m = unsafe { &mut *self.dirty.get() };
208        m.shrink_to_fit();
209    }
210
211    /// Convenient method to create SyncHashMap from HashMap
212    /// 从HashMap创建SyncHashMap的便捷方法
213    pub fn from(map: HashMap<K, V>) -> Self {
214        Self::with_map(map)
215    }
216
217    /// Get a reference to the value corresponding to the key, protected by HashMap read lock (value no lock)
218    /// 获取键对应的值引用,使用HashMap读锁 (值无锁)
219    ///
220    /// Returns a `ReadGuardNoLock` that holds the HashMap read lock until the guard is dropped.
221    /// Other threads can still read other values, but cannot modify the HashMap structure.
222    /// 返回一个 `ReadGuardNoLock`,在 guard 被释放前持有HashMap读锁。
223    /// 其他线程仍可读取其他值,但不能修改HashMap结构。
224    ///
225    /// # Safety
226    /// 此方法绕过了保护值的 `RwLock`,仅当您确定没有其他线程正在修改该值时才应使用它。
227    /// This method bypasses the `RwLock` protecting the value.
228    /// It should only be used when you are sure that no other thread is modifying the value.
229    ///
230    /// # Examples
231    ///
232    /// ```
233    /// use fast_able::SyncHashMap;
234    ///
235    /// let map = SyncHashMap::new();
236    /// map.insert(1, "a");
237    /// assert_eq!(*map.get(&1).unwrap(), "a");
238    /// assert!(map.get(&2).is_none());
239    /// ```
240    #[inline]
241    pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<MapReadGuard<'_, V>>
242    where
243        K: Borrow<Q>,
244        Q: Hash + Eq,
245    {
246        let map_lock = self.lock.read();
247        let m = unsafe { &*self.dirty.get() };
248        let value_lock_wrapper = m.get(k)?;
249        // SAFETY: 只有Map结构锁保护,值无锁
250        let value_ptr = unsafe {
251            let lock_ptr = value_lock_wrapper as *const RwLock<V> as *mut RwLock<V>;
252            &*(*lock_ptr).get_mut()
253        };
254        Some(MapReadGuard {
255            _map_lock: map_lock,
256            _value_ptr: value_ptr,
257        })
258    }
259
260    /// Get a reference to the value corresponding to the key, protected by HashMap read lock + value read lock
261    /// 获取键对应的值引用,使用HashMap读锁 + 值的读锁保护
262    /// Safety: This method is safe as it acquires both the HashMap read lock and the value read lock.
263    /// 安全性: 此方法是安全的,因为它同时获取了HashMap读锁和值的读锁。
264    pub fn get_rlock<Q: ?Sized>(&self, k: &Q) -> Option<ReadGuard<'_, V>>
265    where
266        K: Borrow<Q>,
267        Q: Hash + Eq,
268    {
269        let map_lock = self.lock.read();
270        let m = unsafe { &*self.dirty.get() };
271        let value_lock_wrapper = m.get(k)?;
272        let value_lock = value_lock_wrapper.read();
273        Some(ReadGuard {
274            _map_lock: map_lock,
275            _value_lock: value_lock,
276        })
277    }
278
279    /// Get a reference to the value corresponding to the key (unchecked version), protected by HashMap read lock (value no lock)
280    /// 获取键对应的值引用(无检查版本),使用HashMap读锁 (值无锁)
281    ///
282    /// # Safety
283    /// 此方法绕过了保护值的 `RwLock`,仅当您确定没有其他线程正在修改该值时才应使用它。
284    /// This method bypasses the `RwLock` protecting the value.
285    /// It should only be used when you are sure that no other thread is modifying the value.
286    ///
287    /// # Panics
288    ///
289    /// Panics if the key does not exist.
290    /// 如果键不存在则 panic。
291    #[inline]
292    pub fn get_uncheck<Q: ?Sized>(&self, k: &Q) -> MapReadGuard<'_, V>
293    where
294        K: Borrow<Q>,
295        Q: Hash + Eq,
296    {
297        let map_lock = self.lock.read();
298        let m = unsafe { &*self.dirty.get() };
299        let value_lock_wrapper = m.get(k).expect("key not found");
300        // SAFETY: 只有Map结构锁保护,值无锁
301        let value_ptr = unsafe {
302            let lock_ptr = value_lock_wrapper as *const RwLock<V> as *mut RwLock<V>;
303            &*(*lock_ptr).get_mut()
304        };
305        MapReadGuard {
306            _map_lock: map_lock,
307            _value_ptr: value_ptr,
308        }
309    }
310
311    /// Get a mutable reference to the value corresponding to the key, protected by HashMap read lock + value write lock
312    /// 获取键对应的可变值引用,使用HashMap读锁 + 值的写锁保护
313    ///
314    /// Returns a `WriteGuard` that holds the HashMap read lock and the value write lock until the guard is dropped.
315    /// This allows other threads to still read other values, but cannot modify this value.
316    /// 返回一个 `WriteGuard`,在 guard 被释放前持有HashMap读锁和值的写锁。
317    /// 这样其他线程仍可读取其他值,但不能修改此值。
318    #[inline]
319    pub fn get_mut<Q: ?Sized>(&self, k: &Q) -> Option<WriteGuard<'_, V>>
320    where
321        K: Borrow<Q>,
322        Q: Hash + Eq,
323    {
324        let map_lock = self.lock.read();
325        let m = unsafe { &*self.dirty.get() };
326        let value_lock_wrapper = m.get(k)?;
327        let value_lock = value_lock_wrapper.write();
328        Some(WriteGuard {
329            _map_lock: map_lock,
330            _value_lock: value_lock,
331        })
332    }
333
334    /// Check if the map contains the specified key, protected by HashMap read lock
335    /// 检查是否包含指定的键,使用HashMap读锁保护
336    #[inline]
337    pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
338    where
339        K: Borrow<Q>,
340        Q: Hash + Eq,
341    {
342        let _lock = self.lock.read();
343        let m = unsafe { &*self.dirty.get() };
344        m.contains_key(k)
345    }
346
347    /// Get a mutable iterator, protected by HashMap write lock
348    /// 获取可变迭代器,使用HashMap写锁保护
349    ///
350    /// Note: This method holds the HashMap write lock, so other threads cannot access it during iteration
351    /// 注意:此方法持有HashMap写锁,迭代期间其他线程无法访问
352    pub fn iter_mut(&self) -> IterMut<'_, K, V> {
353        let _lock = self.lock.read();
354        let m = unsafe { &*self.dirty.get() };
355        IterMut {
356            _lock,
357            inner: m.iter(),
358        }
359    }
360
361    /// Get a read-only iterator, protected by HashMap read lock
362    /// 获取只读迭代器,使用HashMap读锁保护
363    ///
364    /// The returned iterator holds the HashMap read lock, ensuring the structure is not modified during iteration.
365    /// Note: You need to acquire a read lock for each value during iteration
366    /// 返回的迭代器持有HashMap读锁,在迭代期间保证结构不被修改。
367    /// 注意:迭代时需要额外获取每个值的读锁
368    pub fn iter_rlock(&self) -> IterRLock<'_, K, V> {
369        let _lock = self.lock.read();
370        let m = unsafe { &*self.dirty.get() };
371        IterRLock {
372            _lock,
373            inner: m.iter(),
374        }
375    }
376
377    /// 不锁值,只锁HashMap结构,适用于只读但不修改值的场景
378    ///
379    /// # Safety
380    /// 此方法是不安全的,因为它绕过了保护每个值的 `RwLock`。
381    /// 仅当您确定没有其他线程正在修改这些值时才应使用它。
382    ///
383    /// This method is unsafe because it bypasses the `RwLock` protecting each value.
384    /// It should only be used when you are sure that no other thread is modifying the values.
385    pub fn iter(&self) -> IterNoLock<'_, K, V> {
386        let _lock = self.lock.read();
387        let m = unsafe { &*self.dirty.get() };
388        IterNoLock {
389            _lock,
390            inner: m.iter(),
391        }
392    }
393
394    /// Get a read-only reference to the underlying HashMap, protected by HashMap read lock
395    /// 获取底层HashMap的只读引用,使用HashMap读锁保护
396    ///
397    /// Returns a `ReadGuardMap` that holds the read lock until the guard is dropped.
398    /// Note: The values in the returned HashMap are of type RwLock<V>
399    /// 返回一个 `ReadGuardMap`,在 guard 被释放前持有读锁。
400    /// 注意:返回的HashMap中的值是 RwLock<V> 类型
401    pub fn dirty_ref(&self) -> ReadGuardMap<'_, K, V> {
402        let _lock = self.lock.read();
403        let v = unsafe { &*self.dirty.get() };
404        ReadGuardMap { _lock, v }
405    }
406
407    /// Get an unsafe reference to the underlying HashMap (no lock protection)
408    /// 获取底层HashMap的不安全引用(无锁保护)
409    ///
410    /// # Safety
411    ///
412    /// The caller must ensure there are no concurrent write operations.
413    /// 调用者需确保没有并发写操作。
414    pub unsafe fn dirty_ref_unsafe(&self) -> &HashMap<K, RwLock<V>, DefaultBuildHasher> {
415        unsafe { &*self.dirty.get() }
416    }
417
418    /// Consume self and return the internal HashMap (unwrap RwLock)
419    /// 消耗self并返回内部的HashMap(解包RwLock)
420    pub fn into_inner(self) -> HashMap<K, V> {
421        self.dirty
422            .into_inner()
423            .into_iter()
424            .map(|(k, v)| (k, v.into_inner()))
425            .collect()
426    }
427
428    /// Get an iterator of keys, protected by HashMap read lock
429    /// 获取键的迭代器,使用HashMap读锁保护
430    ///
431    /// The returned iterator holds the read lock, ensuring the structure is not modified during iteration.
432    /// 返回的迭代器持有读锁,在迭代期间保证结构不被修改。
433    #[inline]
434    pub fn keys(&self) -> KeysGuard<'_, K, V> {
435        let _lock = self.lock.read();
436        let m = unsafe { &*self.dirty.get() };
437        KeysGuard {
438            _lock,
439            inner: m.keys(),
440        }
441    }
442
443    /// Get a read-only iterator of values, protected by HashMap read lock
444    /// 获取值的只读迭代器,使用HashMap读锁保护
445    ///
446    /// The returned iterator holds the HashMap read lock, and acquires a read lock for each value during iteration.
447    /// 返回的迭代器持有HashMap读锁,迭代时会获取每个值的读锁。
448    #[inline]
449    pub fn values(&self) -> ValuesGuard<'_, K, V> {
450        let _lock = self.lock.read();
451        let m = unsafe { &*self.dirty.get() };
452        ValuesGuard {
453            _lock,
454            inner: m.values(),
455        }
456    }
457
458    /// Get a mutable iterator of values, protected by HashMap write lock
459    /// 获取值的可变迭代器,使用HashMap写锁保护
460    ///
461    /// The returned iterator holds the HashMap write lock, ensuring exclusive access during iteration.
462    /// 返回的迭代器持有HashMap写锁,在迭代期间保证独占访问。
463    #[inline]
464    pub fn values_mut(&self) -> ValuesMutGuard<'_, K, V> {
465        let _lock = self.lock.write();
466        let m = unsafe { &*self.dirty.get() };
467        ValuesMutGuard {
468            _lock,
469            inner: m.values(),
470        }
471    }
472
473    /// Retain elements that satisfy the condition, protected by HashMap write lock
474    /// 保留满足条件的元素,使用HashMap写锁保护
475    #[inline]
476    pub fn retain<F>(&self, mut f: F)
477    where
478        F: FnMut(&K, &mut V) -> bool,
479    {
480        let _lock = self.lock.write();
481        let m = unsafe { &mut *self.dirty.get() };
482        m.retain(|k, v| f(k, v.get_mut()));
483    }
484
485    /// Get the capacity of the map, protected by HashMap read lock
486    /// 获取映射的容量,使用HashMap读锁保护
487    #[inline]
488    pub fn capacity(&self) -> usize {
489        let _lock = self.lock.read();
490        let m = unsafe { &*self.dirty.get() };
491        m.capacity()
492    }
493
494    /// Reserve specified capacity, protected by HashMap write lock
495    /// 预留指定容量,使用HashMap写锁保护
496    #[inline]
497    pub fn reserve(&self, additional: usize) {
498        let _lock = self.lock.write();
499        let m = unsafe { &mut *self.dirty.get() };
500        m.reserve(additional);
501    }
502
503    /// Try to remove a key-value pair, returning the removed pair if the key exists, protected by HashMap write lock
504    /// 尝试移除键值对,如果键存在则返回被移除的键值对,使用HashMap写锁保护
505    #[inline]
506    pub fn remove_entry(&self, k: &K) -> Option<(K, V)> {
507        let _lock = self.lock.write();
508        let m = unsafe { &mut *self.dirty.get() };
509        m.remove_entry(k).map(|(k, v)| (k, v.into_inner()))
510    }
511
512    /// If the key exists, return its mutable reference; otherwise, insert a new value. Protected by HashMap write lock + value write lock
513    /// 如果键存在则返回其可变引用,否则插入新值,使用HashMap写锁 + 值写锁保护
514    ///
515    /// Returns a `WriteGuardEntry` that holds the HashMap write lock and the value write lock until the guard is dropped.
516    /// 返回一个 `WriteGuardEntry`,在 guard 被释放前持有HashMap写锁和值的写锁。
517    #[inline]
518    pub fn get_or_insert(&self, k: K, default: V) -> WriteGuardEntry<'_, V> {
519        let map_lock = self.lock.write();
520        let m = unsafe { &mut *self.dirty.get() };
521        let entry = m.entry(k).or_insert_with(|| RwLock::new(default));
522        let value_lock = entry.write();
523        WriteGuardEntry {
524            _map_lock: map_lock,
525            _value_lock: value_lock,
526        }
527    }
528
529    /// If the key exists, return its mutable reference; otherwise, insert the value returned by the function. Protected by HashMap write lock + value write lock
530    /// 如果键存在则返回其可变引用,否则使用函数返回值插入,使用HashMap写锁 + 值写锁保护
531    ///
532    /// Returns a `WriteGuardEntry` that holds the HashMap write lock and the value write lock until the guard is dropped.
533    /// 返回一个 `WriteGuardEntry`,在 guard 被释放前持有HashMap写锁和值的写锁。
534    #[inline]
535    pub fn get_or_insert_with<F>(&self, k: K, default: F) -> WriteGuardEntry<'_, V>
536    where
537        F: FnOnce() -> V,
538    {
539        let map_lock = self.lock.write();
540        let m = unsafe { &mut *self.dirty.get() };
541        let entry = m.entry(k).or_insert_with(|| RwLock::new(default()));
542        let value_lock = entry.write();
543        WriteGuardEntry {
544            _map_lock: map_lock,
545            _value_lock: value_lock,
546        }
547    }
548
549    /// Get a clone of the value corresponding to the key, protected by HashMap read lock + value read lock
550    /// 获取键对应的值的克隆,使用HashMap读锁 + 值的读锁保护
551    ///
552    /// This is a convenient method that directly returns a clone of the value instead of a Guard
553    /// 这是一个便捷方法,直接返回值的克隆而不是Guard
554    #[inline]
555    pub fn get_clone<Q: ?Sized>(&self, k: &Q) -> Option<V>
556    where
557        K: Borrow<Q>,
558        Q: Hash + Eq,
559        V: Clone,
560    {
561        let _map_lock = self.lock.read();
562        let m = unsafe { &*self.dirty.get() };
563        m.get(k).map(|v| v.read().clone())
564    }
565
566    /// Take the value corresponding to the key (remove and return), protected by HashMap write lock
567    /// 取出键对应的值(移除并返回),使用HashMap写锁保护
568    ///
569    /// Same as remove, this is a semantically clearer alias
570    /// 与 remove 相同,这是一个语义更清晰的别名
571    #[inline]
572    pub fn take(&self, k: &K) -> Option<V> {
573        self.remove(k)
574    }
575}
576
577/// Guardian of read-only value reference without value lock, holding HashMap read lock only
578/// 无值锁的只读值引用守护者,仅持有HashMap读锁
579///
580/// # Safety
581/// 此结构绕过了保护值的 `RwLock`,仅当您确定没有其他线程正在修改该值时才应使用。
582/// This struct bypasses the `RwLock` protecting the value.
583/// It should only be used when you are sure that no other thread is modifying the value.
584pub struct MapReadGuard<'a, V> {
585    /// HashMap-level read lock guardian
586    /// HashMap级别的读锁守护者
587    _map_lock: RwLockReadGuard<'a, ()>,
588    /// Value pointer (no lock)
589    /// 值指针(无锁)
590    _value_ptr: &'a V,
591}
592
593impl<'a, V> Deref for MapReadGuard<'a, V> {
594    type Target = V;
595
596    fn deref(&self) -> &Self::Target {
597        self._value_ptr
598    }
599}
600
601impl<'a, V> Debug for MapReadGuard<'a, V>
602where
603    V: Debug,
604{
605    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
606        write!(f, "{:?}", self._value_ptr)
607    }
608}
609
610impl<'a, V> PartialEq for MapReadGuard<'a, V>
611where
612    V: PartialEq,
613{
614    fn eq(&self, other: &Self) -> bool {
615        self._value_ptr.eq(other._value_ptr)
616    }
617}
618
619impl<'a, V> Eq for MapReadGuard<'a, V> where V: Eq {}
620
621impl<'a, V> std::fmt::Display for MapReadGuard<'a, V>
622where
623    V: std::fmt::Display,
624{
625    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
626        self._value_ptr.fmt(f)
627    }
628}
629
630impl<'a, V> AsRef<V> for MapReadGuard<'a, V> {
631    fn as_ref(&self) -> &V {
632        self._value_ptr
633    }
634}
635
636/// Guardian of read-only value reference, holding HashMap read lock and value read lock
637/// 只读值引用的守护者,持有HashMap读锁和值的读锁
638pub struct ReadGuard<'a, V> {
639    /// HashMap-level read lock guardian
640    /// HashMap级别的读锁守护者
641    _map_lock: RwLockReadGuard<'a, ()>,
642    /// Value-level read lock guardian
643    /// 值级别的读锁守护者
644    _value_lock: RwLockReadGuard<'a, V>,
645}
646
647impl<'a, V> Deref for ReadGuard<'a, V> {
648    type Target = V;
649
650    fn deref(&self) -> &Self::Target {
651        &*self._value_lock
652    }
653}
654
655impl<'a, V> Debug for ReadGuard<'a, V>
656where
657    V: Debug,
658{
659    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
660        write!(f, "{:?}", &*self._value_lock)
661    }
662}
663
664impl<'a, V> PartialEq for ReadGuard<'a, V>
665where
666    V: PartialEq,
667{
668    fn eq(&self, other: &Self) -> bool {
669        (*self._value_lock).eq(&*other._value_lock)
670    }
671}
672
673impl<'a, V> Eq for ReadGuard<'a, V> where V: Eq {}
674
675impl<'a, V> std::fmt::Display for ReadGuard<'a, V>
676where
677    V: std::fmt::Display,
678{
679    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
680        (*self._value_lock).fmt(f)
681    }
682}
683
684impl<'a, V> AsRef<V> for ReadGuard<'a, V> {
685    fn as_ref(&self) -> &V {
686        &*self._value_lock
687    }
688}
689
690/// Guardian of read-only HashMap reference, holding HashMap read lock
691/// 只读HashMap引用的守护者,持有HashMap读锁
692///
693/// Note: The values in the returned HashMap are of type RwLock<V>
694/// 注意:返回的HashMap中的值是 RwLock<V> 类型
695pub struct ReadGuardMap<'a, K, V> {
696    /// HashMap read lock guardian
697    /// HashMap读锁守护者
698    _lock: RwLockReadGuard<'a, ()>,
699    /// Read-only HashMap reference (values are RwLock<V>)
700    /// 只读HashMap引用(值为RwLock<V>)
701    v: &'a HashMap<K, RwLock<V>, DefaultBuildHasher>,
702}
703
704impl<'a, K, V> Deref for ReadGuardMap<'a, K, V> {
705    type Target = HashMap<K, RwLock<V>, DefaultBuildHasher>;
706
707    fn deref(&self) -> &Self::Target {
708        self.v
709    }
710}
711
712impl<'a, K, V> Debug for ReadGuardMap<'a, K, V>
713where
714    K: Debug,
715    V: Debug,
716{
717    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
718        // Manually format, read lock for each value
719        // 手动格式化,读取每个值的锁
720        let mut map = f.debug_map();
721        for (k, v) in self.v.iter() {
722            map.entry(k, &*v.read());
723        }
724        map.finish()
725    }
726}
727
728impl<'a, K, V> AsRef<HashMap<K, RwLock<V>, DefaultBuildHasher>> for ReadGuardMap<'a, K, V> {
729    fn as_ref(&self) -> &HashMap<K, RwLock<V>, DefaultBuildHasher> {
730        self.v
731    }
732}
733
734/// Guardian of mutable value reference, holding HashMap read lock and value write lock
735/// 可变值引用的守护者,持有HashMap读锁和值的写锁
736///
737/// This allows other threads to still read other values, but cannot modify this value
738/// 这样其他线程仍可读取其他值,但不能修改此值
739pub struct WriteGuard<'a, V> {
740    /// HashMap-level read lock guardian
741    /// HashMap级别的读锁守护者
742    _map_lock: RwLockReadGuard<'a, ()>,
743    /// Value-level write lock guardian
744    /// 值级别的写锁守护者
745    _value_lock: RwLockWriteGuard<'a, V>,
746}
747
748impl<'a, V> Deref for WriteGuard<'a, V> {
749    type Target = V;
750
751    fn deref(&self) -> &Self::Target {
752        &*self._value_lock
753    }
754}
755
756impl<'a, V> DerefMut for WriteGuard<'a, V> {
757    fn deref_mut(&mut self) -> &mut Self::Target {
758        &mut *self._value_lock
759    }
760}
761
762impl<'a, V> Debug for WriteGuard<'a, V>
763where
764    V: Debug,
765{
766    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
767        write!(f, "{:?}", &*self._value_lock)
768    }
769}
770
771impl<'a, V> PartialEq for WriteGuard<'a, V>
772where
773    V: PartialEq,
774{
775    fn eq(&self, other: &Self) -> bool {
776        (*self._value_lock).eq(&*other._value_lock)
777    }
778}
779
780impl<'a, V> Eq for WriteGuard<'a, V> where V: Eq {}
781
782impl<'a, V> std::fmt::Display for WriteGuard<'a, V>
783where
784    V: std::fmt::Display,
785{
786    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
787        (*self._value_lock).fmt(f)
788    }
789}
790
791impl<'a, V> AsRef<V> for WriteGuard<'a, V> {
792    fn as_ref(&self) -> &V {
793        &*self._value_lock
794    }
795}
796
797impl<'a, V> AsMut<V> for WriteGuard<'a, V> {
798    fn as_mut(&mut self) -> &mut V {
799        &mut *self._value_lock
800    }
801}
802
803/// Guardian for methods like get_or_insert, holding HashMap write lock and value write lock
804/// 用于 get_or_insert 等方法的守护者,持有HashMap写锁和值的写锁
805///
806/// Requires HashMap write lock because it may involve insertion operations
807/// 因为可能涉及插入操作,需要HashMap写锁
808pub struct WriteGuardEntry<'a, V> {
809    /// HashMap-level write lock guardian
810    /// HashMap级别的写锁守护者
811    _map_lock: RwLockWriteGuard<'a, ()>,
812    /// Value-level write lock guardian
813    /// 值级别的写锁守护者
814    _value_lock: RwLockWriteGuard<'a, V>,
815}
816
817impl<'a, V> Deref for WriteGuardEntry<'a, V> {
818    type Target = V;
819
820    fn deref(&self) -> &Self::Target {
821        &*self._value_lock
822    }
823}
824
825impl<'a, V> DerefMut for WriteGuardEntry<'a, V> {
826    fn deref_mut(&mut self) -> &mut Self::Target {
827        &mut *self._value_lock
828    }
829}
830
831impl<'a, V> Debug for WriteGuardEntry<'a, V>
832where
833    V: Debug,
834{
835    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
836        write!(f, "{:?}", &*self._value_lock)
837    }
838}
839
840impl<'a, V> std::fmt::Display for WriteGuardEntry<'a, V>
841where
842    V: std::fmt::Display,
843{
844    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
845        (*self._value_lock).fmt(f)
846    }
847}
848
849impl<'a, V> AsRef<V> for WriteGuardEntry<'a, V> {
850    fn as_ref(&self) -> &V {
851        &*self._value_lock
852    }
853}
854
855impl<'a, V> AsMut<V> for WriteGuardEntry<'a, V> {
856    fn as_mut(&mut self) -> &mut V {
857        &mut *self._value_lock
858    }
859}
860
861/// Type alias, keeping backward compatibility
862/// 类型别名,保持向后兼容
863#[allow(dead_code)]
864#[deprecated(note = "Use ReadGuard instead")]
865pub type SyncMapRefMut<'a, V> = WriteGuard<'a, V>;
866
867/// Guardian of read-only iterator, holding HashMap read lock
868/// 只读迭代器的守护者,持有HashMap读锁
869///
870/// Acquires a read lock for each value during iteration
871/// 迭代时会为每个值获取读锁
872pub struct IterRLock<'a, K, V> {
873    /// HashMap read lock guardian
874    /// HashMap读锁守护者
875    _lock: RwLockReadGuard<'a, ()>,
876    /// Internal iterator (values are RwLock<V>)
877    /// 内部迭代器(值为RwLock<V>)
878    inner: MapIter<'a, K, RwLock<V>>,
879}
880
881impl<'a, K, V> Iterator for IterRLock<'a, K, V> {
882    type Item = (&'a K, RwLockReadGuard<'a, V>);
883
884    fn next(&mut self) -> Option<Self::Item> {
885        self.inner.next().map(|(k, v)| (k, v.read()))
886    }
887}
888
889/// Type alias, keeping backward compatibility
890/// 类型别名,保持向后兼容
891pub type IterMy<'a, K, V> = IterRLock<'a, K, V>;
892
893/// Guardian of mutable iterator, holding HashMap write lock
894/// 可变迭代器的守护者,持有HashMap写锁
895///
896/// Acquires a write lock for each value during iteration
897/// 迭代时会为每个值获取写锁
898pub struct IterMut<'a, K, V> {
899    /// HashMap write lock guardian
900    /// HashMap写锁守护者
901    _lock: RwLockReadGuard<'a, ()>,
902    /// Internal iterator (values are RwLock<V>)
903    /// 内部迭代器(值为RwLock<V>)
904    inner: MapIter<'a, K, RwLock<V>>,
905}
906
907impl<'a, K, V> Iterator for IterMut<'a, K, V> {
908    type Item = (&'a K, RwLockWriteGuard<'a, V>);
909
910    fn next(&mut self) -> Option<Self::Item> {
911        self.inner.next().map(|(k, v)| (k, v.write()))
912    }
913}
914
915/// Guardian of key iterator, holding HashMap read lock
916/// 键迭代器的守护者,持有HashMap读锁
917pub struct KeysGuard<'a, K, V> {
918    /// HashMap read lock guardian
919    /// HashMap读锁守护者
920    _lock: RwLockReadGuard<'a, ()>,
921    /// Internal iterator
922    /// 内部迭代器
923    inner: Keys<'a, K, RwLock<V>>,
924}
925
926impl<'a, K, V> Deref for KeysGuard<'a, K, V> {
927    type Target = Keys<'a, K, RwLock<V>>;
928
929    fn deref(&self) -> &Self::Target {
930        &self.inner
931    }
932}
933
934impl<'a, K, V> DerefMut for KeysGuard<'a, K, V> {
935    fn deref_mut(&mut self) -> &mut Self::Target {
936        &mut self.inner
937    }
938}
939
940impl<'a, K, V> Iterator for KeysGuard<'a, K, V> {
941    type Item = &'a K;
942
943    fn next(&mut self) -> Option<Self::Item> {
944        self.inner.next()
945    }
946}
947
948/// Guardian of read-only value iterator, holding HashMap read lock
949/// 值只读迭代器的守护者,持有HashMap读锁
950///
951/// Acquires a read lock for each value during iteration
952/// 迭代时会为每个值获取读锁
953pub struct ValuesGuard<'a, K, V> {
954    /// HashMap read lock guardian
955    /// HashMap读锁守护者
956    _lock: RwLockReadGuard<'a, ()>,
957    /// Internal iterator
958    /// 内部迭代器
959    inner: std::collections::hash_map::Values<'a, K, RwLock<V>>,
960}
961
962impl<'a, K, V> Iterator for ValuesGuard<'a, K, V> {
963    type Item = RwLockReadGuard<'a, V>;
964
965    fn next(&mut self) -> Option<Self::Item> {
966        self.inner.next().map(|v| v.read())
967    }
968}
969
970/// Guardian of mutable value iterator, holding HashMap write lock
971/// 值可变迭代器的守护者,持有HashMap写锁
972///
973/// Acquires a write lock for each value during iteration
974/// 迭代时会为每个值获取写锁
975pub struct ValuesMutGuard<'a, K, V> {
976    /// HashMap write lock guardian
977    /// HashMap写锁守护者
978    _lock: RwLockWriteGuard<'a, ()>,
979    /// Internal iterator
980    /// 内部迭代器
981    inner: std::collections::hash_map::Values<'a, K, RwLock<V>>,
982}
983
984impl<'a, K, V> Iterator for ValuesMutGuard<'a, K, V> {
985    type Item = RwLockWriteGuard<'a, V>;
986
987    fn next(&mut self) -> Option<Self::Item> {
988        self.inner.next().map(|v| v.write())
989    }
990}
991
992/// 不锁值的迭代器,只锁HashMap结构
993/// Iterator that only locks HashMap structure, not individual values
994pub struct IterNoLock<'a, K, V> {
995    /// HashMap读锁守护者
996    /// HashMap read lock guardian
997    _lock: RwLockReadGuard<'a, ()>,
998    /// 内部迭代器(值为RwLock<V>)
999    /// Internal iterator (values are RwLock<V>)
1000    inner: MapIter<'a, K, RwLock<V>>,
1001}
1002
1003impl<'a, K, V> Iterator for IterNoLock<'a, K, V> {
1004    type Item = (&'a K, &'a V);
1005
1006    fn next(&mut self) -> Option<Self::Item> {
1007        self.inner.next().map(|(k, v)| {
1008            // SAFETY: 调用者通过文档约定保证没有并发写入
1009            unsafe {
1010                let lock_ptr = v as *const RwLock<V> as *mut RwLock<V>;
1011                (k, &*(*lock_ptr).get_mut())
1012            }
1013        })
1014    }
1015}
1016
1017impl<'a, K, V> ExactSizeIterator for IterNoLock<'a, K, V> {
1018    fn len(&self) -> usize {
1019        self.inner.len()
1020    }
1021}
1022
1023impl<'a, K, V> IntoIterator for &'a SyncHashMap<K, V>
1024where
1025    K: Eq + Hash,
1026{
1027    type Item = (&'a K, &'a V);
1028    type IntoIter = IterNoLock<'a, K, V>;
1029
1030    fn into_iter(self) -> Self::IntoIter {
1031        self.iter()
1032    }
1033}
1034
1035impl<'a, K, V> IntoIterator for &'a mut SyncHashMap<K, V>
1036where
1037    K: Eq + Hash,
1038{
1039    type Item = (&'a K, RwLockWriteGuard<'a, V>);
1040    type IntoIter = IterMut<'a, K, V>;
1041
1042    fn into_iter(self) -> Self::IntoIter {
1043        self.iter_mut()
1044    }
1045}
1046
1047impl<K, V> IntoIterator for SyncHashMap<K, V>
1048where
1049    K: Eq + Hash,
1050{
1051    type Item = (K, V);
1052    type IntoIter = MapIntoIter<K, V>;
1053
1054    fn into_iter(self) -> Self::IntoIter {
1055        self.into_inner().into_iter()
1056    }
1057}
1058
1059impl<K, V> From<HashMap<K, V>> for SyncHashMap<K, V>
1060where
1061    K: Eq + Hash,
1062{
1063    fn from(map: HashMap<K, V>) -> Self {
1064        Self::with_map(map)
1065    }
1066}
1067
1068impl<K, V> Serialize for SyncHashMap<K, V>
1069where
1070    K: Eq + Hash + Serialize,
1071    V: Serialize,
1072{
1073    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1074    where
1075        S: Serializer,
1076    {
1077        use serde::ser::SerializeMap;
1078        let _lock = self.lock.read();
1079        let m = unsafe { &*self.dirty.get() };
1080        let mut map = serializer.serialize_map(Some(m.len()))?;
1081        for (k, v) in m.iter() {
1082            map.serialize_entry(k, &*v.read())?;
1083        }
1084        map.end()
1085    }
1086}
1087
1088impl<'de, K, V> Deserialize<'de> for SyncHashMap<K, V>
1089where
1090    K: Eq + Hash + Deserialize<'de>,
1091    V: Deserialize<'de>,
1092{
1093    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1094    where
1095        D: Deserializer<'de>,
1096    {
1097        let m = HashMap::deserialize(deserializer)?;
1098        Ok(Self::with_map(m))
1099    }
1100}
1101
1102impl<K, V> Debug for SyncHashMap<K, V>
1103where
1104    K: Eq + Hash + Debug,
1105    V: Debug,
1106{
1107    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1108        let _lock = self.lock.read();
1109        let m = unsafe { &*self.dirty.get() };
1110        let mut map = f.debug_map();
1111        for (k, v) in m.iter() {
1112            map.entry(k, &*v.read());
1113        }
1114        map.finish()
1115    }
1116}
1117
1118impl<K, V> Clone for SyncHashMap<K, V>
1119where
1120    K: Clone + Eq + Hash,
1121    V: Clone,
1122{
1123    fn clone(&self) -> Self {
1124        let _lock = self.lock.read();
1125        let m = unsafe { &*self.dirty.get() };
1126        let cloned: HashMap<K, V> = m
1127            .iter()
1128            .map(|(k, v)| (k.clone(), v.read().clone()))
1129            .collect();
1130        SyncHashMap::with_map(cloned)
1131    }
1132}
1133
1134impl<K, V> Default for SyncHashMap<K, V>
1135where
1136    K: Eq + Hash,
1137{
1138    fn default() -> Self {
1139        Self::new()
1140    }
1141}
1142
1143impl<K, V> PartialEq for SyncHashMap<K, V>
1144where
1145    K: Eq + Hash,
1146    V: PartialEq,
1147{
1148    fn eq(&self, other: &Self) -> bool {
1149        let _lock_self = self.lock.read();
1150        let _lock_other = other.lock.read();
1151        let self_map = unsafe { &*self.dirty.get() };
1152        let other_map = unsafe { &*other.dirty.get() };
1153
1154        if self_map.len() != other_map.len() {
1155            return false;
1156        }
1157
1158        for (k, v) in self_map.iter() {
1159            match other_map.get(k) {
1160                Some(other_v) => {
1161                    if *v.read() != *other_v.read() {
1162                        return false;
1163                    }
1164                }
1165                None => return false,
1166            }
1167        }
1168        true
1169    }
1170}
1171
1172impl<K, V> Eq for SyncHashMap<K, V>
1173where
1174    K: Eq + Hash,
1175    V: Eq,
1176{
1177}
1178
1179/// Bucketed hash map module, providing higher concurrency hash map implementation
1180/// 分桶哈希映射模块,提供更高并发的哈希映射实现
1181pub mod buckets {
1182    use super::{MapReadGuard, ReadGuard, SyncHashMap, WriteGuard};
1183    use std::hash::{Hash, Hasher};
1184
1185    /// Bucketed hash map, distributing data to multiple sub-maps to improve concurrency performance
1186    /// 分桶哈希映射,将数据分散到多个子映射中以提高并发性能
1187    #[derive(Debug, Clone)]
1188    pub struct SyncHashMapB<K, V>
1189    where
1190        K: Eq + Hash,
1191    {
1192        /// Internal array of sub-maps
1193        /// 内部的子映射数组
1194        inner: Vec<SyncHashMap<K, V>>,
1195        /// Number of buckets
1196        /// 分桶数量
1197        len: usize,
1198    }
1199
1200    impl<K, V> SyncHashMapB<K, V>
1201    where
1202        K: Eq + Hash,
1203    {
1204        /// Create a new bucketed hash map
1205        /// 创建新的分桶哈希映射
1206        ///
1207        /// # Arguments
1208        /// * `bucket_count` - Number of buckets, defaults to 10 if None
1209        /// * `bucket_count` - 分桶数量,如果为None则默认为10
1210        ///
1211        /// # Examples
1212        /// ```
1213        /// use fast_able::map_hash::buckets::SyncHashMapB;
1214        ///
1215        /// let map = SyncHashMapB::new(None);
1216        /// map.insert(1, "a");
1217        /// map.insert(2, "b");
1218        /// assert_eq!(*map.get(&1).unwrap(), "a");
1219        /// assert_eq!(*map.get(&2).unwrap(), "b");
1220        /// assert!(map.get(&3).is_none());
1221        /// ```
1222        pub fn new(bucket_count: Option<usize>) -> Self {
1223            let count = bucket_count.unwrap_or(10);
1224            let mut arr = Vec::with_capacity(count);
1225            for _ in 0..count {
1226                arr.push(SyncHashMap::new());
1227            }
1228            Self {
1229                inner: arr,
1230                len: count,
1231            }
1232        }
1233
1234        /// Convert key to bucket index
1235        /// 将键转换为桶索引
1236        fn key_to_bucket_index(&self, k: &K) -> usize {
1237            let mut hasher = std::collections::hash_map::DefaultHasher::new();
1238            k.hash(&mut hasher);
1239            let hash = hasher.finish();
1240            (hash % self.len as u64) as usize
1241        }
1242
1243        /// Insert a key-value pair
1244        /// 插入键值对
1245        #[inline]
1246        pub fn insert(&self, k: K, v: V) -> Option<V> {
1247            let index = self.key_to_bucket_index(&k);
1248            self.inner[index].insert(k, v)
1249        }
1250
1251        /// Insert operation under mutable reference
1252        /// 可变引用下的插入操作
1253        #[inline]
1254        pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
1255            let index = self.key_to_bucket_index(&k);
1256            self.inner[index].insert_mut(k, v)
1257        }
1258
1259        /// Remove a key-value pair
1260        /// 移除键值对
1261        #[inline]
1262        pub fn remove(&self, k: &K) -> Option<V> {
1263            let index = self.key_to_bucket_index(k);
1264            self.inner[index].remove(k)
1265        }
1266
1267        /// Check if empty
1268        /// 检查是否为空
1269        #[inline]
1270        pub fn is_empty(&self) -> bool {
1271            self.inner.iter().all(|bucket| bucket.is_empty())
1272        }
1273
1274        /// Get total length
1275        /// 获取总长度
1276        #[inline]
1277        pub fn len(&self) -> usize {
1278            self.inner.iter().map(|bucket| bucket.len()).sum()
1279        }
1280
1281        /// Clear all buckets
1282        /// 清空所有桶
1283        #[inline]
1284        pub fn clear(&self) {
1285            self.inner.iter().for_each(|bucket| bucket.clear());
1286        }
1287
1288        /// Get a reference to the value corresponding to the key, protected by read lock (value no lock)
1289        /// 获取键对应的值引用,使用读锁保护 (值无锁)
1290        ///
1291        /// Returns a `ReadGuardNoLock` that holds the read lock until the guard is dropped.
1292        /// 返回一个 `ReadGuardNoLock`,在 guard 被释放前持有读锁。
1293        #[inline]
1294        pub fn get(&self, k: &K) -> Option<MapReadGuard<'_, V>> {
1295            let index = self.key_to_bucket_index(k);
1296            self.inner[index].get(k)
1297        }
1298
1299        /// Get a mutable reference to the value corresponding to the key, protected by write lock
1300        /// 获取键对应的可变值引用,使用写锁保护
1301        ///
1302        /// Returns a `WriteGuard` that holds the write lock until the guard is dropped, ensuring concurrent access safety.
1303        /// 返回一个 `WriteGuard`,在 guard 被释放前持有写锁,保证并发访问安全。
1304        #[inline]
1305        pub fn get_mut(&self, k: &K) -> Option<WriteGuard<'_, V>> {
1306            let index = self.key_to_bucket_index(k);
1307            self.inner[index].get_mut(k)
1308        }
1309
1310        /// Get the number of buckets
1311        /// 获取桶数量
1312        #[inline]
1313        pub fn bucket_count(&self) -> usize {
1314            self.len
1315        }
1316
1317        /// Get an iterator of all keys
1318        /// 获取所有键的迭代器
1319        #[inline]
1320        pub fn keys(&self) -> impl Iterator<Item = &K> {
1321            self.inner.iter().flat_map(|bucket| bucket.keys())
1322        }
1323
1324        /// Get a clone of the value corresponding to the key
1325        /// 获取键对应的值的克隆
1326        #[inline]
1327        pub fn get_clone(&self, k: &K) -> Option<V>
1328        where
1329            V: Clone,
1330        {
1331            let index = self.key_to_bucket_index(k);
1332            self.inner[index].get_clone(k)
1333        }
1334    }
1335
1336    impl<K, V> Default for SyncHashMapB<K, V>
1337    where
1338        K: Eq + Hash,
1339    {
1340        fn default() -> Self {
1341            Self::new(None)
1342        }
1343    }
1344}
1345
1346#[cfg(test)]
1347mod tests {
1348    use super::*;
1349    use std::collections::HashMap;
1350    use std::sync::Arc;
1351    use std::thread;
1352
1353    #[test]
1354    fn test_sync_hash_map_new() {
1355        let map: SyncHashMap<i32, String> = SyncHashMap::new();
1356        assert_eq!(map.len(), 0);
1357        assert!(map.is_empty());
1358    }
1359
1360    #[test]
1361    fn test_sync_hash_map_with_capacity() {
1362        let map = SyncHashMap::<i32, String>::with_capacity(100);
1363        assert!(map.capacity() >= 100);
1364    }
1365
1366    #[test]
1367    fn test_sync_hash_map_with_map() {
1368        let mut original = HashMap::new();
1369        original.insert(1, "one".to_string());
1370        original.insert(2, "two".to_string());
1371
1372        let map = SyncHashMap::with_map(original);
1373        assert_eq!(map.len(), 2);
1374        assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1375        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1376    }
1377
1378    #[test]
1379    fn test_sync_hash_map_insert_and_get() {
1380        let map = SyncHashMap::new();
1381
1382        // 测试插入和获取
1383        assert_eq!(map.insert(1, "one".to_string()), None);
1384        assert_eq!(map.insert(2, "two".to_string()), None);
1385        assert_eq!(map.len(), 2);
1386
1387        assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1388        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1389        assert!(map.get(&3).is_none());
1390    }
1391
1392    #[test]
1393    fn test_sync_hash_map_insert_replace() {
1394        let map = SyncHashMap::new();
1395
1396        assert_eq!(map.insert(1, "one".to_string()), None);
1397        assert_eq!(
1398            map.insert(1, "updated".to_string()),
1399            Some("one".to_string())
1400        );
1401        assert_eq!(*map.get(&1).unwrap(), "updated".to_string());
1402    }
1403
1404    #[test]
1405    fn test_sync_hash_map_remove() {
1406        let map = SyncHashMap::new();
1407
1408        map.insert(1, "one".to_string());
1409        map.insert(2, "two".to_string());
1410
1411        assert_eq!(map.remove(&1), Some("one".to_string()));
1412        assert_eq!(map.remove(&1), None);
1413        assert_eq!(map.len(), 1);
1414        assert!(map.get(&1).is_none());
1415        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1416    }
1417
1418    #[test]
1419    fn test_sync_hash_map_contains_key() {
1420        let map = SyncHashMap::new();
1421
1422        map.insert(1, "one".to_string());
1423
1424        assert!(map.contains_key(&1));
1425        assert!(!map.contains_key(&2));
1426    }
1427
1428    #[test]
1429    fn test_sync_hash_map_clear() {
1430        let map = SyncHashMap::new();
1431
1432        map.insert(1, "one".to_string());
1433        map.insert(2, "two".to_string());
1434
1435        assert_eq!(map.len(), 2);
1436        map.clear();
1437        assert_eq!(map.len(), 0);
1438        assert!(map.is_empty());
1439    }
1440
1441    #[test]
1442    fn test_sync_hash_map_capacity_operations() {
1443        let map = SyncHashMap::new();
1444
1445        assert_eq!(map.capacity(), 0);
1446        map.reserve(100);
1447        assert!(map.capacity() >= 100);
1448
1449        map.insert(1, "one".to_string());
1450        map.insert(2, "two".to_string());
1451
1452        let old_capacity = map.capacity();
1453        map.shrink_to_fit();
1454        assert!(map.capacity() <= old_capacity);
1455    }
1456
1457    #[test]
1458    fn test_sync_hash_map_retain() {
1459        let map = SyncHashMap::new();
1460
1461        map.insert(1, "one".to_string());
1462        map.insert(2, "two".to_string());
1463        map.insert(3, "three".to_string());
1464
1465        map.retain(|&k, _| k % 2 == 1);
1466
1467        assert_eq!(map.len(), 2);
1468        assert!(map.contains_key(&1));
1469        assert!(!map.contains_key(&2));
1470        assert!(map.contains_key(&3));
1471    }
1472
1473    #[test]
1474    fn test_sync_hash_map_get_or_insert() {
1475        let map = SyncHashMap::new();
1476
1477        // 键不存在时插入
1478        {
1479            let value = map.get_or_insert(1, "default".to_string());
1480            assert_eq!(*value, "default");
1481        }
1482        assert_eq!(map.len(), 1);
1483
1484        // 键存在时返回现有值
1485        {
1486            let value = map.get_or_insert(1, "new_default".to_string());
1487            assert_eq!(*value, "default");
1488        }
1489        assert_eq!(map.len(), 1);
1490    }
1491
1492    #[test]
1493    fn test_sync_hash_map_get_or_insert_with() {
1494        let map = SyncHashMap::new();
1495
1496        {
1497            let value = map.get_or_insert_with(1, || "computed".to_string());
1498            assert_eq!(*value, "computed");
1499        }
1500        assert_eq!(map.len(), 1);
1501
1502        {
1503            let value = map.get_or_insert_with(1, || "new_computed".to_string());
1504            assert_eq!(*value, "computed");
1505        }
1506    }
1507
1508    #[test]
1509    fn test_sync_hash_map_remove_entry() {
1510        let map = SyncHashMap::new();
1511
1512        map.insert(1, "one".to_string());
1513        map.insert(2, "two".to_string());
1514
1515        let removed = map.remove_entry(&1);
1516        assert_eq!(removed, Some((1, "one".to_string())));
1517        assert_eq!(map.len(), 1);
1518        assert!(!map.contains_key(&1));
1519    }
1520
1521    #[test]
1522    fn test_sync_hash_map_iterators() {
1523        let map = SyncHashMap::new();
1524
1525        map.insert(1, "one".to_string());
1526        map.insert(2, "two".to_string());
1527        map.insert(3, "three".to_string());
1528
1529        // 测试 keys 迭代器
1530        let keys: Vec<_> = map.keys().collect();
1531        assert!(keys.contains(&&1));
1532        assert!(keys.contains(&&2));
1533        assert!(keys.contains(&&3));
1534
1535        // 测试 values 迭代器 - 使用 get_clone 来验证
1536        assert_eq!(map.get_clone(&1), Some("one".to_string()));
1537        assert_eq!(map.get_clone(&2), Some("two".to_string()));
1538        assert_eq!(map.get_clone(&3), Some("three".to_string()));
1539
1540        // 测试 iter 迭代器
1541        let mut count = 0;
1542        for (k, v) in map.iter() {
1543            count += 1;
1544            assert!(map.contains_key(k));
1545            assert_eq!(*map.get(k).unwrap(), *v);
1546        }
1547        assert_eq!(count, 3);
1548    }
1549
1550    #[test]
1551    fn test_sync_hash_map_iter_mut() {
1552        let map = SyncHashMap::new();
1553
1554        map.insert(1, "one".to_string());
1555        map.insert(2, "two".to_string());
1556
1557        for (k, mut v) in map.iter_mut() {
1558            if *k == 1 {
1559                *v = "modified".to_string();
1560            }
1561        }
1562
1563        assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1564        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1565    }
1566
1567    #[test]
1568    fn test_sync_hash_map_values_mut() {
1569        let map = SyncHashMap::new();
1570
1571        map.insert(1, "one".to_string());
1572        map.insert(2, "two".to_string());
1573
1574        for mut v in map.values_mut() {
1575            if *v == "one" {
1576                *v = "modified".to_string();
1577            }
1578        }
1579
1580        assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1581        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1582    }
1583
1584    #[test]
1585    fn test_sync_hash_map_get_clone() {
1586        let map = SyncHashMap::new();
1587        map.insert(1, "one".to_string());
1588
1589        // 测试 get_clone 方法
1590        assert_eq!(map.get_clone(&1), Some("one".to_string()));
1591        assert_eq!(map.get_clone(&2), None);
1592    }
1593
1594    #[test]
1595    fn test_sync_hash_map_clone() {
1596        let map1 = SyncHashMap::new();
1597        map1.insert(1, "one".to_string());
1598        map1.insert(2, "two".to_string());
1599
1600        let map2 = map1.clone();
1601
1602        assert_eq!(map1.len(), map2.len());
1603        assert_eq!(*map1.get(&1).unwrap(), *map2.get(&1).unwrap());
1604        assert_eq!(*map1.get(&2).unwrap(), *map2.get(&2).unwrap());
1605
1606        // 修改原映射不影响克隆
1607        map1.insert(3, "three".to_string());
1608        assert!(!map2.contains_key(&3));
1609    }
1610
1611    #[test]
1612    fn test_sync_hash_map_partial_eq() {
1613        let map1 = SyncHashMap::new();
1614        map1.insert(1, "one".to_string());
1615        map1.insert(2, "two".to_string());
1616
1617        let map2 = SyncHashMap::new();
1618        map2.insert(1, "one".to_string());
1619        map2.insert(2, "two".to_string());
1620
1621        let map3 = SyncHashMap::new();
1622        map3.insert(1, "different".to_string());
1623
1624        assert_eq!(map1, map2);
1625        assert_ne!(map1, map3);
1626    }
1627
1628    #[test]
1629    fn test_sync_hash_map_debug() {
1630        let map = SyncHashMap::new();
1631        map.insert(1, "one".to_string());
1632
1633        let debug_str = format!("{:?}", map);
1634        assert!(debug_str.contains("1"));
1635        assert!(debug_str.contains("one"));
1636    }
1637
1638    #[test]
1639    fn test_sync_hash_map_serialization() {
1640        let map = SyncHashMap::new();
1641        map.insert(1, "one".to_string());
1642        map.insert(2, "two".to_string());
1643
1644        // 测试序列化
1645        let serialized = serde_json::to_string(&map).unwrap();
1646        assert!(serialized.contains("1"));
1647        assert!(serialized.contains("one"));
1648        assert!(serialized.contains("2"));
1649        assert!(serialized.contains("two"));
1650
1651        // 测试反序列化
1652        let deserialized: SyncHashMap<i32, String> = serde_json::from_str(&serialized).unwrap();
1653        assert_eq!(deserialized.len(), 2);
1654        assert_eq!(*deserialized.get(&1).unwrap(), "one".to_string());
1655        assert_eq!(*deserialized.get(&2).unwrap(), "two".to_string());
1656    }
1657
1658    #[test]
1659    fn test_sync_hash_map_from_hashmap() {
1660        let mut original = HashMap::new();
1661        original.insert(1, "one".to_string());
1662        original.insert(2, "two".to_string());
1663
1664        let map = SyncHashMap::from(original);
1665
1666        assert_eq!(map.len(), 2);
1667        assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1668        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1669    }
1670
1671    #[test]
1672    fn test_sync_hash_map_into_iterator() {
1673        let map = SyncHashMap::new();
1674        map.insert(1, "one".to_string());
1675        map.insert(2, "two".to_string());
1676
1677        // 测试 IntoIterator for &SyncHashMap
1678        let mut count = 0;
1679        for (k, v) in &map {
1680            count += 1;
1681            assert!(map.contains_key(k));
1682            assert_eq!(*map.get(k).unwrap(), *v);
1683        }
1684        assert_eq!(count, 2);
1685
1686        // 测试 IntoIterator for SyncHashMap
1687        let owned_pairs: Vec<_> = map.into_iter().collect();
1688        assert_eq!(owned_pairs.len(), 2);
1689    }
1690
1691    #[test]
1692    fn test_sync_hash_map_default() {
1693        let map: SyncHashMap<i32, String> = Default::default();
1694        assert_eq!(map.len(), 0);
1695        assert!(map.is_empty());
1696    }
1697
1698    #[test]
1699    fn test_sync_hash_map_arc() {
1700        let map = SyncHashMap::new_arc();
1701        map.insert(1, "one".to_string());
1702
1703        assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1704
1705        let map2 = Arc::clone(&map);
1706        map2.insert(2, "two".to_string());
1707
1708        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1709    }
1710
1711    #[test]
1712    fn test_sync_hash_map_get_mut() {
1713        let map = SyncHashMap::new();
1714        map.insert(1, "one".to_string());
1715
1716        {
1717            let mut value = map.get_mut(&1).unwrap();
1718            *value = "modified".to_string();
1719        }
1720
1721        assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1722    }
1723
1724    #[test]
1725    fn test_sync_hash_map_concurrent_access() {
1726        let map = Arc::new(SyncHashMap::new());
1727
1728        // 并发写入测试
1729        let handles: Vec<_> = (0..10)
1730            .map(|i| {
1731                let map = Arc::clone(&map);
1732                thread::spawn(move || {
1733                    map.insert(i, format!("value_{}", i));
1734                })
1735            })
1736            .collect();
1737
1738        for handle in handles {
1739            handle.join().unwrap();
1740        }
1741
1742        // 验证所有值都被插入
1743        assert_eq!(map.len(), 10);
1744        for i in 0..10 {
1745            assert_eq!(*map.get(&i).unwrap(), format!("value_{}", i));
1746        }
1747
1748        // 并发读取测试
1749        let map_read = Arc::clone(&map);
1750        let handles: Vec<_> = (0..10)
1751            .map(|i| {
1752                let map = Arc::clone(&map_read);
1753                thread::spawn(move || {
1754                    let value = map.get(&i);
1755                    assert_eq!(*value.unwrap(), format!("value_{}", i));
1756                })
1757            })
1758            .collect();
1759
1760        for handle in handles {
1761            handle.join().unwrap();
1762        }
1763    }
1764
1765    #[test]
1766    fn test_sync_hash_map_dirty_ref() {
1767        let map = SyncHashMap::new();
1768        map.insert(1, "one".to_string());
1769
1770        let dirty = map.dirty_ref();
1771        assert_eq!(dirty.len(), 1);
1772        // dirty 返回的是 HashMap<K, RwLock<V>>,需要读取锁
1773        assert_eq!(*dirty.get(&1).unwrap().read(), "one".to_string());
1774    }
1775
1776    #[test]
1777    fn test_sync_hash_map_into_inner() {
1778        let map = SyncHashMap::new();
1779        map.insert(1, "one".to_string());
1780        map.insert(2, "two".to_string());
1781
1782        let inner = map.into_inner();
1783        assert_eq!(inner.len(), 2);
1784        assert_eq!(inner.get(&1), Some(&"one".to_string()));
1785        assert_eq!(inner.get(&2), Some(&"two".to_string()));
1786    }
1787
1788    #[test]
1789    fn test_sync_hash_map_guard_debug() {
1790        let map = SyncHashMap::new();
1791        map.insert(1, "test".to_string());
1792
1793        let guard = map.get(&1).unwrap();
1794        let debug_str = format!("{:?}", guard);
1795        assert!(debug_str.contains("test"));
1796    }
1797
1798    #[test]
1799    fn test_sync_hash_map_guard_partial_eq() {
1800        let map = SyncHashMap::new();
1801        map.insert(1, "value".to_string());
1802
1803        let guard1 = map.get(&1).unwrap();
1804        let guard2 = map.get(&1).unwrap();
1805
1806        assert_eq!(guard1, guard2);
1807    }
1808
1809    // 分桶映射测试
1810    mod buckets_tests {
1811        use super::*;
1812
1813        #[test]
1814        fn test_sync_hash_map_buckets_new() {
1815            let map = buckets::SyncHashMapB::<i32, String>::new(None);
1816            assert_eq!(map.len(), 0);
1817            assert!(map.is_empty());
1818            assert_eq!(map.bucket_count(), 10); // 默认桶数量
1819        }
1820
1821        #[test]
1822        fn test_sync_hash_map_buckets_with_custom_size() {
1823            let map = buckets::SyncHashMapB::<i32, String>::new(Some(5));
1824            assert_eq!(map.bucket_count(), 5);
1825        }
1826
1827        #[test]
1828        fn test_sync_hash_map_buckets_insert_and_get() {
1829            let map = buckets::SyncHashMapB::new(Some(3));
1830
1831            assert_eq!(map.insert(1, "one".to_string()), None);
1832            assert_eq!(map.insert(2, "two".to_string()), None);
1833            assert_eq!(map.len(), 2);
1834
1835            assert_eq!(*map.get(&1).unwrap(), "one".to_string());
1836            assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1837            assert!(map.get(&3).is_none());
1838        }
1839
1840        #[test]
1841        fn test_sync_hash_map_buckets_remove() {
1842            let map = buckets::SyncHashMapB::new(Some(3));
1843
1844            map.insert(1, "one".to_string());
1845            map.insert(2, "two".to_string());
1846
1847            assert_eq!(map.remove(&1), Some("one".to_string()));
1848            assert_eq!(map.len(), 1);
1849            assert!(map.get(&1).is_none());
1850            assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1851        }
1852
1853        #[test]
1854        fn test_sync_hash_map_buckets_clear() {
1855            let map = buckets::SyncHashMapB::new(Some(3));
1856
1857            map.insert(1, "one".to_string());
1858            map.insert(2, "two".to_string());
1859
1860            assert_eq!(map.len(), 2);
1861            map.clear();
1862            assert_eq!(map.len(), 0);
1863            assert!(map.is_empty());
1864        }
1865
1866        #[test]
1867        fn test_sync_hash_map_buckets_iterators() {
1868            let map = buckets::SyncHashMapB::new(Some(3));
1869
1870            map.insert(1, "one".to_string());
1871            map.insert(2, "two".to_string());
1872            map.insert(3, "three".to_string());
1873
1874            // 测试 keys 迭代器
1875            let keys: Vec<_> = map.keys().collect();
1876            assert!(keys.contains(&&1));
1877            assert!(keys.contains(&&2));
1878            assert!(keys.contains(&&3));
1879
1880            // 测试 get_clone 方法
1881            assert_eq!(map.get_clone(&1), Some("one".to_string()));
1882            assert_eq!(map.get_clone(&2), Some("two".to_string()));
1883            assert_eq!(map.get_clone(&3), Some("three".to_string()));
1884
1885            // 测试 get_mut
1886            {
1887                let mut v = map.get_mut(&1).unwrap();
1888                *v = "modified".to_string();
1889            }
1890
1891            assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1892        }
1893
1894        #[test]
1895        fn test_sync_hash_map_buckets_default() {
1896            let map: buckets::SyncHashMapB<i32, String> = Default::default();
1897            assert_eq!(map.len(), 0);
1898            assert!(map.is_empty());
1899            assert_eq!(map.bucket_count(), 10);
1900        }
1901
1902        #[test]
1903        fn test_sync_hash_map_buckets_debug() {
1904            let map = buckets::SyncHashMapB::new(Some(2));
1905            map.insert(1, "one".to_string());
1906
1907            let debug_str = format!("{:?}", map);
1908            assert!(debug_str.contains("1"));
1909            assert!(debug_str.contains("one"));
1910        }
1911    }
1912
1913    #[test]
1914    fn test_sync_hash_map_comprehensive() {
1915        let map = SyncHashMap::new();
1916
1917        // 测试各种操作的组合
1918        map.insert("key1", 42);
1919        map.insert("key2", 24);
1920
1921        assert_eq!(map.len(), 2);
1922        assert!(!map.is_empty());
1923
1924        // 测试修改操作
1925        *map.get_mut("key1").unwrap() = 100;
1926        assert_eq!(*map.get(&"key1").unwrap(), 100);
1927
1928        // 测试条件保留
1929        map.insert("key3", 50);
1930        map.retain(|_, v| *v > 30);
1931
1932        assert_eq!(map.len(), 2);
1933        assert_eq!(*map.get(&"key1").unwrap(), 100);
1934        assert!(map.get(&"key2").is_none());
1935        assert_eq!(*map.get(&"key3").unwrap(), 50);
1936
1937        // 测试克隆和比较
1938        let map2 = map.clone();
1939        assert_eq!(map, map2);
1940
1941        // 测试迭代
1942        let mut sum = 0;
1943        for (_, v) in map.iter() {
1944            sum += *v;
1945        }
1946        assert_eq!(sum, 150);
1947
1948        // 测试清空
1949        map.clear();
1950        assert_eq!(map.len(), 0);
1951        assert!(map.is_empty());
1952    }
1953
1954    #[test]
1955    fn test_sync_hash_map_iter_nlock() {
1956        let map = SyncHashMap::new();
1957        map.insert(1, "one".to_string());
1958        map.insert(2, "two".to_string());
1959        map.insert(3, "three".to_string());
1960
1961        // 测试 iter_nlock 基本功能
1962        let mut count = 0;
1963        for (k, v) in map.iter() {
1964            count += 1;
1965            match *k {
1966                1 => assert_eq!(v, "one"),
1967                2 => assert_eq!(v, "two"),
1968                3 => assert_eq!(v, "three"),
1969                _ => panic!("unexpected key"),
1970            }
1971        }
1972        assert_eq!(count, 3);
1973
1974        // 测试 ExactSizeIterator
1975        let iter = map.iter();
1976        assert_eq!(iter.len(), 3);
1977    }
1978
1979    #[test]
1980    fn test_sync_hash_map_into_iter_mut() {
1981        let mut map = SyncHashMap::new();
1982        map.insert(1, "one".to_string());
1983        map.insert(2, "two".to_string());
1984
1985        // 测试 IntoIterator for &mut SyncHashMap
1986        for (k, mut v) in &mut map {
1987            if *k == 1 {
1988                *v = "modified".to_string();
1989            }
1990        }
1991
1992        assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
1993        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
1994    }
1995
1996    #[test]
1997    fn test_sync_hash_map_into_iter_ref() {
1998        let map = SyncHashMap::new();
1999        map.insert(1, 10);
2000        map.insert(2, 20);
2001        map.insert(3, 30);
2002
2003        // 测试 IntoIterator for &SyncHashMap
2004        let mut sum = 0;
2005        for (_, v) in &map {
2006            sum += *v;
2007        }
2008        assert_eq!(sum, 60);
2009
2010        // 确保 map 仍然可用
2011        assert_eq!(map.len(), 3);
2012    }
2013
2014    #[test]
2015    fn test_sync_hash_map_iter_nlock_empty() {
2016        let map: SyncHashMap<i32, String> = SyncHashMap::new();
2017
2018        let mut count = 0;
2019        for _ in map.iter() {
2020            count += 1;
2021        }
2022        assert_eq!(count, 0);
2023
2024        let iter = map.iter();
2025        assert_eq!(iter.len(), 0);
2026    }
2027}