icedwright-types 0.1.0

Shared types for icedwright: roles and capabilities, pixel units, virtual time, frames, key chords and the Messages trait
Documentation
//! Virtual time, which never mixes with the real clock.
//!
//! A [`VirtualInstant`] is an offset from the moment a harness booted, so it prints the same on
//! every run. There is no way to make one from [`std::time::Instant`] and no `now()`: only the
//! harness hands them out. A [`VirtualDuration`] converts from [`std::time::Duration`], because
//! a duration belongs to no clock.

use core::fmt;
use core::ops::{Add, AddAssign, Mul, Sub, SubAssign};
use std::time::Duration;

/// An instant on the harness's virtual clock.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct VirtualInstant(Duration);

/// A span of virtual time.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct VirtualDuration(Duration);

impl VirtualDuration {
    /// No time at all.
    pub const ZERO: Self = Self(Duration::ZERO);
    /// The longest duration that can be represented.
    pub const MAX: Self = Self(Duration::MAX);

    /// A duration of `nanos` nanoseconds.
    #[must_use]
    pub const fn from_nanos(nanos: u64) -> Self {
        Self(Duration::from_nanos(nanos))
    }

    /// A duration of `micros` microseconds.
    #[must_use]
    pub const fn from_micros(micros: u64) -> Self {
        Self(Duration::from_micros(micros))
    }

    /// A duration of `ms` milliseconds.
    #[must_use]
    pub const fn from_millis(ms: u64) -> Self {
        Self(Duration::from_millis(ms))
    }

    /// A duration of `s` seconds.
    #[must_use]
    pub const fn from_secs(s: u64) -> Self {
        Self(Duration::from_secs(s))
    }

    /// The same span as a [`std::time::Duration`].
    #[must_use]
    pub const fn as_std(self) -> Duration {
        self.0
    }

    /// Whole milliseconds, truncated.
    #[must_use]
    pub const fn as_millis(self) -> u128 {
        self.0.as_millis()
    }

    /// `self - other`, or `None` if `other` is longer.
    #[must_use]
    pub const fn checked_sub(self, other: Self) -> Option<Self> {
        match self.0.checked_sub(other.0) {
            Some(d) => Some(Self(d)),
            None => None,
        }
    }

    /// `self - other`, or zero if `other` is longer.
    #[must_use]
    pub const fn saturating_sub(self, other: Self) -> Self {
        Self(self.0.saturating_sub(other.0))
    }

    /// `self + other`, or [`VirtualDuration::MAX`] on overflow.
    #[must_use]
    pub const fn saturating_add(self, other: Self) -> Self {
        Self(self.0.saturating_add(other.0))
    }
}

impl From<Duration> for VirtualDuration {
    fn from(duration: Duration) -> Self {
        Self(duration)
    }
}

impl From<VirtualDuration> for Duration {
    fn from(duration: VirtualDuration) -> Duration {
        duration.0
    }
}

/// Saturates at [`VirtualDuration::MAX`] rather than overflowing.
impl Add for VirtualDuration {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        self.saturating_add(other)
    }
}

impl AddAssign for VirtualDuration {
    fn add_assign(&mut self, other: Self) {
        *self = *self + other;
    }
}

/// Saturates at zero rather than underflowing.
impl Sub for VirtualDuration {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        self.saturating_sub(other)
    }
}

impl SubAssign for VirtualDuration {
    fn sub_assign(&mut self, other: Self) {
        *self = *self - other;
    }
}

/// Saturates at [`VirtualDuration::MAX`] rather than overflowing.
impl Mul<u32> for VirtualDuration {
    type Output = Self;

    fn mul(self, factor: u32) -> Self {
        Self(self.0.saturating_mul(factor))
    }
}

/// Prints seconds with at least three decimals, such as `1.250s`.
impl fmt::Display for VirtualDuration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_seconds(f, self.0)
    }
}

impl VirtualInstant {
    /// The instant `since_boot` after the harness booted. Only the harness calls this; it is
    /// public so that the harness crate can, and hidden so that nothing else does.
    #[doc(hidden)]
    #[must_use]
    pub const fn __from_offset(since_boot: VirtualDuration) -> Self {
        Self(since_boot.0)
    }

    /// The time since the harness booted.
    #[must_use]
    pub const fn since_boot(self) -> VirtualDuration {
        VirtualDuration(self.0)
    }

    /// The time from `earlier` to `self`, or zero if `earlier` is later.
    #[must_use]
    pub const fn duration_since(self, earlier: VirtualInstant) -> VirtualDuration {
        VirtualDuration(self.0.saturating_sub(earlier.0))
    }

    /// The time from `earlier` to `self`, or `None` if `earlier` is later.
    #[must_use]
    pub const fn checked_duration_since(self, earlier: VirtualInstant) -> Option<VirtualDuration> {
        match self.0.checked_sub(earlier.0) {
            Some(d) => Some(VirtualDuration(d)),
            None => None,
        }
    }
}

/// Saturates at the latest representable instant rather than overflowing.
impl Add<VirtualDuration> for VirtualInstant {
    type Output = Self;

    fn add(self, duration: VirtualDuration) -> Self {
        Self(self.0.saturating_add(duration.0))
    }
}

impl AddAssign<VirtualDuration> for VirtualInstant {
    fn add_assign(&mut self, duration: VirtualDuration) {
        *self = *self + duration;
    }
}

/// Saturates at boot rather than going before it.
impl Sub<VirtualDuration> for VirtualInstant {
    type Output = Self;

    fn sub(self, duration: VirtualDuration) -> Self {
        Self(self.0.saturating_sub(duration.0))
    }
}

/// Zero if `earlier` is later; use [`VirtualInstant::checked_duration_since`] to tell.
impl Sub for VirtualInstant {
    type Output = VirtualDuration;

    fn sub(self, earlier: Self) -> VirtualDuration {
        self.duration_since(earlier)
    }
}

/// Prints the offset since boot, such as `@+1.250s`, the same on every run.
impl fmt::Debug for VirtualInstant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("@+")?;
        write_seconds(f, self.0)
    }
}

impl fmt::Display for VirtualInstant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

/// Seconds with the fraction to nanosecond precision, trailing zeros trimmed to three places.
fn write_seconds(f: &mut fmt::Formatter<'_>, duration: Duration) -> fmt::Result {
    let fraction = format!("{:09}", duration.subsec_nanos());
    let trimmed = fraction.trim_end_matches('0');
    let shown = if trimmed.len() < 3 {
        fraction.get(..3).unwrap_or(&fraction)
    } else {
        trimmed
    };
    write!(f, "{}.{shown}s", duration.as_secs())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn at(ms: u64) -> VirtualInstant {
        VirtualInstant::__from_offset(VirtualDuration::from_millis(ms))
    }

    #[test]
    fn debug_prints_the_offset_since_boot() {
        assert_eq!(format!("{:?}", at(1250)), "@+1.250s");
        assert_eq!(format!("{:?}", at(0)), "@+0.000s");
        assert_eq!(at(61_005).to_string(), "@+61.005s");
        let frame = VirtualInstant::__from_offset(VirtualDuration::from_micros(16_667));
        assert_eq!(format!("{frame:?}"), "@+0.016667s");
        let nanos = VirtualInstant::__from_offset(VirtualDuration::from_nanos(1));
        assert_eq!(format!("{nanos:?}"), "@+0.000000001s");
    }

    #[test]
    fn duration_display() {
        assert_eq!(VirtualDuration::from_secs(5).to_string(), "5.000s");
        assert_eq!(VirtualDuration::from_millis(1500).to_string(), "1.500s");
    }

    #[test]
    fn instant_arithmetic() {
        let a = at(1000);
        let b = a + VirtualDuration::from_millis(250);
        assert_eq!(b, at(1250));
        assert_eq!(b - a, VirtualDuration::from_millis(250));
        assert_eq!(b.duration_since(a), VirtualDuration::from_millis(250));
        assert_eq!(a.duration_since(b), VirtualDuration::ZERO);
        assert_eq!(a.checked_duration_since(b), None);
        assert_eq!(
            b.checked_duration_since(a),
            Some(VirtualDuration::from_millis(250))
        );
        assert_eq!(b - VirtualDuration::from_millis(250), a);
        assert_eq!(a - VirtualDuration::from_secs(10), at(0));
        assert_eq!(b.since_boot(), VirtualDuration::from_millis(1250));
        let mut c = a;
        c += VirtualDuration::from_millis(1);
        assert_eq!(c, at(1001));
        assert!(a < b);
    }

    #[test]
    fn instant_addition_saturates() {
        let late = VirtualInstant::__from_offset(VirtualDuration::MAX);
        assert_eq!(late + VirtualDuration::from_secs(1), late);
    }

    #[test]
    fn duration_arithmetic_saturates() {
        let one = VirtualDuration::from_secs(1);
        let two = VirtualDuration::from_secs(2);
        assert_eq!(one + one, two);
        assert_eq!(one - two, VirtualDuration::ZERO);
        assert_eq!(one.checked_sub(two), None);
        assert_eq!(two.checked_sub(one), Some(one));
        assert_eq!(VirtualDuration::MAX + one, VirtualDuration::MAX);
        assert_eq!(VirtualDuration::MAX * 2, VirtualDuration::MAX);
        assert_eq!(one * 3, VirtualDuration::from_secs(3));
        let mut d = one;
        d += one;
        d -= VirtualDuration::from_millis(500);
        assert_eq!(d.as_millis(), 1500);
    }

    #[test]
    fn durations_convert_from_std() {
        const TOAST_TIMEOUT: Duration = Duration::from_secs(4);
        let virtual_timeout: VirtualDuration = TOAST_TIMEOUT.into();
        assert_eq!(virtual_timeout, VirtualDuration::from_secs(4));
        assert_eq!(virtual_timeout.as_std(), TOAST_TIMEOUT);
        assert_eq!(Duration::from(virtual_timeout), TOAST_TIMEOUT);
        assert_eq!(
            VirtualDuration::from_micros(16_667).as_std(),
            Duration::from_micros(16_667)
        );
        assert_eq!(VirtualDuration::default(), VirtualDuration::ZERO);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn instants_serialise_as_offsets() -> Result<(), serde_json::Error> {
        let json = serde_json::to_string(&at(1250))?;
        assert_eq!(serde_json::from_str::<VirtualInstant>(&json)?, at(1250));
        let json = serde_json::to_string(&VirtualDuration::from_millis(5))?;
        assert_eq!(
            serde_json::from_str::<VirtualDuration>(&json)?,
            VirtualDuration::from_millis(5)
        );
        Ok(())
    }
}