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
pub trait Job: Send + 'static {
fn run(&mut self) -> Option<Box<Job>>;
}
pub fn run_to_end<J>(mut job: J) where J: Job {
if let Some(mut job) = job.run() {
loop {
match job.run() {
Some(new_job) => job = new_job,
None => break,
};
}
}
}
#[derive(Debug)]
pub struct OneTime<F> where F: FnOnce() + Send + 'static {
f: Option<F>,
}
impl<F> OneTime<F> where F: FnOnce() + Send + 'static {
pub fn new(f: F) -> Self {
Self {
f: Some(f),
}
}
}
impl<F> Job for OneTime<F> where F: FnOnce() + Send + 'static {
fn run(&mut self) -> Option<Box<Job>> {
self.f.take().expect("OneTime job must be run at most once")();
None
}
}
#[test]
fn test_one_time() {
use std::sync::{
Arc,
atomic::{self, ATOMIC_BOOL_INIT},
};
const ORDERING: atomic::Ordering = atomic::Ordering::Relaxed;
let data = Arc::new(ATOMIC_BOOL_INIT);
assert!(data.load(ORDERING) == false);
run_to_end({
let data = data.clone();
OneTime::new(move || data.store(true, ORDERING))
});
assert!(data.load(ORDERING));
}