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
//
// Copyright (c) 2017, 2020 ADLINK Technology Inc.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
//
use alloc::string::String;
use core::fmt;
use core::ops::{Add, AddAssign, Sub, SubAssign};
use core::time::Duration;
use serde::{Deserialize, Serialize};

#[cfg(feature = "std")]
use {
    core::str::FromStr,
    humantime::{format_rfc3339_nanos, parse_rfc3339},
    std::time::{SystemTime, UNIX_EPOCH},
};

// maximal number of seconds that can be represented in the 32-bits part
const MAX_NB_SEC: u64 = (1u64 << 32) - 1;
// number of NTP fraction per second (2^32)
const FRAC_PER_SEC: u64 = 1u64 << 32;
// Bit-mask for the fraction of a second part within an NTP timestamp
const FRAC_MASK: u64 = 0xFFFF_FFFFu64;

// number of nanoseconds in 1 second
const NANO_PER_SEC: u64 = 1_000_000_000;

/// A NTP 64-bits format as specified in
/// [RFC-5909](https://tools.ietf.org/html/rfc5905#section-6)
///
/// ```text
/// 0                   1                   2                   3
/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                            Seconds                            |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |                            Fraction                           |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// ```
///
/// The 1st 32-bits part is the number of second since the EPOCH of the physical clock,
/// and the 2nd 32-bits part is the fraction of second.  
/// In case it's part of a [`crate::Timestamp`] generated by an [`crate::HLC`] the last few bits
/// of the Fraction part are replaced by the HLC logical counter.
/// The size of this counter currently hard-coded as [`crate::CSIZE`].
///
/// Note that this timestamp in actually similar to a [`std::time::Duration`], as it doesn't
/// define an EPOCH. Only the [`NTP64::to_system_time()`] and [`std::fmt::Display::fmt()`] operations assume that
/// it's relative to UNIX_EPOCH (1st Jan 1970) to display the timpestamp in RFC-3339 format.
#[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct NTP64(pub u64);

impl NTP64 {
    /// Returns this NTP64 as a u64.
    #[inline]
    pub fn as_u64(&self) -> u64 {
        self.0
    }

    /// Returns this NTP64 as a f64 in seconds.
    ///
    /// The integer part of the f64 is the NTP64's Seconds part.  
    /// The decimal part of the f64 is the result of a division of NTP64's Fraction part divided by 2^32.  
    /// Considering the probable large number of Seconds (for a time relative to UNIX_EPOCH), the precision of the resulting f64 might be in the order of microseconds.
    /// Therefore, it should not be used for comparison. Directly comparing [NTP64] objects is preferable.
    #[inline]
    pub fn as_secs_f64(&self) -> f64 {
        let secs: f64 = self.as_secs() as f64;
        let subsec: f64 = ((self.0 & FRAC_MASK) as f64) / FRAC_PER_SEC as f64;
        secs + subsec
    }

    /// Returns the 32-bits seconds part.
    #[inline]
    pub fn as_secs(&self) -> u32 {
        (self.0 >> 32) as u32
    }

    /// Returns the 32-bits fraction of second part converted to nanoseconds.
    #[inline]
    pub fn subsec_nanos(&self) -> u32 {
        let frac = self.0 & FRAC_MASK;
        ((frac * NANO_PER_SEC) / FRAC_PER_SEC) as u32
    }

    /// Convert to a [`Duration`].
    #[inline]
    pub fn to_duration(self) -> Duration {
        Duration::new(self.as_secs().into(), self.subsec_nanos())
    }

    /// Convert to a [`SystemTime`] (making the assumption that this NTP64 is relative to [`UNIX_EPOCH`]).
    #[inline]
    #[cfg(feature = "std")]
    pub fn to_system_time(self) -> SystemTime {
        UNIX_EPOCH + self.to_duration()
    }
}

impl Add for NTP64 {
    type Output = Self;

    #[inline]
    fn add(self, other: Self) -> Self {
        Self(self.0 + other.0)
    }
}

impl<'a> Add<NTP64> for &'a NTP64 {
    type Output = <NTP64 as Add<NTP64>>::Output;

    #[inline]
    fn add(self, other: NTP64) -> <NTP64 as Add<NTP64>>::Output {
        Add::add(*self, other)
    }
}

impl Add<&NTP64> for NTP64 {
    type Output = <NTP64 as Add<NTP64>>::Output;

    #[inline]
    fn add(self, other: &NTP64) -> <NTP64 as Add<NTP64>>::Output {
        Add::add(self, *other)
    }
}

impl Add<&NTP64> for &NTP64 {
    type Output = <NTP64 as Add<NTP64>>::Output;

    #[inline]
    fn add(self, other: &NTP64) -> <NTP64 as Add<NTP64>>::Output {
        Add::add(*self, *other)
    }
}

impl Add<u64> for NTP64 {
    type Output = Self;

    #[inline]
    fn add(self, other: u64) -> Self {
        Self(self.0 + other)
    }
}

impl AddAssign<u64> for NTP64 {
    #[inline]
    fn add_assign(&mut self, other: u64) {
        *self = Self(self.0 + other);
    }
}

impl Sub for NTP64 {
    type Output = Self;

    #[inline]
    fn sub(self, other: Self) -> Self {
        Self(self.0 - other.0)
    }
}

impl<'a> Sub<NTP64> for &'a NTP64 {
    type Output = <NTP64 as Sub<NTP64>>::Output;

    #[inline]
    fn sub(self, other: NTP64) -> <NTP64 as Sub<NTP64>>::Output {
        Sub::sub(*self, other)
    }
}

impl Sub<&NTP64> for NTP64 {
    type Output = <NTP64 as Sub<NTP64>>::Output;

    #[inline]
    fn sub(self, other: &NTP64) -> <NTP64 as Sub<NTP64>>::Output {
        Sub::sub(self, *other)
    }
}

impl Sub<&NTP64> for &NTP64 {
    type Output = <NTP64 as Sub<NTP64>>::Output;

    #[inline]
    fn sub(self, other: &NTP64) -> <NTP64 as Sub<NTP64>>::Output {
        Sub::sub(*self, *other)
    }
}

impl Sub<u64> for NTP64 {
    type Output = Self;

    #[inline]
    fn sub(self, other: u64) -> Self {
        Self(self.0 - other)
    }
}

impl SubAssign<u64> for NTP64 {
    #[inline]
    fn sub_assign(&mut self, other: u64) {
        *self = Self(self.0 - other);
    }
}

impl fmt::Display for NTP64 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        #[cfg(feature = "std")]
        return write!(f, "{}", format_rfc3339_nanos(self.to_system_time()));
        #[cfg(not(feature = "std"))]
        return write!(f, "{:x}", self.0);
    }
}

impl fmt::Debug for NTP64 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:x}", self.0)
    }
}

impl From<Duration> for NTP64 {
    fn from(duration: Duration) -> NTP64 {
        let secs = duration.as_secs();
        assert!(secs <= MAX_NB_SEC);
        let nanos: u64 = duration.subsec_nanos().into();
        NTP64((secs << 32) + ((nanos * FRAC_PER_SEC) / NANO_PER_SEC) + 1)
    }
}

#[cfg(feature = "std")]
impl FromStr for NTP64 {
    type Err = ParseNTP64Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        parse_rfc3339(s)
            .map_err(|e| ParseNTP64Error {
                cause: e.to_string(),
            })
            .and_then(|time| {
                time.duration_since(UNIX_EPOCH)
                    .map_err(|e| ParseNTP64Error {
                        cause: e.to_string(),
                    })
            })
            .map(NTP64::from)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct ParseNTP64Error {
    pub cause: String,
}

mod tests {

    #[test]
    fn as_secs_f64() {
        use crate::*;

        let epoch = NTP64::default();
        assert_eq!(epoch.as_secs_f64(), 0f64);

        let epoch_plus_1 = NTP64(1);
        assert!(epoch_plus_1 > epoch);
        assert!(epoch_plus_1.as_secs_f64() > epoch.as_secs_f64());

        // test that Timestamp precision is less than announced (3.5ns) in README.md
        let epoch_plus_counter_max = NTP64(CMASK);
        println!(
            "Time precision = {} ns",
            epoch_plus_counter_max.as_secs_f64() * (ntp64::NANO_PER_SEC as f64)
        );
        assert!(epoch_plus_counter_max.as_secs_f64() < 0.0000000035f64);
    }
}