1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
use std::convert::From;
use std::cell::UnsafeCell;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicBool, Ordering};
use std::marker::PhantomData;
use std::panic::{UnwindSafe, RefUnwindSafe};
use std::fmt;
use std::fmt::{Debug, Display};
pub struct TryMutex<T> {
data: UnsafeCell<T>,
locked: AtomicBool,
}
impl<T> TryMutex<T> {
#[inline]
pub fn new(t: T) -> TryMutex<T> {
TryMutex {
data: UnsafeCell::new(t),
locked: AtomicBool::new(false),
}
}
#[inline]
pub fn try_lock(&self) -> Option<TryMutexGuard<T>> {
if self.locked.compare_and_swap(false, true, Ordering::Acquire) {
None
} else {
Some(TryMutexGuard{
lock: self,
notsend: PhantomData,
})
}
}
#[inline]
pub fn into_inner(self) -> T {
self.data.into_inner()
}
#[inline]
pub fn get_mut(&mut self) -> &mut T {
unsafe { &mut *self.data.get() }
}
}
impl<T: Default> Default for TryMutex<T> {
fn default() -> Self {
TryMutex::new(T::default())
}
}
impl<T: Debug> Debug for TryMutex<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(guard) = self.try_lock() {
f.debug_struct("TryMutex")
.field("data", &*guard)
.finish()
} else {
struct LockedPlaceholder;
impl fmt::Debug for LockedPlaceholder {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("<locked>") }
}
f.debug_struct("TryMutex").field("data", &LockedPlaceholder).finish()
}
}
}
pub struct TryMutexGuard<'a, T: 'a>{
lock: &'a TryMutex<T>,
notsend: PhantomData<*mut T>,
}
impl<'a, T> Deref for TryMutexGuard<'a, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.lock.data.get() }
}
}
impl<'a, T> DerefMut for TryMutexGuard<'a, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.lock.data.get() }
}
}
impl<'a, T> Drop for TryMutexGuard<'a, T> {
fn drop(&mut self) {
self.lock.locked.store(false, Ordering::Release);
}
}
impl<'a, T: Debug> Debug for TryMutexGuard<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("TryMutexGuard")
.field("data", &*self)
.finish()
}
}
impl<'a, T: Display> Display for TryMutexGuard<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f)
}
}
impl<T> UnwindSafe for TryMutex<T> { }
impl<T> RefUnwindSafe for TryMutex<T> { }
unsafe impl<T> Sync for TryMutex<T> { }
unsafe impl<'a, T> Sync for TryMutexGuard<'a, T> { }
impl<T> From<T> for TryMutex<T> {
fn from(t: T) -> Self {
TryMutex::new(t)
}
}