Skip to main content

dope_core/executor/drive/
clock.rs

1use std::{convert::Infallible, time};
2
3use crate::{
4    driver::schedule::clock,
5    executor::drive::{self, regress::Regression},
6};
7
8pub(crate) struct Elapsed;
9
10#[derive(Clone, Copy, Eq, PartialEq, Debug)]
11pub struct Range {
12    origin: time::Instant,
13    duration: time::Duration,
14}
15
16impl Range {
17    pub fn try_add(origin: time::Instant, duration: time::Duration) -> Result<time::Instant, Self> {
18        match origin.checked_add(duration) {
19            Some(deadline) => Ok(deadline),
20            None => Err(Self { origin, duration }),
21        }
22    }
23
24    pub const fn origin(self) -> time::Instant {
25        self.origin
26    }
27
28    pub const fn duration(self) -> time::Duration {
29        self.duration
30    }
31}
32
33pub trait Input<'d> {
34    type Source: Time;
35    type Error: Into<drive::Error>;
36
37    fn admit(self, current: clock::Clock<'_, 'd>) -> Result<Self::Source, Self::Error>;
38}
39
40impl Input<'_> for () {
41    type Source = Wall;
42    type Error = Infallible;
43
44    fn admit(self, _current: clock::Clock<'_, '_>) -> Result<Wall, Self::Error> {
45        Ok(Wall)
46    }
47}
48
49impl Input<'_> for time::Duration {
50    type Source = Bound<End>;
51    type Error = Range;
52
53    fn admit(self, _current: clock::Clock<'_, '_>) -> Result<Self::Source, Range> {
54        Bound::until(Wall, self)
55    }
56}
57
58impl<'d> Input<'d> for clock::Deadline<'d> {
59    type Source = Self;
60    type Error = Regression;
61
62    fn admit(self, current: clock::Clock<'_, 'd>) -> Result<Self, Self::Error> {
63        check(self.into_raw(), current)?;
64        Ok(self)
65    }
66}
67
68impl<'d> Input<'d> for (clock::Deadline<'d>, time::Duration) {
69    type Source = Bound<End, clock::Deadline<'d>>;
70    type Error = drive::Error;
71
72    fn admit(self, current: clock::Clock<'_, 'd>) -> Result<Self::Source, drive::Error> {
73        let source = self.0.admit(current).map_err(drive::Error::from)?;
74        Bound::until(source, self.1).map_err(drive::Error::from)
75    }
76}
77
78impl Input<'_> for Bound<Span> {
79    type Source = Self;
80    type Error = Infallible;
81
82    fn admit(self, _current: clock::Clock<'_, '_>) -> Result<Self, Self::Error> {
83        Ok(self)
84    }
85}
86
87pub(crate) fn sample<'d>(
88    current: clock::Clock<'_, 'd>,
89    start: Option<clock::Deadline<'d>>,
90) -> Result<clock::Sample, drive::Error> {
91    let now = start.map_or_else(time::Instant::now, clock::Deadline::into_raw);
92    check(now, current)?;
93    Ok(clock::Sample::new(now))
94}
95
96pub(crate) fn check(now: time::Instant, current: clock::Clock<'_, '_>) -> Result<(), Regression> {
97    let current = current.now().into_raw();
98    if now < current {
99        Err(Regression::new(now, current))
100    } else {
101        Ok(())
102    }
103}
104
105pub trait Time: Copy {
106    const FIXED: bool = false;
107
108    fn sample_at(self, wall: time::Instant) -> clock::Sample {
109        clock::Sample::new(wall)
110    }
111
112    fn start(self) -> clock::Sample {
113        self.sample_at(time::Instant::now())
114    }
115
116    fn tick(self) -> Result<clock::Sample, drive::Error> {
117        Ok(self.start())
118    }
119
120    fn quiesce(self) -> Result<clock::Sample, drive::Error> {
121        Ok(self.start())
122    }
123
124    fn timeout(self, deadline: clock::Deadline<'_>) -> time::Duration {
125        deadline
126            .into_raw()
127            .saturating_duration_since(time::Instant::now())
128    }
129
130    fn limit(self, timeout: Option<time::Duration>) -> Option<time::Duration>;
131}
132
133#[derive(Clone, Copy)]
134pub struct Wall;
135
136impl Time for Wall {
137    fn limit(self, timeout: Option<time::Duration>) -> Option<time::Duration> {
138        timeout
139    }
140}
141
142pub(crate) fn wall() -> Wall {
143    Wall
144}
145
146impl Time for clock::Deadline<'_> {
147    const FIXED: bool = true;
148
149    fn sample_at(self, _wall: time::Instant) -> clock::Sample {
150        clock::Sample::new(self.into_raw())
151    }
152
153    fn start(self) -> clock::Sample {
154        clock::Sample::new(self.into_raw())
155    }
156
157    fn timeout(self, deadline: clock::Deadline<'_>) -> time::Duration {
158        deadline
159            .into_raw()
160            .saturating_duration_since(self.into_raw())
161    }
162
163    fn limit(self, timeout: Option<time::Duration>) -> Option<time::Duration> {
164        timeout.filter(time::Duration::is_zero)
165    }
166}
167
168#[derive(Clone, Copy)]
169pub struct Bound<L, S = Wall> {
170    source: S,
171    limit: L,
172}
173
174pub(crate) trait Limit: Copy {
175    fn left(self, wall: time::Instant) -> time::Duration;
176}
177
178#[derive(Clone, Copy)]
179pub struct Span {
180    started: time::Instant,
181    timeout: time::Duration,
182}
183
184impl Limit for Span {
185    fn left(self, wall: time::Instant) -> time::Duration {
186        self.timeout
187            .saturating_sub(wall.saturating_duration_since(self.started))
188    }
189}
190
191#[derive(Clone, Copy)]
192pub struct End(time::Instant);
193
194impl Limit for End {
195    fn left(self, wall: time::Instant) -> time::Duration {
196        self.0.saturating_duration_since(wall)
197    }
198}
199
200impl<L, S: Time> Bound<L, S> {
201    pub(crate) fn elapsed(self) -> Result<clock::Sample, Elapsed>
202    where
203        L: Limit,
204    {
205        let now = time::Instant::now();
206        if self.limit.left(now).is_zero() {
207            Err(Elapsed)
208        } else {
209            Ok(self.source.sample_at(now))
210        }
211    }
212}
213
214impl From<time::Duration> for Bound<Span> {
215    fn from(timeout: time::Duration) -> Self {
216        Self {
217            source: Wall,
218            limit: Span {
219                started: time::Instant::now(),
220                timeout,
221            },
222        }
223    }
224}
225
226impl<'d> From<(clock::Clock<'_, 'd>, time::Duration)> for Bound<Span, clock::Deadline<'d>> {
227    fn from((clock, timeout): (clock::Clock<'_, 'd>, time::Duration)) -> Self {
228        Self {
229            source: clock.now().into(),
230            limit: Span {
231                started: time::Instant::now(),
232                timeout,
233            },
234        }
235    }
236}
237
238impl<S: Time> Bound<End, S> {
239    pub(crate) fn until(source: S, timeout: time::Duration) -> Result<Self, Range> {
240        let origin = time::Instant::now();
241        let end = Range::try_add(origin, timeout)?;
242        Ok(Self {
243            source,
244            limit: End(end),
245        })
246    }
247}
248
249impl<L: Limit, S: Time> Time for Bound<L, S> {
250    const FIXED: bool = S::FIXED;
251
252    fn start(self) -> clock::Sample {
253        self.source.start()
254    }
255
256    fn timeout(self, deadline: clock::Deadline<'_>) -> time::Duration {
257        self.source.timeout(deadline)
258    }
259
260    fn quiesce(self) -> Result<clock::Sample, drive::Error> {
261        self.elapsed().map_err(drive::Error::quiesce)
262    }
263
264    fn tick(self) -> Result<clock::Sample, drive::Error> {
265        self.elapsed().map_err(drive::Error::timeout)
266    }
267
268    fn limit(self, timeout: Option<time::Duration>) -> Option<time::Duration> {
269        let timeout = self.source.limit(timeout);
270        if timeout.is_some_and(|wait| wait.is_zero()) {
271            return timeout;
272        }
273        let left = self.limit.left(time::Instant::now());
274        Some(timeout.map_or(left, |wait| wait.min(left)))
275    }
276}
277
278const _: () = {
279    assert!(std::mem::size_of::<Wall>() == 0);
280    assert!(std::mem::size_of::<Range>() == std::mem::size_of::<(time::Instant, time::Duration)>());
281    assert!(std::mem::size_of::<Bound<End>>() == std::mem::size_of::<time::Instant>());
282    assert!(
283        std::mem::size_of::<Bound<Span>>()
284            == std::mem::size_of::<(time::Instant, time::Duration)>()
285    );
286};