Skip to main content

raw_ether/
clock.rs

1//! A network interface's PTP hardware clock, which gPTP keeps on the
2//! network's time, read from Linux's `/dev/ptpN`, and two such clocks
3//! compared. Elsewhere opening fails as unsupported.
4
5use std::collections::VecDeque;
6use std::io;
7use std::time::Duration;
8
9/// One of this computer's clocks, to compare a hardware clock with.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum SystemClock {
12    /// The wall clock, which NTP steps and slews.
13    Realtime,
14    /// The clock `std::time::Instant` and sleeps run on: slewed by NTP,
15    /// never stepped.
16    Monotonic,
17    /// The oscillator as it runs, which nothing adjusts.
18    MonotonicRaw,
19    /// International atomic time: the wall clock and the kernel's TAI
20    /// offset, which is zero until something such as chrony sets it.
21    Tai,
22}
23
24/// A PTP hardware clock.
25pub struct HardwareClock {
26    inner: platform::HardwareClock,
27}
28
29impl HardwareClock {
30    /// Opens the clock with `index`, as an interface reports it in
31    /// [`crate::Interface::hardware_clock`].
32    pub fn open(index: u32) -> io::Result<Self> {
33        Ok(Self {
34            inner: platform::HardwareClock::open(index, false)?,
35        })
36    }
37
38    /// Opens the clock with `index` to adjust it as well as read it.
39    pub fn open_adjustable(index: u32) -> io::Result<Self> {
40        Ok(Self {
41            inner: platform::HardwareClock::open(index, true)?,
42        })
43    }
44
45    /// How far the clock's frequency is adjusted from its oscillator's, in
46    /// parts per billion.
47    pub fn frequency_adjustment(&self) -> io::Result<f64> {
48        self.inner.frequency_adjustment()
49    }
50
51    /// Adjusts the clock's frequency to `ppb` parts per billion from its
52    /// oscillator's: 0 lets it run free. Needs the clock opened with
53    /// [`open_adjustable`](Self::open_adjustable).
54    pub fn set_frequency_adjustment(&self, ppb: f64) -> io::Result<()> {
55        self.inner.set_frequency_adjustment(ppb)
56    }
57
58    /// Sets the clock `by` nanoseconds on, back where negative. Needs the
59    /// clock opened with [`open_adjustable`](Self::open_adjustable).
60    pub fn step(&self, by: i128) -> io::Result<()> {
61        self.inner.step(by)
62    }
63
64    /// The clock's time, from the PTP epoch.
65    pub fn now(&self) -> io::Result<Duration> {
66        self.inner.now()
67    }
68
69    /// How far this clock is ahead of `other`, in nanoseconds: each read
70    /// by its driver between two readings of the system clock, the
71    /// tightest of several pairs kept, so the system clock drops out.
72    /// Linux only; elsewhere unsupported.
73    pub fn offset_from(&self, other: &HardwareClock) -> io::Result<i128> {
74        self.reading_from(other).map(|reading| reading.offset)
75    }
76
77    /// [`offset_from`](Self::offset_from) with its span: the two clocks'
78    /// spans together.
79    pub fn reading_from(&self, other: &HardwareClock) -> io::Result<Reading> {
80        let ours = self.system_reading(SystemClock::Realtime)?;
81        let theirs = other.system_reading(SystemClock::Realtime)?;
82        Ok(Reading {
83            offset: ours.offset - theirs.offset,
84            span: ours.span.saturating_add(theirs.span),
85        })
86    }
87
88    /// The driver's reading against `system`, or where it has none, one
89    /// read as [`reading_against`](Self::reading_against) reads it.
90    /// iwlwifi's radio clock has none: its PTP_SYS_OFFSET_PRECISE is a
91    /// firmware command of about 1 ms that logs a line each time.
92    fn system_reading(&self, system: SystemClock) -> io::Result<Reading> {
93        match self.inner.reading_from_system(system) {
94            Err(error) if error.kind() == io::ErrorKind::Unsupported => {
95                self.reading_against(system)
96            }
97            read => read,
98        }
99    }
100
101    /// How far this clock is ahead of `system`, in nanoseconds, from its
102    /// driver's tightest of several readings between two of `system`'s
103    /// (PTP_SYS_OFFSET_EXTENDED). A kernel too old to take a clock other
104    /// than the wall clock for it refuses the others, and then
105    /// [`offset_read_against`](Self::offset_read_against) serves.
106    pub fn offset_from_system_clock(&self, system: SystemClock) -> io::Result<i128> {
107        self.reading_from_system_clock(system)
108            .map(|reading| reading.offset)
109    }
110
111    /// [`offset_from_system_clock`](Self::offset_from_system_clock) with
112    /// the span of the reading kept.
113    pub fn reading_from_system_clock(&self, system: SystemClock) -> io::Result<Reading> {
114        self.system_reading(system)
115    }
116
117    /// How far the clock is ahead of this computer's monotonic clock, in
118    /// nanoseconds, read between two readings of the monotonic clock: of
119    /// a few tries, the closest-read of those near their median, as a
120    /// clock can now and then be read wrong (a 2^32 ns tear has been seen
121    /// on one card's).
122    pub fn offset_from_monotonic(&self) -> io::Result<i128> {
123        self.offset_read_against(SystemClock::Monotonic)
124    }
125
126    /// How far the clock is ahead of `system`, in nanoseconds, read as
127    /// [`offset_from_monotonic`](Self::offset_from_monotonic) reads it:
128    /// looser than the driver's readings, but on every kernel.
129    pub fn offset_read_against(&self, system: SystemClock) -> io::Result<i128> {
130        self.reading_against(system).map(|reading| reading.offset)
131    }
132
133    /// [`offset_read_against`](Self::offset_read_against) with the span of
134    /// the try kept. Where none stands near the median, the median's.
135    pub fn reading_against(&self, system: SystemClock) -> io::Result<Reading> {
136        let mut tries = [Reading { offset: 0, span: 0 }; 5];
137        for slot in &mut tries {
138            let before = system_now(system);
139            let clock = self.now()?;
140            let after = system_now(system);
141            let span = after.saturating_sub(before).as_nanos();
142            let middle = before + (after - before) / 2;
143            *slot = Reading {
144                offset: clock.as_nanos() as i128 - middle.as_nanos() as i128,
145                span: u64::try_from(span).unwrap_or(u64::MAX),
146            };
147        }
148        let mut sorted = tries;
149        sorted.sort_unstable_by_key(|reading| reading.offset);
150        let median = sorted[sorted.len() / 2];
151        Ok(tries
152            .into_iter()
153            .filter(|reading| (reading.offset - median.offset).abs() <= 10_000)
154            .min_by_key(|reading| reading.span)
155            .unwrap_or(median))
156    }
157}
158
159/// A hardware clock against another clock, read between two of the
160/// other's readings: how far it was ahead, and how long the reading took
161/// from the other's first to its second. The hardware clock is latched
162/// somewhere in that span, so a reading is off by up to half of it; a
163/// slow one, held up on the way to the latch or after it, by up to half
164/// of what it took beyond the usual. Comparisons that must hold to less
165/// than a microsecond can leave such readings out.
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub struct Reading {
168    /// The hardware clock less the other, in nanoseconds.
169    pub offset: i128,
170    /// How long the reading took, in nanoseconds.
171    pub span: u64,
172}
173
174/// How far back comparisons count towards the rate, in nanoseconds: long
175/// enough that each comparison's own error hardly moves it.
176const SPAN: i128 = 2_000_000_000;
177
178/// Two clocks compared now and then, with the rate between them, so that
179/// a time on one is put on the other as the two stood when it was taken,
180/// not as at the last comparison: clocks some ppm apart drift hundreds of
181/// ns between comparisons. A line fitted through the comparisons kept
182/// gives both, so no one comparison's error carries over whole.
183#[derive(Debug, Clone)]
184pub struct Comparison {
185    /// (when, on the clock compared, in ns; its time less the other's)
186    kept: VecDeque<(i128, i128)>,
187    /// How far back comparisons count, in ns.
188    span: i128,
189}
190
191impl Default for Comparison {
192    fn default() -> Self {
193        Self {
194            kept: VecDeque::new(),
195            span: SPAN,
196        }
197    }
198}
199
200impl Comparison {
201    /// Comparisons kept over `span` rather than 2 s, for a clock read so
202    /// coarsely that 2 s of them leave its line moving with each new one.
203    pub fn keeping(span: Duration) -> Self {
204        Self {
205            kept: VecDeque::new(),
206            span: i128::try_from(span.as_nanos()).unwrap_or(i128::MAX),
207        }
208    }
209
210    /// The clock compared read `at`, and `offset` ahead of the other.
211    pub fn update(&mut self, at: i128, offset: i128) {
212        if self.kept.back().is_some_and(|(last, _)| at <= *last) {
213            return;
214        }
215        self.kept.push_back((at, offset));
216        while self
217            .kept
218            .front()
219            .is_some_and(|(first, _)| at - first > self.span)
220            && self.kept.len() > 2
221        {
222            self.kept.pop_front();
223        }
224    }
225
226    /// How far ahead of the other the clock compared was at `at`, a time
227    /// on it.
228    pub fn offset_at(&self, at: i128) -> i128 {
229        let Some(&(last_at, last_offset)) = self.kept.back() else {
230            return 0;
231        };
232        let Some((mean_at, mean_offset, rate)) = self.fit() else {
233            return last_offset;
234        };
235        last_offset + (mean_offset + rate * ((at - last_at) as f64 - mean_at)).round() as i128
236    }
237
238    /// How much faster the clock compared runs than the other, as a
239    /// fraction, once compared twice.
240    pub fn rate(&self) -> Option<f64> {
241        self.fit().map(|(_, _, rate)| rate)
242    }
243
244    /// The least-squares line through the comparisons kept: their mean
245    /// time and offset, each from the last's so as to keep the precision,
246    /// and the slope.
247    fn fit(&self) -> Option<(f64, f64, f64)> {
248        let &(last_at, last_offset) = self.kept.back()?;
249        if self.kept.len() < 2 {
250            return None;
251        }
252        let count = self.kept.len() as f64;
253        let points = || {
254            self.kept
255                .iter()
256                .map(move |&(at, offset)| ((at - last_at) as f64, (offset - last_offset) as f64))
257        };
258        let mean_at = points().map(|(at, _)| at).sum::<f64>() / count;
259        let mean_offset = points().map(|(_, offset)| offset).sum::<f64>() / count;
260        let (spread, covariance) =
261            points().fold((0.0, 0.0), |(spread, covariance), (at, offset)| {
262                let at = at - mean_at;
263                (spread + at * at, covariance + at * (offset - mean_offset))
264            });
265        (spread > 0.0).then(|| (mean_at, mean_offset, covariance / spread))
266    }
267
268    /// When the clock compared read for the last comparison kept, on it.
269    pub fn last_at(&self) -> Option<i128> {
270        self.kept.back().map(|(at, _)| *at)
271    }
272
273    /// Whether the clocks have been compared yet.
274    pub fn is_empty(&self) -> bool {
275        self.kept.is_empty()
276    }
277
278    /// Forgets all but the last `count` comparisons, as when the rate
279    /// between the clocks changed and the older ones would only drag the
280    /// line.
281    pub fn keep_last(&mut self, count: usize) {
282        while self.kept.len() > count {
283            self.kept.pop_front();
284        }
285    }
286
287    /// Forgets every comparison, as after one of the clocks was set.
288    pub fn clear(&mut self) {
289        self.kept.clear();
290    }
291
292    /// The clock compared was set `by` ns on, by a step known exactly:
293    /// every comparison kept moves with it, so the line keeps its rate.
294    pub fn step(&mut self, by: i128) {
295        for (at, offset) in &mut self.kept {
296            *at += by;
297            *offset += by;
298        }
299    }
300}
301
302/// This computer's monotonic clock: the clock `std::time::Instant` reads,
303/// as a duration from its unspecified start.
304pub fn monotonic_now() -> Duration {
305    platform::monotonic_now()
306}
307
308/// One of this computer's clocks, as a duration from its epoch. Elsewhere
309/// than on Linux the monotonic clock stands in for all three.
310pub fn system_now(system: SystemClock) -> Duration {
311    platform::system_now(system)
312}
313
314/// How long this computer has been suspended since it started: what the
315/// boot clock has counted beyond the monotonic clock. It grows at each
316/// resume. Elsewhere than on Linux it stays zero.
317pub fn suspended() -> Duration {
318    platform::suspended()
319}
320
321/// Has the calling thread's sleeps end as close to when they were asked
322/// for as the system can, for a thread that paces frames: on Linux a
323/// timer slack of a nanosecond in place of 50 microseconds. Elsewhere it
324/// does nothing.
325pub fn precise_sleeps() {
326    platform::precise_sleeps();
327}
328
329#[cfg(target_os = "linux")]
330#[allow(unsafe_code)]
331mod platform {
332    use super::{Reading, SystemClock};
333    use std::io;
334    use std::mem::size_of;
335    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
336    use std::time::Duration;
337
338    pub struct HardwareClock {
339        _fd: OwnedFd,
340        id: libc::clockid_t,
341    }
342
343    fn read(id: libc::clockid_t) -> io::Result<Duration> {
344        let mut time = libc::timespec {
345            tv_sec: 0,
346            tv_nsec: 0,
347        };
348        // SAFETY: `time` is a valid timespec that lives through the call.
349        if unsafe { libc::clock_gettime(id, &raw mut time) } < 0 {
350            return Err(io::Error::last_os_error());
351        }
352        Ok(Duration::new(time.tv_sec as u64, time.tv_nsec as u32))
353    }
354
355    impl HardwareClock {
356        pub fn open(index: u32, adjustable: bool) -> io::Result<Self> {
357            let path = format!("/dev/ptp{index}\0");
358            let mode = if adjustable {
359                libc::O_RDWR
360            } else {
361                libc::O_RDONLY
362            };
363            // SAFETY: `path` is NUL-terminated and lives through the call.
364            let raw = unsafe { libc::open(path.as_ptr().cast(), mode | libc::O_CLOEXEC) };
365            if raw < 0 {
366                return Err(io::Error::last_os_error());
367            }
368            // SAFETY: `raw` is a descriptor this function just opened.
369            let fd = unsafe { OwnedFd::from_raw_fd(raw) };
370            // A dynamic clock's ID is made from its descriptor
371            // (FD_TO_CLOCKID: CLOCKFD in the low bits).
372            let id = ((!fd.as_raw_fd()) << 3) | 3;
373            Ok(Self { _fd: fd, id })
374        }
375
376        pub fn now(&self) -> io::Result<Duration> {
377            read(self.id)
378        }
379
380        /// clock_adjtime on the clock: sets what `modes` names, here no
381        /// more than the frequency, and gives the adjustments as they stand.
382        fn adjust(&self, modes: libc::c_uint, frequency: libc::c_long) -> io::Result<libc::timex> {
383            // SAFETY: timex is plain data, valid when zeroed.
384            let mut time: libc::timex = unsafe { std::mem::zeroed() };
385            time.modes = modes;
386            time.freq = frequency;
387            // SAFETY: `time` is a valid timex that lives through the call.
388            if unsafe { libc::clock_adjtime(self.id, &raw mut time) } < 0 {
389                return Err(io::Error::last_os_error());
390            }
391            Ok(time)
392        }
393
394        /// timex's freq is in ppm with 16 fractional bits.
395        const SCALED_PPB: f64 = 65.536;
396
397        pub fn frequency_adjustment(&self) -> io::Result<f64> {
398            Ok(self.adjust(0, 0)?.freq as f64 / Self::SCALED_PPB)
399        }
400
401        pub fn set_frequency_adjustment(&self, ppb: f64) -> io::Result<()> {
402            self.adjust(
403                libc::ADJ_FREQUENCY,
404                (ppb * Self::SCALED_PPB).round() as libc::c_long,
405            )
406            .map(|_| ())
407        }
408
409        pub fn step(&self, by: i128) -> io::Result<()> {
410            // SAFETY: timex is plain data, valid when zeroed.
411            let mut time: libc::timex = unsafe { std::mem::zeroed() };
412            // With ADJ_NANO, the offset's microseconds field holds
413            // nanoseconds, from 0 to a second.
414            time.modes = libc::ADJ_SETOFFSET | libc::ADJ_NANO;
415            time.time.tv_sec = by.div_euclid(1_000_000_000) as libc::time_t;
416            time.time.tv_usec = by.rem_euclid(1_000_000_000) as libc::suseconds_t;
417            // SAFETY: `time` is a valid timex that lives through the call.
418            if unsafe { libc::clock_adjtime(self.id, &raw mut time) } < 0 {
419                return Err(io::Error::last_os_error());
420            }
421            Ok(())
422        }
423
424        /// The clock less the system clock, from its driver's tightest of
425        /// several readings between two of the system clock
426        /// (PTP_SYS_OFFSET_EXTENDED), or unsupported where it has none.
427        pub fn reading_from_system(&self, system: SystemClock) -> io::Result<Reading> {
428            self.extended_reading(system).map_err(|error| {
429                if error.raw_os_error() == Some(libc::EOPNOTSUPP) {
430                    io::Error::new(io::ErrorKind::Unsupported, error)
431                } else {
432                    error
433                }
434            })
435        }
436
437        fn extended_reading(&self, system: SystemClock) -> io::Result<Reading> {
438            /// struct ptp_clock_time, from linux/ptp_clock.h.
439            #[repr(C)]
440            #[derive(Clone, Copy, Default)]
441            struct Time {
442                seconds: i64,
443                nanoseconds: u32,
444                reserved: u32,
445            }
446            /// struct ptp_sys_offset_extended: system, clock and system
447            /// again, for each sample.
448            #[repr(C)]
449            struct Extended {
450                samples: u32,
451                clock: i32,
452                reserved: [u32; 2],
453                times: [[Time; 3]; 25],
454            }
455            /// _IOWR('=', 9, struct ptp_sys_offset_extended).
456            const PTP_SYS_OFFSET_EXTENDED: libc::c_ulong =
457                0xc000_0000 | ((size_of::<Extended>() as libc::c_ulong) << 16) | (0x3d << 8) | 9;
458            let mut request = Extended {
459                samples: 9,
460                clock: id_of(system),
461                reserved: [0; 2],
462                times: [[Time::default(); 3]; 25],
463            };
464            // SAFETY: `request` is the struct the ioctl takes, and lives
465            // through the call.
466            if unsafe {
467                libc::ioctl(
468                    self._fd.as_raw_fd(),
469                    PTP_SYS_OFFSET_EXTENDED as _,
470                    &raw mut request,
471                )
472            } < 0
473            {
474                return Err(io::Error::last_os_error());
475            }
476            let nanos = |time: Time| {
477                i128::from(time.seconds) * 1_000_000_000 + i128::from(time.nanoseconds)
478            };
479            request.times[..request.samples.min(25) as usize]
480                .iter()
481                .map(|[before, clock, after]| {
482                    let (before, after) = (nanos(*before), nanos(*after));
483                    Reading {
484                        offset: nanos(*clock) - (before + after) / 2,
485                        span: u64::try_from(after - before).unwrap_or(u64::MAX),
486                    }
487                })
488                .min_by_key(|reading| reading.span)
489                .ok_or_else(|| io::Error::other("the clock gave no samples"))
490        }
491    }
492
493    pub fn monotonic_now() -> Duration {
494        read(libc::CLOCK_MONOTONIC).unwrap_or_default()
495    }
496
497    fn id_of(system: SystemClock) -> libc::clockid_t {
498        match system {
499            SystemClock::Realtime => libc::CLOCK_REALTIME,
500            SystemClock::Monotonic => libc::CLOCK_MONOTONIC,
501            SystemClock::MonotonicRaw => libc::CLOCK_MONOTONIC_RAW,
502            SystemClock::Tai => libc::CLOCK_TAI,
503        }
504    }
505
506    pub fn system_now(system: SystemClock) -> Duration {
507        read(id_of(system)).unwrap_or_default()
508    }
509
510    pub fn suspended() -> Duration {
511        let boot = read(libc::CLOCK_BOOTTIME).unwrap_or_default();
512        boot.saturating_sub(monotonic_now())
513    }
514
515    pub fn precise_sleeps() {
516        // SAFETY: prctl with PR_SET_TIMERSLACK takes plain integers and
517        // changes only the calling thread.
518        unsafe {
519            libc::prctl(libc::PR_SET_TIMERSLACK, 1 as libc::c_ulong);
520        }
521    }
522}
523
524#[cfg(not(target_os = "linux"))]
525mod platform {
526    use std::io;
527    use std::time::Duration;
528
529    pub struct HardwareClock;
530
531    impl HardwareClock {
532        pub fn open(_index: u32, _adjustable: bool) -> io::Result<Self> {
533            Err(unsupported())
534        }
535
536        pub fn now(&self) -> io::Result<Duration> {
537            Ok(Duration::ZERO)
538        }
539
540        pub fn frequency_adjustment(&self) -> io::Result<f64> {
541            Err(unsupported())
542        }
543
544        pub fn set_frequency_adjustment(&self, _ppb: f64) -> io::Result<()> {
545            Err(unsupported())
546        }
547
548        pub fn step(&self, _by: i128) -> io::Result<()> {
549            Err(unsupported())
550        }
551
552        pub fn reading_from_system(
553            &self,
554            _system: super::SystemClock,
555        ) -> io::Result<super::Reading> {
556            Err(unsupported())
557        }
558    }
559
560    fn unsupported() -> io::Error {
561        io::Error::new(
562            io::ErrorKind::Unsupported,
563            "hardware clocks are not supported on this system yet",
564        )
565    }
566
567    pub fn monotonic_now() -> Duration {
568        use std::sync::OnceLock;
569        static START: OnceLock<std::time::Instant> = OnceLock::new();
570        START.get_or_init(std::time::Instant::now).elapsed()
571    }
572
573    pub fn system_now(_system: super::SystemClock) -> Duration {
574        monotonic_now()
575    }
576
577    pub fn suspended() -> Duration {
578        Duration::ZERO
579    }
580
581    pub fn precise_sleeps() {}
582}
583
584#[cfg(test)]
585mod comparison_tests {
586    use super::*;
587
588    #[test]
589    fn a_steady_drift_is_followed_between_comparisons() {
590        let mut comparison = Comparison::default();
591        // 6 ppm apart: 600 ns more every 100 ms.
592        for step in 0..30i128 {
593            comparison.update(step * 100_000_000, 1_000 + step * 600);
594        }
595        let last = 29 * 100_000_000;
596        assert_eq!(comparison.offset_at(last), 1_000 + 29 * 600);
597        assert_eq!(
598            comparison.offset_at(last + 50_000_000),
599            1_000 + 29 * 600 + 300
600        );
601        assert_eq!(
602            comparison.offset_at(last - 50_000_000),
603            1_000 + 29 * 600 - 300
604        );
605        assert!((comparison.rate().unwrap() - 6e-6).abs() < 1e-12);
606    }
607
608    #[test]
609    fn the_error_of_one_comparison_is_mostly_filtered_out() {
610        let mut comparison = Comparison::default();
611        // 6 ppm apart, each comparison 50 ns off one way or the other.
612        for step in 0..20i128 {
613            let error = if step % 2 == 0 { 50 } else { -50 };
614            comparison.update(step * 100_000_000, step * 600 + error);
615        }
616        let last = 19 * 100_000_000;
617        let off = comparison.offset_at(last) - 19 * 600;
618        assert!(off.abs() <= 15, "off by {off} ns");
619    }
620
621    #[test]
622    fn a_longer_span_keeps_older_comparisons() {
623        let mut short = Comparison::default();
624        let mut long = Comparison::keeping(Duration::from_secs(16));
625        for step in 0..100i128 {
626            short.update(step * 100_000_000, step * 600);
627            long.update(step * 100_000_000, step * 600);
628        }
629        assert_eq!(short.kept.len(), 21);
630        assert_eq!(long.kept.len(), 100);
631        long.clear();
632        long.update(0, 0);
633        long.update(20_000_000_000, 0);
634        assert_eq!(long.kept.len(), 2);
635    }
636
637    #[test]
638    fn a_step_moves_the_line_and_keeps_its_rate() {
639        let mut comparison = Comparison::keeping(Duration::from_secs(16));
640        for step in 0..100i128 {
641            comparison.update(step * 100_000_000, 5_000 + step * 774);
642        }
643        let rate = comparison.rate();
644        let before = comparison.offset_at(10_000_000_000);
645        let by = (1 << 32) * 1_000;
646        comparison.step(by);
647        assert_eq!(comparison.rate(), rate);
648        assert_eq!(comparison.offset_at(10_000_000_000 + by), before + by);
649        assert_eq!(comparison.last_at(), Some(9_900_000_000 + by));
650        comparison.update(10_000_000_000 + by, before + by);
651        assert_eq!(comparison.kept.len(), 101);
652    }
653
654    #[test]
655    fn one_comparison_is_taken_as_it_is() {
656        let mut comparison = Comparison::default();
657        assert!(comparison.is_empty());
658        assert_eq!(comparison.offset_at(5), 0);
659        comparison.update(10, 42);
660        assert_eq!(comparison.offset_at(1_000_000), 42);
661        assert_eq!(comparison.rate(), None);
662        comparison.clear();
663        assert!(comparison.is_empty());
664    }
665}
666
667#[cfg(all(test, target_os = "linux"))]
668mod tests {
669    use super::*;
670
671    #[test]
672    fn a_hardware_clock_reads_when_there_is_one() {
673        // Computers without /dev/ptp0, or not allowed to read it, skip it.
674        let Ok(clock) = HardwareClock::open(0) else {
675            return;
676        };
677        // The grandmaster keeps whatever timescale it has; the clock only
678        // has to run on, at the monotonic clock's pace give or take.
679        let first = clock.offset_from_monotonic().unwrap();
680        std::thread::sleep(Duration::from_millis(20));
681        let second = clock.offset_from_monotonic().unwrap();
682        assert!((second - first).abs() < 100_000, "{first} then {second}");
683    }
684
685    #[test]
686    fn the_monotonic_clock_moves_on() {
687        let before = monotonic_now();
688        std::thread::sleep(Duration::from_millis(2));
689        assert!(monotonic_now() > before);
690    }
691}