Skip to main content

aura_anim_iced/runtime/
clock.rs

1use std::time::Instant;
2
3use crate::timing::Duration;
4
5/// Clock used by the animation runtime.
6pub trait AnimationClock {
7    /// Returns the current runtime timestamp.
8    fn now(&self) -> Duration;
9}
10
11/// Monotonic runtime clock backed by `std::time::Instant`.
12#[derive(Debug, Clone)]
13pub struct SystemClock {
14    started_at: Instant,
15}
16
17impl SystemClock {
18    /// Creates a system clock whose zero point is now.
19    #[must_use]
20    pub fn new() -> Self {
21        Self {
22            started_at: Instant::now(),
23        }
24    }
25}
26
27impl Default for SystemClock {
28    fn default() -> Self {
29        Self::new()
30    }
31}
32
33impl AnimationClock for SystemClock {
34    fn now(&self) -> Duration {
35        self.started_at.elapsed().into()
36    }
37}
38
39/// Deterministic clock for tests runtime checks.
40#[derive(Debug, Clone, Copy, PartialEq)]
41pub struct TestClock {
42    now: Duration,
43}
44
45impl TestClock {
46    /// Creates a test clock at zero.
47    #[must_use]
48    pub const fn new() -> Self {
49        Self {
50            now: Duration::ZERO,
51        }
52    }
53
54    /// Creates a test clock at `now`.
55    #[must_use]
56    pub fn at(now: impl Into<Duration>) -> Self {
57        Self { now: now.into() }
58    }
59
60    /// Sets the current timestamp.
61    pub fn set_now(&mut self, now: impl Into<Duration>) {
62        self.now = now.into();
63    }
64
65    /// Advances the current timestamp by `duration`.
66    pub fn advance_by(&mut self, duration: impl Into<Duration>) {
67        self.now += duration.into();
68    }
69}
70
71impl Default for TestClock {
72    fn default() -> Self {
73        Self::new()
74    }
75}
76
77impl AnimationClock for TestClock {
78    fn now(&self) -> Duration {
79        self.now
80    }
81}