vexide_async/
time.rs

1//! Utilities for tracking time.
2//!
3//! This module provides a types for executing code after a set period of time.
4//!
5//! * [`Sleep`] is a future that does no work and completes at a specific [`Instant`]
6//!   in time.
7//!
8//! * [`sleep`] and [`sleep_until`] provide ways to yield control away from a future
9//!   for or until a specific instant in time.
10
11use core::{
12    future::Future,
13    pin::Pin,
14    task::{Context, Poll},
15    time::Duration,
16};
17
18use vexide_core::time::Instant;
19
20use crate::executor::EXECUTOR;
21
22/// A future that will complete after a certain instant is reached in time.
23#[derive(Debug)]
24#[must_use = "futures do nothing unless you `.await` or poll them"]
25pub struct Sleep(Instant);
26
27impl Future for Sleep {
28    type Output = ();
29
30    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> core::task::Poll<Self::Output> {
31        if Instant::now() > self.0 {
32            Poll::Ready(())
33        } else {
34            EXECUTOR.with_reactor(|reactor| reactor.sleepers.push(cx.waker().clone(), self.0));
35
36            Poll::Pending
37        }
38    }
39}
40
41/// Returns a future that will complete after the given duration.
42pub fn sleep(duration: Duration) -> Sleep {
43    Sleep(Instant::now() + duration)
44}
45
46/// Returns a future that waits until a deadline is reached.
47pub const fn sleep_until(deadline: Instant) -> Sleep {
48    Sleep(deadline)
49}