fast_able/
map_hash.rs

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