1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
use rand::{
    distributions::{Distribution, Standard},
    Rng,
};
use serde::{de::Unexpected, Deserialize, Serialize};
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use std::time::{Duration, Instant};

/// NtpInstant is a monotonically increasing value modelling the uptime of the NTP service
///
/// It is used to validate packets that we send out, and to order internal operations.
#[derive(Debug, Copy, Clone, Eq, PartialEq, PartialOrd, Ord)]
pub struct NtpInstant {
    instant: Instant,
}

impl NtpInstant {
    pub fn now() -> Self {
        Self {
            instant: Instant::now(),
        }
    }

    pub fn abs_diff(self, rhs: Self) -> NtpDuration {
        // our code should always give the bigger argument first.
        debug_assert!(
            self >= rhs,
            "self >= rhs, this could indicate another program adjusted the clock"
        );

        // NOTE: `std::time::Duration` cannot be negative, so a simple `lhs - rhs` could give an
        // empty duration. In our logic, we're always interested in the absolute delta between two
        // points in time.
        let duration = if self.instant >= rhs.instant {
            self.instant - rhs.instant
        } else {
            rhs.instant - self.instant
        };

        NtpDuration::from_system_duration(duration)
    }

    pub fn elapsed(&self) -> std::time::Duration {
        self.instant.elapsed()
    }
}

impl Add<Duration> for NtpInstant {
    type Output = NtpInstant;

    fn add(mut self, rhs: Duration) -> Self::Output {
        self.instant += rhs;

        self
    }
}

/// NtpTimestamp represents an ntp timestamp without the era number.
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Default, Serialize, Deserialize)]
pub struct NtpTimestamp {
    timestamp: u64,
}

impl std::fmt::Debug for NtpTimestamp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("NtpTimestamp")
            .field(&self.timestamp)
            .finish()
    }
}

impl NtpTimestamp {
    pub(crate) const fn from_bits(bits: [u8; 8]) -> NtpTimestamp {
        NtpTimestamp {
            timestamp: u64::from_be_bytes(bits),
        }
    }

    pub(crate) const fn to_bits(self) -> [u8; 8] {
        self.timestamp.to_be_bytes()
    }

    /// Create an NTP timestamp from the number of seconds and nanoseconds that have
    /// passed since the last ntp era boundary.
    pub const fn from_seconds_nanos_since_ntp_era(seconds: u32, nanos: u32) -> Self {
        // Although having a valid interpretation, providing more
        // than 1 second worth of nanoseconds as input probably
        // indicates an error from the caller.
        debug_assert!(nanos < 1_000_000_000);
        // NTP uses 1/2^32 sec as its unit of fractional time.
        // our time is in nanoseconds, so 1/1e9 seconds
        let fraction = ((nanos as u64) << 32) / 1_000_000_000;

        // alternatively, abuse FP arithmetic to save an instruction
        // let fraction = (nanos as f64 * 4.294967296) as u64;

        let timestamp = ((seconds as u64) << 32) + fraction;
        NtpTimestamp::from_bits(timestamp.to_be_bytes())
    }

    pub fn is_before(self, other: NtpTimestamp) -> bool {
        // Around an era change, self can be near the maximum value
        // for NtpTimestamp and other near the minimum, and that must
        // be interpreted as self being before other (which it is due
        // to wrapping in substraction of NtpTimestamp)
        self - other < NtpDuration::ZERO
    }

    #[cfg(any(test, feature = "fuzz"))]
    pub(crate) const fn from_fixed_int(timestamp: u64) -> NtpTimestamp {
        NtpTimestamp { timestamp }
    }
}

// In order to provide increased entropy on origin timestamps,
// we should generate these randomly. This helps avoid
// attacks from attackers guessing our current time.
impl Distribution<NtpTimestamp> for Standard {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> NtpTimestamp {
        NtpTimestamp {
            timestamp: rng.gen(),
        }
    }
}

impl Add<NtpDuration> for NtpTimestamp {
    type Output = NtpTimestamp;

    fn add(self, rhs: NtpDuration) -> Self::Output {
        // In order to properly deal with ntp era changes, timestamps
        // need to roll over. Converting the duration to u64 here
        // still gives desired effects because of how two's complement
        // arithmetic works.
        NtpTimestamp {
            timestamp: self.timestamp.wrapping_add(rhs.duration as u64),
        }
    }
}

impl AddAssign<NtpDuration> for NtpTimestamp {
    fn add_assign(&mut self, rhs: NtpDuration) {
        // In order to properly deal with ntp era changes, timestamps
        // need to roll over. Converting the duration to u64 here
        // still gives desired effects because of how two's complement
        // arithmetic works.
        self.timestamp = self.timestamp.wrapping_add(rhs.duration as u64);
    }
}

impl Sub for NtpTimestamp {
    type Output = NtpDuration;

    fn sub(self, rhs: Self) -> Self::Output {
        // In order to properly deal with ntp era changes, timestamps
        // need to roll over. Doing a wrapping substract to a signed
        // integer type always gives us the result as if the eras of
        // the timestamps were chosen to minimize the norm of the
        // difference, which is the desired behaviour
        NtpDuration {
            duration: self.timestamp.wrapping_sub(rhs.timestamp) as i64,
        }
    }
}

impl Sub<NtpDuration> for NtpTimestamp {
    type Output = NtpTimestamp;

    fn sub(self, rhs: NtpDuration) -> Self::Output {
        // In order to properly deal with ntp era changes, timestamps
        // need to roll over. Converting the duration to u64 here
        // still gives desired effects because of how two's complement
        // arithmetic works.
        NtpTimestamp {
            timestamp: self.timestamp.wrapping_sub(rhs.duration as u64),
        }
    }
}

impl SubAssign<NtpDuration> for NtpTimestamp {
    fn sub_assign(&mut self, rhs: NtpDuration) {
        // In order to properly deal with ntp era changes, timestamps
        // need to roll over. Converting the duration to u64 here
        // still gives desired effects because of how two's complement
        // arithmetic works.
        self.timestamp = self.timestamp.wrapping_sub(rhs.duration as u64);
    }
}

/// NtpDuration is used to represent signed intervals between NtpTimestamps.
/// A negative duration interval is interpreted to mean that the first
/// timestamp used to define the interval represents a point in time after
/// the second timestamp.
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Default)]
pub struct NtpDuration {
    duration: i64,
}

impl std::fmt::Debug for NtpDuration {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "NtpDuration({} ms)", self.to_seconds() * 1e3)
    }
}

impl NtpDuration {
    pub const ZERO: Self = Self { duration: 0 };
    pub(crate) const ONE: Self = Self { duration: 1 << 32 };

    /// NtpDuration::from_seconds(0.125)
    pub(crate) const STEP_THRESHOLD: Self = Self { duration: 1 << 29 };

    /// NtpDuration::from_seconds(16.0)
    pub(crate) const MAX_DISPERSION: Self = Self {
        duration: 68719476736,
    };

    /// NtpDuration::from_seconds(0.005)
    pub(crate) const MIN_DISPERSION: Self = Self { duration: 21474836 };

    pub(crate) const fn from_bits(bits: [u8; 8]) -> Self {
        Self {
            duration: i64::from_be_bytes(bits),
        }
    }

    pub(crate) const fn from_bits_short(bits: [u8; 4]) -> Self {
        NtpDuration {
            duration: (u32::from_be_bytes(bits) as i64) << 16,
        }
    }

    pub(crate) const fn to_bits_short(self) -> [u8; 4] {
        // serializing negative durations should never happen
        // and indicates a programming error elsewhere.
        // as for duration that are too large, saturating is
        // the safe option.
        assert!(self.duration >= 0);

        // Although saturating is safe to do, it probably still
        // should never happen in practice, so ensure we will
        // see it when running in debug mode.
        debug_assert!(self.duration <= 0x0000FFFFFFFFFFFF);

        match self.duration > 0x0000FFFFFFFFFFFF {
            true => 0xFFFFFFFF_u32,
            false => ((self.duration & 0x0000FFFFFFFF0000) >> 16) as u32,
        }
        .to_be_bytes()
    }

    /// Convert to an f64; required for statistical calculations
    /// (e.g. in clock filtering)
    pub fn to_seconds(self) -> f64 {
        // dividing by u32::MAX moves the decimal point to the right position
        self.duration as f64 / u32::MAX as f64
    }

    pub fn from_seconds(seconds: f64) -> Self {
        debug_assert!(!(seconds.is_nan() || seconds.is_infinite()));

        let i = seconds.floor();
        let f = seconds - i;

        // Ensure proper saturating behaviour
        let duration = match i as i64 {
            i if i >= std::i32::MIN as i64 && i <= std::i32::MAX as i64 => {
                (i << 32) | (f * u32::MAX as f64) as i64
            }
            i if i < std::i32::MIN as i64 => std::i64::MIN,
            i if i > std::i32::MAX as i64 => std::i64::MAX,
            _ => unreachable!(),
        };

        Self { duration }
    }

    /// Interval of same length, but positive direction
    pub const fn abs(self) -> Self {
        Self {
            duration: self.duration.abs(),
        }
    }

    /// Get the number of seconds (first return value) and nanoseconds
    /// (second return value) representing the length of this duration.
    /// The number of nanoseconds is guaranteed to be positiv and less
    /// than 10^9
    pub const fn as_seconds_nanos(self) -> (i32, u32) {
        (
            (self.duration >> 32) as i32,
            (((self.duration & 0xFFFFFFFF) * 1_000_000_000) >> 32) as u32,
        )
    }

    /// Interpret an exponent `k` as `2^k` seconds, expressed as an NtpDuration
    pub fn from_exponent(input: i8) -> Self {
        Self {
            duration: match input {
                exp if exp > 30 => std::i64::MAX,
                exp if exp > 0 && exp <= 30 => 0x1_0000_0000_i64 << exp,
                exp if (-32..=0).contains(&exp) => 0x1_0000_0000_i64 >> -exp,
                _ => 0,
            },
        }
    }

    /// calculate the log2 (floored) of the duration in seconds (i8::MIN if 0)
    pub fn log2(self) -> i8 {
        if self == NtpDuration::ZERO {
            return i8::MIN;
        }

        31 - (self.duration.leading_zeros() as i8)
    }

    pub fn from_system_duration(duration: Duration) -> Self {
        let seconds = duration.as_secs();
        let nanos = duration.subsec_nanos();
        // Although having a valid interpretation, providing more
        // than 1 second worth of nanoseconds as input probably
        // indicates an error from the caller.
        debug_assert!(nanos < 1_000_000_000);
        // NTP uses 1/2^32 sec as its unit of fractional time.
        // our time is in nanoseconds, so 1/1e9 seconds
        let fraction = ((nanos as u64) << 32) / 1_000_000_000;

        // alternatively, abuse FP arithmetic to save an instruction
        // let fraction = (nanos as f64 * 4.294967296) as u64;

        let timestamp = (seconds << 32) + fraction;
        NtpDuration::from_bits(timestamp.to_be_bytes())
    }

    #[cfg(any(test, feature = "fuzz"))]
    pub(crate) const fn from_fixed_int(duration: i64) -> NtpDuration {
        NtpDuration { duration }
    }
}

impl Serialize for NtpDuration {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let seconds = self.to_seconds();
        seconds.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for NtpDuration {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let seconds: f64 = Deserialize::deserialize(deserializer)?;

        if seconds.is_nan() || seconds.is_infinite() {
            return Err(serde::de::Error::invalid_value(
                Unexpected::Float(seconds),
                &"a valid number",
            ));
        }

        Ok(NtpDuration::from_seconds(seconds))
    }
}

impl Add for NtpDuration {
    type Output = NtpDuration;

    fn add(self, rhs: Self) -> Self::Output {
        // For duration, saturation is safer as that ensures
        // addition or substraction of two big durations never
        // unintentionally cancel, ensuring that filtering
        // can properly reject on the result.
        NtpDuration {
            duration: self.duration.saturating_add(rhs.duration),
        }
    }
}

impl AddAssign for NtpDuration {
    fn add_assign(&mut self, rhs: Self) {
        // For duration, saturation is safer as that ensures
        // addition or substraction of two big durations never
        // unintentionally cancel, ensuring that filtering
        // can properly reject on the result.
        self.duration = self.duration.saturating_add(rhs.duration);
    }
}

impl Sub for NtpDuration {
    type Output = NtpDuration;

    fn sub(self, rhs: Self) -> Self::Output {
        // For duration, saturation is safer as that ensures
        // addition or substraction of two big durations never
        // unintentionally cancel, ensuring that filtering
        // can properly reject on the result.
        NtpDuration {
            duration: self.duration.saturating_sub(rhs.duration),
        }
    }
}

impl SubAssign for NtpDuration {
    fn sub_assign(&mut self, rhs: Self) {
        // For duration, saturation is safer as that ensures
        // addition or substraction of two big durations never
        // unintentionally cancel, ensuring that filtering
        // can properly reject on the result.
        self.duration = self.duration.saturating_sub(rhs.duration);
    }
}

impl Neg for NtpDuration {
    type Output = NtpDuration;

    fn neg(self) -> Self::Output {
        NtpDuration {
            duration: -self.duration,
        }
    }
}

macro_rules! ntp_duration_scalar_mul {
    ($scalar_type:ty) => {
        impl Mul<NtpDuration> for $scalar_type {
            type Output = NtpDuration;

            fn mul(self, rhs: NtpDuration) -> NtpDuration {
                // For duration, saturation is safer as that ensures
                // addition or substraction of two big durations never
                // unintentionally cancel, ensuring that filtering
                // can properly reject on the result.
                NtpDuration {
                    duration: rhs.duration.saturating_mul(self as i64),
                }
            }
        }

        impl Mul<$scalar_type> for NtpDuration {
            type Output = NtpDuration;

            fn mul(self, rhs: $scalar_type) -> NtpDuration {
                // For duration, saturation is safer as that ensures
                // addition or substraction of two big durations never
                // unintentionally cancel, ensuring that filtering
                // can properly reject on the result.
                NtpDuration {
                    duration: self.duration.saturating_mul(rhs as i64),
                }
            }
        }

        impl MulAssign<$scalar_type> for NtpDuration {
            fn mul_assign(&mut self, rhs: $scalar_type) {
                // For duration, saturation is safer as that ensures
                // addition or substraction of two big durations never
                // unintentionally cancel, ensuring that filtering
                // can properly reject on the result.
                self.duration = self.duration.saturating_mul(rhs as i64);
            }
        }
    };
}

ntp_duration_scalar_mul!(i8);
ntp_duration_scalar_mul!(i16);
ntp_duration_scalar_mul!(i32);
ntp_duration_scalar_mul!(i64);
ntp_duration_scalar_mul!(isize);
ntp_duration_scalar_mul!(u8);
ntp_duration_scalar_mul!(u16);
ntp_duration_scalar_mul!(u32);
// u64 and usize deliberately excluded as they can result in overflows

macro_rules! ntp_duration_scalar_div {
    ($scalar_type:ty) => {
        impl Div<$scalar_type> for NtpDuration {
            type Output = NtpDuration;

            fn div(self, rhs: $scalar_type) -> NtpDuration {
                // No overflow risks for division
                NtpDuration {
                    duration: self.duration / (rhs as i64),
                }
            }
        }

        impl DivAssign<$scalar_type> for NtpDuration {
            fn div_assign(&mut self, rhs: $scalar_type) {
                // No overflow risks for division
                self.duration /= (rhs as i64);
            }
        }
    };
}

ntp_duration_scalar_div!(i8);
ntp_duration_scalar_div!(i16);
ntp_duration_scalar_div!(i32);
ntp_duration_scalar_div!(i64);
ntp_duration_scalar_div!(isize);
ntp_duration_scalar_div!(u8);
ntp_duration_scalar_div!(u16);
ntp_duration_scalar_div!(u32);
// u64 and usize deliberately excluded as they can result in overflows

/// Stores when we will next exchange packages with a remote server.
//
// The value is in seconds stored in log2 format:
//
// - a value of 4 means 2^4 = 16 seconds
// - a value of 17 is 2^17 = ~36h
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct PollInterval(i8);

#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PollIntervalLimits {
    pub min: PollInterval,
    pub max: PollInterval,
}

// here we follow the spec (the code skeleton and ntpd repository use different values)
// with the exception that we have lowered the MAX value, which is needed because
// we don't support bursting, and hence using a larger poll interval gives issues
// with the responsiveness of the client to environmental changes
impl Default for PollIntervalLimits {
    fn default() -> Self {
        Self {
            min: PollInterval(4),
            max: PollInterval(10),
        }
    }
}

impl std::fmt::Debug for PollInterval {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "PollInterval({} s)", 2.0_f64.powf(self.0 as _))
    }
}

impl PollInterval {
    #[must_use]
    pub fn inc(self, limits: PollIntervalLimits) -> Self {
        Self(self.0 + 1).min(limits.max)
    }

    #[must_use]
    pub fn dec(self, limits: PollIntervalLimits) -> Self {
        Self(self.0 - 1).max(limits.min)
    }

    pub const fn as_log(self) -> i8 {
        self.0
    }

    pub const fn as_duration(self) -> NtpDuration {
        NtpDuration {
            duration: 1 << (self.0 + 32),
        }
    }

    pub const fn as_system_duration(self) -> Duration {
        Duration::from_secs(1 << self.0)
    }
}

impl Default for PollInterval {
    fn default() -> Self {
        Self(4)
    }
}

/// Frequency tolerance PHI (unit: seconds per second)
#[derive(Debug, Clone, Copy)]
pub struct FrequencyTolerance {
    ppm: u32,
}

impl<'de> Deserialize<'de> for FrequencyTolerance {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let val: u32 = Deserialize::deserialize(deserializer)?;
        Ok(FrequencyTolerance { ppm: val })
    }
}

impl FrequencyTolerance {
    pub const fn ppm(ppm: u32) -> Self {
        Self { ppm }
    }
}

impl Mul<FrequencyTolerance> for NtpDuration {
    type Output = NtpDuration;

    fn mul(self, rhs: FrequencyTolerance) -> Self::Output {
        (self * rhs.ppm) / 1_000_000
    }
}

#[cfg(feature = "fuzz")]
pub fn fuzz_duration_from_seconds(v: f64) {
    if v.is_finite() {
        let duration = NtpDuration::from_seconds(v);
        assert!(v.signum() as i64 * duration.duration.signum() >= 0);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_timestamp_sub() {
        let a = NtpTimestamp::from_fixed_int(5);
        let b = NtpTimestamp::from_fixed_int(3);
        assert_eq!(a - b, NtpDuration::from_fixed_int(2));
        assert_eq!(b - a, NtpDuration::from_fixed_int(-2));
    }

    #[test]
    fn test_timestamp_era_change() {
        let mut a = NtpTimestamp::from_fixed_int(1);
        let b = NtpTimestamp::from_fixed_int(0xFFFFFFFFFFFFFFFF);
        assert_eq!(a - b, NtpDuration::from_fixed_int(2));
        assert_eq!(b - a, NtpDuration::from_fixed_int(-2));

        let c = NtpDuration::from_fixed_int(2);
        let d = NtpDuration::from_fixed_int(-2);
        assert_eq!(b + c, a);
        assert_eq!(b - d, a);
        assert_eq!(a - c, b);
        assert_eq!(a + d, b);

        a -= c;
        assert_eq!(a, b);
        a += c;
        assert_eq!(a, NtpTimestamp::from_fixed_int(1));
    }

    #[test]
    fn test_timestamp_from_seconds_nanos() {
        assert_eq!(
            NtpTimestamp::from_seconds_nanos_since_ntp_era(0, 500_000_000),
            NtpTimestamp::from_fixed_int(0x80000000)
        );
        assert_eq!(
            NtpTimestamp::from_seconds_nanos_since_ntp_era(1, 0),
            NtpTimestamp::from_fixed_int(1 << 32)
        );
    }

    #[test]
    fn test_timestamp_duration_math() {
        let mut a = NtpTimestamp::from_fixed_int(5);
        let b = NtpDuration::from_fixed_int(2);
        assert_eq!(a + b, NtpTimestamp::from_fixed_int(7));
        assert_eq!(a - b, NtpTimestamp::from_fixed_int(3));
        a += b;
        assert_eq!(a, NtpTimestamp::from_fixed_int(7));
        a -= b;
        assert_eq!(a, NtpTimestamp::from_fixed_int(5));
    }

    #[test]
    fn test_duration_as_seconds_nanos() {
        assert_eq!(
            NtpDuration::from_fixed_int(0x80000000).as_seconds_nanos(),
            (0, 500_000_000)
        );
        assert_eq!(
            NtpDuration::from_fixed_int(1 << 33).as_seconds_nanos(),
            (2, 0)
        );
    }

    #[test]
    fn test_duration_math() {
        let mut a = NtpDuration::from_fixed_int(5);
        let b = NtpDuration::from_fixed_int(2);
        assert_eq!(a + b, NtpDuration::from_fixed_int(7));
        assert_eq!(a - b, NtpDuration::from_fixed_int(3));
        a += b;
        assert_eq!(a, NtpDuration::from_fixed_int(7));
        a -= b;
        assert_eq!(a, NtpDuration::from_fixed_int(5));
    }

    macro_rules! ntp_duration_scaling_test {
        ($name:ident, $scalar_type:ty) => {
            #[test]
            fn $name() {
                let mut a = NtpDuration::from_fixed_int(31);
                let b: $scalar_type = 2;
                assert_eq!(a * b, NtpDuration::from_fixed_int(62));
                assert_eq!(b * a, NtpDuration::from_fixed_int(62));
                assert_eq!(a / b, NtpDuration::from_fixed_int(15));
                a /= b;
                assert_eq!(a, NtpDuration::from_fixed_int(15));
                a *= b;
                assert_eq!(a, NtpDuration::from_fixed_int(30));
            }
        };
    }

    ntp_duration_scaling_test!(ntp_duration_scaling_i8, i8);
    ntp_duration_scaling_test!(ntp_duration_scaling_i16, i16);
    ntp_duration_scaling_test!(ntp_duration_scaling_i32, i32);
    ntp_duration_scaling_test!(ntp_duration_scaling_i64, i64);
    ntp_duration_scaling_test!(ntp_duration_scaling_isize, isize);
    ntp_duration_scaling_test!(ntp_duration_scaling_u8, u8);
    ntp_duration_scaling_test!(ntp_duration_scaling_u16, u16);
    ntp_duration_scaling_test!(ntp_duration_scaling_u32, u32);

    macro_rules! assert_eq_epsilon {
        ($a:expr, $b:expr, $epsilon:expr) => {
            assert!(
                ($a - $b).abs() < $epsilon,
                "Left not nearly equal to right:\nLeft: {}\nRight: {}\n",
                $a,
                $b
            );
        };
    }

    #[test]
    fn duration_seconds_roundtrip() {
        assert_eq_epsilon!(NtpDuration::from_seconds(0.0).to_seconds(), 0.0, 1e-9);
        assert_eq_epsilon!(NtpDuration::from_seconds(1.0).to_seconds(), 1.0, 1e-9);
        assert_eq_epsilon!(NtpDuration::from_seconds(1.5).to_seconds(), 1.5, 1e-9);
        assert_eq_epsilon!(NtpDuration::from_seconds(2.0).to_seconds(), 2.0, 1e-9);
    }

    #[test]
    fn duration_from_exponent() {
        assert_eq_epsilon!(NtpDuration::from_exponent(0).to_seconds(), 1.0, 1e-9);

        assert_eq_epsilon!(NtpDuration::from_exponent(1).to_seconds(), 2.0, 1e-9);

        assert_eq_epsilon!(
            NtpDuration::from_exponent(17).to_seconds(),
            2.0f64.powi(17),
            1e-4 // Less precision due to larger exponent
        );

        assert_eq_epsilon!(NtpDuration::from_exponent(-1).to_seconds(), 0.5, 1e-9);

        assert_eq_epsilon!(
            NtpDuration::from_exponent(-5).to_seconds(),
            1.0 / 2.0f64.powi(5),
            1e-9
        );
    }

    #[test]
    fn duration_from_exponent_reasonable() {
        for i in -32..=127 {
            assert!(NtpDuration::from_exponent(i) > NtpDuration::from_fixed_int(0));
        }
        for i in -128..-32 {
            NtpDuration::from_exponent(i); // should not crash
        }
    }

    #[test]
    fn duration_from_float_seconds_saturates() {
        assert_eq!(
            NtpDuration::from_seconds(1e40),
            NtpDuration::from_fixed_int(std::i64::MAX)
        );
        assert_eq!(
            NtpDuration::from_seconds(-1e40),
            NtpDuration::from_fixed_int(std::i64::MIN)
        );
    }

    #[test]
    fn poll_interval_clamps() {
        let mut interval = PollInterval::default();
        let limits = PollIntervalLimits::default();
        for _ in 0..100 {
            interval = interval.inc(limits);
            assert!(interval <= limits.max);
        }
        for _ in 0..100 {
            interval = interval.dec(limits);
            assert!(interval >= limits.min);
        }
        for _ in 0..100 {
            interval = interval.inc(limits);
            assert!(interval <= limits.max);
        }
    }

    #[test]
    fn poll_interval_to_duration() {
        assert_eq!(
            PollInterval(4).as_duration(),
            NtpDuration::from_fixed_int(16 << 32)
        );
        assert_eq!(
            PollInterval(5).as_duration(),
            NtpDuration::from_fixed_int(32 << 32)
        );

        let mut interval = PollInterval::default();
        for _ in 0..100 {
            assert_eq!(
                interval.as_duration().as_seconds_nanos().0,
                interval.as_system_duration().as_secs() as i32
            );
            interval = interval.inc(PollIntervalLimits::default());
        }

        for _ in 0..100 {
            assert_eq!(
                interval.as_duration().as_seconds_nanos().0,
                interval.as_system_duration().as_secs() as i32
            );
            interval = interval.dec(PollIntervalLimits::default());
        }
    }

    #[test]
    fn frequency_tolerance() {
        assert_eq!(
            NtpDuration::from_seconds(1.0),
            NtpDuration::from_seconds(1.0) * FrequencyTolerance::ppm(1_000_000),
        );
    }
}