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
75
76
/*
    Appellation: timestamp <module>
    Contrib: FL03 <jo3mccain@icloud.com>
*/
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::ops::Deref;

/// Timestamp implements a host of useful utilities for stamping data
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize,))]
#[repr(transparent)]
pub struct Timestamp(u128);

impl Timestamp {
    /// Create a new timestamp
    pub fn now() -> Self {
        Self(crate::time::systime())
    }

    pub const fn timestamp(&self) -> u128 {
        self.0
    }
}

impl AsRef<u128> for Timestamp {
    fn as_ref(&self) -> &u128 {
        &self.0
    }
}

impl Default for Timestamp {
    fn default() -> Self {
        Self::now()
    }
}

impl Deref for Timestamp {
    type Target = u128;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::fmt::Display for Timestamp {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<u128> for Timestamp {
    fn from(timestamp: u128) -> Self {
        Self(timestamp)
    }
}

impl From<Timestamp> for u128 {
    fn from(timestamp: Timestamp) -> Self {
        timestamp.0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_timestamp() {
        let a = Timestamp::now();
        std::thread::sleep(std::time::Duration::from_secs(1));
        let b = Timestamp::now();
        assert_ne!(a, b);
        assert!(a < b);
    }
}