agnostic_lite/time/
sleep.rs

1use core::{
2  future::Future,
3  pin::Pin,
4  time::Duration,
5};
6
7/// The sleep abstraction for a runtime.
8pub trait AsyncSleep: Future<Output = Self::Instant> + Send {
9  /// The instant type
10  type Instant: super::Instant;
11
12  /// Resets the Sleep instance to a new deadline.
13  ///
14  /// The behavior of this function may different in different runtime implementations.
15  fn reset(self: Pin<&mut Self>, deadline: Self::Instant);
16}
17
18/// Extension trait for [`AsyncSleep`].
19pub trait AsyncSleepExt: AsyncSleep {
20  /// Creates a timer that emits an event once after the given duration of time.
21  fn sleep(after: Duration) -> Self
22  where
23    Self: Sized;
24
25  /// Creates a timer that emits an event once at the given time instant.
26  fn sleep_until(deadline: Self::Instant) -> Self
27  where
28    Self: Sized;
29}
30
31impl<T: Send + AsyncLocalSleep> AsyncSleep for T
32where
33  T: Send + AsyncLocalSleep,
34  T::Instant: Send,
35{
36  type Instant = T::Instant;
37
38  fn reset(self: Pin<&mut Self>, deadline: Self::Instant) {
39    AsyncLocalSleep::reset(self, deadline)
40  }
41}
42
43impl<T> AsyncSleepExt for T
44where
45  T: Send + AsyncLocalSleepExt,
46  T::Instant: Send,
47{
48  fn sleep(after: Duration) -> Self
49  where
50    Self: Sized,
51  {
52    AsyncLocalSleepExt::sleep_local(after)
53  }
54
55  fn sleep_until(deadline: Self::Instant) -> Self
56  where
57    Self: Sized,
58  {
59    AsyncLocalSleepExt::sleep_local_until(deadline)
60  }
61}
62
63/// Like [`AsyncSleep`], but does not requires `Send`.
64pub trait AsyncLocalSleep: Future<Output = Self::Instant> {
65  /// The instant type
66  type Instant: super::Instant;
67
68  /// Resets the Sleep instance to a new deadline.
69  ///
70  /// The behavior of this function may different in different runtime implementations.
71  fn reset(self: Pin<&mut Self>, deadline: Self::Instant);
72}
73
74/// Extension trait for [`AsyncLocalSleep`].
75pub trait AsyncLocalSleepExt: AsyncLocalSleep {
76  /// Creates a timer that emits an event once after the given duration of time.
77  fn sleep_local(after: Duration) -> Self
78  where
79    Self: Sized;
80
81  /// Creates a timer that emits an event once at the given time instant.
82  fn sleep_local_until(deadline: Self::Instant) -> Self
83  where
84    Self: Sized;
85}