zero_client/client/
scheduler.rs1use super::Error;
4use std::cell::RefCell;
5use std::future::Future;
6use std::pin::Pin;
7use std::rc::Rc;
8use std::task::{Context, Poll, Waker};
9
10pub trait Scheduler {
19 fn now(&self) -> f64;
21 fn monotonic_now(&self) -> f64;
23 fn schedule(&self, ms: f64, action: Box<dyn FnOnce()>) -> Box<dyn Timer>;
25 fn schedule_repeating(&self, ms: f64, action: Box<dyn FnMut()>) -> Box<dyn Timer>;
27 fn checkpoint(&self, action: Box<dyn FnOnce()>);
31}
32
33pub trait Timer {
35 fn cancel(&self);
37}
38
39pub fn timer_delay(ms: f64) -> f64 {
43 if (0.0..=2_147_483_647.0).contains(&ms) {
44 ms
45 } else {
46 0.0
47 }
48}
49
50type Observer<T> = Box<dyn FnOnce(&Result<T, Error>)>;
51
52struct DeferredState<T> {
53 result: Option<Result<T, Error>>,
54 observers: Vec<Observer<T>>,
55 wakers: Vec<Waker>,
56}
57
58pub struct Deferred<T>(Rc<RefCell<DeferredState<T>>>);
62
63impl<T> Clone for Deferred<T> {
64 fn clone(&self) -> Self {
65 Deferred(self.0.clone())
66 }
67}
68
69impl<T: Clone + 'static> Default for Deferred<T> {
70 fn default() -> Self {
71 Self::new()
72 }
73}
74
75impl<T: Clone + 'static> Deferred<T> {
76 pub fn new() -> Self {
78 Deferred(Rc::new(RefCell::new(DeferredState {
79 result: None,
80 observers: Vec::new(),
81 wakers: Vec::new(),
82 })))
83 }
84
85 pub fn result(&self) -> Option<Result<T, Error>> {
87 self.0.borrow().result.clone()
88 }
89
90 pub fn is_settled(&self) -> bool {
92 self.0.borrow().result.is_some()
93 }
94
95 pub(crate) fn resolve(&self, value: T) {
96 self.settle(Ok(value));
97 }
98
99 pub(crate) fn reject(&self, error: impl Into<Error>) {
100 self.settle(Err(error.into()));
101 }
102
103 pub(crate) fn settle(&self, result: Result<T, Error>) {
104 let (observers, wakers) = {
105 let mut s = self.0.borrow_mut();
106 if s.result.is_some() {
107 return;
108 }
109 s.result = Some(result.clone());
110 (
111 std::mem::take(&mut s.observers),
112 std::mem::take(&mut s.wakers),
113 )
114 };
115 for o in observers {
116 o(&result);
117 }
118 for w in wakers {
119 w.wake();
120 }
121 }
122
123 pub fn on_settle(&self, observer: impl FnOnce(&Result<T, Error>) + 'static) {
125 let result = self.0.borrow().result.clone();
126 match result {
127 Some(r) => observer(&r),
128 None => self.0.borrow_mut().observers.push(Box::new(observer)),
129 }
130 }
131}
132
133impl<T: Clone + 'static> Future for Deferred<T> {
134 type Output = Result<T, Error>;
135
136 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
137 let mut s = self.0.borrow_mut();
138 match &s.result {
139 Some(r) => Poll::Ready(r.clone()),
140 None => {
141 s.wakers.push(cx.waker().clone());
142 Poll::Pending
143 }
144 }
145 }
146}