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
#![deny(missing_docs)]
use std::ops::Deref;
use left_right::Absorb;
struct SetOp<T>(T);
impl<T> Absorb<SetOp<T>> for Inner<T>
where
T: Clone,
{
fn absorb_first(&mut self, operation: &mut SetOp<T>, _: &Self) {
self.0 = operation.0.clone();
}
fn absorb_second(&mut self, operation: SetOp<T>, _: &Self) {
self.0 = operation.0;
}
fn drop_first(self: Box<Self>) {}
fn sync_with(&mut self, first: &Self) {
self.0 = first.0.clone()
}
}
#[derive(Clone)]
struct Inner<T>(T);
pub struct ReadHandle<T>(left_right::ReadHandle<Inner<T>>);
impl<T> ReadHandle<T> {
pub fn get(&self) -> Option<ReadGuard<T>> {
self.0.enter().map(|guard| ReadGuard(guard))
}
pub unsafe fn get_unchecked(&self) -> ReadGuard<T> {
self.0
.enter()
.map(|guard| ReadGuard(guard))
.unwrap_unchecked()
}
}
pub struct ReadGuard<'a, T>(left_right::ReadGuard<'a, Inner<T>>);
impl<T> Deref for ReadGuard<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0.as_ref().0
}
}
pub struct WriteHandle<T: Clone>(left_right::WriteHandle<Inner<T>, SetOp<T>>);
impl<T> WriteHandle<T>
where
T: Clone,
{
pub fn set(&mut self, value: T) {
self.0.append(SetOp(value));
}
pub fn publish(&mut self) {
self.0.publish();
}
}
pub fn new<T: Clone>(value: T) -> (WriteHandle<T>, ReadHandle<T>) {
let (w, r) = left_right::new_from_empty::<Inner<T>, SetOp<T>>(Inner(value));
(WriteHandle(w), ReadHandle(r))
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
let (mut w, r) = super::new(false);
let t = std::thread::spawn(move || loop {
let value = r.get().unwrap();
if *value {
break;
}
});
w.set(true);
w.publish();
t.join().unwrap();
assert!(true);
}
}