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