use serde::{Deserialize, Deserializer, Serialize, Serializer};
use spin::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::borrow::Borrow;
use std::cell::UnsafeCell;
use std::collections::hash_map::{
    IntoIter as MapIntoIter, Iter as MapIter, Keys,
};
use std::collections::HashMap;
use std::fmt::{Debug, Formatter};
use std::hash::{Hash, DefaultHasher, BuildHasherDefault};
use std::ops::{Deref, DerefMut};
use std::sync::Arc;

/// Default hasher type alias
/// 默认哈希器类型别名
/// 
/// Use `BuildHasherDefault<DefaultHasher>` to support `const fn new()`.
/// Note: This hasher has no random seed. If untrusted external input is accepted as a key,
/// it may be subject to hash collision attacks (HashDoS).
/// 使用 `BuildHasherDefault<DefaultHasher>` 以支持 `const fn new()`。
/// 注意：此哈希器没有随机种子，如果接受不可信的外部输入作为 key，
/// 可能会受到哈希碰撞攻击（HashDoS）。
pub type DefaultBuildHasher = BuildHasherDefault<DefaultHasher>;

/// Synchronous hash map supporting fine-grained lock control
/// 同步哈希映射，支持细粒度锁控制
/// 
/// Locking strategy:
/// - Read operations like `get`: HashMap read lock + value read lock
/// - Value modification operations like `get_mut`: HashMap read lock + value write lock
/// - Structure modification operations like `insert`/`remove`: HashMap write lock
/// 锁策略:
/// - get 等读取操作: HashMap读锁 + 值的读锁
/// - get_mut 等修改值操作: HashMap读锁 + 值的写锁
/// - insert/remove 等修改结构操作: HashMap写锁
/// 
/// This allows:
/// - Multiple threads can read different values simultaneously
/// - When one thread modifies a value, other threads can still read other values
/// - Exclusive access when modifying the HashMap structure
/// 这样可以实现:
/// - 多个线程可以同时读取不同的值
/// - 一个线程修改某个值时，其他线程仍可读取其他值
/// - 修改HashMap结构时独占访问
/// 
/// ## Note
/// ## 注意
/// 
/// Use `BuildHasherDefault<DefaultHasher>` hasher to support `const fn new()`.
/// This hasher has no random seed. If the HashMap accepts untrusted external input as a key,
/// it may be subject to hash collision attacks (HashDoS).
/// 使用 `BuildHasherDefault<DefaultHasher>` 哈希器以支持 `const fn new()`。
/// 此哈希器没有随机种子，如果 HashMap 接受不可信的外部输入作为 key，
/// 可能会受到哈希碰撞攻击（HashDoS）。
pub struct SyncHashMap<K, V> {
    /// Underlying data storage, each value has an independent read-write lock
    /// 底层数据存储，每个值都有独立的读写锁
    dirty: UnsafeCell<HashMap<K, RwLock<V>, DefaultBuildHasher>>,
    /// HashMap-level read-write lock, used to protect the HashMap structure
    /// HashMap级别的读写锁，用于保护HashMap结构
    lock: RwLock<()>,
}

/// Marked as Send because UnsafeCell is used but protected by a lock
/// 标记为Send，因为使用了UnsafeCell但有锁保护
/// this is safety, dirty mutex ensure
unsafe impl<K, V> Send for SyncHashMap<K, V> {}

/// Marked as Sync because UnsafeCell is used but protected by a lock
/// 标记为Sync，因为使用了UnsafeCell但有锁保护
/// this is safety, dirty mutex ensure
unsafe impl<K, V> Sync for SyncHashMap<K, V> {}

// const NONRANDOM_EMPTY_MAP: HashMap<String, Vec<i32>, std::hash::BuildHasherDefault<std::hash::DefaultHasher>> = HashMap::with_hasher(std::hash::BuildHasherDefault::new());

impl<K, V> SyncHashMap<K, V>
where
    K: Eq + Hash,
{
    /// Create a new Arc-wrapped SyncHashMap
    /// 创建一个新的Arc包装的SyncHashMap
    pub fn new_arc() -> Arc<Self> {
        Arc::new(Self::new())
    }

    /// Create a new empty map
    /// 创建一个新的空映射
    pub const fn new() -> Self {
        Self {
            dirty: UnsafeCell::new(HashMap::with_hasher(DefaultBuildHasher::new())),
            lock: RwLock::new(()),
        }
    }

    /// Create a new map with the specified capacity
    /// 使用指定容量创建一个新的映射
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            dirty: UnsafeCell::new(HashMap::with_capacity_and_hasher(
                capacity,
                std::hash::BuildHasherDefault::default(),
            )),
            lock: RwLock::new(()),
        }
    }

    /// Create a synchronous map using an existing HashMap
    /// 使用现有的HashMap创建一个同步映射
    /// 
    /// Note: Values in the passed HashMap will be wrapped in RwLock
    /// 注意：传入的HashMap中的值会被包装在RwLock中
    pub fn with_map(map: HashMap<K, V>) -> Self {
        let mut wrapped = HashMap::with_capacity_and_hasher(
            map.len(),
            std::hash::BuildHasherDefault::default(),
        );
        for (k, v) in map {
            wrapped.insert(k, RwLock::new(v));
        }
        Self {
            dirty: UnsafeCell::new(wrapped),
            lock: RwLock::new(()),
        }
    }

    /// Insert a key-value pair, protected by HashMap write lock
    /// 插入键值对，使用HashMap写锁保护
    /// 
    /// If the key already exists, return the old value
    /// 如果键已存在，返回旧值
    #[inline(always)]
    pub fn insert(&self, k: K, v: V) -> Option<V> {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.insert(k, RwLock::new(v)).map(|old| old.into_inner())
    }

    /// Insert operation under mutable reference, no lock protection (caller must ensure thread safety)
    /// 可变引用下的插入操作，无锁保护（调用者需确保线程安全）
    #[inline(always)]
    pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
        let m = unsafe { &mut *self.dirty.get() };
        m.insert(k, RwLock::new(v)).map(|old| old.into_inner())
    }

    /// Remove a key-value pair, protected by HashMap write lock
    /// 移除键值对，使用HashMap写锁保护
    #[inline(always)]
    pub fn remove(&self, k: &K) -> Option<V> {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.remove(k).map(|v| v.into_inner())
    }

    /// Remove operation under mutable reference, no lock protection (caller must ensure thread safety)
    /// 可变引用下的移除操作，无锁保护（调用者需确保线程安全）
    #[inline(always)]
    pub fn remove_mut(&mut self, k: &K) -> Option<V> {
        let m = unsafe { &mut *self.dirty.get() };
        m.remove(k).map(|v| v.into_inner())
    }

    /// Get the length of the map, protected by HashMap read lock
    /// 获取映射长度，使用HashMap读锁保护
    #[inline(always)]
    pub fn len(&self) -> usize {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        m.len()
    }

    /// Check if the map is empty, protected by HashMap read lock
    /// 判断映射是否为空，使用HashMap读锁保护
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        m.is_empty()
    }

    /// Clear the map, protected by HashMap write lock
    /// 清空映射，使用HashMap写锁保护
    #[inline(always)]
    pub fn clear(&self) {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.clear();
    }

    /// Clear operation under mutable reference, no lock protection (caller must ensure thread safety)
    /// 可变引用下的清空操作，无锁保护（调用者需确保线程安全）
    #[inline(always)]
    pub fn clear_mut(&mut self) {
        let m = unsafe { &mut *self.dirty.get() };
        m.clear();
    }

    /// Shrink capacity to fit the number of elements, protected by HashMap write lock
    /// 收缩容量以适应元素数量，使用HashMap写锁保护
    #[inline(always)]
    pub fn shrink_to_fit(&self) {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.shrink_to_fit();
    }

    /// Shrink capacity operation under mutable reference, no lock protection (caller must ensure thread safety)
    /// 可变引用下的收缩容量操作，无锁保护（调用者需确保线程安全）
    #[inline(always)]
    pub fn shrink_to_fit_mut(&mut self) {
        let m = unsafe { &mut *self.dirty.get() };
        m.shrink_to_fit();
    }

    /// Convenient method to create SyncHashMap from HashMap
    /// 从HashMap创建SyncHashMap的便捷方法
    pub fn from(map: HashMap<K, V>) -> Self {
        Self::with_map(map)
    }

    /// Get a reference to the value corresponding to the key, protected by HashMap read lock (value no lock)
    /// 获取键对应的值引用，使用HashMap读锁 (值无锁)
    ///
    /// Returns a `ReadGuardNoLock` that holds the HashMap read lock until the guard is dropped.
    /// Other threads can still read other values, but cannot modify the HashMap structure.
    /// 返回一个 `ReadGuardNoLock`，在 guard 被释放前持有HashMap读锁。
    /// 其他线程仍可读取其他值，但不能修改HashMap结构。
    ///
    /// # Safety
    /// 此方法绕过了保护值的 `RwLock`，仅当您确定没有其他线程正在修改该值时才应使用它。
    /// This method bypasses the `RwLock` protecting the value.
    /// It should only be used when you are sure that no other thread is modifying the value.
    ///
    /// # Examples
    ///
    /// ```
    /// use fast_able::SyncHashMap;
    ///
    /// let map = SyncHashMap::new();
    /// map.insert(1, "a");
    /// assert_eq!(*map.get(&1).unwrap(), "a");
    /// assert!(map.get(&2).is_none());
    /// ```
    #[inline]
    pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<MapReadGuard<'_, V>>
    where
        K: Borrow<Q>,
        Q: Hash + Eq,
    {
        let map_lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        let value_lock_wrapper = m.get(k)?;
        // SAFETY: 只有Map结构锁保护，值无锁
        let value_ptr = unsafe {
            let lock_ptr = value_lock_wrapper as *const RwLock<V> as *mut RwLock<V>;
            &*(*lock_ptr).get_mut()
        };
        Some(MapReadGuard {
            _map_lock: map_lock,
            _value_ptr: value_ptr,
        })
    }

    /// Get a reference to the value corresponding to the key (unchecked version), protected by HashMap read lock (value no lock)
    /// 获取键对应的值引用（无检查版本），使用HashMap读锁 (值无锁)
    ///
    /// # Safety
    /// 此方法绕过了保护值的 `RwLock`，仅当您确定没有其他线程正在修改该值时才应使用它。
    /// This method bypasses the `RwLock` protecting the value.
    /// It should only be used when you are sure that no other thread is modifying the value.
    ///
    /// # Panics
    ///
    /// Panics if the key does not exist.
    /// 如果键不存在则 panic。
    #[inline]
    pub fn get_uncheck<Q: ?Sized>(&self, k: &Q) -> MapReadGuard<'_, V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq,
    {
        let map_lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        let value_lock_wrapper = m.get(k).expect("key not found");
        // SAFETY: 只有Map结构锁保护，值无锁
        let value_ptr = unsafe {
            let lock_ptr = value_lock_wrapper as *const RwLock<V> as *mut RwLock<V>;
            &*(*lock_ptr).get_mut()
        };
        MapReadGuard {
            _map_lock: map_lock,
            _value_ptr: value_ptr,
        }
    }

    /// Get a mutable reference to the value corresponding to the key, protected by HashMap read lock + value write lock
    /// 获取键对应的可变值引用，使用HashMap读锁 + 值的写锁保护
    ///
    /// Returns a `WriteGuard` that holds the HashMap read lock and the value write lock until the guard is dropped.
    /// This allows other threads to still read other values, but cannot modify this value.
    /// 返回一个 `WriteGuard`，在 guard 被释放前持有HashMap读锁和值的写锁。
    /// 这样其他线程仍可读取其他值，但不能修改此值。
    #[inline]
    pub fn get_mut<Q: ?Sized>(&self, k: &Q) -> Option<WriteGuard<'_, V>>
    where
        K: Borrow<Q>,
        Q: Hash + Eq,
    {
        let map_lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        let value_lock_wrapper = m.get(k)?;
        let value_lock = value_lock_wrapper.write();
        Some(WriteGuard {
            _map_lock: map_lock,
            _value_lock: value_lock,
        })
    }

    /// Check if the map contains the specified key, protected by HashMap read lock
    /// 检查是否包含指定的键，使用HashMap读锁保护
    #[inline]
    pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
    where
        K: Borrow<Q>,
        Q: Hash + Eq,
    {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        m.contains_key(k)
    }

    /// Get a mutable iterator, protected by HashMap write lock
    /// 获取可变迭代器，使用HashMap写锁保护
    /// 
    /// Note: This method holds the HashMap write lock, so other threads cannot access it during iteration
    /// 注意：此方法持有HashMap写锁，迭代期间其他线程无法访问
    pub fn iter_mut(&self) -> IterMut<'_, K, V> {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        IterMut {
            _lock,
            inner: m.iter(),
        }
    }

    /// Get a read-only iterator, protected by HashMap read lock
    /// 获取只读迭代器，使用HashMap读锁保护
    ///
    /// The returned iterator holds the HashMap read lock, ensuring the structure is not modified during iteration.
    /// Note: You need to acquire a read lock for each value during iteration
    /// 返回的迭代器持有HashMap读锁，在迭代期间保证结构不被修改。
    /// 注意：迭代时需要额外获取每个值的读锁
    pub fn iter_rlock(&self) -> IterRLock<'_, K, V> {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        IterRLock {
            _lock,
            inner: m.iter(),
        }
    }

    /// 不锁值，只锁HashMap结构，适用于只读但不修改值的场景
    /// 
    /// # Safety
    /// 此方法是不安全的，因为它绕过了保护每个值的 `RwLock`。
    /// 仅当您确定没有其他线程正在修改这些值时才应使用它。
    /// 
    /// This method is unsafe because it bypasses the `RwLock` protecting each value.
    /// It should only be used when you are sure that no other thread is modifying the values.
    pub fn iter(&self) -> IterNoLock<'_, K, V> {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        IterNoLock {
            _lock,
            inner: m.iter(),
        }
    }

    /// Get a read-only reference to the underlying HashMap, protected by HashMap read lock
    /// 获取底层HashMap的只读引用，使用HashMap读锁保护
    ///
    /// Returns a `ReadGuardMap` that holds the read lock until the guard is dropped.
    /// Note: The values in the returned HashMap are of type RwLock<V>
    /// 返回一个 `ReadGuardMap`，在 guard 被释放前持有读锁。
    /// 注意：返回的HashMap中的值是 RwLock<V> 类型
    pub fn dirty_ref(&self) -> ReadGuardMap<'_, K, V> {
        let _lock = self.lock.read();
        let v = unsafe { &*self.dirty.get() };
        ReadGuardMap { _lock, v }
    }

    /// Get an unsafe reference to the underlying HashMap (no lock protection)
    /// 获取底层HashMap的不安全引用（无锁保护）
    ///
    /// # Safety
    ///
    /// The caller must ensure there are no concurrent write operations.
    /// 调用者需确保没有并发写操作。
    pub unsafe fn dirty_ref_unsafe(&self) -> &HashMap<K, RwLock<V>, DefaultBuildHasher> {
        unsafe { &*self.dirty.get() }
    }

    /// Consume self and return the internal HashMap (unwrap RwLock)
    /// 消耗self并返回内部的HashMap（解包RwLock）
    pub fn into_inner(self) -> HashMap<K, V> {
        self.dirty
            .into_inner()
            .into_iter()
            .map(|(k, v)| (k, v.into_inner()))
            .collect()
    }

    /// Get an iterator of keys, protected by HashMap read lock
    /// 获取键的迭代器，使用HashMap读锁保护
    ///
    /// The returned iterator holds the read lock, ensuring the structure is not modified during iteration.
    /// 返回的迭代器持有读锁，在迭代期间保证结构不被修改。
    #[inline]
    pub fn keys(&self) -> KeysGuard<'_, K, V> {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        KeysGuard {
            _lock,
            inner: m.keys(),
        }
    }

    /// Get a read-only iterator of values, protected by HashMap read lock
    /// 获取值的只读迭代器，使用HashMap读锁保护
    ///
    /// The returned iterator holds the HashMap read lock, and acquires a read lock for each value during iteration.
    /// 返回的迭代器持有HashMap读锁，迭代时会获取每个值的读锁。
    #[inline]
    pub fn values(&self) -> ValuesGuard<'_, K, V> {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        ValuesGuard {
            _lock,
            inner: m.values(),
        }
    }

    /// Get a mutable iterator of values, protected by HashMap write lock
    /// 获取值的可变迭代器，使用HashMap写锁保护
    ///
    /// The returned iterator holds the HashMap write lock, ensuring exclusive access during iteration.
    /// 返回的迭代器持有HashMap写锁，在迭代期间保证独占访问。
    #[inline]
    pub fn values_mut(&self) -> ValuesMutGuard<'_, K, V> {
        let _lock = self.lock.write();
        let m = unsafe { &*self.dirty.get() };
        ValuesMutGuard {
            _lock,
            inner: m.values(),
        }
    }

    /// Retain elements that satisfy the condition, protected by HashMap write lock
    /// 保留满足条件的元素，使用HashMap写锁保护
    #[inline]
    pub fn retain<F>(&self, mut f: F)
    where
        F: FnMut(&K, &mut V) -> bool,
    {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.retain(|k, v| f(k, v.get_mut()));
    }

    /// Get the capacity of the map, protected by HashMap read lock
    /// 获取映射的容量，使用HashMap读锁保护
    #[inline]
    pub fn capacity(&self) -> usize {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        m.capacity()
    }

    /// Reserve specified capacity, protected by HashMap write lock
    /// 预留指定容量，使用HashMap写锁保护
    #[inline]
    pub fn reserve(&self, additional: usize) {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.reserve(additional);
    }

    /// Try to remove a key-value pair, returning the removed pair if the key exists, protected by HashMap write lock
    /// 尝试移除键值对，如果键存在则返回被移除的键值对，使用HashMap写锁保护
    #[inline]
    pub fn remove_entry(&self, k: &K) -> Option<(K, V)> {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.remove_entry(k).map(|(k, v)| (k, v.into_inner()))
    }

    /// If the key exists, return its mutable reference; otherwise, insert a new value. Protected by HashMap write lock + value write lock
    /// 如果键存在则返回其可变引用，否则插入新值，使用HashMap写锁 + 值写锁保护
    ///
    /// Returns a `WriteGuardEntry` that holds the HashMap write lock and the value write lock until the guard is dropped.
    /// 返回一个 `WriteGuardEntry`，在 guard 被释放前持有HashMap写锁和值的写锁。
    #[inline]
    pub fn get_or_insert(&self, k: K, default: V) -> WriteGuardEntry<'_, V> {
        let map_lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        let entry = m.entry(k).or_insert_with(|| RwLock::new(default));
        let value_lock = entry.write();
        WriteGuardEntry {
            _map_lock: map_lock,
            _value_lock: value_lock,
        }
    }

    /// If the key exists, return its mutable reference; otherwise, insert the value returned by the function. Protected by HashMap write lock + value write lock
    /// 如果键存在则返回其可变引用，否则使用函数返回值插入，使用HashMap写锁 + 值写锁保护
    ///
    /// Returns a `WriteGuardEntry` that holds the HashMap write lock and the value write lock until the guard is dropped.
    /// 返回一个 `WriteGuardEntry`，在 guard 被释放前持有HashMap写锁和值的写锁。
    #[inline]
    pub fn get_or_insert_with<F>(&self, k: K, default: F) -> WriteGuardEntry<'_, V>
    where
        F: FnOnce() -> V,
    {
        let map_lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        let entry = m.entry(k).or_insert_with(|| RwLock::new(default()));
        let value_lock = entry.write();
        WriteGuardEntry {
            _map_lock: map_lock,
            _value_lock: value_lock,
        }
    }

    /// Get a clone of the value corresponding to the key, protected by HashMap read lock + value read lock
    /// 获取键对应的值的克隆，使用HashMap读锁 + 值的读锁保护
    /// 
    /// This is a convenient method that directly returns a clone of the value instead of a Guard
    /// 这是一个便捷方法，直接返回值的克隆而不是Guard
    #[inline]
    pub fn get_clone<Q: ?Sized>(&self, k: &Q) -> Option<V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq,
        V: Clone,
    {
        let _map_lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        m.get(k).map(|v| v.read().clone())
    }

    /// Take the value corresponding to the key (remove and return), protected by HashMap write lock
    /// 取出键对应的值（移除并返回），使用HashMap写锁保护
    /// 
    /// Same as remove, this is a semantically clearer alias
    /// 与 remove 相同，这是一个语义更清晰的别名
    #[inline]
    pub fn take(&self, k: &K) -> Option<V> {
        self.remove(k)
    }
}

/// Guardian of read-only value reference without value lock, holding HashMap read lock only
/// 无值锁的只读值引用守护者，仅持有HashMap读锁
/// 
/// # Safety
/// 此结构绕过了保护值的 `RwLock`，仅当您确定没有其他线程正在修改该值时才应使用。
/// This struct bypasses the `RwLock` protecting the value.
/// It should only be used when you are sure that no other thread is modifying the value.
pub struct MapReadGuard<'a, V> {
    /// HashMap-level read lock guardian
    /// HashMap级别的读锁守护者
    _map_lock: RwLockReadGuard<'a, ()>,
    /// Value pointer (no lock)
    /// 值指针（无锁）
    _value_ptr: &'a V,
}

impl<'a, V> Deref for MapReadGuard<'a, V> {
    type Target = V;

    fn deref(&self) -> &Self::Target {
        self._value_ptr
    }
}

impl<'a, V> Debug for MapReadGuard<'a, V>
where
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self._value_ptr)
    }
}

impl<'a, V> PartialEq for MapReadGuard<'a, V>
where
    V: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self._value_ptr.eq(other._value_ptr)
    }
}

impl<'a, V> Eq for MapReadGuard<'a, V> where V: Eq {}

impl<'a, V> std::fmt::Display for MapReadGuard<'a, V>
where
    V: std::fmt::Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self._value_ptr.fmt(f)
    }
}

impl<'a, V> AsRef<V> for MapReadGuard<'a, V> {
    fn as_ref(&self) -> &V {
        self._value_ptr
    }
}

/// Guardian of read-only value reference, holding HashMap read lock and value read lock
/// 只读值引用的守护者，持有HashMap读锁和值的读锁
pub struct ReadGuard<'a, V> {
    /// HashMap-level read lock guardian
    /// HashMap级别的读锁守护者
    _map_lock: RwLockReadGuard<'a, ()>,
    /// Value-level read lock guardian
    /// 值级别的读锁守护者
    _value_lock: RwLockReadGuard<'a, V>,
}

impl<'a, V> Deref for ReadGuard<'a, V> {
    type Target = V;

    fn deref(&self) -> &Self::Target {
        &*self._value_lock
    }
}

impl<'a, V> Debug for ReadGuard<'a, V>
where
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", &*self._value_lock)
    }
}

impl<'a, V> PartialEq for ReadGuard<'a, V>
where
    V: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        (*self._value_lock).eq(&*other._value_lock)
    }
}

impl<'a, V> Eq for ReadGuard<'a, V> where V: Eq {}

impl<'a, V> std::fmt::Display for ReadGuard<'a, V>
where
    V: std::fmt::Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        (*self._value_lock).fmt(f)
    }
}

impl<'a, V> AsRef<V> for ReadGuard<'a, V> {
    fn as_ref(&self) -> &V {
        &*self._value_lock
    }
}

/// Guardian of read-only HashMap reference, holding HashMap read lock
/// 只读HashMap引用的守护者，持有HashMap读锁
/// 
/// Note: The values in the returned HashMap are of type RwLock<V>
/// 注意：返回的HashMap中的值是 RwLock<V> 类型
pub struct ReadGuardMap<'a, K, V> {
    /// HashMap read lock guardian
    /// HashMap读锁守护者
    _lock: RwLockReadGuard<'a, ()>,
    /// Read-only HashMap reference (values are RwLock<V>)
    /// 只读HashMap引用（值为RwLock<V>）
    v: &'a HashMap<K, RwLock<V>, DefaultBuildHasher>,
}

impl<'a, K, V> Deref for ReadGuardMap<'a, K, V> {
    type Target = HashMap<K, RwLock<V>, DefaultBuildHasher>;

    fn deref(&self) -> &Self::Target {
        self.v
    }
}

impl<'a, K, V> Debug for ReadGuardMap<'a, K, V>
where
    K: Debug,
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        // Manually format, read lock for each value
        // 手动格式化，读取每个值的锁
        let mut map = f.debug_map();
        for (k, v) in self.v.iter() {
            map.entry(k, &*v.read());
        }
        map.finish()
    }
}

impl<'a, K, V> AsRef<HashMap<K, RwLock<V>, DefaultBuildHasher>> for ReadGuardMap<'a, K, V> {
    fn as_ref(&self) -> &HashMap<K, RwLock<V>, DefaultBuildHasher> {
        self.v
    }
}

/// Guardian of mutable value reference, holding HashMap read lock and value write lock
/// 可变值引用的守护者，持有HashMap读锁和值的写锁
/// 
/// This allows other threads to still read other values, but cannot modify this value
/// 这样其他线程仍可读取其他值，但不能修改此值
pub struct WriteGuard<'a, V> {
    /// HashMap-level read lock guardian
    /// HashMap级别的读锁守护者
    _map_lock: RwLockReadGuard<'a, ()>,
    /// Value-level write lock guardian
    /// 值级别的写锁守护者
    _value_lock: RwLockWriteGuard<'a, V>,
}

impl<'a, V> Deref for WriteGuard<'a, V> {
    type Target = V;

    fn deref(&self) -> &Self::Target {
        &*self._value_lock
    }
}

impl<'a, V> DerefMut for WriteGuard<'a, V> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut *self._value_lock
    }
}

impl<'a, V> Debug for WriteGuard<'a, V>
where
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", &*self._value_lock)
    }
}

impl<'a, V> PartialEq for WriteGuard<'a, V>
where
    V: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        (*self._value_lock).eq(&*other._value_lock)
    }
}

impl<'a, V> Eq for WriteGuard<'a, V> where V: Eq {}

impl<'a, V> std::fmt::Display for WriteGuard<'a, V>
where
    V: std::fmt::Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        (*self._value_lock).fmt(f)
    }
}

impl<'a, V> AsRef<V> for WriteGuard<'a, V> {
    fn as_ref(&self) -> &V {
        &*self._value_lock
    }
}

impl<'a, V> AsMut<V> for WriteGuard<'a, V> {
    fn as_mut(&mut self) -> &mut V {
        &mut *self._value_lock
    }
}

/// Guardian for methods like get_or_insert, holding HashMap write lock and value write lock
/// 用于 get_or_insert 等方法的守护者，持有HashMap写锁和值的写锁
/// 
/// Requires HashMap write lock because it may involve insertion operations
/// 因为可能涉及插入操作，需要HashMap写锁
pub struct WriteGuardEntry<'a, V> {
    /// HashMap-level write lock guardian
    /// HashMap级别的写锁守护者
    _map_lock: RwLockWriteGuard<'a, ()>,
    /// Value-level write lock guardian
    /// 值级别的写锁守护者
    _value_lock: RwLockWriteGuard<'a, V>,
}

impl<'a, V> Deref for WriteGuardEntry<'a, V> {
    type Target = V;

    fn deref(&self) -> &Self::Target {
        &*self._value_lock
    }
}

impl<'a, V> DerefMut for WriteGuardEntry<'a, V> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut *self._value_lock
    }
}

impl<'a, V> Debug for WriteGuardEntry<'a, V>
where
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", &*self._value_lock)
    }
}

impl<'a, V> std::fmt::Display for WriteGuardEntry<'a, V>
where
    V: std::fmt::Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        (*self._value_lock).fmt(f)
    }
}

impl<'a, V> AsRef<V> for WriteGuardEntry<'a, V> {
    fn as_ref(&self) -> &V {
        &*self._value_lock
    }
}

impl<'a, V> AsMut<V> for WriteGuardEntry<'a, V> {
    fn as_mut(&mut self) -> &mut V {
        &mut *self._value_lock
    }
}

/// Type alias, keeping backward compatibility
/// 类型别名，保持向后兼容
#[allow(dead_code)]
#[deprecated(note = "Use ReadGuard instead")]
pub type SyncMapRefMut<'a, V> = WriteGuard<'a, V>;

/// Guardian of read-only iterator, holding HashMap read lock
/// 只读迭代器的守护者，持有HashMap读锁
/// 
/// Acquires a read lock for each value during iteration
/// 迭代时会为每个值获取读锁
pub struct IterRLock<'a, K, V> {
    /// HashMap read lock guardian
    /// HashMap读锁守护者
    _lock: RwLockReadGuard<'a, ()>,
    /// Internal iterator (values are RwLock<V>)
    /// 内部迭代器（值为RwLock<V>）
    inner: MapIter<'a, K, RwLock<V>>,
}

impl<'a, K, V> Iterator for IterRLock<'a, K, V> {
    type Item = (&'a K, RwLockReadGuard<'a, V>);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(k, v)| (k, v.read()))
    }
}

/// Type alias, keeping backward compatibility
/// 类型别名，保持向后兼容
pub type IterMy<'a, K, V> = IterRLock<'a, K, V>;

/// Guardian of mutable iterator, holding HashMap write lock
/// 可变迭代器的守护者，持有HashMap写锁
/// 
/// Acquires a write lock for each value during iteration
/// 迭代时会为每个值获取写锁
pub struct IterMut<'a, K, V> {
    /// HashMap write lock guardian
    /// HashMap写锁守护者
    _lock: RwLockReadGuard<'a, ()>,
    /// Internal iterator (values are RwLock<V>)
    /// 内部迭代器（值为RwLock<V>）
    inner: MapIter<'a, K, RwLock<V>>,
}

impl<'a, K, V> Iterator for IterMut<'a, K, V> {
    type Item = (&'a K, RwLockWriteGuard<'a, V>);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(k, v)| (k, v.write()))
    }
}

/// Guardian of key iterator, holding HashMap read lock
/// 键迭代器的守护者，持有HashMap读锁
pub struct KeysGuard<'a, K, V> {
    /// HashMap read lock guardian
    /// HashMap读锁守护者
    _lock: RwLockReadGuard<'a, ()>,
    /// Internal iterator
    /// 内部迭代器
    inner: Keys<'a, K, RwLock<V>>,
}

impl<'a, K, V> Deref for KeysGuard<'a, K, V> {
    type Target = Keys<'a, K, RwLock<V>>;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<'a, K, V> DerefMut for KeysGuard<'a, K, V> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl<'a, K, V> Iterator for KeysGuard<'a, K, V> {
    type Item = &'a K;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

/// Guardian of read-only value iterator, holding HashMap read lock
/// 值只读迭代器的守护者，持有HashMap读锁
/// 
/// Acquires a read lock for each value during iteration
/// 迭代时会为每个值获取读锁
pub struct ValuesGuard<'a, K, V> {
    /// HashMap read lock guardian
    /// HashMap读锁守护者
    _lock: RwLockReadGuard<'a, ()>,
    /// Internal iterator
    /// 内部迭代器
    inner: std::collections::hash_map::Values<'a, K, RwLock<V>>,
}

impl<'a, K, V> Iterator for ValuesGuard<'a, K, V> {
    type Item = RwLockReadGuard<'a, V>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|v| v.read())
    }
}

/// Guardian of mutable value iterator, holding HashMap write lock
/// 值可变迭代器的守护者，持有HashMap写锁
/// 
/// Acquires a write lock for each value during iteration
/// 迭代时会为每个值获取写锁
pub struct ValuesMutGuard<'a, K, V> {
    /// HashMap write lock guardian
    /// HashMap写锁守护者
    _lock: RwLockWriteGuard<'a, ()>,
    /// Internal iterator
    /// 内部迭代器
    inner: std::collections::hash_map::Values<'a, K, RwLock<V>>,
}

impl<'a, K, V> Iterator for ValuesMutGuard<'a, K, V> {
    type Item = RwLockWriteGuard<'a, V>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|v| v.write())
    }
}

/// 不锁值的迭代器，只锁HashMap结构
/// Iterator that only locks HashMap structure, not individual values
pub struct IterNoLock<'a, K, V> {
    /// HashMap读锁守护者
    /// HashMap read lock guardian
    _lock: RwLockReadGuard<'a, ()>,
    /// 内部迭代器（值为RwLock<V>）
    /// Internal iterator (values are RwLock<V>)
    inner: MapIter<'a, K, RwLock<V>>,
}

impl<'a, K, V> Iterator for IterNoLock<'a, K, V> {
    type Item = (&'a K, &'a V);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(k, v)| {
            // SAFETY: 调用者通过文档约定保证没有并发写入
            unsafe {
                let lock_ptr = v as *const RwLock<V> as *mut RwLock<V>;
                (k, &*(*lock_ptr).get_mut())
            }
        })
    }
}

impl<'a, K, V> ExactSizeIterator for IterNoLock<'a, K, V> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

impl<'a, K, V> IntoIterator for &'a SyncHashMap<K, V>
where
    K: Eq + Hash,
{
    type Item = (&'a K, &'a V);
    type IntoIter = IterNoLock<'a, K, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, K, V> IntoIterator for &'a mut SyncHashMap<K, V>
where
    K: Eq + Hash,
{
    type Item = (&'a K, RwLockWriteGuard<'a, V>);
    type IntoIter = IterMut<'a, K, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

impl<K, V> IntoIterator for SyncHashMap<K, V>
where
    K: Eq + Hash,
{
    type Item = (K, V);
    type IntoIter = MapIntoIter<K, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.into_inner().into_iter()
    }
}

impl<K, V> From<HashMap<K, V>> for SyncHashMap<K, V>
where
    K: Eq + Hash,
{
    fn from(map: HashMap<K, V>) -> Self {
        Self::with_map(map)
    }
}

impl<K, V> Serialize for SyncHashMap<K, V>
where
    K: Eq + Hash + Serialize,
    V: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use serde::ser::SerializeMap;
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        let mut map = serializer.serialize_map(Some(m.len()))?;
        for (k, v) in m.iter() {
            map.serialize_entry(k, &*v.read())?;
        }
        map.end()
    }
}

impl<'de, K, V> Deserialize<'de> for SyncHashMap<K, V>
where
    K: Eq + Hash + Deserialize<'de>,
    V: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let m = HashMap::deserialize(deserializer)?;
        Ok(Self::with_map(m))
    }
}

impl<K, V> Debug for SyncHashMap<K, V>
where
    K: Eq + Hash + Debug,
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        let mut map = f.debug_map();
        for (k, v) in m.iter() {
            map.entry(k, &*v.read());
        }
        map.finish()
    }
}

impl<K, V> Clone for SyncHashMap<K, V>
where
    K: Clone + Eq + Hash,
    V: Clone,
{
    fn clone(&self) -> Self {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        let cloned: HashMap<K, V> = m
            .iter()
            .map(|(k, v)| (k.clone(), v.read().clone()))
            .collect();
        SyncHashMap::with_map(cloned)
    }
}

impl<K, V> Default for SyncHashMap<K, V>
where
    K: Eq + Hash,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<K, V> PartialEq for SyncHashMap<K, V>
where
    K: Eq + Hash,
    V: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        let _lock_self = self.lock.read();
        let _lock_other = other.lock.read();
        let self_map = unsafe { &*self.dirty.get() };
        let other_map = unsafe { &*other.dirty.get() };
        
        if self_map.len() != other_map.len() {
            return false;
        }
        
        for (k, v) in self_map.iter() {
            match other_map.get(k) {
                Some(other_v) => {
                    if *v.read() != *other_v.read() {
                        return false;
                    }
                }
                None => return false,
            }
        }
        true
    }
}

impl<K, V> Eq for SyncHashMap<K, V>
where
    K: Eq + Hash,
    V: Eq,
{
}

/// Bucketed hash map module, providing higher concurrency hash map implementation
/// 分桶哈希映射模块，提供更高并发的哈希映射实现
pub mod buckets {
    use super::{ReadGuard, MapReadGuard, SyncHashMap, WriteGuard};
    use std::hash::{Hash, Hasher};

    /// Bucketed hash map, distributing data to multiple sub-maps to improve concurrency performance
    /// 分桶哈希映射，将数据分散到多个子映射中以提高并发性能
    #[derive(Debug, Clone)]
    pub struct SyncHashMapB<K, V>
    where
        K: Eq + Hash,
    {
        /// Internal array of sub-maps
        /// 内部的子映射数组
        inner: Vec<SyncHashMap<K, V>>,
        /// Number of buckets
        /// 分桶数量
        len: usize,
    }

    impl<K, V> SyncHashMapB<K, V>
    where
        K: Eq + Hash,
    {
        /// Create a new bucketed hash map
        /// 创建新的分桶哈希映射
        ///
        /// # Arguments
        /// * `bucket_count` - Number of buckets, defaults to 10 if None
        /// * `bucket_count` - 分桶数量，如果为None则默认为10
        ///
        /// # Examples
        /// ```
        /// use fast_able::map_hash::buckets::SyncHashMapB;
        ///
        /// let map = SyncHashMapB::new(None);
        /// map.insert(1, "a");
        /// map.insert(2, "b");
        /// assert_eq!(*map.get(&1).unwrap(), "a");
        /// assert_eq!(*map.get(&2).unwrap(), "b");
        /// assert!(map.get(&3).is_none());
        /// ```
        pub fn new(bucket_count: Option<usize>) -> Self {
            let count = bucket_count.unwrap_or(10);
            let mut arr = Vec::with_capacity(count);
            for _ in 0..count {
                arr.push(SyncHashMap::new());
            }
            Self {
                inner: arr,
                len: count,
            }
        }

        /// Convert key to bucket index
        /// 将键转换为桶索引
        fn key_to_bucket_index(&self, k: &K) -> usize {
            let mut hasher = std::collections::hash_map::DefaultHasher::new();
            k.hash(&mut hasher);
            let hash = hasher.finish();
            (hash % self.len as u64) as usize
        }

        /// Insert a key-value pair
        /// 插入键值对
        #[inline]
        pub fn insert(&self, k: K, v: V) -> Option<V> {
            let index = self.key_to_bucket_index(&k);
            self.inner[index].insert(k, v)
        }

        /// Insert operation under mutable reference
        /// 可变引用下的插入操作
        #[inline]
        pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
            let index = self.key_to_bucket_index(&k);
            self.inner[index].insert_mut(k, v)
        }

        /// Remove a key-value pair
        /// 移除键值对
        #[inline]
        pub fn remove(&self, k: &K) -> Option<V> {
            let index = self.key_to_bucket_index(k);
            self.inner[index].remove(k)
        }

        /// Check if empty
        /// 检查是否为空
        #[inline]
        pub fn is_empty(&self) -> bool {
            self.inner.iter().all(|bucket| bucket.is_empty())
        }

        /// Get total length
        /// 获取总长度
        #[inline]
        pub fn len(&self) -> usize {
            self.inner.iter().map(|bucket| bucket.len()).sum()
        }

        /// Clear all buckets
        /// 清空所有桶
        #[inline]
        pub fn clear(&self) {
            self.inner.iter().for_each(|bucket| bucket.clear());
        }

        /// Get a reference to the value corresponding to the key, protected by read lock (value no lock)
        /// 获取键对应的值引用，使用读锁保护 (值无锁)
        ///
        /// Returns a `ReadGuardNoLock` that holds the read lock until the guard is dropped.
        /// 返回一个 `ReadGuardNoLock`，在 guard 被释放前持有读锁。
        #[inline]
        pub fn get(&self, k: &K) -> Option<MapReadGuard<'_, V>> {
            let index = self.key_to_bucket_index(k);
            self.inner[index].get(k)
        }

        /// Get a mutable reference to the value corresponding to the key, protected by write lock
        /// 获取键对应的可变值引用，使用写锁保护
        ///
        /// Returns a `WriteGuard` that holds the write lock until the guard is dropped, ensuring concurrent access safety.
        /// 返回一个 `WriteGuard`，在 guard 被释放前持有写锁，保证并发访问安全。
        #[inline]
        pub fn get_mut(&self, k: &K) -> Option<WriteGuard<'_, V>> {
            let index = self.key_to_bucket_index(k);
            self.inner[index].get_mut(k)
        }

        /// Get the number of buckets
        /// 获取桶数量
        #[inline]
        pub fn bucket_count(&self) -> usize {
            self.len
        }

        /// Get an iterator of all keys
        /// 获取所有键的迭代器
        #[inline]
        pub fn keys(&self) -> impl Iterator<Item = &K> {
            self.inner.iter().flat_map(|bucket| bucket.keys())
        }

        /// Get a clone of the value corresponding to the key
        /// 获取键对应的值的克隆
        #[inline]
        pub fn get_clone(&self, k: &K) -> Option<V>
        where
            V: Clone,
        {
            let index = self.key_to_bucket_index(k);
            self.inner[index].get_clone(k)
        }
    }

    impl<K, V> Default for SyncHashMapB<K, V>
    where
        K: Eq + Hash,
    {
        fn default() -> Self {
            Self::new(None)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::sync::Arc;
    use std::thread;

    #[test]
    fn test_sync_hash_map_new() {
        let map: SyncHashMap<i32, String> = SyncHashMap::new();
        assert_eq!(map.len(), 0);
        assert!(map.is_empty());
    }

    #[test]
    fn test_sync_hash_map_with_capacity() {
        let map = SyncHashMap::<i32, String>::with_capacity(100);
        assert!(map.capacity() >= 100);
    }

    #[test]
    fn test_sync_hash_map_with_map() {
        let mut original = HashMap::new();
        original.insert(1, "one".to_string());
        original.insert(2, "two".to_string());

        let map = SyncHashMap::with_map(original);
        assert_eq!(map.len(), 2);
        assert_eq!(*map.get(&1).unwrap(), "one".to_string());
        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
    }

    #[test]
    fn test_sync_hash_map_insert_and_get() {
        let map = SyncHashMap::new();

        // 测试插入和获取
        assert_eq!(map.insert(1, "one".to_string()), None);
        assert_eq!(map.insert(2, "two".to_string()), None);
        assert_eq!(map.len(), 2);

        assert_eq!(*map.get(&1).unwrap(), "one".to_string());
        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
        assert!(map.get(&3).is_none());
    }

    #[test]
    fn test_sync_hash_map_insert_replace() {
        let map = SyncHashMap::new();

        assert_eq!(map.insert(1, "one".to_string()), None);
        assert_eq!(map.insert(1, "updated".to_string()), Some("one".to_string()));
        assert_eq!(*map.get(&1).unwrap(), "updated".to_string());
    }

    #[test]
    fn test_sync_hash_map_remove() {
        let map = SyncHashMap::new();

        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        assert_eq!(map.remove(&1), Some("one".to_string()));
        assert_eq!(map.remove(&1), None);
        assert_eq!(map.len(), 1);
        assert!(map.get(&1).is_none());
        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
    }

    #[test]
    fn test_sync_hash_map_contains_key() {
        let map = SyncHashMap::new();

        map.insert(1, "one".to_string());

        assert!(map.contains_key(&1));
        assert!(!map.contains_key(&2));
    }

    #[test]
    fn test_sync_hash_map_clear() {
        let map = SyncHashMap::new();

        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        assert_eq!(map.len(), 2);
        map.clear();
        assert_eq!(map.len(), 0);
        assert!(map.is_empty());
    }

    #[test]
    fn test_sync_hash_map_capacity_operations() {
        let map = SyncHashMap::new();

        assert_eq!(map.capacity(), 0);
        map.reserve(100);
        assert!(map.capacity() >= 100);

        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        let old_capacity = map.capacity();
        map.shrink_to_fit();
        assert!(map.capacity() <= old_capacity);
    }

    #[test]
    fn test_sync_hash_map_retain() {
        let map = SyncHashMap::new();

        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());
        map.insert(3, "three".to_string());

        map.retain(|&k, _| k % 2 == 1);

        assert_eq!(map.len(), 2);
        assert!(map.contains_key(&1));
        assert!(!map.contains_key(&2));
        assert!(map.contains_key(&3));
    }

    #[test]
    fn test_sync_hash_map_get_or_insert() {
        let map = SyncHashMap::new();

        // 键不存在时插入
        {
            let value = map.get_or_insert(1, "default".to_string());
            assert_eq!(*value, "default");
        }
        assert_eq!(map.len(), 1);

        // 键存在时返回现有值
        {
            let value = map.get_or_insert(1, "new_default".to_string());
            assert_eq!(*value, "default");
        }
        assert_eq!(map.len(), 1);
    }

    #[test]
    fn test_sync_hash_map_get_or_insert_with() {
        let map = SyncHashMap::new();

        {
            let value = map.get_or_insert_with(1, || "computed".to_string());
            assert_eq!(*value, "computed");
        }
        assert_eq!(map.len(), 1);

        {
            let value = map.get_or_insert_with(1, || "new_computed".to_string());
            assert_eq!(*value, "computed");
        }
    }

    #[test]
    fn test_sync_hash_map_remove_entry() {
        let map = SyncHashMap::new();

        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        let removed = map.remove_entry(&1);
        assert_eq!(removed, Some((1, "one".to_string())));
        assert_eq!(map.len(), 1);
        assert!(!map.contains_key(&1));
    }

    #[test]
    fn test_sync_hash_map_iterators() {
        let map = SyncHashMap::new();

        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());
        map.insert(3, "three".to_string());

        // 测试 keys 迭代器
        let keys: Vec<_> = map.keys().collect();
        assert!(keys.contains(&&1));
        assert!(keys.contains(&&2));
        assert!(keys.contains(&&3));

        // 测试 values 迭代器 - 使用 get_clone 来验证
        assert_eq!(map.get_clone(&1), Some("one".to_string()));
        assert_eq!(map.get_clone(&2), Some("two".to_string()));
        assert_eq!(map.get_clone(&3), Some("three".to_string()));

        // 测试 iter 迭代器
        let mut count = 0;
        for (k, v) in map.iter() {
            count += 1;
            assert!(map.contains_key(k));
            assert_eq!(*map.get(k).unwrap(), *v);
        }
        assert_eq!(count, 3);
    }

    #[test]
    fn test_sync_hash_map_iter_mut() {
        let map = SyncHashMap::new();

        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        for (k, mut v) in map.iter_mut() {
            if *k == 1 {
                *v = "modified".to_string();
            }
        }

        assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
    }

    #[test]
    fn test_sync_hash_map_values_mut() {
        let map = SyncHashMap::new();

        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        for mut v in map.values_mut() {
            if *v == "one" {
                *v = "modified".to_string();
            }
        }

        assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
    }

    #[test]
    fn test_sync_hash_map_get_clone() {
        let map = SyncHashMap::new();
        map.insert(1, "one".to_string());

        // 测试 get_clone 方法
        assert_eq!(map.get_clone(&1), Some("one".to_string()));
        assert_eq!(map.get_clone(&2), None);
    }

    #[test]
    fn test_sync_hash_map_clone() {
        let map1 = SyncHashMap::new();
        map1.insert(1, "one".to_string());
        map1.insert(2, "two".to_string());

        let map2 = map1.clone();

        assert_eq!(map1.len(), map2.len());
        assert_eq!(*map1.get(&1).unwrap(), *map2.get(&1).unwrap());
        assert_eq!(*map1.get(&2).unwrap(), *map2.get(&2).unwrap());

        // 修改原映射不影响克隆
        map1.insert(3, "three".to_string());
        assert!(!map2.contains_key(&3));
    }

    #[test]
    fn test_sync_hash_map_partial_eq() {
        let map1 = SyncHashMap::new();
        map1.insert(1, "one".to_string());
        map1.insert(2, "two".to_string());

        let map2 = SyncHashMap::new();
        map2.insert(1, "one".to_string());
        map2.insert(2, "two".to_string());

        let map3 = SyncHashMap::new();
        map3.insert(1, "different".to_string());

        assert_eq!(map1, map2);
        assert_ne!(map1, map3);
    }

    #[test]
    fn test_sync_hash_map_debug() {
        let map = SyncHashMap::new();
        map.insert(1, "one".to_string());

        let debug_str = format!("{:?}", map);
        assert!(debug_str.contains("1"));
        assert!(debug_str.contains("one"));
    }

    #[test]
    fn test_sync_hash_map_serialization() {
        let map = SyncHashMap::new();
        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        // 测试序列化
        let serialized = serde_json::to_string(&map).unwrap();
        assert!(serialized.contains("1"));
        assert!(serialized.contains("one"));
        assert!(serialized.contains("2"));
        assert!(serialized.contains("two"));

        // 测试反序列化
        let deserialized: SyncHashMap<i32, String> = serde_json::from_str(&serialized).unwrap();
        assert_eq!(deserialized.len(), 2);
        assert_eq!(*deserialized.get(&1).unwrap(), "one".to_string());
        assert_eq!(*deserialized.get(&2).unwrap(), "two".to_string());
    }

    #[test]
    fn test_sync_hash_map_from_hashmap() {
        let mut original = HashMap::new();
        original.insert(1, "one".to_string());
        original.insert(2, "two".to_string());

        let map = SyncHashMap::from(original);

        assert_eq!(map.len(), 2);
        assert_eq!(*map.get(&1).unwrap(), "one".to_string());
        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
    }

    #[test]
    fn test_sync_hash_map_into_iterator() {
        let map = SyncHashMap::new();
        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        // 测试 IntoIterator for &SyncHashMap
        let mut count = 0;
        for (k, v) in &map {
            count += 1;
            assert!(map.contains_key(k));
            assert_eq!(*map.get(k).unwrap(), *v);
        }
        assert_eq!(count, 2);

        // 测试 IntoIterator for SyncHashMap
        let owned_pairs: Vec<_> = map.into_iter().collect();
        assert_eq!(owned_pairs.len(), 2);
    }

    #[test]
    fn test_sync_hash_map_default() {
        let map: SyncHashMap<i32, String> = Default::default();
        assert_eq!(map.len(), 0);
        assert!(map.is_empty());
    }

    #[test]
    fn test_sync_hash_map_arc() {
        let map = SyncHashMap::new_arc();
        map.insert(1, "one".to_string());

        assert_eq!(*map.get(&1).unwrap(), "one".to_string());

        let map2 = Arc::clone(&map);
        map2.insert(2, "two".to_string());

        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
    }

    #[test]
    fn test_sync_hash_map_get_mut() {
        let map = SyncHashMap::new();
        map.insert(1, "one".to_string());

        {
            let mut value = map.get_mut(&1).unwrap();
            *value = "modified".to_string();
        }

        assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
    }

    #[test]
    fn test_sync_hash_map_concurrent_access() {
        let map = Arc::new(SyncHashMap::new());

        // 并发写入测试
        let handles: Vec<_> = (0..10).map(|i| {
            let map = Arc::clone(&map);
            thread::spawn(move || {
                map.insert(i, format!("value_{}", i));
            })
        }).collect();

        for handle in handles {
            handle.join().unwrap();
        }

        // 验证所有值都被插入
        assert_eq!(map.len(), 10);
        for i in 0..10 {
            assert_eq!(*map.get(&i).unwrap(), format!("value_{}", i));
        }

        // 并发读取测试
        let map_read = Arc::clone(&map);
        let handles: Vec<_> = (0..10).map(|i| {
            let map = Arc::clone(&map_read);
            thread::spawn(move || {
                let value = map.get(&i);
                assert_eq!(*value.unwrap(), format!("value_{}", i));
            })
        }).collect();

        for handle in handles {
            handle.join().unwrap();
        }
    }

    #[test]
    fn test_sync_hash_map_dirty_ref() {
        let map = SyncHashMap::new();
        map.insert(1, "one".to_string());

        let dirty = map.dirty_ref();
        assert_eq!(dirty.len(), 1);
        // dirty 返回的是 HashMap<K, RwLock<V>>，需要读取锁
        assert_eq!(*dirty.get(&1).unwrap().read(), "one".to_string());
    }

    #[test]
    fn test_sync_hash_map_into_inner() {
        let map = SyncHashMap::new();
        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        let inner = map.into_inner();
        assert_eq!(inner.len(), 2);
        assert_eq!(inner.get(&1), Some(&"one".to_string()));
        assert_eq!(inner.get(&2), Some(&"two".to_string()));
    }

    #[test]
    fn test_sync_hash_map_guard_debug() {
        let map = SyncHashMap::new();
        map.insert(1, "test".to_string());

        let guard = map.get(&1).unwrap();
        let debug_str = format!("{:?}", guard);
        assert!(debug_str.contains("test"));
    }

    #[test]
    fn test_sync_hash_map_guard_partial_eq() {
        let map = SyncHashMap::new();
        map.insert(1, "value".to_string());

        let guard1 = map.get(&1).unwrap();
        let guard2 = map.get(&1).unwrap();

        assert_eq!(guard1, guard2);
    }

    // 分桶映射测试
    mod buckets_tests {
        use super::*;

        #[test]
        fn test_sync_hash_map_buckets_new() {
            let map = buckets::SyncHashMapB::<i32, String>::new(None);
            assert_eq!(map.len(), 0);
            assert!(map.is_empty());
            assert_eq!(map.bucket_count(), 10); // 默认桶数量
        }

        #[test]
        fn test_sync_hash_map_buckets_with_custom_size() {
            let map = buckets::SyncHashMapB::<i32, String>::new(Some(5));
            assert_eq!(map.bucket_count(), 5);
        }

        #[test]
        fn test_sync_hash_map_buckets_insert_and_get() {
            let map = buckets::SyncHashMapB::new(Some(3));

            assert_eq!(map.insert(1, "one".to_string()), None);
            assert_eq!(map.insert(2, "two".to_string()), None);
            assert_eq!(map.len(), 2);

            assert_eq!(*map.get(&1).unwrap(), "one".to_string());
            assert_eq!(*map.get(&2).unwrap(), "two".to_string());
            assert!(map.get(&3).is_none());
        }

        #[test]
        fn test_sync_hash_map_buckets_remove() {
            let map = buckets::SyncHashMapB::new(Some(3));

            map.insert(1, "one".to_string());
            map.insert(2, "two".to_string());

            assert_eq!(map.remove(&1), Some("one".to_string()));
            assert_eq!(map.len(), 1);
            assert!(map.get(&1).is_none());
            assert_eq!(*map.get(&2).unwrap(), "two".to_string());
        }

        #[test]
        fn test_sync_hash_map_buckets_clear() {
            let map = buckets::SyncHashMapB::new(Some(3));

            map.insert(1, "one".to_string());
            map.insert(2, "two".to_string());

            assert_eq!(map.len(), 2);
            map.clear();
            assert_eq!(map.len(), 0);
            assert!(map.is_empty());
        }

        #[test]
        fn test_sync_hash_map_buckets_iterators() {
            let map = buckets::SyncHashMapB::new(Some(3));

            map.insert(1, "one".to_string());
            map.insert(2, "two".to_string());
            map.insert(3, "three".to_string());

            // 测试 keys 迭代器
            let keys: Vec<_> = map.keys().collect();
            assert!(keys.contains(&&1));
            assert!(keys.contains(&&2));
            assert!(keys.contains(&&3));

            // 测试 get_clone 方法
            assert_eq!(map.get_clone(&1), Some("one".to_string()));
            assert_eq!(map.get_clone(&2), Some("two".to_string()));
            assert_eq!(map.get_clone(&3), Some("three".to_string()));

            // 测试 get_mut
            {
                let mut v = map.get_mut(&1).unwrap();
                *v = "modified".to_string();
            }

            assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
        }

        #[test]
        fn test_sync_hash_map_buckets_default() {
            let map: buckets::SyncHashMapB<i32, String> = Default::default();
            assert_eq!(map.len(), 0);
            assert!(map.is_empty());
            assert_eq!(map.bucket_count(), 10);
        }

        #[test]
        fn test_sync_hash_map_buckets_debug() {
            let map = buckets::SyncHashMapB::new(Some(2));
            map.insert(1, "one".to_string());

            let debug_str = format!("{:?}", map);
            assert!(debug_str.contains("1"));
            assert!(debug_str.contains("one"));
        }
    }

    #[test]
    fn test_sync_hash_map_comprehensive() {
        let map = SyncHashMap::new();

        // 测试各种操作的组合
        map.insert("key1", 42);
        map.insert("key2", 24);

        assert_eq!(map.len(), 2);
        assert!(!map.is_empty());

        // 测试修改操作
        *map.get_mut("key1").unwrap() = 100;
        assert_eq!(*map.get(&"key1").unwrap(), 100);

        // 测试条件保留
        map.insert("key3", 50);
        map.retain(|_, v| *v > 30);

        assert_eq!(map.len(), 2);
        assert_eq!(*map.get(&"key1").unwrap(), 100);
        assert!(map.get(&"key2").is_none());
        assert_eq!(*map.get(&"key3").unwrap(), 50);

        // 测试克隆和比较
        let map2 = map.clone();
        assert_eq!(map, map2);

        // 测试迭代
        let mut sum = 0;
        for (_, v) in map.iter() {
            sum += *v;
        }
        assert_eq!(sum, 150);

        // 测试清空
        map.clear();
        assert_eq!(map.len(), 0);
        assert!(map.is_empty());
    }

    #[test]
    fn test_sync_hash_map_iter_nlock() {
        let map = SyncHashMap::new();
        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());
        map.insert(3, "three".to_string());

        // 测试 iter_nlock 基本功能
        let mut count = 0;
        for (k, v) in map.iter() {
            count += 1;
            match *k {
                1 => assert_eq!(v, "one"),
                2 => assert_eq!(v, "two"),
                3 => assert_eq!(v, "three"),
                _ => panic!("unexpected key"),
            }
        }
        assert_eq!(count, 3);

        // 测试 ExactSizeIterator
        let iter = map.iter();
        assert_eq!(iter.len(), 3);
    }

    #[test]
    fn test_sync_hash_map_into_iter_mut() {
        let mut map = SyncHashMap::new();
        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        // 测试 IntoIterator for &mut SyncHashMap
        for (k, mut v) in &mut map {
            if *k == 1 {
                *v = "modified".to_string();
            }
        }

        assert_eq!(*map.get(&1).unwrap(), "modified".to_string());
        assert_eq!(*map.get(&2).unwrap(), "two".to_string());
    }

    #[test]
    fn test_sync_hash_map_into_iter_ref() {
        let map = SyncHashMap::new();
        map.insert(1, 10);
        map.insert(2, 20);
        map.insert(3, 30);

        // 测试 IntoIterator for &SyncHashMap
        let mut sum = 0;
        for (_, v) in &map {
            sum += *v;
        }
        assert_eq!(sum, 60);

        // 确保 map 仍然可用
        assert_eq!(map.len(), 3);
    }

    #[test]
    fn test_sync_hash_map_iter_nlock_empty() {
        let map: SyncHashMap<i32, String> = SyncHashMap::new();
        
        let mut count = 0;
        for _ in map.iter() {
            count += 1;
        }
        assert_eq!(count, 0);
        
        let iter = map.iter();
        assert_eq!(iter.len(), 0);
    }
}
