1use std::{fmt, time};
2
3use libc::{time_t, timeval};
4
5#[derive(Debug, Default, Clone, Copy)]
6pub struct Timestamp {
8 pub sec: time_t,
9 pub usec: time_t,
10}
11
12impl Timestamp {
13 pub fn new(sec: time_t, usec: time_t) -> Self {
27 Timestamp { sec, usec }
28 }
29}
30
31impl fmt::Display for Timestamp {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 let floating: f64 = self.sec as f64 + self.usec as f64 / 1_000_000.0;
34 write!(f, "{} [s]", floating)
35 }
36}
37
38impl From<timeval> for Timestamp {
39 fn from(tv: timeval) -> Self {
40 Self {
41 sec: tv.tv_sec as time_t,
42 usec: tv.tv_usec as time_t,
43 }
44 }
45}
46
47impl From<Timestamp> for timeval {
48 fn from(timestamp: Timestamp) -> Self {
49 Self {
50 tv_sec: timestamp.sec as time_t,
51 tv_usec: timestamp.usec as time_t,
52 }
53 }
54}
55
56impl From<time::Duration> for Timestamp {
57 fn from(duration: time::Duration) -> Self {
58 Self::new(duration.as_secs() as time_t, duration.subsec_micros() as time_t)
59 }
60}
61
62impl From<Timestamp> for time::Duration {
63 fn from(ts: Timestamp) -> Self {
64 Self::new(ts.sec as u64, (ts.usec * 1000) as u32)
65 }
66}