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, KeyEncoding};
9

            
10
/// A timestamp relative to [`UNIX_EPOCH`].
11
1241216
#[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
    /// The minimum representable Timestamp. This is equivalent to [`UNIX_EPOCH`].
21
    pub const MIN: Self = Self {
22
        seconds: 0,
23
        nanos: 0,
24
    };
25

            
26
    /// The maximum valid value of Timestamp.
27
    pub const MAX: Self = Self {
28
        seconds: u64::MAX,
29
        nanos: 999_999_999,
30
    };
31

            
32
    /// Returns the current timestamp according to the OS. Uses [`SystemTime::now()`].
33
    #[must_use]
34
5557185
    pub fn now() -> Self {
35
5557185
        Self::from(SystemTime::now())
36
5557185
    }
37
}
38

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

            
51
impl From<Timestamp> for Duration {
52
421786
    fn from(t: Timestamp) -> Self {
53
421786
        Self::new(t.seconds, t.nanos)
54
421786
    }
55
}
56

            
57
impl std::ops::Sub for Timestamp {
58
    type Output = Option<Duration>;
59

            
60
210893
    fn sub(self, rhs: Self) -> Self::Output {
61
210893
        Duration::from(self).checked_sub(Duration::from(rhs))
62
210893
    }
63
}
64

            
65
impl std::ops::Add<Duration> for Timestamp {
66
    type Output = Self;
67

            
68
90241
    fn add(self, rhs: Duration) -> Self::Output {
69
90241
        let mut nanos = self.nanos + rhs.subsec_nanos();
70
90241
        let mut seconds = self.seconds.saturating_add(rhs.as_secs());
71
90303
        while nanos > 1_000_000_000 {
72
62
            nanos -= 1_000_000_000;
73
62
            seconds = seconds.saturating_add(1);
74
62
        }
75
90241
        Self { seconds, nanos }
76
90241
    }
77
}
78

            
79
impl<'a> Key<'a> for Timestamp {
80
1
    fn from_ord_bytes(bytes: &'a [u8]) -> Result<Self, Self::Error> {
81
1
        if bytes.len() != 12 {
82
            return Err(IncorrectByteLength);
83
1
        }
84
1

            
85
1
        Ok(Self {
86
1
            seconds: u64::from_ord_bytes(&bytes[0..8])?,
87
1
            nanos: u32::from_ord_bytes(&bytes[8..12])?,
88
        })
89
1
    }
90
}
91

            
92
impl<'a> KeyEncoding<'a, Self> for Timestamp {
93
    type Error = IncorrectByteLength;
94

            
95
    const LENGTH: Option<usize> = Some(12);
96

            
97
1
    fn as_ord_bytes(&'a self) -> Result<std::borrow::Cow<'a, [u8]>, Self::Error> {
98
1
        let seconds_bytes: &[u8] = &self.seconds.to_be_bytes();
99
1
        let nanos_bytes = &self.nanos.to_be_bytes();
100
1
        Ok(Cow::Owned([seconds_bytes, nanos_bytes].concat()))
101
1
    }
102
}
103

            
104
1
#[test]
105
1
fn key_test() {
106
1
    let original = Timestamp::now();
107
1
    assert_eq!(
108
1
        Timestamp::from_ord_bytes(&original.as_ord_bytes().unwrap()).unwrap(),
109
1
        original
110
1
    );
111
1
}