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
/// A UTC timestamp
#[derive(Copy, Clone)]
pub struct UtcTimestamp {
    inner: time::OffsetDateTime,
}

impl UtcTimestamp {
    #[inline]
    pub fn now() -> Self {
        Self {
            inner: time::OffsetDateTime::now_utc(),
        }
    }

    /// Gets the current [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time)
    #[inline]
    pub fn unix(self) -> i64 {
        self.inner.unix_timestamp()
    }

    /// Gets the current [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time) in nanoseconds.
    ///
    /// Note we truncate to a 64-bit integer, which will be fine unless someone happens
    /// to be running quilkin in a couple of hundred years
    #[inline]
    pub fn unix_nanos(self) -> i64 {
        self.inner.unix_timestamp_nanos() as _
    }

    #[inline]
    pub fn from_nanos(nanos: i64) -> Self {
        Self {
            inner: time::OffsetDateTime::from_unix_timestamp_nanos(nanos as _)
                .expect("hello future person, apologies"),
        }
    }
}

use std::fmt;

impl fmt::Debug for UtcTimestamp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.inner)
    }
}

#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
#[cfg_attr(test, derive(Debug))]
pub struct DurationNanos(i64);

impl DurationNanos {
    #[inline]
    pub fn from_nanos(n: i64) -> Self {
        Self(n)
    }

    #[inline]
    pub fn nanos(self) -> i64 {
        self.0
    }

    #[inline]
    pub fn duration(self) -> std::time::Duration {
        std::time::Duration::from_nanos(self.0 as _)
    }
}

impl std::ops::Sub for UtcTimestamp {
    type Output = DurationNanos;

    fn sub(self, rhs: Self) -> Self::Output {
        DurationNanos(self.unix_nanos() - rhs.unix_nanos())
    }
}