use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use crate::executor;
pub struct SleepFuture {
registered: bool,
duration_ms: u64,
}
impl SleepFuture {
pub(crate) fn new(duration: Duration) -> Self {
Self {
registered: false,
duration_ms: duration.as_millis() as u64,
}
}
}
impl Future for SleepFuture {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if !self.registered {
self.registered = true;
let task_id = executor::with_current_polling_task(|id| {
id.expect("timer::sleep must be called from within an auralis task")
});
let now = executor::current_time_ms();
let deadline = now.saturating_add(self.duration_ms);
executor::Executor::schedule_timer(
&executor::current_executor_instance(),
deadline,
task_id,
);
cx.waker().wake_by_ref();
Poll::Pending
} else {
Poll::Ready(())
}
}
}
pub async fn sleep(duration: Duration) {
SleepFuture::new(duration).await
}