SyncHashMap

Struct SyncHashMap 

Source
pub struct SyncHashMap<K, V> { /* private fields */ }
Expand description

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)。

Implementations§

Source§

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

Source

pub fn new_arc() -> Arc<Self>

Create a new Arc-wrapped SyncHashMap 创建一个新的Arc包装的SyncHashMap

Source

pub const fn new() -> Self

Create a new empty map 创建一个新的空映射

Source

pub fn with_capacity(capacity: usize) -> Self

Create a new map with the specified capacity 使用指定容量创建一个新的映射

Source

pub fn with_map(map: HashMap<K, V>) -> Self

Create a synchronous map using an existing HashMap 使用现有的HashMap创建一个同步映射

Note: Values in the passed HashMap will be wrapped in RwLock 注意:传入的HashMap中的值会被包装在RwLock中

Source

pub fn insert(&self, k: K, v: V) -> Option<V>

Insert a key-value pair, protected by HashMap write lock 插入键值对,使用HashMap写锁保护

If the key already exists, return the old value 如果键已存在,返回旧值

Source

pub fn insert_mut(&mut self, k: K, v: V) -> Option<V>

Insert operation under mutable reference, no lock protection (caller must ensure thread safety) 可变引用下的插入操作,无锁保护(调用者需确保线程安全)

Source

pub fn remove(&self, k: &K) -> Option<V>

Remove a key-value pair, protected by HashMap write lock 移除键值对,使用HashMap写锁保护

Source

pub fn remove_mut(&mut self, k: &K) -> Option<V>

Remove operation under mutable reference, no lock protection (caller must ensure thread safety) 可变引用下的移除操作,无锁保护(调用者需确保线程安全)

Source

pub fn len(&self) -> usize

Get the length of the map, protected by HashMap read lock 获取映射长度,使用HashMap读锁保护

Source

pub fn is_empty(&self) -> bool

Check if the map is empty, protected by HashMap read lock 判断映射是否为空,使用HashMap读锁保护

Source

pub fn clear(&self)

Clear the map, protected by HashMap write lock 清空映射,使用HashMap写锁保护

Source

pub fn clear_mut(&mut self)

Clear operation under mutable reference, no lock protection (caller must ensure thread safety) 可变引用下的清空操作,无锁保护(调用者需确保线程安全)

Source

pub fn shrink_to_fit(&self)

Shrink capacity to fit the number of elements, protected by HashMap write lock 收缩容量以适应元素数量,使用HashMap写锁保护

Source

pub fn shrink_to_fit_mut(&mut self)

Shrink capacity operation under mutable reference, no lock protection (caller must ensure thread safety) 可变引用下的收缩容量操作,无锁保护(调用者需确保线程安全)

Source

pub fn from(map: HashMap<K, V>) -> Self

Convenient method to create SyncHashMap from HashMap 从HashMap创建SyncHashMap的便捷方法

Source

pub fn get<Q>(&self, k: &Q) -> Option<RefGuard<'_, V>>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

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());
Source

pub fn get_rlock<Q>(&self, k: &Q) -> Option<ReadGuard<'_, V>>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Get a reference to the value corresponding to the key, protected by HashMap read lock + value read lock 获取键对应的值引用,使用HashMap读锁 + 值的读锁保护 Safety: This method is safe as it acquires both the HashMap read lock and the value read lock. 安全性: 此方法是安全的,因为它同时获取了HashMap读锁和值的读锁。

Source

pub fn get_uncheck<Q>(&self, k: &Q) -> RefGuard<'_, V>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

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。

Source

pub fn get_mut<Q>(&self, k: &Q) -> Option<MutRefGuard<'_, V>>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Get a mutable reference to the value corresponding to the key, 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.

Source

pub fn get_mut_lock<Q>(&self, k: &Q) -> Option<WriteGuard<'_, V>>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

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读锁和值的写锁。 这样其他线程仍可读取其他值,但不能修改此值。

Source

pub fn contains_key<Q>(&self, k: &Q) -> bool
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Check if the map contains the specified key, protected by HashMap read lock 检查是否包含指定的键,使用HashMap读锁保护

Source

pub fn iter_mut_lock(&self) -> IterLock<'_, K, V>

Get a mutable iterator, protected by HashMap read lock + value write lock 获取可变迭代器,使用Iter读锁 + 各个值的写锁保护

Source

pub fn iter_mut(&self) -> IterMut<'_, K, V>

Get a mutable iterator over the values, protected by Map read lock (value no lock) 获取可变迭代器,使用map读锁 (值无锁)

§Safety

此方法绕过了保护每个值的 RwLock。 仅当您确定没有其他线程正在修改这些值时才应使用它。

This method bypasses the RwLock protecting each value. It should only be used when you are sure that no other thread is modifying the values.

Source

pub fn iter_rlock(&self) -> IterRLock<'_, K, V>

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读锁,在迭代期间保证结构不被修改。 注意:迭代时需要额外获取每个值的读锁

Source

pub fn iter(&self) -> Iter<'_, K, V>

不锁值,只锁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.

Source

pub fn dirty_ref(&self) -> ReadGuardMap<'_, K, V>

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 返回一个 ReadGuardMap,在 guard 被释放前持有读锁。 注意:返回的HashMap中的值是 RwLock 类型

Source

pub unsafe fn dirty_ref_unsafe( &self, ) -> &HashMap<K, RwLock<V>, DefaultBuildHasher>

Get an unsafe reference to the underlying HashMap (no lock protection) 获取底层HashMap的不安全引用(无锁保护)

§Safety

The caller must ensure there are no concurrent write operations. 调用者需确保没有并发写操作。

Source

pub fn into_inner(self) -> HashMap<K, V>

Consume self and return the internal HashMap (unwrap RwLock) 消耗self并返回内部的HashMap(解包RwLock)

Source

pub fn keys(&self) -> KeysGuard<'_, K, V>

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. 返回的迭代器持有读锁,在迭代期间保证结构不被修改。

Source

pub fn values(&self) -> ValuesGuard<'_, K, V>

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读锁,迭代时会获取每个值的读锁。

Source

pub fn values_mut(&self) -> ValuesMutGuard<'_, K, V>

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写锁,在迭代期间保证独占访问。

Source

pub fn retain<F>(&self, f: F)
where F: FnMut(&K, &mut V) -> bool,

Retain elements that satisfy the condition, protected by HashMap write lock 保留满足条件的元素,使用HashMap写锁保护

Source

pub fn capacity(&self) -> usize

Get the capacity of the map, protected by HashMap read lock 获取映射的容量,使用HashMap读锁保护

Source

pub fn reserve(&self, additional: usize)

Reserve specified capacity, protected by HashMap write lock 预留指定容量,使用HashMap写锁保护

Source

pub fn remove_entry(&self, k: &K) -> Option<(K, V)>

Try to remove a key-value pair, returning the removed pair if the key exists, protected by HashMap write lock 尝试移除键值对,如果键存在则返回被移除的键值对,使用HashMap写锁保护

Source

pub fn get_or_insert(&self, k: K, default: V) -> EntryGuard<'_, V>

If the key exists, return its mutable reference; otherwise, insert a new value. Protected by HashMap write lock + value write lock 如果键存在则返回其可变引用,否则插入新值,使用HashMap写锁 + 值写锁保护

Returns a EntryGuard that holds the HashMap write lock and the value write lock until the guard is dropped. 返回一个 EntryGuard,在 guard 被释放前持有HashMap写锁和值的写锁。

Source

pub fn get_or_insert_with<F>(&self, k: K, default: F) -> EntryGuard<'_, V>
where F: FnOnce() -> V,

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 EntryGuard that holds the HashMap write lock and the value write lock until the guard is dropped. 返回一个 EntryGuard,在 guard 被释放前持有HashMap写锁和值的写锁。

Source

pub fn get_clone<Q>(&self, k: &Q) -> Option<V>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized, V: Clone,

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

Source

pub fn take(&self, k: &K) -> Option<V>

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 相同,这是一个语义更清晰的别名

Trait Implementations§

Source§

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

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

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

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

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

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de, K, V> Deserialize<'de> for SyncHashMap<K, V>
where K: Eq + Hash + Deserialize<'de>, V: Deserialize<'de>,

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<K, V> From<HashMap<K, V>> for SyncHashMap<K, V>
where K: Eq + Hash,

Source§

fn from(map: HashMap<K, V>) -> Self

Converts to this type from the input type.
Source§

impl<'a, K, V> IntoIterator for &'a SyncHashMap<K, V>
where K: Eq + Hash,

Source§

type Item = (&'a K, &'a V)

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, K, V>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a, K, V> IntoIterator for &'a mut SyncHashMap<K, V>
where K: Eq + Hash,

Source§

type Item = (&'a K, &'a mut V)

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'a, K, V>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

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

Source§

type Item = (K, V)

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<K, V>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

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

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

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

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

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

Source§

impl<K, V> Send for SyncHashMap<K, V>

Marked as Send because UnsafeCell is used but protected by a lock 标记为Send,因为使用了UnsafeCell但有锁保护 this is safety, dirty mutex ensure

Source§

impl<K, V> Sync for SyncHashMap<K, V>

Marked as Sync because UnsafeCell is used but protected by a lock 标记为Sync,因为使用了UnsafeCell但有锁保护 this is safety, dirty mutex ensure

Auto Trait Implementations§

§

impl<K, V> !Freeze for SyncHashMap<K, V>

§

impl<K, V> !RefUnwindSafe for SyncHashMap<K, V>

§

impl<K, V> Unpin for SyncHashMap<K, V>
where K: Unpin, V: Unpin,

§

impl<K, V> UnwindSafe for SyncHashMap<K, V>
where K: UnwindSafe, V: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,