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
4 changed files with 29 additions and 3 deletions
Generated
+1
View File
@@ -963,6 +963,7 @@ dependencies = [
"itertools 0.14.0",
"libc",
"libloading",
"lock_api",
"log",
"maplit",
"nix",
+2 -2
View File
@@ -519,8 +519,8 @@ version = "1.0"
version = "0.12.4"
# Use this when extending with_lock::WithLock to parking_lot
# [workspace.dependencies.lock_api]
# version = "0.4.13"
[workspace.dependencies.lock_api]
version = "0.4.13"
[workspace.dependencies.bytesize]
version = "2.0"
+1
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
+25 -1
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 = ()>