Skip to main content

use_event_timestamp/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use std::time::SystemTime;
5
6#[derive(Clone, Copy, Debug, Eq, PartialEq)]
7pub struct EventTimestamp(SystemTime);
8
9impl EventTimestamp {
10    pub fn now() -> Self {
11        Self(SystemTime::now())
12    }
13
14    pub fn from_system_time(value: SystemTime) -> Self {
15        Self(value)
16    }
17
18    pub const fn as_system_time(&self) -> SystemTime {
19        self.0
20    }
21}
22
23impl Default for EventTimestamp {
24    fn default() -> Self {
25        Self::now()
26    }
27}
28
29#[cfg(test)]
30mod tests {
31    use super::EventTimestamp;
32    use std::time::{Duration, SystemTime};
33
34    #[test]
35    fn wraps_system_time() {
36        let timestamp = EventTimestamp::from_system_time(SystemTime::UNIX_EPOCH);
37
38        assert_eq!(timestamp.as_system_time(), SystemTime::UNIX_EPOCH);
39    }
40
41    #[test]
42    fn creates_current_timestamp_by_default() {
43        let timestamp = EventTimestamp::default();
44
45        assert!(timestamp.as_system_time() >= SystemTime::UNIX_EPOCH);
46    }
47
48    #[test]
49    fn preserves_precise_system_time() {
50        let value = SystemTime::UNIX_EPOCH + Duration::from_secs(5);
51        let timestamp = EventTimestamp::from_system_time(value);
52
53        assert_eq!(timestamp.as_system_time(), value);
54    }
55}