tokio/loom/std/
rwlock.rs

1use std::sync::{self, RwLockReadGuard, RwLockWriteGuard, TryLockError};
2
3/// Adapter for `std::sync::RwLock` that removes the poisoning aspects
4/// from its api.
5#[derive(Debug)]
6pub(crate) struct RwLock<T: ?Sized>(sync::RwLock<T>);
7
8#[allow(dead_code)]
9impl<T> RwLock<T> {
10    #[inline]
11    pub(crate) fn new(t: T) -> Self {
12        Self(sync::RwLock::new(t))
13    }
14
15    #[inline]
16    pub(crate) fn read(&self) -> RwLockReadGuard<'_, T> {
17        match self.0.read() {
18            Ok(guard) => guard,
19            Err(p_err) => p_err.into_inner(),
20        }
21    }
22
23    #[inline]
24    pub(crate) fn try_read(&self) -> Option<RwLockReadGuard<'_, T>> {
25        match self.0.try_read() {
26            Ok(guard) => Some(guard),
27            Err(TryLockError::Poisoned(p_err)) => Some(p_err.into_inner()),
28            Err(TryLockError::WouldBlock) => None,
29        }
30    }
31
32    #[inline]
33    pub(crate) fn write(&self) -> RwLockWriteGuard<'_, T> {
34        match self.0.write() {
35            Ok(guard) => guard,
36            Err(p_err) => p_err.into_inner(),
37        }
38    }
39
40    #[inline]
41    pub(crate) fn try_write(&self) -> Option<RwLockWriteGuard<'_, T>> {
42        match self.0.try_write() {
43            Ok(guard) => Some(guard),
44            Err(TryLockError::Poisoned(p_err)) => Some(p_err.into_inner()),
45            Err(TryLockError::WouldBlock) => None,
46        }
47    }
48}