async_defer/
locks.rs

1use async_lock::{Mutex, RwLock};
2use std::{
3    future::Future,
4    ops::{Deref, DerefMut},
5};
6
7// --- MUT ---
8
9/// Locking primitives, Mutable Access
10pub trait LockMut: Send + Sync + 'static {
11    type Inner;
12    type Output<'a>: DerefMut<Target = Self::Inner> + Send;
13    fn lock_mut<'a>(&'a self) -> impl Future<Output = Self::Output<'a>> + Send;
14}
15
16impl<T: Send + Sync + 'static> LockMut for RwLock<T> {
17    type Inner = T;
18    type Output<'a> = async_lock::RwLockWriteGuard<'a, T>;
19    fn lock_mut<'a>(&'a self) -> impl Future<Output = Self::Output<'a>> + Send {
20        async { self.write().await }
21    }
22}
23
24impl<T: Send + Sync + 'static> LockMut for Mutex<T> {
25    type Inner = T;
26    type Output<'a> = async_lock::MutexGuard<'a, T>;
27    fn lock_mut<'a>(&'a self) -> impl Future<Output = Self::Output<'a>> + Send {
28        async { self.lock().await }
29    }
30}
31
32// --- REF ---
33
34/// Locking primitives, Immutable Access
35pub trait LockRef: Send + Sync + 'static {
36    type Inner;
37    type Output<'a>: Deref<Target = Self::Inner> + Send;
38    fn lock_ref<'a>(&'a self) -> impl Future<Output = Self::Output<'a>> + Send;
39}
40
41impl<T: Send + Sync + 'static> LockRef for RwLock<T> {
42    type Inner = T;
43    type Output<'a> = async_lock::RwLockReadGuard<'a, T>;
44    fn lock_ref<'a>(&'a self) -> impl Future<Output = Self::Output<'a>> + Send {
45        async { self.read().await }
46    }
47}
48
49impl<T: Send + Sync + 'static> LockRef for Mutex<T> {
50    type Inner = T;
51    type Output<'a> = async_lock::MutexGuard<'a, T>;
52    fn lock_ref<'a>(&'a self) -> impl Future<Output = Self::Output<'a>> + Send {
53        async { self.lock().await }
54    }
55}