1use core::{
4 self,
5 cmp::{Ord, Ordering, PartialOrd},
6 ops::{Add, Sub},
7 time::Duration,
8};
9
10#[derive(Eq, PartialEq, PartialOrd, Copy, Clone, Default)]
13pub struct Instant {
14 count_ns: i128,
16 }
18
19impl Instant {
23 pub(crate) fn new(count_ns: i128) -> Self {
24 Self { count_ns }
25 }
26
27 pub fn as_secs(&self) -> f32 {
29 self.count_ns as f32 / 1_000_000_000.
30 }
31
32 pub fn as_millis(&self) -> u32 {
34 (self.count_ns / 1_000_000) as u32
35 }
36
37 pub fn as_millis_f32(&self) -> f32 {
39 self.count_ns as f32 / 1_000_000.
40 }
41
42 pub fn as_micros(&self) -> u64 {
44 (self.count_ns / 1_000) as u64
45 }
46
47 pub fn as_nanos(&self) -> u128 {
49 self.count_ns as u128
50 }
51}
52
53impl Ord for Instant {
54 fn cmp(&self, other: &Self) -> Ordering {
55 self.count_ns.cmp(&other.count_ns)
57 }
58}
59
60impl Add<Duration> for Instant {
61 type Output = Self;
62
63 fn add(self, rhs: Duration) -> Self::Output {
64 Self {
65 count_ns: self.count_ns + rhs.as_nanos() as i128,
66 }
67 }
68}
69
70impl Sub<Duration> for Instant {
71 type Output = Self;
72
73 fn sub(self, rhs: Duration) -> Self::Output {
74 Self {
75 count_ns: self.count_ns - rhs.as_nanos() as i128,
76 }
77 }
78}
79
80impl Sub<Self> for Instant {
81 type Output = Duration;
82
83 fn sub(self, rhs: Self) -> Self::Output {
84 Duration::from_nanos((self.count_ns - rhs.count_ns) as u64)
86 }
87}