egui_cha/helpers/
clock.rs

1//! Clock abstraction for time-based helpers
2//!
3//! This module provides a `Clock` trait that abstracts time access,
4//! enabling testable time-dependent code with `FakeClock`.
5
6use std::time::{Duration, Instant};
7
8/// A clock that provides the current time
9///
10/// This trait abstracts time access, allowing for:
11/// - Normal operation with `SystemClock`
12/// - Testing with `FakeClock` (see `testing` module)
13pub trait Clock: Clone {
14    /// Get the current time as a duration since the clock's epoch
15    fn now(&self) -> Duration;
16}
17
18/// System clock using real time
19///
20/// Uses `std::time::Instant` internally, with the epoch being
21/// when the clock was created.
22#[derive(Clone)]
23pub struct SystemClock {
24    start: Instant,
25}
26
27impl SystemClock {
28    /// Create a new system clock
29    ///
30    /// The current time becomes the epoch (time zero).
31    pub fn new() -> Self {
32        Self {
33            start: Instant::now(),
34        }
35    }
36}
37
38impl Default for SystemClock {
39    fn default() -> Self {
40        Self::new()
41    }
42}
43
44impl Clock for SystemClock {
45    fn now(&self) -> Duration {
46        self.start.elapsed()
47    }
48}