From b635e825d2ba002170ff1c25a26270f875699ca5 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 19 Jul 2025 22:30:41 +0100 Subject: [PATCH] refactor: Implement with_lock for lock_api --- Cargo.lock | 1 + Cargo.toml | 4 ++-- src/core/Cargo.toml | 1 + src/core/utils/with_lock.rs | 26 +++++++++++++++++++++++++- 4 files changed, 29 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b084f72a..ed9be6d9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -963,6 +963,7 @@ dependencies = [ "itertools 0.14.0", "libc", "libloading", + "lock_api", "log", "maplit", "nix", diff --git a/Cargo.toml b/Cargo.toml index 3e52c4b2..54f7ae82 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/src/core/Cargo.toml b/src/core/Cargo.toml index 7a3721d6..462b8e54 100644 --- a/src/core/Cargo.toml +++ b/src/core/Cargo.toml @@ -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 diff --git a/src/core/utils/with_lock.rs b/src/core/utils/with_lock.rs index 76f014d1..914749de 100644 --- a/src/core/utils/with_lock.rs +++ b/src/core/utils/with_lock.rs @@ -2,7 +2,7 @@ use std::sync::{Arc, Mutex}; -pub trait WithLock { +pub trait WithLock { /// Acquires a lock and executes the given closure with the locked data. fn with_lock(&self, f: F) where @@ -33,6 +33,30 @@ impl WithLock for Arc> { } } +impl WithLock for lock_api::Mutex { + fn with_lock(&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 WithLock for Arc> { + fn with_lock(&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 { /// Acquires a lock and executes the given closure with the locked data. fn with_lock(&self, f: F) -> impl Future