use super::Error;
use std::cell::RefCell;
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll, Waker};
pub trait Scheduler {
fn now(&self) -> f64;
fn monotonic_now(&self) -> f64;
fn schedule(&self, ms: f64, action: Box<dyn FnOnce()>) -> Box<dyn Timer>;
fn schedule_repeating(&self, ms: f64, action: Box<dyn FnMut()>) -> Box<dyn Timer>;
fn checkpoint(&self, action: Box<dyn FnOnce()>);
}
pub trait Timer {
fn cancel(&self);
}
pub fn timer_delay(ms: f64) -> f64 {
if (0.0..=2_147_483_647.0).contains(&ms) {
ms
} else {
0.0
}
}
type Observer<T> = Box<dyn FnOnce(&Result<T, Error>)>;
struct DeferredState<T> {
result: Option<Result<T, Error>>,
observers: Vec<Observer<T>>,
wakers: Vec<Waker>,
}
pub struct Deferred<T>(Rc<RefCell<DeferredState<T>>>);
impl<T> Clone for Deferred<T> {
fn clone(&self) -> Self {
Deferred(self.0.clone())
}
}
impl<T: Clone + 'static> Default for Deferred<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Clone + 'static> Deferred<T> {
pub fn new() -> Self {
Deferred(Rc::new(RefCell::new(DeferredState {
result: None,
observers: Vec::new(),
wakers: Vec::new(),
})))
}
pub fn result(&self) -> Option<Result<T, Error>> {
self.0.borrow().result.clone()
}
pub fn is_settled(&self) -> bool {
self.0.borrow().result.is_some()
}
pub(crate) fn resolve(&self, value: T) {
self.settle(Ok(value));
}
pub(crate) fn reject(&self, error: impl Into<Error>) {
self.settle(Err(error.into()));
}
pub(crate) fn settle(&self, result: Result<T, Error>) {
let (observers, wakers) = {
let mut s = self.0.borrow_mut();
if s.result.is_some() {
return;
}
s.result = Some(result.clone());
(
std::mem::take(&mut s.observers),
std::mem::take(&mut s.wakers),
)
};
for o in observers {
o(&result);
}
for w in wakers {
w.wake();
}
}
pub fn on_settle(&self, observer: impl FnOnce(&Result<T, Error>) + 'static) {
let result = self.0.borrow().result.clone();
match result {
Some(r) => observer(&r),
None => self.0.borrow_mut().observers.push(Box::new(observer)),
}
}
}
impl<T: Clone + 'static> Future for Deferred<T> {
type Output = Result<T, Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut s = self.0.borrow_mut();
match &s.result {
Some(r) => Poll::Ready(r.clone()),
None => {
s.wakers.push(cx.waker().clone());
Poll::Pending
}
}
}
}