1
use std::{
2
    borrow::Cow,
3
    time::{Duration, SystemTime, UNIX_EPOCH},
4
};
5

            
6
use serde::{Deserialize, Serialize};
7

            
8
use crate::key::{IncorrectByteLength, Key};
9

            
10
/// A timestamp relative to [`UNIX_EPOCH`].
11
751611
#[derive(Serialize, Deserialize, Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Default)]
12
pub struct Timestamp {
13
    /// The number of whole seconds since [`UNIX_EPOCH`].
14
    pub seconds: u64,
15
    /// The number of nanoseconds in the timestamp.
16
    pub nanos: u32,
17
}
18

            
19
impl Timestamp {
20
    /// Returns the current timestamp according to the OS. Uses [`SystemTime::now()`].
21
    #[must_use]
22
3136429
    pub fn now() -> Self {
23
3136429
        Self::from(SystemTime::now())
24
3136429
    }
25

            
26
    /// Returns the maximum value for this type.
27
    #[must_use]
28
1525068
    pub const fn max() -> Self {
29
1525068
        Self {
30
1525068
            seconds: u64::MAX,
31
1525068
            nanos: 999_999_999,
32
1525068
        }
33
1525068
    }
34
}
35

            
36
impl From<SystemTime> for Timestamp {
37
3137320
    fn from(time: SystemTime) -> Self {
38
3137320
        let duration_since_epoch = time
39
3137320
            .duration_since(UNIX_EPOCH)
40
3137320
            .expect("unrealistic system time");
41
3137320
        Self {
42
3137320
            seconds: duration_since_epoch.as_secs(),
43
3137320
            nanos: duration_since_epoch.subsec_nanos(),
44
3137320
        }
45
3137320
    }
46
}
47

            
48
impl From<Timestamp> for Duration {
49
612738
    fn from(t: Timestamp) -> Self {
50
612738
        Self::new(t.seconds, t.nanos)
51
612738
    }
52
}
53

            
54
impl std::ops::Sub for Timestamp {
55
    type Output = Option<Duration>;
56

            
57
306369
    fn sub(self, rhs: Self) -> Self::Output {
58
306369
        Duration::from(self).checked_sub(Duration::from(rhs))
59
306369
    }
60
}
61

            
62
impl std::ops::Add<Duration> for Timestamp {
63
    type Output = Self;
64

            
65
63396
    fn add(self, rhs: Duration) -> Self::Output {
66
63396
        let mut nanos = self.nanos + rhs.subsec_nanos();
67
63396
        let mut seconds = self.seconds.saturating_add(rhs.as_secs());
68
126549
        while nanos > 1_000_000_000 {
69
63153
            nanos -= 1_000_000_000;
70
63153
            seconds = seconds.saturating_add(1);
71
63153
        }
72
63396
        Self { seconds, nanos }
73
63396
    }
74
}
75

            
76
impl<'a> Key<'a> for Timestamp {
77
    type Error = IncorrectByteLength;
78
    const LENGTH: Option<usize> = Some(12);
79

            
80
1
    fn as_ord_bytes(&'a self) -> Result<std::borrow::Cow<'a, [u8]>, Self::Error> {
81
1
        let seconds_bytes: &[u8] = &self.seconds.to_be_bytes();
82
1
        let nanos_bytes = &self.nanos.to_be_bytes();
83
1
        Ok(Cow::Owned([seconds_bytes, nanos_bytes].concat()))
84
1
    }
85

            
86
1
    fn from_ord_bytes(bytes: &'a [u8]) -> Result<Self, Self::Error> {
87
1
        if bytes.len() != 12 {
88
            return Err(IncorrectByteLength);
89
1
        }
90
1

            
91
1
        Ok(Self {
92
1
            seconds: u64::from_ord_bytes(&bytes[0..8])?,
93
1
            nanos: u32::from_ord_bytes(&bytes[8..12])?,
94
        })
95
1
    }
96
}
97

            
98
1
#[test]
99
1
fn key_test() {
100
1
    let original = Timestamp::now();
101
1
    assert_eq!(
102
1
        Timestamp::from_ord_bytes(&original.as_ord_bytes().unwrap()).unwrap(),
103
1
        original
104
1
    );
105
1
}