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
#![no_std]

extern crate x86;

#[allow(unused_imports)]
#[macro_use(info, debug)]
extern crate log;

#[cfg(test)]
extern crate env_logger;

#[macro_use(lazy_static)]
extern crate lazy_static;

use core::fmt;
use core::ops;
pub use core::time::Duration;

#[cfg(all(target_arch = "x86_64", target_os = "none"))]
#[path = "x86_64/mod.rs"]
pub mod arch;

#[cfg(all(target_arch = "x86_64", target_os = "nrk"))]
#[path = "nrk/mod.rs"]
pub mod arch;

#[cfg(all(target_arch = "x86_64", target_os = "redleaf"))]
#[path = "redleaf/mod.rs"]
pub mod arch;

#[cfg(all(target_arch = "x86_64", target_family = "unix"))]
#[path = "unix/mod.rs"]
pub mod arch;

use arch::{precise_time_ns, wallclock};

pub const ONE_GHZ_IN_HZ: u64 = 1_000_000_000;

lazy_static! {
    pub static ref WALL_TIME_ANCHOR: DateTime = wallclock();
    pub static ref BOOT_TIME_ANCHOR: Instant = Instant::now();
}

#[inline]
pub fn duration_since_boot() -> Duration {
    (*BOOT_TIME_ANCHOR).elapsed()
}

#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DateTime {
    pub sec: u8,
    pub min: u8,
    pub hour: u8,
    pub day: u8,
    pub mon: u8,
    pub year: u64,
}

impl DateTime {
    const FEBRUARY: u64 = 2;
    const POSIX_BASE_YEAR: u64 = 1970;
    const SECS_PER_MINUTE: u64 = 60;
    const SECS_PER_HOUR: u64 = 3600;
    const SECS_PER_DAY: u64 = 86400;
    const DAYS_PER_COMMON_YEAR: u64 = 365;
    const DAYS_PER_LEAP_YEAR: u64 = 366;

    fn month_to_days(month: u64) -> u64 {
        match month {
            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
            2 => 28,
            4 | 6 | 9 | 11 => 30,
            _ => !0,
        }
    }

    fn is_leap_year(year: u64) -> bool {
        ((year % 4) == 0 && (year % 100) != 0) || (year % 400) == 0
    }

    fn year_to_days(year: u64) -> u64 {
        if DateTime::is_leap_year(year) {
            DateTime::DAYS_PER_LEAP_YEAR
        } else {
            DateTime::DAYS_PER_COMMON_YEAR
        }
    }

    /// The number of seconds elapsed since Thursday, 1 January 1970, 00:00 UTC
    pub fn as_unix_time(&self) -> u64 {
        let year: u64 = self.year as u64;
        if year < DateTime::POSIX_BASE_YEAR {
            return 0;
        }

        // Years to days
        let mon: u64 = self.mon as u64;
        let mut days = if DateTime::is_leap_year(year) && mon > DateTime::FEBRUARY {
            1
        } else {
            0
        };

        for i in DateTime::POSIX_BASE_YEAR..year {
            days += DateTime::year_to_days(i);
        }

        // Month to days
        for i in 1..self.mon {
            days += DateTime::month_to_days(i as u64);
        }

        // Add days in current month
        days += self.day as u64 - 1;

        // To seconds
        (days * DateTime::SECS_PER_DAY)
            + (self.hour as u64 * DateTime::SECS_PER_HOUR)
            + (self.min as u64 * DateTime::SECS_PER_MINUTE)
            + self.sec as u64
    }
}

impl fmt::Debug for DateTime {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "DateTime {}-{:02}-{:02} {:02}:{:02}:{:02} UTC",
            self.year, self.mon, self.day, self.hour, self.min, self.sec
        )
    }
}

impl fmt::Display for DateTime {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}-{:02}-{:02} {:02}:{:02}:{:02} UTC",
            self.year, self.mon, self.day, self.hour, self.min, self.sec
        )
    }
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Instant(u128);

impl Instant {
    pub fn now() -> Instant {
        Instant(precise_time_ns() as u128)
    }

    pub fn from_nanos(ns: u128) -> Instant {
        Instant(ns)
    }

    pub fn as_nanos(&self) -> u128 {
        self.0
    }

    pub fn duration_since(&self, earlier: Instant) -> Duration {
        if earlier > *self {
            //error!("Second instance is later than self");
            Duration::from_nanos(0 as u64)
        } else {
            Duration::from_nanos((self.0 - earlier.0) as u64)
        }
    }

    pub fn elapsed(&self) -> Duration {
        Instant::now() - *self
    }
}

impl ops::Add<Duration> for Instant {
    type Output = Instant;

    fn add(self, other: Duration) -> Instant {
        Instant(self.0 + other.as_nanos())
    }
}

impl ops::AddAssign<Duration> for Instant {
    fn add_assign(&mut self, other: Duration) {
        *self = *self + other;
    }
}

impl ops::Sub<Duration> for Instant {
    type Output = Instant;

    fn sub(self, other: Duration) -> Instant {
        Instant(self.0 - other.as_nanos())
    }
}

impl ops::Sub<Instant> for Instant {
    type Output = Duration;

    fn sub(self, other: Instant) -> Duration {
        self.duration_since(other)
    }
}

impl ops::SubAssign<Duration> for Instant {
    fn sub_assign(&mut self, other: Duration) {
        *self = *self - other;
    }
}

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

#[test]
fn wait_one_sec() {
    //env_logger::init();
    assert!(*arch::tsc::TSC_FREQUENCY > 0);
    //debug!("{}", *arch::tsc::TSC_FREQUENCY);

    let time1 = duration_since_boot();
    let now = Instant::now();
    while now.elapsed().as_secs() < 1 {}
    let time2 = duration_since_boot();

    let range: core::ops::Range<u128> = 999..1100;
    assert!(
        range.contains(&(time2 - time1).as_millis()),
        "Less than one second apart."
    );
}