awak/time/
delay.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4use std::time::{Duration, Instant};
5
6use crate::io::Timer;
7
8pub struct Delay {
9    timer: Timer,
10}
11
12pub fn delay_until(deadline: Instant) -> Delay {
13    Delay {
14        timer: Timer::new(deadline),
15    }
16}
17
18pub fn delay_for(duration: Duration) -> Delay {
19    delay_until(Instant::now() + duration)
20}
21
22impl Delay {
23    pub fn deadline(&self) -> Instant {
24        self.timer.deadline()
25    }
26
27    pub fn is_elapsed(&self) -> bool {
28        self.timer.is_elapsed()
29    }
30
31    pub fn reset(&mut self, deadline: Instant) {
32        self.timer.reset(deadline);
33    }
34}
35
36impl Future for Delay {
37    type Output = ();
38
39    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
40        match self.timer.poll_timeout(cx) {
41            Poll::Ready(_) => Poll::Ready(()),
42            Poll::Pending => Poll::Pending,
43        }
44    }
45}