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
#![no_std]
use core::cell::UnsafeCell;
use core::sync::atomic::{AtomicUsize, spin_loop_hint};
use core::sync::atomic::Ordering::{Acquire, Release};
#[derive(Debug)]
pub struct PingPongCell<T> {
state: AtomicUsize,
value: UnsafeCell<Option<T>>,
}
unsafe impl<T: Send> Send for PingPongCell<T> {}
unsafe impl<T: Sync> Sync for PingPongCell<T> {}
const WAITING: usize = 0;
const WORKING: usize = 0b01;
impl<T> PingPongCell<T> {
pub fn new(value: Option<T>) -> Self {
PingPongCell {
state: AtomicUsize::new(WAITING),
value: UnsafeCell::new(value),
}
}
pub fn take(&self) -> Option<T> {
self.transact(|state| state.take() )
}
pub fn put(&self, value: T) {
self.transact(|state| { *state = Some(value); })
}
pub fn put_if_empty(&self, value: T) -> Result<(), T> {
self.transact(|state| {
if state.is_some() {
Err(value)
} else {
*state = Some(value);
Ok(())
}
})
}
pub fn transact<F, R>(&self, fun: F) -> R
where F: FnOnce(&mut Option<T>) -> R {
loop {
if let WAITING = self.state.compare_and_swap(WAITING, WORKING, Acquire) {
return unsafe {
let ret = fun(&mut *self.value.get());
self.state.store(WAITING, Release);
ret
}
} else {
spin_loop_hint();
}
}
}
}
impl<T: Clone> PingPongCell<T> {
pub fn put_empty_clone(&self, value: T) -> Result<(), (T, T)> {
self.transact(|state| {
if let Some(ref old) = state {
Err((value, old.clone()))
} else {
*state = Some(value);
Ok(())
}
})
}
pub fn clone_inner(&self) -> Option<T> {
self.transact(|state| {
state.clone()
})
}
}
impl<T: Eq> PingPongCell<T> {
pub fn compare_and_swap(&self, expected: &T, new: T) -> Result<(), T> {
self.transact(|state| {
if let Some(val) = state {
if val == expected {
*state = Some(new);
return Ok(())
}
}
Err(new)
})
}
}
impl<T: Clone + Eq> PingPongCell<T> {
pub fn compare_swap_clone(
&self,
expected: &T,
new: T
) -> Result<(), (T, Option<T>)> {
self.transact(|state| {
if let Some(val) = state {
if val == expected {
*state = Some(new);
Ok(())
} else {
Err((new, Some(val.clone())))
}
} else {
Err((new, None))
}
})
}
}
#[cfg(test)]
mod tests {
}