rart_rs/futures/
time.rs

1use core::future::Future;
2use core::pin::Pin;
3use core::task::{Context, Poll, Waker};
4use core::time::Duration;
5use crate::common::arc::Arc;
6use crate::common::ArcMutex;
7use crate::common::blocking_mutex::BlockingMutex;
8use crate::common::timer::timer_new_delay;
9use crate::Expect;
10
11pub struct DelayFuture {
12    state: ArcMutex<DelayState>,
13    timeout: Duration,
14}
15
16impl Future for DelayFuture {
17    type Output = ();
18
19    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
20        if let Ok(mut state) = self.state.lock() {
21            match &mut *state {
22                DelayState::None => {
23                    *state = DelayState::Waiting(cx.waker().clone());
24                    timer_new_delay(self.state.clone(), self.timeout.as_millis() as u32).rart_expect("Cannot create a new delay");
25                    Poll::Pending
26                }
27                DelayState::Waiting(_) => {
28                    panic!("The \"Waiting\" state must be unreachable at the delay future poll")
29                }
30                DelayState::Completed => {
31                    Poll::Ready(())
32                }
33            }
34        } else {
35            panic!("Cannot get delay future mutex");
36        }
37    }
38}
39
40pub enum DelayState {
41    None,
42    Waiting(Waker),
43    Completed,
44}
45
46pub fn delay(duration: Duration) -> DelayFuture {
47    DelayFuture {
48        state: Arc::new(BlockingMutex::new(DelayState::None)),
49        timeout: duration,
50    }
51}