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
670812
#[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
3113423
    pub fn now() -> Self {
23
3113423
        Self::from(SystemTime::now())
24
3113423
    }
25

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

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

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

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

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

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

            
65
114790
    fn add(self, rhs: Duration) -> Self::Output {
66
114790
        let mut nanos = self.nanos + rhs.subsec_nanos();
67
114790
        let mut seconds = self.seconds.saturating_add(rhs.as_secs());
68
229346
        while nanos > 1_000_000_000 {
69
114556
            nanos -= 1_000_000_000;
70
114556
            seconds = seconds.saturating_add(1);
71
114556
        }
72
114790
        Self { seconds, nanos }
73
114790
    }
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
}