1use std::time::{Instant, SystemTime, UNIX_EPOCH};
2
3pub struct TimePivot {
4 instant: Instant,
5 time_us: u64,
6}
7
8impl TimePivot {
9 pub fn build() -> Self {
10 let start = SystemTime::now();
11 let since_the_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards");
12
13 Self {
14 instant: Instant::now(),
15 time_us: since_the_epoch.as_micros() as u64,
16 }
17 }
18
19 pub fn started_ms(&self) -> u64 {
20 self.time_us / 1000
21 }
22
23 pub fn timestamp_ms(&self, now: Instant) -> u64 {
24 self.time_us / 1000 + now.duration_since(self.instant).as_millis() as u64
25 }
26
27 pub fn started_us(&self) -> u64 {
28 self.time_us
29 }
30
31 pub fn timestamp_us(&self, now: Instant) -> u64 {
32 self.time_us + now.duration_since(self.instant).as_micros() as u64
33 }
34}
35
36pub struct TimeTicker {
37 last_tick: Instant,
38 tick_ms: u64,
39}
40
41impl TimeTicker {
42 pub fn build(tick_ms: u64) -> Self {
43 Self { last_tick: Instant::now(), tick_ms }
44 }
45
46 pub fn tick(&mut self, now: Instant) -> bool {
47 if now.duration_since(self.last_tick).as_millis() as u64 >= self.tick_ms {
48 self.last_tick = now;
49 true
50 } else {
51 false
52 }
53 }
54}