1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
use serde::{de, ser, Serializer};
use std::{
    fmt,
    time::{Duration, SystemTime, UNIX_EPOCH},
};

/// Represents fractional seconds since the epoch
/// These can be derived from std::time::Duration and be converted
/// too std::time::Duration
///
/// A Default implementation is provided which yields the number of seconds since the epoch from
/// the system time's `now` value
#[derive(Debug, PartialEq)]
pub struct Seconds(pub(crate) f64);

impl Seconds {
    /// return the current time in seconds since the unix epoch (1-1-1970 midnight)
    pub fn now() -> Self {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .into()
    }

    /// truncate epoc time to remove fractional seconds
    pub fn trunc(&self) -> u64 {
        self.0.trunc() as u64
    }
}

impl Default for Seconds {
    fn default() -> Self {
        Seconds::now()
    }
}

impl From<Duration> for Seconds {
    fn from(d: Duration) -> Self {
        Seconds(d.as_secs() as f64 + (f64::from(d.subsec_nanos()) / 1.0e9))
    }
}

impl From<Seconds> for Duration {
    fn from(s: Seconds) -> Self {
        Duration::new(s.0.trunc() as u64, (s.0.fract() * 1.0e9) as u32)
    }
}

struct SecondsVisitor;

impl<'de> de::Visitor<'de> for SecondsVisitor {
    type Value = Seconds;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a string value")
    }
    fn visit_f64<E>(self, value: f64) -> Result<Seconds, E>
    where
        E: de::Error,
    {
        Ok(Seconds(value))
    }
}

impl ser::Serialize for Seconds {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let Seconds(seconds) = self;
        serializer.serialize_f64(*seconds)
    }
}

impl<'de> de::Deserialize<'de> for Seconds {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        deserializer.deserialize_f64(SecondsVisitor)
    }
}

#[cfg(test)]
mod tests {
    use super::Seconds;

    #[test]
    fn seconds_serialize() {
        assert_eq!(
            serde_json::to_string(&Seconds(1_545_136_342.711_932)).expect("failed to serialize"),
            "1545136342.711932"
        );
    }

    #[test]
    fn seconds_deserialize() {
        assert_eq!(
            serde_json::from_slice::<Seconds>(b"1545136342.711932").expect("failed to serialize"),
            Seconds(1_545_136_342.711_932)
        );
    }
}