1
0
Fork 0
mirror of https://forgejo.ellis.link/continuwuation/continuwuity.git synced 2025-07-28 10:48:30 +00:00

refactor: Implement with_lock for lock_api

This commit is contained in:
Jade Ellis 2025-07-19 22:30:41 +01:00
parent 6d29098d1a
commit b635e825d2
No known key found for this signature in database
GPG key ID: 8705A2A3EBF77BD2
4 changed files with 29 additions and 3 deletions

View file

@ -111,6 +111,7 @@ tracing-subscriber.workspace = true
tracing.workspace = true
url.workspace = true
parking_lot.workspace = true
lock_api.workspace = true
[target.'cfg(unix)'.dependencies]
nix.workspace = true

View file

@ -2,7 +2,7 @@
use std::sync::{Arc, Mutex};
pub trait WithLock<T> {
pub trait WithLock<T: ?Sized> {
/// Acquires a lock and executes the given closure with the locked data.
fn with_lock<F>(&self, f: F)
where
@ -33,6 +33,30 @@ impl<T> WithLock<T> for Arc<Mutex<T>> {
}
}
impl<R: lock_api::RawMutex, T: ?Sized> WithLock<T> for lock_api::Mutex<R, 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();
f(&mut data_guard);
// Lock is released here when `data_guard` goes out of scope.
}
}
impl<R: lock_api::RawMutex, T: ?Sized> WithLock<T> for Arc<lock_api::Mutex<R, 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();
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 = ()>