1use core::{
6 fmt::Debug,
7 ops::{Add, Sub},
8 time::Duration,
9};
10
11#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
14pub struct Instant(Duration);
15
16impl Debug for Instant {
17 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
18 if *self >= Instant::reference() {
19 f.debug_tuple("Instant")
20 .field(&(self.duration_since(Instant::reference())))
21 .field(&"after reference point")
22 .finish()
23 } else {
24 f.debug_tuple("Instant")
25 .field(&(Instant::reference().duration_since(*self)))
26 .field(&"before reference point")
27 .finish()
28 }
29 }
30}
31
32impl Instant {
33 pub const fn reference() -> Instant {
40 Instant(Duration::from_secs(u64::MAX / 2))
41 }
42
43 pub fn duration_since(self, past_instant: Instant) -> Option<Duration> {
47 if self.0 >= past_instant.0 {
48 Some(self.0 - past_instant.0)
49 } else {
50 None
51 }
52 }
53}
54
55impl Sub<Duration> for Instant {
56 type Output = Instant;
57 fn sub(self, rhs: Duration) -> Self::Output {
58 Instant(self.0 - rhs)
59 }
60}
61
62impl Add<Duration> for Instant {
63 type Output = Instant;
64 fn add(self, rhs: Duration) -> Self::Output {
65 Instant(self.0 + rhs)
66 }
67}