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 into_inner(self) -> LockResult<T> {
41 Ok(self.inner.into_inner())
45 impl<'a, T: 'a> LockTestExt<'a> for Mutex<T> {
47 fn held_by_thread(&self) -> LockHeldState {
48 if self.inner.try_borrow_mut().is_err() { return LockHeldState::HeldByThread; }
49 else { return LockHeldState::NotHeldByThread; }
51 type ExclLock = MutexGuard<'a, T>;
53 fn unsafe_well_ordered_double_lock_self(&'a self) -> MutexGuard<T> { self.lock().unwrap() }
56 pub struct RwLock<T: ?Sized> {
60 pub struct RwLockReadGuard<'a, T: ?Sized + 'a> {
64 pub struct RwLockWriteGuard<'a, T: ?Sized + 'a> {
68 impl<T: ?Sized> Deref for RwLockReadGuard<'_, T> {
71 fn deref(&self) -> &T {
76 impl<T: ?Sized> Deref for RwLockWriteGuard<'_, T> {
79 fn deref(&self) -> &T {
84 impl<T: ?Sized> DerefMut for RwLockWriteGuard<'_, T> {
85 fn deref_mut(&mut self) -> &mut T {
91 pub fn new(inner: T) -> RwLock<T> {
92 RwLock { inner: RefCell::new(inner) }
95 pub fn read<'a>(&'a self) -> LockResult<RwLockReadGuard<'a, T>> {
96 Ok(RwLockReadGuard { lock: self.inner.borrow() })
99 pub fn write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
100 Ok(RwLockWriteGuard { lock: self.inner.borrow_mut() })
103 pub fn try_write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
104 match self.inner.try_borrow_mut() {
105 Ok(lock) => Ok(RwLockWriteGuard { lock }),
111 impl<'a, T: 'a> LockTestExt<'a> for RwLock<T> {
113 fn held_by_thread(&self) -> LockHeldState {
114 if self.inner.try_borrow_mut().is_err() { return LockHeldState::HeldByThread; }
115 else { return LockHeldState::NotHeldByThread; }
117 type ExclLock = RwLockWriteGuard<'a, T>;
119 fn unsafe_well_ordered_double_lock_self(&'a self) -> RwLockWriteGuard<T> { self.write().unwrap() }
122 pub type FairRwLock<T> = RwLock<T>;