use futures::{Future, FutureExt};
use std::{
pin::Pin,
task::{Context, Poll},
time::Duration,
};
use zduny_wasm_timer::Delay;
pub use zduny_wasm_timer::Instant;
#[must_use]
pub fn sleep(duration: Duration) -> Sleep {
sleep_until(Instant::now() + duration)
}
#[must_use]
pub fn sleep_until(deadline: Instant) -> Sleep {
Sleep {
deadline,
delay: Delay::new_at(deadline),
}
}
#[derive(Debug)]
pub struct Sleep {
deadline: Instant,
delay: Delay,
}
impl Sleep {
pub fn deadline(&self) -> Instant {
self.deadline
}
pub fn is_elapsed(&self) -> bool {
Instant::now() > self.deadline
}
pub fn reset(&mut self, deadline: Instant) {
self.delay.reset_at(deadline);
}
}
impl Future for Sleep {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.delay.poll_unpin(cx) {
Poll::Ready(_) => Poll::Ready(()),
Poll::Pending => Poll::Pending,
}
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use wasm_bindgen_test::wasm_bindgen_test;
use crate::{sleep, sleep::Instant};
#[wasm_bindgen_test]
async fn test_sleep() {
let current = Instant::now();
sleep(Duration::from_secs(1)).await;
let difference = Instant::now() - current;
assert!(difference.as_secs_f64() >= 1.0)
}
}