scsys_core/time/
mod.rs

1/*
2    Appellation: time <module>
3    Contrib: FL03 <jo3mccain@icloud.com>
4*/
5//! # Time
6//!
7//! The `time` module provides a set of utilities for working with time and timestamps.
8#[allow(unused_imports)]
9#[doc(inline)]
10pub use self::{epoch::Epoch, timestamp::Timestamp, utils::*};
11
12#[doc(hidden)]
13pub mod datetime;
14pub mod epoch;
15pub mod timestamp;
16
17pub(crate) mod prelude {
18    pub use super::epoch::Epoch;
19    pub use super::timestamp::Timestamp;
20    #[allow(unused_imports)]
21    pub use super::utils::*;
22    pub use super::Now;
23}
24
25///
26pub trait Now {
27    type Output;
28
29    fn now() -> Self::Output;
30}
31
32pub(crate) mod utils {
33    /// [systime] is a utilitarian function that returns the current system time in milliseconds.
34    #[cfg(feature = "std")]
35    #[inline]
36    pub fn systime() -> core::time::Duration {
37        std::time::SystemTime::now()
38            .duration_since(std::time::UNIX_EPOCH)
39            .unwrap()
40    }
41    /// [systime] is a utilitarian function that returns the current system time in milliseconds.
42    #[cfg(feature = "std")]
43    #[inline]
44    pub fn std_time() -> u128 {
45        std::time::SystemTime::now()
46            .duration_since(std::time::UNIX_EPOCH)
47            .unwrap()
48            .as_millis()
49    }
50}
51
52#[allow(unused)]
53#[cfg(test)]
54mod tests {
55
56    use super::*;
57    use core::time::Duration;
58
59    fn absdiff<A, B, C>(a: A, b: B) -> C
60    where
61        A: PartialOrd<B> + core::ops::Sub<B, Output = C>,
62        B: core::ops::Sub<A, Output = C>,
63    {
64        if a > b {
65            a - b
66        } else {
67            b - a
68        }
69    }
70
71    #[cfg(feature = "std")]
72    #[test]
73    fn test_timestamp() {
74        let now = systime();
75        let ts = Timestamp::<u128>::now();
76
77        let tsd = Duration::from_millis(ts.0 as u64);
78        let diff = absdiff(tsd, now).as_millis();
79        assert!(diff < 1);
80    }
81}