Skip to main content

icedwright_types/
time.rs

1//! Virtual time, which never mixes with the real clock.
2//!
3//! A [`VirtualInstant`] is an offset from the moment a harness booted, so it prints the same on
4//! every run. There is no way to make one from [`std::time::Instant`] and no `now()`: only the
5//! harness hands them out. A [`VirtualDuration`] converts from [`std::time::Duration`], because
6//! a duration belongs to no clock.
7
8use core::fmt;
9use core::ops::{Add, AddAssign, Mul, Sub, SubAssign};
10use std::time::Duration;
11
12/// An instant on the harness's virtual clock.
13#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15#[cfg_attr(feature = "serde", serde(transparent))]
16pub struct VirtualInstant(Duration);
17
18/// A span of virtual time.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21#[cfg_attr(feature = "serde", serde(transparent))]
22pub struct VirtualDuration(Duration);
23
24impl VirtualDuration {
25    /// No time at all.
26    pub const ZERO: Self = Self(Duration::ZERO);
27    /// The longest duration that can be represented.
28    pub const MAX: Self = Self(Duration::MAX);
29
30    /// A duration of `nanos` nanoseconds.
31    #[must_use]
32    pub const fn from_nanos(nanos: u64) -> Self {
33        Self(Duration::from_nanos(nanos))
34    }
35
36    /// A duration of `micros` microseconds.
37    #[must_use]
38    pub const fn from_micros(micros: u64) -> Self {
39        Self(Duration::from_micros(micros))
40    }
41
42    /// A duration of `ms` milliseconds.
43    #[must_use]
44    pub const fn from_millis(ms: u64) -> Self {
45        Self(Duration::from_millis(ms))
46    }
47
48    /// A duration of `s` seconds.
49    #[must_use]
50    pub const fn from_secs(s: u64) -> Self {
51        Self(Duration::from_secs(s))
52    }
53
54    /// The same span as a [`std::time::Duration`].
55    #[must_use]
56    pub const fn as_std(self) -> Duration {
57        self.0
58    }
59
60    /// Whole milliseconds, truncated.
61    #[must_use]
62    pub const fn as_millis(self) -> u128 {
63        self.0.as_millis()
64    }
65
66    /// `self - other`, or `None` if `other` is longer.
67    #[must_use]
68    pub const fn checked_sub(self, other: Self) -> Option<Self> {
69        match self.0.checked_sub(other.0) {
70            Some(d) => Some(Self(d)),
71            None => None,
72        }
73    }
74
75    /// `self - other`, or zero if `other` is longer.
76    #[must_use]
77    pub const fn saturating_sub(self, other: Self) -> Self {
78        Self(self.0.saturating_sub(other.0))
79    }
80
81    /// `self + other`, or [`VirtualDuration::MAX`] on overflow.
82    #[must_use]
83    pub const fn saturating_add(self, other: Self) -> Self {
84        Self(self.0.saturating_add(other.0))
85    }
86}
87
88impl From<Duration> for VirtualDuration {
89    fn from(duration: Duration) -> Self {
90        Self(duration)
91    }
92}
93
94impl From<VirtualDuration> for Duration {
95    fn from(duration: VirtualDuration) -> Duration {
96        duration.0
97    }
98}
99
100/// Saturates at [`VirtualDuration::MAX`] rather than overflowing.
101impl Add for VirtualDuration {
102    type Output = Self;
103
104    fn add(self, other: Self) -> Self {
105        self.saturating_add(other)
106    }
107}
108
109impl AddAssign for VirtualDuration {
110    fn add_assign(&mut self, other: Self) {
111        *self = *self + other;
112    }
113}
114
115/// Saturates at zero rather than underflowing.
116impl Sub for VirtualDuration {
117    type Output = Self;
118
119    fn sub(self, other: Self) -> Self {
120        self.saturating_sub(other)
121    }
122}
123
124impl SubAssign for VirtualDuration {
125    fn sub_assign(&mut self, other: Self) {
126        *self = *self - other;
127    }
128}
129
130/// Saturates at [`VirtualDuration::MAX`] rather than overflowing.
131impl Mul<u32> for VirtualDuration {
132    type Output = Self;
133
134    fn mul(self, factor: u32) -> Self {
135        Self(self.0.saturating_mul(factor))
136    }
137}
138
139/// Prints seconds with at least three decimals, such as `1.250s`.
140impl fmt::Display for VirtualDuration {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        write_seconds(f, self.0)
143    }
144}
145
146impl VirtualInstant {
147    /// The instant `since_boot` after the harness booted. Only the harness calls this; it is
148    /// public so that the harness crate can, and hidden so that nothing else does.
149    #[doc(hidden)]
150    #[must_use]
151    pub const fn __from_offset(since_boot: VirtualDuration) -> Self {
152        Self(since_boot.0)
153    }
154
155    /// The time since the harness booted.
156    #[must_use]
157    pub const fn since_boot(self) -> VirtualDuration {
158        VirtualDuration(self.0)
159    }
160
161    /// The time from `earlier` to `self`, or zero if `earlier` is later.
162    #[must_use]
163    pub const fn duration_since(self, earlier: VirtualInstant) -> VirtualDuration {
164        VirtualDuration(self.0.saturating_sub(earlier.0))
165    }
166
167    /// The time from `earlier` to `self`, or `None` if `earlier` is later.
168    #[must_use]
169    pub const fn checked_duration_since(self, earlier: VirtualInstant) -> Option<VirtualDuration> {
170        match self.0.checked_sub(earlier.0) {
171            Some(d) => Some(VirtualDuration(d)),
172            None => None,
173        }
174    }
175}
176
177/// Saturates at the latest representable instant rather than overflowing.
178impl Add<VirtualDuration> for VirtualInstant {
179    type Output = Self;
180
181    fn add(self, duration: VirtualDuration) -> Self {
182        Self(self.0.saturating_add(duration.0))
183    }
184}
185
186impl AddAssign<VirtualDuration> for VirtualInstant {
187    fn add_assign(&mut self, duration: VirtualDuration) {
188        *self = *self + duration;
189    }
190}
191
192/// Saturates at boot rather than going before it.
193impl Sub<VirtualDuration> for VirtualInstant {
194    type Output = Self;
195
196    fn sub(self, duration: VirtualDuration) -> Self {
197        Self(self.0.saturating_sub(duration.0))
198    }
199}
200
201/// Zero if `earlier` is later; use [`VirtualInstant::checked_duration_since`] to tell.
202impl Sub for VirtualInstant {
203    type Output = VirtualDuration;
204
205    fn sub(self, earlier: Self) -> VirtualDuration {
206        self.duration_since(earlier)
207    }
208}
209
210/// Prints the offset since boot, such as `@+1.250s`, the same on every run.
211impl fmt::Debug for VirtualInstant {
212    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213        f.write_str("@+")?;
214        write_seconds(f, self.0)
215    }
216}
217
218impl fmt::Display for VirtualInstant {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        fmt::Debug::fmt(self, f)
221    }
222}
223
224/// Seconds with the fraction to nanosecond precision, trailing zeros trimmed to three places.
225fn write_seconds(f: &mut fmt::Formatter<'_>, duration: Duration) -> fmt::Result {
226    let fraction = format!("{:09}", duration.subsec_nanos());
227    let trimmed = fraction.trim_end_matches('0');
228    let shown = if trimmed.len() < 3 {
229        fraction.get(..3).unwrap_or(&fraction)
230    } else {
231        trimmed
232    };
233    write!(f, "{}.{shown}s", duration.as_secs())
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    fn at(ms: u64) -> VirtualInstant {
241        VirtualInstant::__from_offset(VirtualDuration::from_millis(ms))
242    }
243
244    #[test]
245    fn debug_prints_the_offset_since_boot() {
246        assert_eq!(format!("{:?}", at(1250)), "@+1.250s");
247        assert_eq!(format!("{:?}", at(0)), "@+0.000s");
248        assert_eq!(at(61_005).to_string(), "@+61.005s");
249        let frame = VirtualInstant::__from_offset(VirtualDuration::from_micros(16_667));
250        assert_eq!(format!("{frame:?}"), "@+0.016667s");
251        let nanos = VirtualInstant::__from_offset(VirtualDuration::from_nanos(1));
252        assert_eq!(format!("{nanos:?}"), "@+0.000000001s");
253    }
254
255    #[test]
256    fn duration_display() {
257        assert_eq!(VirtualDuration::from_secs(5).to_string(), "5.000s");
258        assert_eq!(VirtualDuration::from_millis(1500).to_string(), "1.500s");
259    }
260
261    #[test]
262    fn instant_arithmetic() {
263        let a = at(1000);
264        let b = a + VirtualDuration::from_millis(250);
265        assert_eq!(b, at(1250));
266        assert_eq!(b - a, VirtualDuration::from_millis(250));
267        assert_eq!(b.duration_since(a), VirtualDuration::from_millis(250));
268        assert_eq!(a.duration_since(b), VirtualDuration::ZERO);
269        assert_eq!(a.checked_duration_since(b), None);
270        assert_eq!(
271            b.checked_duration_since(a),
272            Some(VirtualDuration::from_millis(250))
273        );
274        assert_eq!(b - VirtualDuration::from_millis(250), a);
275        assert_eq!(a - VirtualDuration::from_secs(10), at(0));
276        assert_eq!(b.since_boot(), VirtualDuration::from_millis(1250));
277        let mut c = a;
278        c += VirtualDuration::from_millis(1);
279        assert_eq!(c, at(1001));
280        assert!(a < b);
281    }
282
283    #[test]
284    fn instant_addition_saturates() {
285        let late = VirtualInstant::__from_offset(VirtualDuration::MAX);
286        assert_eq!(late + VirtualDuration::from_secs(1), late);
287    }
288
289    #[test]
290    fn duration_arithmetic_saturates() {
291        let one = VirtualDuration::from_secs(1);
292        let two = VirtualDuration::from_secs(2);
293        assert_eq!(one + one, two);
294        assert_eq!(one - two, VirtualDuration::ZERO);
295        assert_eq!(one.checked_sub(two), None);
296        assert_eq!(two.checked_sub(one), Some(one));
297        assert_eq!(VirtualDuration::MAX + one, VirtualDuration::MAX);
298        assert_eq!(VirtualDuration::MAX * 2, VirtualDuration::MAX);
299        assert_eq!(one * 3, VirtualDuration::from_secs(3));
300        let mut d = one;
301        d += one;
302        d -= VirtualDuration::from_millis(500);
303        assert_eq!(d.as_millis(), 1500);
304    }
305
306    #[test]
307    fn durations_convert_from_std() {
308        const TOAST_TIMEOUT: Duration = Duration::from_secs(4);
309        let virtual_timeout: VirtualDuration = TOAST_TIMEOUT.into();
310        assert_eq!(virtual_timeout, VirtualDuration::from_secs(4));
311        assert_eq!(virtual_timeout.as_std(), TOAST_TIMEOUT);
312        assert_eq!(Duration::from(virtual_timeout), TOAST_TIMEOUT);
313        assert_eq!(
314            VirtualDuration::from_micros(16_667).as_std(),
315            Duration::from_micros(16_667)
316        );
317        assert_eq!(VirtualDuration::default(), VirtualDuration::ZERO);
318    }
319
320    #[cfg(feature = "serde")]
321    #[test]
322    fn instants_serialise_as_offsets() -> Result<(), serde_json::Error> {
323        let json = serde_json::to_string(&at(1250))?;
324        assert_eq!(serde_json::from_str::<VirtualInstant>(&json)?, at(1250));
325        let json = serde_json::to_string(&VirtualDuration::from_millis(5))?;
326        assert_eq!(
327            serde_json::from_str::<VirtualDuration>(&json)?,
328            VirtualDuration::from_millis(5)
329        );
330        Ok(())
331    }
332}