futures_time/task/
sleep_until.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4
5use async_io::Timer;
6use pin_project_lite::pin_project;
7
8use crate::time::Instant;
9
10/// Sleeps until the specified instant.
11pub fn sleep_until(deadline: Instant) -> SleepUntil {
12    SleepUntil {
13        timer: Timer::at(deadline.into()),
14        completed: false,
15    }
16}
17
18pin_project! {
19    /// Sleeps until the specified instant.
20    #[must_use = "futures do nothing unless polled or .awaited"]
21    pub struct SleepUntil {
22        #[pin]
23        timer: Timer,
24        completed: bool,
25    }
26}
27
28impl Future for SleepUntil {
29    type Output = Instant;
30
31    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
32        assert!(!self.completed, "future polled after completing");
33        let this = self.project();
34        match this.timer.poll(cx) {
35            Poll::Ready(instant) => {
36                *this.completed = true;
37                Poll::Ready(instant.into())
38            }
39            Poll::Pending => Poll::Pending,
40        }
41    }
42}