|
| 1 | +//! A custom read write lock safe implementation |
| 2 | +
|
| 3 | +use std::sync::{PoisonError, RwLock as InnerRwLock, RwLockReadGuard, RwLockWriteGuard}; |
| 4 | + |
| 5 | +/// A thin wrapper around [`std::sync::RwLock`] with an explicit locking policy. |
| 6 | +/// |
| 7 | +/// This type exists to provide clearer, more ergonomic locking APIs while |
| 8 | +/// preserving the semantics of `std::sync::RwLock`. |
| 9 | +/// |
| 10 | +/// Higher-level methods on this type distinguish between: |
| 11 | +/// - Scoped, closure-based access, which prevents lock guards from escaping |
| 12 | +/// - Explicit guard-based access, for advanced use cases that require flexible control flow |
| 13 | +#[derive(Debug)] |
| 14 | +pub struct RwLock<T: ?Sized>(InnerRwLock<T>); |
| 15 | + |
| 16 | +impl<T> RwLock<T> { |
| 17 | + /// Creates a new `RwLock` protecting `value`. |
| 18 | + pub fn new(value: T) -> Self { |
| 19 | + Self(InnerRwLock::new(value)) |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +impl<T: ?Sized> RwLock<T> { |
| 24 | + /// Executes `f` while holding a read lock. |
| 25 | + /// |
| 26 | + /// The lock guard cannot escape this method. |
| 27 | + /// Prefer this over [`read`] for small, self-contained operations. |
| 28 | + pub fn safe_read<F, R>(&self, f: F) -> Result<R, PoisonError<RwLockReadGuard<'_, T>>> |
| 29 | + where |
| 30 | + F: FnOnce(&T) -> R, |
| 31 | + { |
| 32 | + let guard = self.0.read()?; |
| 33 | + Ok(f(&*guard)) |
| 34 | + } |
| 35 | + |
| 36 | + /// Executes `f` while holding a write lock. |
| 37 | + /// |
| 38 | + /// The lock guard cannot escape this method. |
| 39 | + /// Poisoning is propagated to the caller. |
| 40 | + pub fn safe_write<F, R>(&self, f: F) -> Result<R, PoisonError<RwLockWriteGuard<'_, T>>> |
| 41 | + where |
| 42 | + F: FnOnce(&mut T) -> R, |
| 43 | + { |
| 44 | + let mut guard = self.0.write()?; |
| 45 | + Ok(f(&mut *guard)) |
| 46 | + } |
| 47 | + |
| 48 | + /// Acquires a read lock and returns the guard directly. |
| 49 | + /// |
| 50 | + /// This is an API intended for complex control flow where |
| 51 | + /// closure-based locking would harm readability. |
| 52 | + pub fn read(&self) -> Result<RwLockReadGuard<'_, T>, PoisonError<RwLockReadGuard<'_, T>>> { |
| 53 | + self.0.read() |
| 54 | + } |
| 55 | + |
| 56 | + /// Acquires a write lock and returns the guard directly. |
| 57 | + /// |
| 58 | + /// Callers are responsible for keeping the |
| 59 | + /// guard scope small and avoiding `.await` while holding it. |
| 60 | + pub fn write(&self) -> Result<RwLockWriteGuard<'_, T>, PoisonError<RwLockWriteGuard<'_, T>>> { |
| 61 | + self.0.write() |
| 62 | + } |
| 63 | +} |
0 commit comments