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 #[inline]
15 fn from(system_time: std::time::SystemTime) -> Self {
16 Self(system_time.duration_since(UNIX_EPOCH).unwrap().as_nanos() as u64)
17 }
18}
19
20impl SystemTime {
21 #[inline]
23 pub fn to_system_time(&self) -> std::time::SystemTime {
24 let duration = Duration::from_nanos(self.0);
25 UNIX_EPOCH + duration
26 }
27}
28
29impl FromBytes<'_> for SystemTime {
30 #[inline]
31 fn from_bytes(buf: &mut &[u8]) -> Result<Self, FromBytesError>
32 where
33 Self: Sized,
34 {
35 let nanos = u64::from_bytes(buf)?;
36 Ok(Self(nanos))
37 }
38}
39
40impl ToBytes for SystemTime {
41 #[inline]
42 fn binary_size(&self) -> usize {
43 std::mem::size_of::<u64>()
44 }
45
46 #[inline]
47 fn write<W: Write>(&self, writer: W) -> std::io::Result<()> {
48 self.0.write(writer)
49 }
50
51 #[inline]
52 fn default_repr() -> impl ToBytes {
53 0u64
54 }
55}
56
57impl std::fmt::Debug for SystemTime {
58 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59 let dt = chrono::DateTime::<Local>::from(self.to_system_time());
60 f.write_str(&dt.to_rfc3339_opts(chrono::SecondsFormat::AutoSi, false))
61 }
62}