scheduler.rs

 1mod clock;
 2mod executor;
 3mod test_scheduler;
 4#[cfg(test)]
 5mod tests;
 6
 7pub use clock::*;
 8pub use executor::*;
 9pub use test_scheduler::*;
10
11use async_task::Runnable;
12use futures::{FutureExt as _, channel::oneshot, future::LocalBoxFuture};
13use std::{
14    future::Future,
15    pin::Pin,
16    sync::Arc,
17    task::{Context, Poll},
18    time::Duration,
19};
20
21pub trait Scheduler: Send + Sync {
22    fn block(
23        &self,
24        session_id: Option<SessionId>,
25        future: LocalBoxFuture<()>,
26        timeout: Option<Duration>,
27    );
28    fn schedule_foreground(&self, session_id: SessionId, runnable: Runnable);
29    fn schedule_background(&self, runnable: Runnable);
30    fn timer(&self, timeout: Duration) -> Timer;
31    fn clock(&self) -> Arc<dyn Clock>;
32    fn as_test(&self) -> &TestScheduler {
33        panic!("this is not a test scheduler")
34    }
35}
36
37#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
38pub struct SessionId(u16);
39
40impl SessionId {
41    pub const fn new(id: u16) -> Self {
42        SessionId(id)
43    }
44}
45
46pub struct Timer(oneshot::Receiver<()>);
47
48impl Timer {
49    pub const fn new(rx: oneshot::Receiver<()>) -> Self {
50        Timer(rx)
51    }
52}
53
54impl Future for Timer {
55    type Output = ();
56
57    fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
58        match self.0.poll_unpin(cx) {
59            Poll::Ready(_) => Poll::Ready(()),
60            Poll::Pending => Poll::Pending,
61        }
62    }
63}