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
use std::thread::sleep;
use std::time::Duration;
use std::time::Instant;
pub fn wait_until<F, T, E>(deadline: Instant, interval: Duration, mut op: F) -> Result<Option<T>, E>
where
F: FnMut() -> Result<Option<T>, E>,
{
'l: loop {
match op() {
Ok(None) => sleep(interval),
v @ Ok(Some(_)) => break 'l v,
e @ Err(_) => break 'l e,
}
if Instant::now() >= deadline {
break 'l Ok(None);
}
}
}
pub fn wait_for<F, T, E>(timeout: Duration, interval: Duration, op: F) -> Result<Option<T>, E>
where
F: FnMut() -> Result<Option<T>, E>,
{
wait_until(Instant::now() + timeout, interval, op)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn wait_for_success() {
let result = wait_for::<_, _, ()>(Duration::from_secs(5), Duration::from_nanos(1), || {
static mut COUNTER: u64 = 1;
if unsafe { COUNTER } == 5 {
Ok(Some(5))
} else {
unsafe { COUNTER += 1 };
Ok(None)
}
});
assert_eq!(result, Ok(Some(5)))
}
#[test]
fn wait_for_error() {
let result = wait_for::<_, (), _>(Duration::from_secs(5), Duration::from_nanos(1), || {
static mut COUNTER: u64 = 1;
if unsafe { COUNTER } == 5 {
Err("expected")
} else {
unsafe { COUNTER += 1 };
Ok(None)
}
});
assert_eq!(result, Err("expected"))
}
#[test]
fn wait_for_timeout() {
let result = wait_for::<_, (), ()>(Duration::from_millis(10), Duration::from_nanos(1), || {
Ok(None)
});
assert_eq!(result, Ok(None))
}
}