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