Skip to main content

veilid_tools/async_locks/
async_rw_lock.rs

1//! AsyncRwLock
2use super::*;
3
4use async_lock::RwLock as InnerAsyncRwLock;
5use async_lock::RwLockReadGuard as InnerAsyncRwLockReadGuard;
6use async_lock::RwLockReadGuardArc as InnerAsyncRwLockReadGuardArc;
7use async_lock::RwLockWriteGuard as InnerAsyncRwLockWriteGuard;
8use async_lock::RwLockWriteGuardArc as InnerAsyncRwLockWriteGuardArc;
9
10/// An async reader-writer lock allowing many concurrent readers or one writer.
11///
12/// Wraps `async_lock::RwLock`; under the `debug-locks` feature, acquisitions that
13/// stall past [`DEBUG_LOCKS_DURATION_MS`] are reported as deadlocks.
14#[derive(Debug)]
15pub struct AsyncRwLock<T>
16where
17    T: ?Sized,
18{
19    inner: Arc<InnerAsyncRwLock<T>>,
20    #[cfg(feature = "debug-locks")]
21    lock_id_container: LockIdContainer,
22}
23
24impl<T> AsyncRwLock<T> {
25    /// Create a new lock holding `t`, initially unlocked.
26    pub fn new(t: T) -> AsyncRwLock<T> {
27        AsyncRwLock {
28            inner: Arc::new(InnerAsyncRwLock::new(t)),
29            #[cfg(feature = "debug-locks")]
30            lock_id_container: LockIdContainer::next(),
31        }
32    }
33
34    /// Acquire shared read access, waiting for any writer to finish, returning an owned guard.
35    ///
36    /// Blocks until no writer holds the lock. The returned guard holds read access until dropped.
37    /// Under `debug-locks`, a wait past [`DEBUG_LOCKS_DURATION_MS`] is reported as a deadlock.
38    #[inline]
39    pub async fn read_arc(self: &Arc<Self>) -> AsyncRwLockReadGuardArc<T> {
40        cfg_if! {
41            if #[cfg(feature = "debug-locks")] {
42                let inner = match timeout(DEBUG_LOCKS_DURATION_MS, self.inner.read_arc()).await {
43                    Ok(v) => v,
44                    Err(_) => {
45                        self.lock_id_container.report_deadlock("AsyncRwLock::read_arc deadlock");
46                    }
47                };
48            } else {
49                let inner = self.inner.read_arc().await;
50            }
51        }
52
53        AsyncRwLockReadGuardArc {
54            inner,
55            #[cfg(feature = "debug-locks")]
56            _guard_id_container: GuardIdContainer::next(self.lock_id_container.clone()),
57        }
58    }
59
60    /// Try to acquire shared read access without waiting, returning an owned guard, or `None` if a writer holds the lock.
61    ///
62    /// Never blocks. On success the guard holds read access until dropped.
63    #[inline]
64    #[must_use]
65    pub fn try_read_arc(self: &Arc<Self>) -> Option<AsyncRwLockReadGuardArc<T>> {
66        let inner = self.inner.try_read_arc()?;
67
68        let out = AsyncRwLockReadGuardArc {
69            inner,
70            #[cfg(feature = "debug-locks")]
71            _guard_id_container: GuardIdContainer::next(self.lock_id_container.clone()),
72        };
73
74        Some(out)
75    }
76}
77
78impl<T: ?Sized> AsyncRwLock<T> {
79    /// Try to acquire shared read access without waiting, or `None` if a writer holds the lock.
80    ///
81    /// Never blocks. On success the guard holds read access until dropped.
82    #[inline]
83    #[must_use]
84    pub fn try_read(&self) -> Option<AsyncRwLockReadGuard<'_, T>> {
85        let inner = self.inner.try_read()?;
86
87        let out = AsyncRwLockReadGuard {
88            inner,
89            #[cfg(feature = "debug-locks")]
90            _guard_id_container: GuardIdContainer::next(self.lock_id_container.clone()),
91        };
92
93        Some(out)
94    }
95
96    /// Acquire shared read access, waiting for any writer to finish.
97    ///
98    /// Blocks until no writer holds the lock. The returned guard holds read access until dropped.
99    /// Under `debug-locks`, a wait past [`DEBUG_LOCKS_DURATION_MS`] is reported as a deadlock.
100    #[inline]
101    pub async fn read(&self) -> AsyncRwLockReadGuard<'_, T> {
102        cfg_if! {
103            if #[cfg(feature = "debug-locks")] {
104                let inner = match timeout(DEBUG_LOCKS_DURATION_MS, self.inner.read()).await {
105                    Ok(v) => v,
106                    Err(_) => {
107                        self.lock_id_container.report_deadlock("AsyncRwLock::read deadlock");
108                    }
109                };
110            } else {
111                let inner = self.inner.read().await;
112            }
113        }
114
115        AsyncRwLockReadGuard {
116            inner,
117            #[cfg(feature = "debug-locks")]
118            _guard_id_container: GuardIdContainer::next(self.lock_id_container.clone()),
119        }
120    }
121
122    /// Try to acquire exclusive write access without waiting, or `None` if any reader or writer holds the lock.
123    ///
124    /// Never blocks. On success the guard holds write access until dropped.
125    #[inline]
126    #[must_use]
127    pub fn try_write(&self) -> Option<AsyncRwLockWriteGuard<'_, T>> {
128        let inner = self.inner.try_write()?;
129
130        let out = AsyncRwLockWriteGuard {
131            inner,
132            #[cfg(feature = "debug-locks")]
133            _guard_id_container: GuardIdContainer::next(self.lock_id_container.clone()),
134        };
135
136        Some(out)
137    }
138
139    /// Acquire exclusive write access, waiting for all readers and any writer to finish.
140    ///
141    /// Blocks until no reader or writer holds the lock. The returned guard holds write access until dropped.
142    /// Under `debug-locks`, a wait past [`DEBUG_LOCKS_DURATION_MS`] is reported as a deadlock.
143    #[inline]
144    pub async fn write(&self) -> AsyncRwLockWriteGuard<'_, T> {
145        cfg_if! {
146            if #[cfg(feature = "debug-locks")] {
147                let inner = match timeout(DEBUG_LOCKS_DURATION_MS, self.inner.write()).await {
148                    Ok(v) => v,
149                    Err(_) => {
150                        self.lock_id_container.report_deadlock("AsyncRwLock::write deadlock");
151                    }
152                };
153            } else {
154                let inner = self.inner.write().await;
155            }
156        }
157
158        AsyncRwLockWriteGuard {
159            inner,
160            #[cfg(feature = "debug-locks")]
161            _guard_id_container: GuardIdContainer::next(self.lock_id_container.clone()),
162        }
163    }
164
165    /// Try to acquire exclusive write access without waiting, returning an owned guard, or `None` if any reader or writer holds the lock.
166    ///
167    /// Never blocks. On success the guard holds write access until dropped.
168    #[inline]
169    #[must_use]
170    pub fn try_write_arc(self: &Arc<Self>) -> Option<AsyncRwLockWriteGuardArc<T>> {
171        let inner = self.inner.try_write_arc()?;
172
173        let out = AsyncRwLockWriteGuardArc {
174            inner,
175            #[cfg(feature = "debug-locks")]
176            _guard_id_container: GuardIdContainer::next(self.lock_id_container.clone()),
177        };
178
179        Some(out)
180    }
181
182    /// Acquire exclusive write access, waiting for all readers and any writer to finish, returning an owned guard.
183    ///
184    /// Blocks until no reader or writer holds the lock. The returned guard holds write access until dropped.
185    /// Under `debug-locks`, a wait past [`DEBUG_LOCKS_DURATION_MS`] is reported as a deadlock.
186    #[inline]
187    pub async fn write_arc(self: &Arc<Self>) -> AsyncRwLockWriteGuardArc<T> {
188        cfg_if! {
189            if #[cfg(feature = "debug-locks")] {
190                let inner = match timeout(DEBUG_LOCKS_DURATION_MS, self.inner.write_arc()).await {
191                    Ok(v) => v,
192                    Err(_) => {
193                        self.lock_id_container.report_deadlock("AsyncRwLock::write_arc deadlock");
194                    }
195                };
196            } else {
197                let inner = self.inner.write_arc().await;
198            }
199        }
200
201        AsyncRwLockWriteGuardArc {
202            inner,
203            #[cfg(feature = "debug-locks")]
204            _guard_id_container: GuardIdContainer::next(self.lock_id_container.clone()),
205        }
206    }
207}
208
209impl<T> From<T> for AsyncRwLock<T> {
210    #[inline]
211    fn from(val: T) -> AsyncRwLock<T> {
212        AsyncRwLock::new(val)
213    }
214}
215
216/// Borrowed guard for shared read access; derefs to `T` and releases on drop.
217#[clippy::has_significant_drop]
218#[derive(Debug)]
219pub struct AsyncRwLockReadGuard<'a, T: ?Sized> {
220    inner: InnerAsyncRwLockReadGuard<'a, T>,
221    #[cfg(feature = "debug-locks")]
222    _guard_id_container: GuardIdContainer,
223}
224
225impl<T: fmt::Display + ?Sized> fmt::Display for AsyncRwLockReadGuard<'_, T> {
226    #[inline]
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        self.inner.fmt(f)
229    }
230}
231
232impl<T: ?Sized> std::ops::Deref for AsyncRwLockReadGuard<'_, T> {
233    type Target = T;
234
235    #[inline]
236    fn deref(&self) -> &T {
237        &self.inner
238    }
239}
240
241/// Owned guard for shared read access; derefs to `T` and releases on drop.
242#[clippy::has_significant_drop]
243#[derive(Debug)]
244pub struct AsyncRwLockReadGuardArc<T> {
245    inner: InnerAsyncRwLockReadGuardArc<T>,
246    #[cfg(feature = "debug-locks")]
247    _guard_id_container: GuardIdContainer,
248}
249
250impl<T: fmt::Display> fmt::Display for AsyncRwLockReadGuardArc<T> {
251    #[inline]
252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253        self.inner.fmt(f)
254    }
255}
256
257impl<T> std::ops::Deref for AsyncRwLockReadGuardArc<T> {
258    type Target = T;
259
260    #[inline]
261    fn deref(&self) -> &T {
262        &self.inner
263    }
264}
265
266/// Borrowed guard for exclusive write access; derefs to `T` (mutably) and releases on drop.
267#[clippy::has_significant_drop]
268#[derive(Debug)]
269pub struct AsyncRwLockWriteGuard<'a, T: ?Sized> {
270    inner: InnerAsyncRwLockWriteGuard<'a, T>,
271    #[cfg(feature = "debug-locks")]
272    _guard_id_container: GuardIdContainer,
273}
274
275impl<T: fmt::Display + ?Sized> fmt::Display for AsyncRwLockWriteGuard<'_, T> {
276    #[inline]
277    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278        self.inner.fmt(f)
279    }
280}
281
282impl<T: ?Sized> std::ops::Deref for AsyncRwLockWriteGuard<'_, T> {
283    type Target = T;
284
285    #[inline]
286    fn deref(&self) -> &T {
287        &self.inner
288    }
289}
290
291impl<T: ?Sized> std::ops::DerefMut for AsyncRwLockWriteGuard<'_, T> {
292    #[inline]
293    fn deref_mut(&mut self) -> &mut T {
294        &mut self.inner
295    }
296}
297
298/// Owned guard for exclusive write access; derefs to `T` (mutably) and releases on drop.
299#[clippy::has_significant_drop]
300#[derive(Debug)]
301pub struct AsyncRwLockWriteGuardArc<T: ?Sized> {
302    inner: InnerAsyncRwLockWriteGuardArc<T>,
303    #[cfg(feature = "debug-locks")]
304    _guard_id_container: GuardIdContainer,
305}
306
307impl<T: fmt::Display + ?Sized> fmt::Display for AsyncRwLockWriteGuardArc<T> {
308    #[inline]
309    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
310        self.inner.fmt(f)
311    }
312}
313
314impl<T: ?Sized> std::ops::Deref for AsyncRwLockWriteGuardArc<T> {
315    type Target = T;
316
317    #[inline]
318    fn deref(&self) -> &T {
319        &self.inner
320    }
321}
322
323impl<T: ?Sized> std::ops::DerefMut for AsyncRwLockWriteGuardArc<T> {
324    #[inline]
325    fn deref_mut(&mut self) -> &mut T {
326        &mut self.inner
327    }
328}