scsys_time/timestamp.rs
1/*
2 Appellation: timestamp <module>
3 Contrib: FL03 <jo3mccain@icloud.com>
4*/
5mod impl_timestamp;
6mod impl_timestamp_repr;
7
8#[allow(deprecated)]
9mod impl_deprecated;
10
11/// [`Timestamp`] is a generic implementation of a type that represents some point in time.
12///
13/// ## Basic Usage
14///
15/// ```rust
16/// use scsys_time::Timestamp;
17///
18/// let ts = Timestamp::<u128>::now();
19/// println!("Current Timestamp: {}", ts);
20/// ```
21///
22/// ## Features
23///
24/// The timestamps implementation dynamically reflects the extensive feature-gating of the
25/// crate. Listed below are the features that customize the behavior of the [`Timestamp`] type:
26///
27/// - `serde`: Enables serialization and deserialization of the [`Timestamp`] type.
28///
29/// - `chrono`: Enables support for `chrono` timestamps, uses [`i64`] for the [Now] impl
30/// - `std`: Enables the use of system time for the default implementation of:
31/// - `Timestamp<u64>`: for seconds
32/// - `Timestamp<u128>`: for milliseconds
33///
34#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
35#[cfg_attr(
36 feature = "serde",
37 derive(serde::Deserialize, serde::Serialize),
38 serde(transparent)
39)]
40#[repr(transparent)]
41pub struct Timestamp<T = u128>(pub T);
42
43/*
44 ************* Implementations *************
45*/
46
47impl From<core::time::Duration> for Timestamp<u64> {
48 fn from(dur: core::time::Duration) -> Self {
49 Self(dur.as_secs())
50 }
51}
52
53impl From<core::time::Duration> for Timestamp<u128> {
54 fn from(dur: core::time::Duration) -> Self {
55 Self(dur.as_millis())
56 }
57}
58
59impl From<Timestamp<u64>> for core::time::Duration {
60 fn from(ts: Timestamp<u64>) -> Self {
61 Self::from_secs(*ts)
62 }
63}
64
65impl From<Timestamp<u128>> for core::time::Duration {
66 fn from(ts: Timestamp<u128>) -> Self {
67 Self::from_millis(*ts as u64)
68 }
69}
70
71#[cfg(feature = "chrono")]
72impl<Tz> From<chrono::DateTime<Tz>> for Timestamp<i64>
73where
74 Tz: chrono::TimeZone,
75{
76 fn from(ts: chrono::DateTime<Tz>) -> Self {
77 Self(ts.timestamp())
78 }
79}