use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use crate::{SimulationResult, sim::WeakSimWorld};
pub struct SleepFuture {
sim: WeakSimWorld,
task_id: u64,
completed: bool,
}
impl SleepFuture {
pub fn new(sim: WeakSimWorld, task_id: u64) -> Self {
Self {
sim,
task_id,
completed: false,
}
}
}
impl Future for SleepFuture {
type Output = SimulationResult<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.completed {
return Poll::Ready(Ok(()));
}
let sim = match self.sim.upgrade() {
Ok(sim) => sim,
Err(e) => return Poll::Ready(Err(e)),
};
match sim.is_task_awake(self.task_id) {
Ok(true) => {
self.completed = true;
Poll::Ready(Ok(()))
}
Ok(false) => {
match sim.register_task_waker(self.task_id, cx.waker().clone()) {
Ok(()) => Poll::Pending,
Err(e) => Poll::Ready(Err(e)),
}
}
Err(e) => Poll::Ready(Err(e)),
}
}
}