refactor: Add with_lock traits

This commit is contained in:
Jade Ellis 2025-07-01 23:57:24 +01:00
parent 7e0c021603
commit 1aa891c053
No known key found for this signature in database
GPG key ID: 8705A2A3EBF77BD2
2 changed files with 66 additions and 0 deletions

View file

@ -19,6 +19,7 @@ pub mod sys;
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
pub mod time; pub mod time;
pub mod with_lock;
pub use ::conduwuit_macros::implement; pub use ::conduwuit_macros::implement;
pub use ::ctor::{ctor, dtor}; pub use ::ctor::{ctor, dtor};

View file

@ -0,0 +1,65 @@
//! Traits for explicitly scoping the lifetime of locks.
use std::sync::{Arc, Mutex};
pub trait WithLock<T> {
/// Acquires a lock and executes the given closure with the locked data.
fn with_lock<F>(&self, f: F)
where
F: FnMut(&mut T);
}
impl<T> WithLock<T> for Mutex<T> {
fn with_lock<F>(&self, mut f: F)
where
F: FnMut(&mut T),
{
// The locking and unlocking logic is hidden inside this function.
let mut data_guard = self.lock().unwrap();
f(&mut data_guard);
// Lock is released here when `data_guard` goes out of scope.
}
}
impl<T> WithLock<T> for Arc<Mutex<T>> {
fn with_lock<F>(&self, mut f: F)
where
F: FnMut(&mut T),
{
// The locking and unlocking logic is hidden inside this function.
let mut data_guard = self.lock().unwrap();
f(&mut data_guard);
// Lock is released here when `data_guard` goes out of scope.
}
}
pub trait WithLockAsync<T> {
/// Acquires a lock and executes the given closure with the locked data.
fn with_lock<F>(&self, f: F) -> impl Future<Output = ()>
where
F: FnMut(&mut T);
}
impl<T> WithLockAsync<T> for futures::lock::Mutex<T> {
async fn with_lock<F>(&self, mut f: F)
where
F: FnMut(&mut T),
{
// The locking and unlocking logic is hidden inside this function.
let mut data_guard = self.lock().await;
f(&mut data_guard);
// Lock is released here when `data_guard` goes out of scope.
}
}
impl<T> WithLockAsync<T> for Arc<futures::lock::Mutex<T>> {
async fn with_lock<F>(&self, mut f: F)
where
F: FnMut(&mut T),
{
// The locking and unlocking logic is hidden inside this function.
let mut data_guard = self.lock().await;
f(&mut data_guard);
// Lock is released here when `data_guard` goes out of scope.
}
}