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