Skip to main content

AsyncShardedHashMap

Struct AsyncShardedHashMap 

Source
pub struct AsyncShardedHashMap<K, V, S = FxBuildHasher>
where K: Eq + Hash + Clone + Send + Sync, V: Clone + Send + Sync, S: BuildHasher + Clone + Send + Sync,
{ /* private fields */ }
Available on crate feature async only.
Expand description

Asynchronous sharded concurrent HashMap (Tokio RwLock).

Implementations§

Source§

impl<K, V> AsyncShardedHashMap<K, V, FxBuildHasher>
where K: Eq + Hash + Clone + Send + Sync + 'static, V: Clone + Send + Sync + 'static,

Source

pub fn new(shard_count: usize) -> Self

Create with default hasher.

Source§

impl<K, V, S> AsyncShardedHashMap<K, V, S>
where K: Eq + Hash + Clone + Send + Sync + 'static, V: Clone + Send + Sync + 'static, S: BuildHasher + Clone + Send + Sync,

Source

pub fn with_shards_and_hasher(shard_count: usize, hasher: S) -> Self

Create with custom hasher.

This preserves backward compatibility while enforcing the default safety cap (MAX_SHARDS) to avoid oversized allocations.

Source

pub fn with_shards_and_hasher_capped( shard_count: usize, hasher: S, max_shards: usize, ) -> Self

Create with custom hasher and a custom cap.

Source

pub fn try_with_shards_and_hasher( shard_count: usize, hasher: S, ) -> Result<Self, ShardCountError>

Strict constructor with custom hasher.

Returns an error when the requested shard count exceeds MAX_SHARDS.

Source

pub fn try_with_shards_and_hasher_capped( shard_count: usize, hasher: S, max_shards: usize, ) -> Result<Self, ShardCountError>

Strict constructor with custom hasher and caller-provided cap.

Source

pub fn shard_count(&self) -> usize

Configured shard capacity.

Source

pub async fn initialized_shards(&self) -> usize

Number of initialized shards.

Source

pub async fn insert(&self, key: K, value: V) -> Option<V>

Insert key/value asynchronously.

§Arguments
  • key: key to insert.
  • value: value to associate with the key.
§Returns
  • Option<V>: previous value if the key was already present.
Source

pub async fn get(&self, key: &K) -> Option<V>

Get cloned value; uses try_read first (fast path, reduces scheduler churn).

§Arguments
  • key: key to look up.
§Returns
  • Option<V>: cloned value if the key exists.
Source

pub async fn contains(&self, key: &K) -> bool

Check if a key exists; uses try_read first (fast path, reduces scheduler churn).

§Arguments
  • key: key to check.
§Returns
  • bool: true if the key exists in the map, false otherwise.
Source

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

Remove key.

§Arguments
  • key: key to remove.
§Returns
  • Option<V>: previous value if the key existed.
Source

pub async fn len(&self) -> usize

Length (atomic).

§Returns
  • usize: total number of key/value pairs in the map.
Source

pub async fn is_empty(&self) -> bool

Check if map is empty.

§Returns
  • bool: true if the map is empty, false otherwise.
Source

pub async fn clear(&self)

Clear (retains allocated shards).

§Notes
  • Resets length counter to zero.
Source

pub async fn iter(&self) -> Vec<(K, V)>

Snapshot iteration (async).

Steps:

  1. Snapshot Arc of initialized shards under read lock of the shard vector.
  2. For each shard: try try_read; fallback to await read.
  3. Clone inner HashMaps (short critical sections).
  4. If rayon enabled, parallel flatten of snapshots.

Returns a materialized Vec.

Source

pub async fn batch_insert<I>(&self, entries: I) -> usize
where I: IntoIterator<Item = (K, V)>,

Batch insert multiple key-value pairs asynchronously.

§Arguments
  • entries: iterator of (K, V) pairs
§Returns
  • usize: number of new entries inserted
Source

pub async fn batch_remove<I>(&self, keys: I) -> usize
where I: IntoIterator<Item = K>,

Batch remove multiple keys asynchronously.

§Arguments
  • keys: iterator of keys to remove
§Returns
  • usize: number of entries actually removed
Source

pub async fn batch_get(&self, keys: &[K]) -> Vec<Option<V>>

Batch get multiple keys asynchronously.

§Arguments
  • keys: slice of keys to fetch
§Returns
  • Vec<Option<V>>: results in same order as keys
Source

pub async fn compute_if_present<F>(&self, key: &K, f: F) -> Option<V>
where F: FnOnce(V) -> Option<V>,

Update value only if key is present; remove if closure returns None (async).

§Arguments
  • key: key to check
  • f: function that receives current value and returns new value (or None to remove)
§Returns
  • Option<V>: the new value if present, None if removed or key absent
Source

pub async fn compute_if_absent<F>(&self, key: K, f: F) -> V
where F: FnOnce() -> V,

Insert value only if key is absent; returns final value (async).

§Arguments
  • key: key to check/insert
  • f: function to generate value if key absent
§Returns
  • V: either the existing value or newly inserted value
Source

pub async fn retain<F>(&self, predicate: F)
where F: Fn(&K, &V) -> bool,

Remove entries where predicate returns false (async).

Locks each shard independently to maximize parallelism.

§Arguments
  • predicate: function that returns true to keep, false to remove
Source

pub async fn execute_transaction( &self, txn: Transaction<K, V>, ) -> TransactionResult<()>

Execute a transaction (basic implementation, async).

This method executes a transaction by acquiring locks on all involved shards in a deterministic order to avoid deadlocks.

§Arguments
  • txn: The transaction to execute.
§Returns
  • TransactionResult<()>: The result of the transaction.
Source

pub async fn compare_and_swap( &self, key: &K, expected: &V, new: V, ) -> CasResult<V>
where V: PartialEq,

Compare and swap: atomically replace value if it matches expected (async).

§Arguments
  • key: The key to update.
  • expected: The expected current value.
  • new: The new value to swap in.
§Returns
  • CasResult<V>: Success with new value, or Failure with current value.
Source

pub async fn compare_and_remove(&self, key: &K, expected: &V) -> bool
where V: PartialEq,

Compare and remove: atomically remove entry if value matches expected (async).

§Arguments
  • key: The key to remove.
  • expected: The expected current value.
§Returns
  • bool: true if removed, false if value didn’t match or key not found.
Source

pub async fn cow_snapshot(&self) -> CowSnapshot<K, V>

Create a copy-on-write snapshot for minimal-locking reads (async).

§Returns
  • CowSnapshot<K, V>: Immutable snapshot of current state.
Source

pub async fn versioned_snapshot(&self) -> IsolatedSnapshot<K, V>

Create a versioned snapshot for time-travel queries (async).

§Returns
  • IsolatedSnapshot<K, V>: Snapshot with version information.
Source

pub async fn snapshot_at_version( &self, version: u64, ) -> Option<IsolatedSnapshot<K, V>>

Create a snapshot at a specific version (if available, async).

§Arguments
  • version: The version number to snapshot at.
§Returns
  • Option<IsolatedSnapshot<K, V>>: Snapshot if version is current, None otherwise.
Source

pub async fn lock_profiles(&self) -> Vec<LockProfile>

Get lock profiling data for all shards (async).

§Returns
  • Vec<LockProfile>: Per-shard lock statistics.
Source

pub fn enable_profiling(&self, enabled: bool)

Enable or disable lock profiling (async).

§Arguments
  • enabled: Whether to enable profiling.
Source

pub fn with_replication( shard_count: usize, replicas: Vec<Arc<dyn Replica<K, V>>>, quorum_config: QuorumConfig, ) -> Self
where S: Default,

Create an AsyncShardedHashMap with replication support.

§Arguments
  • shard_count: Number of shards.
  • replicas: Vector of replica implementations.
  • quorum_config: Quorum configuration for consistency.
§Returns
  • Self: New map with replication configured.
Source

pub async fn insert_replicated( &self, key: K, value: V, ) -> Result<Option<V>, ReplicaError>

Insert with replication to configured replicas.

§Arguments
  • key: The key to insert.
  • value: The value to insert.
§Returns
  • Result<Option<V>, ReplicaError>: Previous value or error.
Source

pub async fn remove_replicated( &self, key: &K, ) -> Result<Option<V>, ReplicaError>

Remove with replication to configured replicas.

§Arguments
  • key: The key to remove.
§Returns
  • Result<Option<V>, ReplicaError>: Removed value or error.
Source

pub async fn keys(&self) -> Vec<K>

Iterate over all keys (snapshot-based, async).

§Returns
  • Vec<K>: vector of cloned keys
Source

pub async fn values(&self) -> Vec<V>

Iterate over all values (snapshot-based, async).

§Returns
  • Vec<V>: vector of cloned values
Source

pub async fn shard_stats(&self) -> ShardStats

Returns statistics about shard distribution and utilization (async).

§Returns
  • ShardStats: structure containing shard metrics
Source

pub async fn shard_utilization(&self) -> f64

Returns shard utilization as a percentage (0-100, async).

§Returns
  • f64: percentage of shards that have been initialized
Source

pub async fn per_shard_load(&self) -> Vec<PerShardLoad>

Returns load statistics for each initialized shard (async).

Source

pub async fn memory_stats(&self) -> MemoryStats

Returns current memory-oriented shard statistics (async).

Source

pub async fn drain(&self) -> DrainIterator<K, V>

Drains all entries from the map and returns them as an iterator (async).

Shard allocations are retained.

Source§

impl<K, V> AsyncShardedHashMap<K, V>
where K: Eq + Hash + Clone + Send + Sync + Serialize + 'static, V: Clone + Send + Sync + Serialize + 'static,

Source

pub async fn async_snapshot_serializable( &self, ) -> AsyncShardedHashMapSnapshot<K, V>

Available on crate feature serde only.

Obtain a serializable snapshot wrapper (for serde).

Trait Implementations§

Source§

impl<K, V, S> Clone for AsyncShardedHashMap<K, V, S>
where K: Eq + Hash + Clone + Send + Sync + Clone, V: Clone + Send + Sync + Clone, S: BuildHasher + Clone + Send + Sync + Clone,

Source§

fn clone(&self) -> AsyncShardedHashMap<K, V, S>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl<K, V, S> Freeze for AsyncShardedHashMap<K, V, S>
where S: Freeze,

§

impl<K, V, S = FxBuildHasher> !RefUnwindSafe for AsyncShardedHashMap<K, V, S>

§

impl<K, V, S> Send for AsyncShardedHashMap<K, V, S>

§

impl<K, V, S> Sync for AsyncShardedHashMap<K, V, S>

§

impl<K, V, S> Unpin for AsyncShardedHashMap<K, V, S>
where S: Unpin,

§

impl<K, V, S> UnsafeUnpin for AsyncShardedHashMap<K, V, S>
where S: UnsafeUnpin,

§

impl<K, V, S = FxBuildHasher> !UnwindSafe for AsyncShardedHashMap<K, V, S>

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> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
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> 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> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more