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
133
134
135
136
137
138
139
140
141
142
143
144
use std::{
cell::UnsafeCell,
ops::{Deref, DerefMut},
sync::atomic::{AtomicBool, Ordering},
};
pub struct FusedRwLock<T: ?Sized> {
inner: parking_lot::RwLock<()>,
locked: AtomicBool,
object: UnsafeCell<T>,
}
unsafe impl<T: ?Sized + Send> Send for FusedRwLock<T> {}
unsafe impl<T: ?Sized + Send + Sync> Sync for FusedRwLock<T> {}
impl<T: Default> Default for FusedRwLock<T> {
fn default() -> Self {
Self::new(Default::default())
}
}
impl<T> FusedRwLock<T> {
pub const fn new(x: T) -> Self {
Self {
inner: parking_lot::const_rwlock(()),
locked: AtomicBool::new(false),
object: UnsafeCell::new(x),
}
}
pub fn into_inner(self) -> T {
self.object.into_inner()
}
}
impl<T: ?Sized> FusedRwLock<T> {
pub fn try_get_mut(&mut self) -> Option<&mut T> {
if *self.locked.get_mut() {
Some(self.object.get_mut())
} else {
None
}
}
pub unsafe fn get_mut_unlocked(&mut self) -> &mut T {
self.object.get_mut()
}
pub fn is_locked(&self) -> bool {
self.locked.load(Ordering::Relaxed)
}
pub fn lock(&self) {
let _guard = self.inner.read();
self.locked
.store(true, std::sync::atomic::Ordering::Release)
}
pub fn try_read(&self) -> Option<&T> {
if self.locked.load(Ordering::Acquire) {
Some(unsafe { &*self.object.get() })
} else {
None
}
}
pub fn read(&self) -> &T {
if !self.is_locked() {
self.lock();
}
self.try_read().unwrap()
}
pub fn try_write(&self) -> Option<FusedRwLockGuard<T>> {
if !self.is_locked() {
let guard = self.inner.write();
if !self.is_locked() {
Some(FusedRwLockGuard {
_guard: guard,
inner: unsafe { &mut *self.object.get() },
})
} else {
None
}
} else {
None
}
}
}
pub struct FusedRwLockGuard<'a, T: ?Sized> {
_guard: parking_lot::RwLockWriteGuard<'a, ()>,
inner: &'a mut T,
}
impl<'a, T: ?Sized> Deref for FusedRwLockGuard<'a, T> {
type Target = T;
fn deref(&self) -> &T {
self.inner
}
}
impl<'a, T: ?Sized> DerefMut for FusedRwLockGuard<'a, T> {
fn deref_mut(&mut self) -> &mut T {
self.inner
}
}