crisol-core 1.0.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
//! Injectable time. The core never reads a wall clock on its own.
//!
//! History, jobs, debounce, and key sequences take a [`Clock`]. Native builds use
//! [`SystemClock`], wasm builds use `PerformanceClock`, and tests use [`ManualClock`]
//! and never sleep (CORE-DET-02).
//!
//! ```
//! use crisol_core::time;
//! ```

use std::sync::Mutex;
use std::time::Duration;

/// A monotonic source of seconds.
///
/// The origin is arbitrary; only differences are meaningful. Implementations must be
/// cheap and thread-safe.
/// # Example
///
/// ```
/// use crisol_core::time::Clock;
/// ```
pub trait Clock: Send + Sync + 'static {
    /// Seconds since this clock's origin.
    fn now(&self) -> f64;

    /// A duration since an earlier `now()` value, never negative.
    fn elapsed_since(&self, earlier: f64) -> f64 {
        (self.now() - earlier).max(0.0)
    }
}

/// A clock for tests and deterministic replays.
#[derive(Debug, Default)]
/// # Example
///
/// ```
/// use crisol_core::time::ManualClock;
/// ```
pub struct ManualClock {
    seconds: Mutex<f64>,
}

impl ManualClock {
    /// A clock at zero.
    pub fn new() -> Self {
        Self::default()
    }

    /// A clock at `seconds`.
    pub fn at(seconds: f64) -> Self {
        Self {
            seconds: Mutex::new(seconds),
        }
    }

    /// Move the clock to `seconds`.
    pub fn set(&self, seconds: f64) {
        if let Ok(mut current) = self.seconds.lock() {
            *current = seconds;
        }
    }

    /// Move the clock forward.
    pub fn advance(&self, seconds: f64) {
        if let Ok(mut current) = self.seconds.lock() {
            *current += seconds;
        }
    }
}

impl Clock for ManualClock {
    fn now(&self) -> f64 {
        self.seconds.lock().map(|seconds| *seconds).unwrap_or(0.0)
    }
}

/// A native monotonic clock backed by `Instant`.
#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
#[derive(Debug)]
/// # Example
///
/// ```
/// use crisol_core::time::SystemClock;
/// ```
pub struct SystemClock {
    origin: std::time::Instant,
}

#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
impl Default for SystemClock {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
impl SystemClock {
    /// A clock whose origin is now.
    pub fn new() -> Self {
        Self {
            origin: std::time::Instant::now(),
        }
    }
}

#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
impl Clock for SystemClock {
    fn now(&self) -> f64 {
        self.origin.elapsed().as_secs_f64()
    }
}

/// A wasm clock that counts cooperative steps between frames.
///
/// The host calls [`PerformanceClock::tick`] once per frame with the frame delta; the
/// core then has time without touching `std::time` (which is unavailable on
/// `wasm32-unknown-unknown`).
#[cfg(target_arch = "wasm32")]
#[derive(Debug, Default)]
pub struct PerformanceClock {
    seconds: std::sync::Mutex<f64>,
}

#[cfg(target_arch = "wasm32")]
impl PerformanceClock {
    /// A clock at zero.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add one frame delta in seconds.
    pub fn tick(&self, delta: f64) {
        if let Ok(mut seconds) = self.seconds.lock() {
            *seconds += delta.max(0.0);
        }
    }

    /// Set the elapsed time directly.
    pub fn set(&self, seconds: f64) {
        if let Ok(mut current) = self.seconds.lock() {
            *current = seconds.max(0.0);
        }
    }
}

#[cfg(target_arch = "wasm32")]
impl Clock for PerformanceClock {
    fn now(&self) -> f64 {
        self.seconds.lock().map(|seconds| *seconds).unwrap_or(0.0)
    }
}

/// Convert a `Duration` to seconds.
/// # Example
///
/// ```
/// use crisol_core::time::seconds;
/// ```
pub fn seconds(duration: Duration) -> f64 {
    duration.as_secs_f64()
}

// spec: CORE-DET-02
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_manual_clock_moves_without_sleeping() {
        let clock = ManualClock::new();
        assert_eq!(clock.now(), 0.0);
        clock.advance(1.5);
        assert_eq!(clock.now(), 1.5);
        assert_eq!(clock.elapsed_since(0.5), 1.0);
        clock.set(10.0);
        assert_eq!(clock.now(), 10.0);
        assert_eq!(clock.elapsed_since(12.0), 0.0);
    }

    #[test]
    fn the_system_clock_is_monotonic() {
        #[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
        {
            let clock = SystemClock::new();
            let first = clock.now();
            let second = clock.now();
            assert!(second >= first);
        }
    }
}