Skip to main content

v4l/
timestamp.rs

1use std::{fmt, time};
2
3use crate::v4l_sys::*;
4
5#[derive(Debug, Default, Clone, Copy)]
6/// Timestamp consisting of a seconds and a microseconds component
7pub struct Timestamp {
8    pub sec: time_t,
9    pub usec: time_t,
10}
11
12impl Timestamp {
13    /// Returns a timestamp representation
14    ///
15    /// # Arguments
16    ///
17    /// * `sec` - Seconds
18    /// * `usec` - Microseconds
19    ///
20    /// # Example
21    ///
22    /// ```
23    /// use v4l::timestamp::Timestamp;
24    /// let ts = Timestamp::new(5, 5);
25    /// ```
26    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(
59            duration.as_secs() as time_t,
60            duration.subsec_micros() as time_t,
61        )
62    }
63}
64
65impl From<Timestamp> for time::Duration {
66    fn from(ts: Timestamp) -> Self {
67        Self::new(ts.sec as u64, (ts.usec * 1000) as u32)
68    }
69}