midenc_log/fmt/
humantime.rs1use std::{fmt, time::SystemTime};
2
3use crate::fmt::{Formatter, TimestampPrecision};
4
5impl Formatter {
6 pub fn timestamp(&self) -> Timestamp {
24 Timestamp {
25 time: SystemTime::now(),
26 precision: TimestampPrecision::Seconds,
27 }
28 }
29
30 pub fn timestamp_seconds(&self) -> Timestamp {
33 Timestamp {
34 time: SystemTime::now(),
35 precision: TimestampPrecision::Seconds,
36 }
37 }
38
39 pub fn timestamp_millis(&self) -> Timestamp {
42 Timestamp {
43 time: SystemTime::now(),
44 precision: TimestampPrecision::Millis,
45 }
46 }
47
48 pub fn timestamp_micros(&self) -> Timestamp {
51 Timestamp {
52 time: SystemTime::now(),
53 precision: TimestampPrecision::Micros,
54 }
55 }
56
57 pub fn timestamp_nanos(&self) -> Timestamp {
60 Timestamp {
61 time: SystemTime::now(),
62 precision: TimestampPrecision::Nanos,
63 }
64 }
65}
66
67pub struct Timestamp {
74 time: SystemTime,
75 precision: TimestampPrecision,
76}
77
78impl fmt::Debug for Timestamp {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 struct TimestampValue<'a>(&'a Timestamp);
82
83 impl fmt::Debug for TimestampValue<'_> {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 fmt::Display::fmt(&self.0, f)
86 }
87 }
88
89 f.debug_tuple("Timestamp").field(&TimestampValue(self)).finish()
90 }
91}
92
93impl fmt::Display for Timestamp {
94 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95 let Ok(ts) = jiff::Timestamp::try_from(self.time) else {
96 return Err(fmt::Error);
97 };
98
99 match self.precision {
100 TimestampPrecision::Seconds => write!(f, "{ts:.0}"),
101 TimestampPrecision::Millis => write!(f, "{ts:.3}"),
102 TimestampPrecision::Micros => write!(f, "{ts:.6}"),
103 TimestampPrecision::Nanos => write!(f, "{ts:.9}"),
104 }
105 }
106}
107
108#[cfg(test)]
109mod tests {
110 use super::Timestamp;
111 use crate::TimestampPrecision;
112
113 #[test]
114 fn test_display_timestamp() {
115 let mut ts = Timestamp {
116 time: std::time::SystemTime::UNIX_EPOCH,
117 precision: TimestampPrecision::Nanos,
118 };
119
120 assert_eq!("1970-01-01T00:00:00.000000000Z", format!("{ts}"));
121
122 ts.precision = TimestampPrecision::Micros;
123 assert_eq!("1970-01-01T00:00:00.000000Z", format!("{ts}"));
124
125 ts.precision = TimestampPrecision::Millis;
126 assert_eq!("1970-01-01T00:00:00.000Z", format!("{ts}"));
127
128 ts.precision = TimestampPrecision::Seconds;
129 assert_eq!("1970-01-01T00:00:00Z", format!("{ts}"));
130 }
131}