falco_event/types/time/
duration.rs

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
use crate::event_derive::{FromBytes, FromBytesResult, ToBytes};
use crate::types::format::Format;
use crate::types::{BorrowDeref, Borrowed};
use byteorder::{NativeEndian, ReadBytesExt};
use std::fmt::Formatter;
use std::io::Write;
use std::time::Duration;

impl FromBytes<'_> for Duration {
    fn from_bytes(buf: &mut &[u8]) -> FromBytesResult<Self>
    where
        Self: Sized,
    {
        Ok(buf.read_u64::<NativeEndian>().map(Self::from_nanos)?)
    }
}

impl ToBytes for Duration {
    fn binary_size(&self) -> usize {
        std::mem::size_of::<u64>()
    }

    fn write<W: Write>(&self, writer: W) -> std::io::Result<()> {
        (self.as_nanos() as u64).write(writer)
    }

    fn default_repr() -> impl ToBytes {
        0u64
    }
}

impl<F> Format<F> for Duration {
    fn format(&self, fmt: &mut Formatter) -> std::fmt::Result {
        std::fmt::Debug::fmt(self, fmt)
    }
}

impl Borrowed for Duration {
    type Owned = Self;
}

impl BorrowDeref for Duration {
    type Target<'a> = Duration;

    fn borrow_deref(&self) -> Self::Target<'_> {
        *self
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    #[test]
    fn test_serde_duration() {
        let duration = Duration::from_nanos(1_234_567_890);
        let json = serde_json::to_string(&duration).unwrap();
        assert_eq!(json, r#"{"secs":1,"nanos":234567890}"#);

        let duration2: Duration = serde_json::from_str(&json).unwrap();
        assert_eq!(duration, duration2);
    }
}