non_blocking_mutex/
mutex_guard.rs

1use std::cell::UnsafeCell;
2use std::fmt::{Debug, Display, Formatter};
3use std::marker::PhantomData;
4use std::ops::{Deref, DerefMut};
5
6/// Code was mostly taken from [std::sync::MutexGuard], it is expected to protect [State]
7/// from moving out of synchronized block
8pub struct MutexGuard<'unsafe_state_ref, State: ?Sized + 'unsafe_state_ref> {
9    unsafe_state: &'unsafe_state_ref UnsafeCell<State>,
10    /// Adding it to ensure that [MutexGuard] implements [Send] and [Sync] in same cases
11    /// as [std::sync::MutexGuard] and protects [State] from going out of synchronized
12    /// execution loop
13    ///
14    /// todo remove when this error is no longer actual
15    ///  negative trait bounds are not yet fully implemented; use marker types for now [E0658]
16    _phantom_unsend: PhantomData<std::sync::MutexGuard<'unsafe_state_ref, State>>,
17}
18
19// todo uncomment when this error is no longer actual
20//  negative trait bounds are not yet fully implemented; use marker types for now [E0658]
21// impl<'unsafe_state_ref, State: ?Sized> !Send for MutexGuard<'unsafe_state_ref, State> {}
22unsafe impl<'unsafe_state_ref, State: ?Sized + Sync> Sync for MutexGuard<'unsafe_state_ref, State> {}
23
24impl<'unsafe_state_ref, State: ?Sized> MutexGuard<'unsafe_state_ref, State> {
25    pub unsafe fn new(unsafe_state: &'unsafe_state_ref UnsafeCell<State>) -> Self {
26        Self {
27            unsafe_state,
28            _phantom_unsend: PhantomData,
29        }
30    }
31}
32
33impl<'unsafe_state_ref, State: ?Sized> Deref for MutexGuard<'unsafe_state_ref, State> {
34    type Target = State;
35
36    fn deref(&self) -> &State {
37        unsafe { &*self.unsafe_state.get() }
38    }
39}
40
41impl<'unsafe_state_ref, State: ?Sized> DerefMut for MutexGuard<'unsafe_state_ref, State> {
42    fn deref_mut(&mut self) -> &mut State {
43        unsafe { &mut *self.unsafe_state.get() }
44    }
45}
46
47impl<'unsafe_state_ref, State: ?Sized + Debug> Debug for MutexGuard<'unsafe_state_ref, State> {
48    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
49        Debug::fmt(&**self, f)
50    }
51}
52
53impl<'unsafe_state_ref, State: ?Sized + Display> Display for MutexGuard<'unsafe_state_ref, State> {
54    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
55        (**self).fmt(f)
56    }
57}