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
use humantime::format_rfc3339_nanos;
use std::fmt;
use std::ops::{Add, AddAssign, Sub};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
const MAX_NB_SEC: u64 = (1u64 << 32) - 1;
const FRAC_PER_SEC: u64 = 1u64 << 32;
const FRAC_MASK: u64 = 0xFFFF_FFFFu64;
const NANO_PER_SEC: u64 = 1_000_000_000;
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default)]
pub struct NTP64(pub u64);
impl NTP64 {
#[inline]
pub fn as_u64(&self) -> u64 {
self.0
}
#[inline]
pub fn as_secs(&self) -> u32 {
(self.0 >> 32) as u32
}
#[inline]
pub fn subsec_nanos(&self) -> u32 {
let frac = self.0 & FRAC_MASK;
((frac * NANO_PER_SEC) / FRAC_PER_SEC) as u32
}
#[inline]
pub fn to_duration(&self) -> Duration {
Duration::new(self.as_secs().into(), self.subsec_nanos())
}
#[inline]
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 fmt::Display for NTP64 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", format_rfc3339_nanos(self.to_system_time()))
}
}
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)
}
}