statime/
shared_clock.rs

1use std::sync::{Arc, Mutex};
2
3use crate::{
4    time::{Duration, Time},
5    Clock,
6};
7
8/// A wrapper for stateful `statime::Clock` implementations to make them behave
9/// like e.g. `statime_linux::LinuxClock` - clones share state with each other
10#[derive(Debug)]
11pub struct SharedClock<C>(pub Arc<Mutex<C>>)
12where
13    C: Clock;
14
15impl<C: Clock> SharedClock<C> {
16    /// Take given clock and make it a `SharedClock`
17    pub fn new(clock: C) -> Self {
18        Self(Arc::new(Mutex::new(clock)))
19    }
20}
21
22impl<C: Clock> Clone for SharedClock<C> {
23    /// Clone the shared reference to the clock (behaviour consistent with
24    /// `statime_linux::LinuxClock`)
25    fn clone(&self) -> Self {
26        Self(self.0.clone())
27    }
28}
29
30impl<C: Clock> Clock for SharedClock<C> {
31    type Error = C::Error;
32    fn now(&self) -> Time {
33        self.0.lock().unwrap().now()
34    }
35    fn set_frequency(&mut self, ppm: f64) -> Result<Time, Self::Error> {
36        self.0.lock().unwrap().set_frequency(ppm)
37    }
38    fn step_clock(&mut self, offset: Duration) -> Result<Time, Self::Error> {
39        self.0.lock().unwrap().step_clock(offset)
40    }
41    fn set_properties(
42        &mut self,
43        time_properties_ds: &crate::config::TimePropertiesDS,
44    ) -> Result<(), Self::Error> {
45        self.0.lock().unwrap().set_properties(time_properties_ds)
46    }
47}