dope_core/executor/task/time/
sleep.rs1use std::{mem, task, time};
2
3use crate::{
4 driver::schedule::clock::{self, timer},
5 executor::task::{Fiber, context},
6};
7
8pub const MAXIMUM_DURATION: time::Duration = time::Duration::new(i64::MAX as u64 / 2, 999_999_999);
9
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12#[repr(u8)]
13pub enum Error {
14 Duration { actual: time::Duration },
15 Capacity,
16}
17
18impl From<timer::Exhausted> for Error {
19 fn from(_: timer::Exhausted) -> Self {
20 Self::Capacity
21 }
22}
23
24#[must_use = "a fiber does nothing unless it is driven"]
25pub struct Sleep<'d, T = time::Duration> {
26 alarm: timer::Alarm<'d>,
27 start: T,
28}
29
30impl<'d> Sleep<'d> {
31 pub fn new(timer: timer::Timer<'d>, duration: time::Duration) -> Result<Self, Error> {
32 if duration > MAXIMUM_DURATION {
33 return Err(Error::Duration { actual: duration });
34 }
35 Ok(Self {
36 alarm: timer.try_alarm()?,
37 start: duration,
38 })
39 }
40
41 pub fn until(
42 timer: timer::Timer<'d>,
43 deadline: clock::Deadline<'d>,
44 ) -> Result<Sleep<'d, clock::Deadline<'d>>, Error> {
45 Ok(Sleep {
46 alarm: timer.try_alarm()?,
47 start: deadline,
48 })
49 }
50}
51
52impl<'d> Sleep<'d> {
53 pub fn poll_sleep(&mut self, context: &mut context::Context<'_, 'd>) -> task::Poll<()> {
55 let now = context.driver().driver_ref().clock().now();
56 self.alarm
57 .poll_after(&self.start, now, context.completion())
58 }
59}
60
61impl<'d> Sleep<'d, clock::Deadline<'d>> {
62 pub fn poll_sleep(&mut self, context: &mut context::Context<'_, 'd>) -> task::Poll<()> {
64 let now = context.driver().driver_ref().clock().now();
65 self.alarm
66 .poll_until(&self.start, now, context.completion())
67 }
68}
69
70impl<'d> Fiber<'d> for Sleep<'d> {
71 type Output = ();
72
73 fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> task::Poll<()> {
74 let (this, context) = call.into_parts();
75 this.get_mut().poll_sleep(context)
76 }
77}
78
79impl<'d> Fiber<'d> for Sleep<'d, clock::Deadline<'d>> {
80 type Output = ();
81
82 fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> task::Poll<()> {
83 let (this, context) = call.into_parts();
84 this.get_mut().poll_sleep(context)
85 }
86}
87
88const _: () = assert!(mem::size_of::<Sleep<'static>>() == 4 * mem::size_of::<usize>());
89const _: () = assert!(mem::size_of::<Error>() == 3 * mem::size_of::<usize>());
90const _: () =
91 assert!(mem::size_of::<Result<Sleep<'static>, Error>>() == 4 * mem::size_of::<usize>());
92const _: () = {
93 assert!(
94 mem::size_of::<Sleep<'static, clock::Deadline<'static>>>() == 4 * mem::size_of::<usize>()
95 );
96 assert!(
97 mem::size_of::<Result<Sleep<'static, clock::Deadline<'static>>, Error>>()
98 == 4 * mem::size_of::<usize>()
99 );
100};