Skip to main content

clack_common/utils/
timestamp.rs

1use std::fmt::{Debug, Display, Formatter};
2use std::num::NonZeroU64;
3use std::time::Duration;
4
5/// A timestamp, defined as the number of seconds since UNIX EPOCH.
6#[derive(Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
7pub struct Timestamp(NonZeroU64);
8
9impl Timestamp {
10    /// Returns the timestamp from its raw, C-FFI compatible representation.
11    ///
12    /// This returns `None` if `raw` is `0`.
13    #[inline]
14    pub const fn from_raw(raw: u64) -> Option<Self> {
15        match NonZeroU64::new(raw) {
16            Some(raw) => Some(Self(raw)),
17            None => None,
18        }
19    }
20
21    /// Returns the number of seconds since EPOCH that this timestamp represents.
22    #[inline]
23    pub const fn seconds_since_epoch(self) -> u64 {
24        self.0.get()
25    }
26
27    /// Returns the duration since EPOCH that this timestamp represents.
28    #[inline]
29    pub fn duration_since_epoch(self) -> Duration {
30        Duration::from_secs(self.0.get())
31    }
32
33    /// Gets the raw, C-FFI representation of a given optional timestamp.
34    ///
35    /// If `timestamp` is `None`, this returns `0`.
36    #[inline]
37    pub fn optional_to_raw(timestamp: Option<Self>) -> u64 {
38        match timestamp {
39            None => 0,
40            Some(t) => t.0.get(),
41        }
42    }
43}
44
45impl Debug for Timestamp {
46    #[inline]
47    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
48        Display::fmt(&self.0.get(), f)
49    }
50}