linux_video_core/impls/
timestamp.rs

1use crate::types::{TimeSpec, TimeVal};
2use core::time::Duration;
3use nix::sys::time::TimeValLike;
4use std::time::SystemTime;
5
6/// Something which can be used as timestamp
7pub trait IsTimestamp {
8    /// Convert from time val
9    fn from_time_val(time_val: TimeVal) -> Self;
10
11    /// Convert from time spec
12    fn from_time_spec(time_spec: TimeSpec) -> Self;
13
14    /// Convert into time val
15    fn into_time_val(self) -> TimeVal;
16
17    /// Convert into time spec
18    fn into_time_spec(self) -> TimeSpec;
19}
20
21impl IsTimestamp for TimeVal {
22    fn from_time_val(time_val: TimeVal) -> Self {
23        time_val
24    }
25
26    fn from_time_spec(time_spec: TimeSpec) -> Self {
27        Self::nanoseconds(time_spec.num_nanoseconds())
28    }
29
30    fn into_time_val(self) -> TimeVal {
31        self
32    }
33
34    fn into_time_spec(self) -> TimeSpec {
35        TimeSpec::nanoseconds(self.num_nanoseconds())
36    }
37}
38
39impl IsTimestamp for Duration {
40    fn from_time_val(time_val: TimeVal) -> Self {
41        Duration::from_micros(time_val.num_microseconds() as _)
42    }
43
44    fn from_time_spec(time_spec: TimeSpec) -> Self {
45        Duration::from_nanos(time_spec.num_nanoseconds() as _)
46    }
47
48    fn into_time_val(self) -> TimeVal {
49        TimeVal::microseconds(self.as_micros() as _)
50    }
51
52    fn into_time_spec(self) -> TimeSpec {
53        TimeSpec::from_duration(self)
54    }
55}
56
57impl IsTimestamp for SystemTime {
58    fn from_time_val(time_val: TimeVal) -> Self {
59        SystemTime::UNIX_EPOCH + Duration::from_time_val(time_val)
60    }
61
62    fn from_time_spec(time_spec: TimeSpec) -> Self {
63        SystemTime::UNIX_EPOCH + Duration::from_time_spec(time_spec)
64    }
65
66    fn into_time_val(self) -> TimeVal {
67        self.duration_since(SystemTime::UNIX_EPOCH)
68            .unwrap()
69            .into_time_val()
70    }
71
72    fn into_time_spec(self) -> TimeSpec {
73        self.duration_since(SystemTime::UNIX_EPOCH)
74            .unwrap()
75            .into_time_spec()
76    }
77}