timber_rust/config/
timestamp.rs

1use serde::{Deserialize, Serialize};
2use std::time::{Duration, SystemTime};
3
4#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
5pub enum Timestamp {
6    Seconds(u64),
7    DecimalSeconds(f64),
8    SecondsNanoseconds(u64, u32),
9}
10
11impl From<SystemTime> for Timestamp {
12    fn from(t: SystemTime) -> Self {
13        let duration = t
14            .duration_since(SystemTime::UNIX_EPOCH)
15            .expect("SystemTime before UNIX EPOCH!");
16        Timestamp::from(duration)
17    }
18}
19
20impl From<Timestamp> for SystemTime {
21    fn from(value: Timestamp) -> Self {
22        let duration = Duration::from(value);
23        let time = SystemTime::UNIX_EPOCH;
24        time + duration
25    }
26}
27
28impl From<Timestamp> for Duration {
29    fn from(value: Timestamp) -> Self {
30        match value {
31            Timestamp::Seconds(seconds) => Duration::new(seconds, 0),
32            Timestamp::DecimalSeconds(seconds) => {
33                let secs = seconds.floor() as u64;
34                let nsecs = (seconds.fract() * 1e9) as u32;
35                Duration::new(secs, nsecs)
36            }
37            Timestamp::SecondsNanoseconds(secs, nsecs) => Duration::new(secs, nsecs),
38        }
39    }
40}
41
42impl From<Duration> for Timestamp {
43    fn from(value: Duration) -> Self {
44        Timestamp::SecondsNanoseconds(value.as_secs(), value.subsec_nanos())
45    }
46}