use std::{hash::Hash, sync::Arc}; type Value = tokio::sync::Mutex; type ArcMutex = Arc>; type HashMap = std::collections::HashMap>; type MapMutex = std::sync::Mutex>; type Map = MapMutex; /// Map of Mutexes pub struct MutexMap { map: Map, } pub struct Guard { _guard: tokio::sync::OwnedMutexGuard, } impl MutexMap where Key: Send + Hash + Eq + Clone, Val: Send + Default, { #[must_use] pub fn new() -> Self { Self { map: Map::::new(HashMap::::new()), } } pub async fn lock(&self, k: &K) -> Guard where K: ?Sized + Send + Sync, Key: for<'a> From<&'a K>, { let val = self .map .lock() .expect("map mutex locked") .entry(k.into()) .or_default() .clone(); let guard = val.lock_owned().await; Guard:: { _guard: guard, } } } impl Default for MutexMap where Key: Send + Hash + Eq + Clone, Val: Send + Default, { fn default() -> Self { Self::new() } }