Skip to main content

dope_core/driver/schedule/clock/
mod.rs

1//! Driver-branded monotonic time sampled once per runtime turn.
2
3use std::{borrow, cell, cmp, marker, mem, time};
4
5use crate::driver;
6
7mod range;
8pub mod timer;
9#[doc(hidden)]
10pub mod watchdog;
11
12pub use range::Range;
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
15#[repr(C)]
16struct Point<'d> {
17    at: time::Instant,
18    driver: driver::Invariant<'d>,
19}
20/// Read-only access to the monotonic sample installed for one driver turn.
21#[derive(Clone, Copy)]
22#[repr(transparent)]
23pub struct Clock<'turn, 'd> {
24    source: &'turn cell::Cell<time::Instant>,
25    driver: driver::Invariant<'d>,
26}
27/// Generative monotonic domain for code running outside a runtime driver.
28///
29#[derive(Clone, Copy)]
30pub struct Scope<'d> {
31    proof: driver::Invariant<'d>,
32}
33/// Owned monotonic origin that accepts no foreign time-domain input.
34#[derive(Clone, Copy, Debug, Eq, PartialEq)]
35#[repr(transparent)]
36pub struct Origin(time::Instant);
37
38/// A persistent monotonic observation belonging to exactly one driver scope.
39///
40/// Driver brands are invariant, so observations from independently generated
41/// scopes cannot be compared or used to derive one another's deadlines:
42///
43#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
44#[repr(transparent)]
45pub struct Moment<'d>(Point<'d>);
46/// A persistent absolute monotonic deadline belonging to one driver scope.
47///
48#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
49#[repr(transparent)]
50pub struct Deadline<'d>(Point<'d>);
51/// A deadline and its exact elapsed cause, without a timer loan.
52#[derive(Clone, Copy, Debug)]
53pub struct Check<'d, E: Copy> {
54    deadline: Deadline<'d>,
55    error: E,
56}
57
58impl<'d, E: Copy> Check<'d, E> {
59    pub const fn new(deadline: Deadline<'d>, error: E) -> Self {
60        Self { deadline, error }
61    }
62
63    /// Checks fresh monotonic time without changing the driver's turn sample.
64    pub fn check(self) -> Result<(), E> {
65        if self.deadline.into_raw() <= time::Instant::now() {
66            Err(self.error)
67        } else {
68            Ok(())
69        }
70    }
71}
72
73/// One raw runtime-boundary sample waiting to be installed into a turn.
74#[derive(Clone, Copy)]
75#[repr(transparent)]
76pub struct Sample(time::Instant);
77
78impl Sample {
79    /// Wraps the raw monotonic sample for installation into a runtime turn.
80    pub const fn new(now: time::Instant) -> Self {
81        Self(now)
82    }
83
84    pub(in crate::driver) const fn into_raw(self) -> time::Instant {
85        self.0
86    }
87}
88
89impl Scope<'_> {
90    /// Runs with a fresh time domain whose observations cannot escape.
91    pub fn run<R>(run: impl for<'d> FnOnce(Scope<'d>) -> R) -> R {
92        run(Scope::new())
93    }
94}
95
96impl<'d> Scope<'d> {
97    const fn new() -> Self {
98        Self {
99            proof: driver::Invariant(marker::PhantomData),
100        }
101    }
102
103    pub fn now(self) -> Moment<'d> {
104        Moment::new(time::Instant::now(), self.proof)
105    }
106}
107
108impl Origin {
109    pub fn elapsed(self) -> time::Duration {
110        self.0.elapsed()
111    }
112}
113
114impl<'d> Point<'d> {
115    const fn new(at: time::Instant, driver: driver::Invariant<'d>) -> Self {
116        Self { at, driver }
117    }
118
119    const fn at(self, at: time::Instant) -> Self {
120        Self::new(at, self.driver)
121    }
122
123    const fn get(self) -> time::Instant {
124        self.at
125    }
126
127    fn try_add<D: Copy + borrow::Borrow<time::Duration>>(
128        self,
129        duration: D,
130    ) -> Result<Self, Range<D>> {
131        match self.at.checked_add(*duration.borrow()) {
132            Some(at) => Ok(self.at(at)),
133            None => Err(Range::new(Origin(self.at), duration)),
134        }
135    }
136
137    fn clamp_add<D: Copy + borrow::Borrow<time::Duration>>(self, duration: D) -> Self {
138        match self.try_add(duration) {
139            Ok(point) => point,
140            Err(range) => self.at(range.furthest()),
141        }
142    }
143}
144
145impl<'turn, 'd> Clock<'turn, 'd> {
146    pub(in crate::driver) const fn new(
147        source: &'turn cell::Cell<time::Instant>,
148        driver: driver::Invariant<'d>,
149    ) -> Self {
150        Self { source, driver }
151    }
152
153    /// Returns the one sample installed at the beginning of this turn.
154    pub fn now(self) -> Moment<'d> {
155        Moment::new(self.source.get(), self.driver)
156    }
157
158    /// Adopts an external absolute instant as this driver's deadline.
159    pub fn deadline_at(self, at: time::Instant) -> Deadline<'d> {
160        Deadline(Point::new(at, self.driver))
161    }
162}
163
164impl<'d> Moment<'d> {
165    const fn new(at: time::Instant, driver: driver::Invariant<'d>) -> Self {
166        Self(Point::new(at, driver))
167    }
168
169    /// Retains this observation without its driver brand.
170    pub const fn retain(self) -> Origin {
171        Origin(self.0.get())
172    }
173
174    pub fn try_add<D: Copy + borrow::Borrow<time::Duration>>(
175        self,
176        duration: D,
177    ) -> Result<Deadline<'d>, Range<D>> {
178        Ok(Deadline(self.0.try_add(duration)?))
179    }
180
181    /// Adds a duration, clamping only at the platform's furthest instant.
182    pub fn clamp_add<D: Copy + borrow::Borrow<time::Duration>>(self, duration: D) -> Deadline<'d> {
183        Deadline(self.0.clamp_add(duration))
184    }
185
186    pub fn moment_at(self, at: time::Instant) -> Self {
187        Self(self.0.at(at))
188    }
189
190    pub fn deadline_at(self, at: time::Instant) -> Deadline<'d> {
191        Deadline(self.0.at(at))
192    }
193
194    pub fn since(self, earlier: Self) -> time::Duration {
195        self.0.get().duration_since(earlier.0.get())
196    }
197
198    pub fn clamp_since(self, earlier: Self) -> time::Duration {
199        self.0.get().saturating_duration_since(earlier.0.get())
200    }
201
202    pub fn try_since(self, earlier: Self) -> Option<time::Duration> {
203        self.0.get().checked_duration_since(earlier.0.get())
204    }
205
206    pub fn past_due(self, earlier: Deadline<'d>) -> time::Duration {
207        self.0.get().duration_since(earlier.0.get())
208    }
209
210    /// Exposes the underlying monotonic sample at a runtime boundary.
211    pub const fn into_raw(self) -> time::Instant {
212        self.0.get()
213    }
214}
215
216impl<'d> Deadline<'d> {
217    pub fn try_add<D: Copy + borrow::Borrow<time::Duration>>(
218        self,
219        duration: D,
220    ) -> Result<Self, Range<D>> {
221        Ok(Self(self.0.try_add(duration)?))
222    }
223
224    /// Adds a duration, clamping only at the platform's furthest instant.
225    pub fn clamp_add<D: Copy + borrow::Borrow<time::Duration>>(self, duration: D) -> Self {
226        Self(self.0.clamp_add(duration))
227    }
228
229    pub fn checked_sub(self, duration: time::Duration) -> Option<Self> {
230        self.0
231            .get()
232            .checked_sub(duration)
233            .map(|at| Self(self.0.at(at)))
234    }
235
236    pub fn is_due(self, now: Moment<'d>) -> bool {
237        self.0.get() <= now.0.get()
238    }
239
240    pub fn try_left(self, now: Moment<'d>) -> Option<time::Duration> {
241        self.0.get().checked_duration_since(now.0.get())
242    }
243
244    /// Exposes the underlying monotonic deadline at a runtime boundary.
245    pub const fn into_raw(self) -> time::Instant {
246        self.0.get()
247    }
248}
249
250impl From<Moment<'_>> for time::Instant {
251    fn from(moment: Moment<'_>) -> Self {
252        moment.0.at
253    }
254}
255
256impl<'d> From<Moment<'d>> for Deadline<'d> {
257    fn from(moment: Moment<'d>) -> Self {
258        Self(moment.0)
259    }
260}
261
262impl<'d> PartialEq<Moment<'d>> for Deadline<'d> {
263    fn eq(&self, other: &Moment<'d>) -> bool {
264        self.0.get() == other.0.get()
265    }
266}
267
268impl<'d> PartialOrd<Moment<'d>> for Deadline<'d> {
269    fn partial_cmp(&self, other: &Moment<'d>) -> Option<cmp::Ordering> {
270        self.0.get().partial_cmp(&other.0.get())
271    }
272}
273
274impl<'d> PartialEq<Deadline<'d>> for Moment<'d> {
275    fn eq(&self, other: &Deadline<'d>) -> bool {
276        self.0.get() == other.0.get()
277    }
278}
279
280impl<'d> PartialOrd<Deadline<'d>> for Moment<'d> {
281    fn partial_cmp(&self, other: &Deadline<'d>) -> Option<cmp::Ordering> {
282        self.0.get().partial_cmp(&other.0.get())
283    }
284}
285
286const _: () = {
287    assert!(mem::size_of::<Scope<'static>>() == 0);
288    assert!(mem::size_of::<Origin>() == mem::size_of::<time::Instant>());
289    assert!(mem::align_of::<Origin>() == mem::align_of::<time::Instant>());
290    assert!(!mem::needs_drop::<Origin>());
291    assert!(mem::size_of::<Clock<'static, 'static>>() == mem::size_of::<usize>());
292    assert!(mem::align_of::<Clock<'static, 'static>>() == mem::align_of::<usize>());
293    assert!(mem::size_of::<Moment<'static>>() == mem::size_of::<time::Instant>());
294    assert!(mem::align_of::<Moment<'static>>() == mem::align_of::<time::Instant>());
295    assert!(mem::size_of::<Deadline<'static>>() == mem::size_of::<time::Instant>());
296    assert!(mem::align_of::<Deadline<'static>>() == mem::align_of::<time::Instant>());
297    assert!(!mem::needs_drop::<Moment<'static>>());
298    assert!(!mem::needs_drop::<Deadline<'static>>());
299    assert!(mem::size_of::<Sample>() == mem::size_of::<time::Instant>());
300};