1 pub use ::alloc::sync::Arc;
2 use core::ops::{Deref, DerefMut};
3 use core::cell::{RefCell, Ref, RefMut};
4 use super::{LockTestExt, LockHeldState};
6 pub type LockResult<Guard> = Result<Guard, ()>;
8 pub struct Mutex<T: ?Sized> {
12 #[must_use = "if unused the Mutex will immediately unlock"]
13 pub struct MutexGuard<'a, T: ?Sized + 'a> {
17 impl<T: ?Sized> Deref for MutexGuard<'_, T> {
20 fn deref(&self) -> &T {
25 impl<T: ?Sized> DerefMut for MutexGuard<'_, T> {
26 fn deref_mut(&mut self) -> &mut T {
32 pub fn new(inner: T) -> Mutex<T> {
33 Mutex { inner: RefCell::new(inner) }
36 pub fn lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
37 Ok(MutexGuard { lock: self.inner.borrow_mut() })
40 pub fn try_lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
41 Ok(MutexGuard { lock: self.inner.borrow_mut() })
44 pub fn into_inner(self) -> LockResult<T> {
45 Ok(self.inner.into_inner())
49 impl<'a, T: 'a> LockTestExt<'a> for Mutex<T> {
51 fn held_by_thread(&self) -> LockHeldState {
52 if self.inner.try_borrow_mut().is_err() { return LockHeldState::HeldByThread; }
53 else { return LockHeldState::NotHeldByThread; }
55 type ExclLock = MutexGuard<'a, T>;
57 fn unsafe_well_ordered_double_lock_self(&'a self) -> MutexGuard<T> { self.lock().unwrap() }
60 pub struct RwLock<T: ?Sized> {
64 pub struct RwLockReadGuard<'a, T: ?Sized + 'a> {
68 pub struct RwLockWriteGuard<'a, T: ?Sized + 'a> {
72 impl<T: ?Sized> Deref for RwLockReadGuard<'_, T> {
75 fn deref(&self) -> &T {
80 impl<T: ?Sized> Deref for RwLockWriteGuard<'_, T> {
83 fn deref(&self) -> &T {
88 impl<T: ?Sized> DerefMut for RwLockWriteGuard<'_, T> {
89 fn deref_mut(&mut self) -> &mut T {
95 pub fn new(inner: T) -> RwLock<T> {
96 RwLock { inner: RefCell::new(inner) }
99 pub fn read<'a>(&'a self) -> LockResult<RwLockReadGuard<'a, T>> {
100 Ok(RwLockReadGuard { lock: self.inner.borrow() })
103 pub fn write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
104 Ok(RwLockWriteGuard { lock: self.inner.borrow_mut() })
107 pub fn try_write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
108 match self.inner.try_borrow_mut() {
109 Ok(lock) => Ok(RwLockWriteGuard { lock }),
115 impl<'a, T: 'a> LockTestExt<'a> for RwLock<T> {
117 fn held_by_thread(&self) -> LockHeldState {
118 if self.inner.try_borrow_mut().is_err() { return LockHeldState::HeldByThread; }
119 else { return LockHeldState::NotHeldByThread; }
121 type ExclLock = RwLockWriteGuard<'a, T>;
123 fn unsafe_well_ordered_double_lock_self(&'a self) -> RwLockWriteGuard<T> { self.write().unwrap() }
126 pub type FairRwLock<T> = RwLock<T>;