falco_event/types/time/
system_time.rs1use crate::fields::{FromBytes, FromBytesError, ToBytes};
2use chrono::Local;
3use std::io::Write;
4use std::time::{Duration, UNIX_EPOCH};
5
6#[derive(Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
10pub struct SystemTime(pub u64);
11
12impl From<std::time::SystemTime> for SystemTime {
13 fn from(system_time: std::time::SystemTime) -> Self {
14 Self(system_time.duration_since(UNIX_EPOCH).unwrap().as_nanos() as u64)
15 }
16}
17
18impl SystemTime {
19 pub fn to_system_time(&self) -> std::time::SystemTime {
21 let duration = Duration::from_nanos(self.0);
22 UNIX_EPOCH + duration
23 }
24}
25
26impl FromBytes<'_> for SystemTime {
27 #[inline]
28 fn from_bytes(buf: &mut &[u8]) -> Result<Self, FromBytesError>
29 where
30 Self: Sized,
31 {
32 let nanos = u64::from_bytes(buf)?;
33 Ok(Self(nanos))
34 }
35}
36
37impl ToBytes for SystemTime {
38 #[inline]
39 fn binary_size(&self) -> usize {
40 std::mem::size_of::<u64>()
41 }
42
43 #[inline]
44 fn write<W: Write>(&self, writer: W) -> std::io::Result<()> {
45 self.0.write(writer)
46 }
47
48 #[inline]
49 fn default_repr() -> impl ToBytes {
50 0u64
51 }
52}
53
54impl std::fmt::Debug for SystemTime {
55 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56 let dt = chrono::DateTime::<Local>::from(self.to_system_time());
57 f.write_str(&dt.to_rfc3339_opts(chrono::SecondsFormat::AutoSi, false))
58 }
59}