fast_clock/
clock_synchronization.rs

1use crate::{CalibratedClock, Clock};
2
3#[derive(Clone, Copy)]
4pub struct ClockSynchronization<A: Clock, B: Clock> {
5    at: A::Instant,
6    bt: B::Instant,
7    a: A,
8    b: B,
9}
10
11impl<A: CalibratedClock, B: Clock> ClockSynchronization<A, B> {
12    pub fn new_aba(a: A, b: B) -> Self {
13        let (a0, bt, da) = (0..3)
14            .map(|_| {
15                let a0 = a.now();
16                let b = b.now();
17                let a1 = a.now();
18                let da = a.between_u64_ns(a1, a0);
19                (a0, b, da)
20            })
21            .min_by_key(|(.., da)| *da)
22            .unwrap();
23        ClockSynchronization {
24            a,
25            b,
26            bt,
27            at: a.add_u64_ns(a0, da / 2),
28        }
29    }
30}
31
32impl<A: CalibratedClock, B: CalibratedClock> ClockSynchronization<A, B> {
33    pub fn to_a(&self, t: B::Instant) -> A::Instant {
34        self.a
35            .add_u64_ns(self.at, self.b.between_u64_ns(t, self.bt))
36    }
37
38    pub fn to_b(&self, t: A::Instant) -> B::Instant {
39        self.b
40            .add_u64_ns(self.bt, self.a.between_u64_ns(t, self.at))
41    }
42
43    pub fn epoch_a(&self) -> A::Instant {
44        self.at
45    }
46
47    pub fn epoch_b(&self) -> B::Instant {
48        self.bt
49    }
50
51    pub fn a(&self) -> A {
52        self.a
53    }
54
55    pub fn b(&self) -> B {
56        self.b
57    }
58}