round_based/state_machine/
runtime.rs

1use core::task::{ready, Poll};
2
3/// State machine runtime
4pub struct Runtime<M> {
5    shared_state: super::shared_state::SharedStateRef<M>,
6}
7
8impl<M> Runtime<M> {
9    pub(super) fn new(shared_state: super::shared_state::SharedStateRef<M>) -> Self {
10        Self { shared_state }
11    }
12}
13
14impl<M> crate::runtime::AsyncRuntime for Runtime<M> {
15    type YieldNowFuture = YieldNow<M>;
16
17    fn yield_now(&self) -> Self::YieldNowFuture {
18        YieldNow {
19            shared_state: self.shared_state.clone(),
20            yielded: false,
21        }
22    }
23}
24
25/// Future returned by [`runtime.yield_now()`](Runtime)
26pub struct YieldNow<M> {
27    shared_state: super::shared_state::SharedStateRef<M>,
28    yielded: bool,
29}
30
31impl<M> core::future::Future for YieldNow<M> {
32    type Output = ();
33
34    fn poll(
35        mut self: core::pin::Pin<&mut Self>,
36        _cx: &mut core::task::Context<'_>,
37    ) -> Poll<Self::Output> {
38        if !self.yielded {
39            let scheduler = ready!(self.shared_state.can_schedule());
40            scheduler.protocol_yields();
41            self.yielded = true;
42            Poll::Pending
43        } else {
44            Poll::Ready(())
45        }
46    }
47}