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