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
use std::thread::sleep;
use std::time::{Instant, Duration};
#[derive(Clone, Debug)]
pub struct Delay {
time: Option<Instant>,
delay: Duration,
}
impl Delay {
pub fn new(delay: Duration) -> Self {
Delay {
time: Some(Instant::now()),
delay: delay,
}
}
pub fn remaining(&self) -> Duration {
self.time.as_ref().and_then(|time| self.delay.checked_sub(time.elapsed())).unwrap_or(Duration::default())
}
pub fn sleep(&mut self) {
if let Some(delay) = self.time.take().and_then(|time| self.delay.checked_sub(time.elapsed())) {
sleep(delay);
}
}
}
impl Default for Delay {
fn default() -> Self {
Delay {
time: None,
delay: Default::default(),
}
}
}