Skip to main content

rusty_time_clock/
virtual_driver.rs

1//! The no-privilege driver: commands adjust a [`VirtualClock`] view, never the OS
2//! clock. This is the wasm story and the unprivileged-process story, and it is
3//! what the TIMECORP simulator validates against.
4
5use crate::{ClockDrive, ClockError};
6use rusty_time_core::{ClockCommand, VirtualClock};
7
8#[derive(Debug, Default)]
9pub struct VirtualDriver {
10    vclock: VirtualClock,
11    /// Accumulated step corrections commanded so far, seconds.
12    stepped: f64,
13    /// Last commanded frequency, ppm.
14    freq_ppm: f64,
15}
16
17impl VirtualDriver {
18    pub fn new() -> Self {
19        Self::default()
20    }
21
22    /// The disciplined view of time. `mono` and `raw_wall` are the platform's
23    /// current readings (or the host page's, on wasm).
24    pub fn vclock(&mut self) -> &mut VirtualClock {
25        &mut self.vclock
26    }
27
28    pub fn freq_ppm(&self) -> f64 {
29        self.freq_ppm
30    }
31
32    pub fn stepped_total(&self) -> f64 {
33        self.stepped
34    }
35
36    /// Feed the latest measurement (mono seconds, offset-to-add seconds, skew ppm,
37    /// error bound) straight through to the virtual clock.
38    pub fn update_measurement(
39        &mut self,
40        mono: f64,
41        offset: f64,
42        skew_ppm: Option<f64>,
43        error_bound: f64,
44    ) {
45        self.vclock.update(mono, offset, skew_ppm, error_bound);
46    }
47}
48
49impl ClockDrive for VirtualDriver {
50    fn apply(&mut self, cmd: &ClockCommand) -> Result<(), ClockError> {
51        match *cmd {
52            ClockCommand::Step { add_seconds } => {
53                self.stepped += add_seconds;
54                Ok(())
55            }
56            ClockCommand::Slew { freq_ppm, .. } => {
57                // The virtual clock absorbs offset corrections through
58                // update_measurement; the drive side only tracks frequency.
59                self.freq_ppm = freq_ppm;
60                Ok(())
61            }
62        }
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    #[test]
71    fn commands_are_absorbed() {
72        let mut d = VirtualDriver::new();
73        d.apply(&ClockCommand::Step { add_seconds: 0.5 })
74            .expect("step");
75        d.apply(&ClockCommand::Slew {
76            freq_ppm: -12.0,
77            drain_offset: 0.001,
78            drain_rate_ppm: 500.0,
79        })
80        .expect("slew");
81        assert!((d.stepped_total() - 0.5).abs() < 1e-12);
82        assert!((d.freq_ppm() + 12.0).abs() < 1e-12);
83    }
84}