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
use std::sync::atomic::{AtomicBool,Ordering};
use std::sync::{Arc};
#[derive(Clone)]
pub struct Latch {
latch: Arc<AtomicBool>,
}
impl Latch {
pub fn new () -> Latch {
Latch { latch: Arc::new(AtomicBool::new(false)) }
}
pub fn close (&self) -> bool {
if !self.latch.compare_and_swap(false,true,Ordering::Release) {true}
else {false}
}
pub fn latched (&self) -> bool {
self.latch.load(Ordering::Acquire)
}
pub fn open (&self) -> bool {
if self.latched() {
self.latch.compare_and_swap(true,false,Ordering::Release)
}
else { true }
}
}
#[cfg(test)]
mod tests {
use Latch;
#[test]
fn test_latch() {
let l = Latch::new();
assert_eq!(l.latched(),false);
assert_eq!(l.close(),true);
assert_eq!(l.close(),false);
assert_eq!(l.latched(),true);
assert_eq!(l.open(),true);
assert_eq!(l.latched(),false);
}
}