Skip to main content

viva_genapi/
clock.rs

1//! The time a [`NodeMap`](crate::NodeMap) measures `<PollingTime>` against.
2//!
3//! A register with a `<PollingTime>` holds its cached value for that long and
4//! then reads the device again (GenICam Standard v2.1.1 §2.8.3). The node map
5//! asks a [`Clock`] for the time rather than `std::time::Instant` itself:
6//! `Instant::now()` panics on `wasm32-unknown-unknown`, where Viva Studio
7//! browses XML offline, and a test needs to move time by hand. A clock is
8//! consulted only for a node that polls, so a document without
9//! `<PollingTime>` never asks it.
10
11use std::fmt;
12use std::sync::atomic::{AtomicU64, Ordering};
13use std::time::{Duration, Instant};
14
15/// A monotonic time source.
16pub trait Clock: fmt::Debug + Send + Sync {
17    /// Time since an origin of the clock's choosing. Never decreases.
18    fn now(&self) -> Duration;
19}
20
21/// The system's monotonic clock, `std::time::Instant`.
22///
23/// Not for `wasm32-unknown-unknown`, where `Instant::now()` panics; a node map
24/// built there starts with a [`ManualClock`] instead.
25#[derive(Debug, Clone, Copy)]
26pub struct SystemClock {
27    origin: Instant,
28}
29
30impl SystemClock {
31    /// A clock whose origin is now.
32    pub fn new() -> Self {
33        Self {
34            origin: Instant::now(),
35        }
36    }
37}
38
39impl Default for SystemClock {
40    fn default() -> Self {
41        Self::new()
42    }
43}
44
45impl Clock for SystemClock {
46    fn now(&self) -> Duration {
47        self.origin.elapsed()
48    }
49}
50
51/// A clock that moves only when told to: for tests, and for a host without
52/// a system clock, which advances it from its own (a browser's
53/// `performance.now()`, say).
54///
55/// Shared through an `Arc`, so a test keeps a handle on the clock it gave the
56/// node map.
57#[derive(Debug, Default)]
58pub struct ManualClock {
59    nanos: AtomicU64,
60}
61
62impl ManualClock {
63    /// A clock standing at zero.
64    pub fn new() -> Self {
65        Self::default()
66    }
67
68    /// Move the clock forward by `by`.
69    pub fn advance(&self, by: Duration) {
70        let by = u64::try_from(by.as_nanos()).unwrap_or(u64::MAX);
71        let mut current = self.nanos.load(Ordering::SeqCst);
72        loop {
73            let next = current.saturating_add(by);
74            match self.nanos.compare_exchange_weak(
75                current,
76                next,
77                Ordering::SeqCst,
78                Ordering::SeqCst,
79            ) {
80                Ok(_) => return,
81                Err(actual) => current = actual,
82            }
83        }
84    }
85
86    /// Set the time to `to`; a time earlier than now is ignored, so the clock
87    /// stays monotonic.
88    pub fn set(&self, to: Duration) {
89        let to = u64::try_from(to.as_nanos()).unwrap_or(u64::MAX);
90        self.nanos.fetch_max(to, Ordering::SeqCst);
91    }
92}
93
94impl Clock for ManualClock {
95    fn now(&self) -> Duration {
96        Duration::from_nanos(self.nanos.load(Ordering::SeqCst))
97    }
98}
99
100/// The clock a node map starts with: the system clock, or on
101/// `wasm32-unknown-unknown`, which has none, a [`ManualClock`] that stands
102/// still until the host replaces it — polled values then never expire.
103pub(crate) fn default_clock() -> std::sync::Arc<dyn Clock> {
104    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
105    {
106        std::sync::Arc::new(ManualClock::new())
107    }
108    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
109    {
110        std::sync::Arc::new(SystemClock::new())
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    #[test]
119    fn a_manual_clock_moves_only_forward() {
120        let clock = ManualClock::new();
121        assert_eq!(clock.now(), Duration::ZERO);
122        clock.advance(Duration::from_millis(500));
123        assert_eq!(clock.now(), Duration::from_millis(500));
124        clock.set(Duration::from_millis(200));
125        assert_eq!(clock.now(), Duration::from_millis(500), "never backwards");
126        clock.set(Duration::from_secs(2));
127        assert_eq!(clock.now(), Duration::from_secs(2));
128    }
129}