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

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

            
8
use crate::schema::{view::IncorrectByteLength, Key};
9

            
10
/// A timestamp relative to [`UNIX_EPOCH`].
11
943578
#[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
3194926
    pub fn now() -> Self {
23
3194926
        Self::from(SystemTime::now())
24
3194926
    }
25

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

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

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

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

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

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

            
65
1469975
    fn add(self, rhs: Duration) -> Self::Output {
66
1469975
        let mut nanos = self.nanos + rhs.subsec_nanos();
67
1469975
        let mut seconds = self.seconds.saturating_add(rhs.as_secs());
68
2867050
        while nanos > 1_000_000_000 {
69
1397075
            nanos -= 1_000_000_000;
70
1397075
            seconds = seconds.saturating_add(1);
71
1397075
        }
72
1469975
        Self { seconds, nanos }
73
1469975
    }
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_big_endian_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_big_endian_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_big_endian_bytes(&bytes[0..8])?,
93
1
            nanos: u32::from_big_endian_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_big_endian_bytes(&original.as_big_endian_bytes().unwrap()).unwrap(),
103
1
        original
104
1
    );
105
1
}