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
use fluvio_wasm_timer::Delay;
pub use fluvio_wasm_timer::Instant;
use futures::{Future, FutureExt};
use std::{
pin::Pin,
task::{Context, Poll},
time::Duration,
};
#[must_use]
pub fn sleep(duration: Duration) -> Sleep {
sleep_until(Instant::now() + duration)
}
#[must_use]
pub fn sleep_until(deadline: Instant) -> Sleep {
Sleep {
deadline,
delay: Delay::new_at(deadline),
}
}
pub struct Sleep {
deadline: Instant,
delay: Delay,
}
impl Sleep {
pub fn deadline(&self) -> Instant {
self.deadline
}
pub fn is_elapsed(&self) -> bool {
Instant::now() > self.deadline
}
pub fn reset(&mut self, deadline: Instant) {
self.delay.reset_at(deadline);
}
}
impl Future for Sleep {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.delay.poll_unpin(cx) {
Poll::Ready(_) => Poll::Ready(()),
Poll::Pending => Poll::Pending,
}
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use wasm_bindgen_test::wasm_bindgen_test;
use crate::{sleep, sleep::Instant};
#[wasm_bindgen_test]
async fn test_sleep() {
let current = Instant::now();
sleep(Duration::from_secs(1)).await;
let difference = Instant::now() - current;
assert!(difference.as_secs_f64() > 1.0)
}
}