use crate::time::driver::{Handle, TimerEntry};
use crate::time::{error::Error, Duration, Instant};
use pin_project_lite::pin_project;
use std::future::Future;
use std::pin::Pin;
use std::task::{self, Poll};
pub fn sleep_until(deadline: Instant) -> Sleep {
Sleep::new_timeout(deadline)
}
pub fn sleep(duration: Duration) -> Sleep {
sleep_until(Instant::now() + duration)
}
pin_project! {
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Sleep {
deadline: Instant,
#[pin]
entry: TimerEntry,
}
}
impl Sleep {
pub(crate) fn new_timeout(deadline: Instant) -> Sleep {
let handle = Handle::current();
let entry = TimerEntry::new(&handle, deadline);
Sleep { deadline, entry }
}
pub fn deadline(&self) -> Instant {
self.deadline
}
pub fn is_elapsed(&self) -> bool {
self.entry.is_elapsed()
}
pub fn reset(self: Pin<&mut Self>, deadline: Instant) {
let me = self.project();
me.entry.reset(deadline);
*me.deadline = deadline;
}
fn poll_elapsed(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Result<(), Error>> {
let me = self.project();
let coop = ready!(crate::coop::poll_proceed(cx));
me.entry.poll_elapsed(cx).map(move |r| {
coop.made_progress();
r
})
}
}
impl Future for Sleep {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
match ready!(self.as_mut().poll_elapsed(cx)) {
Ok(()) => Poll::Ready(()),
Err(e) => panic!("timer error: {}", e),
}
}
}