tg_syscall/
time.rs

1//! see <https://github.com/torvalds/linux/blob/master/include/uapi/linux/time.h>.
2
3#[derive(Clone, Copy, PartialEq, Eq, Debug)]
4#[repr(transparent)]
5pub struct ClockId(pub usize);
6
7impl ClockId {
8    pub const CLOCK_REALTIME: Self = Self(0);
9    pub const CLOCK_MONOTONIC: Self = Self(1);
10    pub const CLOCK_PROCESS_CPUTIME_ID: Self = Self(2);
11    pub const CLOCK_THREAD_CPUTIME_ID: Self = Self(3);
12    pub const CLOCK_MONOTONIC_RAW: Self = Self(4);
13    pub const CLOCK_REALTIME_COARSE: Self = Self(5);
14    pub const CLOCK_MONOTONIC_COARSE: Self = Self(6);
15    pub const CLOCK_BOOTTIME: Self = Self(7);
16    pub const CLOCK_REALTIME_ALARM: Self = Self(8);
17    pub const CLOCK_BOOTTIME_ALARM: Self = Self(9);
18    pub const CLOCK_SGI_CYCLE: Self = Self(10);
19    pub const CLOCK_TAI: Self = Self(11);
20}
21
22#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug)]
23#[repr(C)]
24pub struct TimeSpec {
25    // seconds
26    pub tv_sec: usize,
27    // nanoseconds
28    pub tv_nsec: usize,
29}
30
31impl TimeSpec {
32    pub const ZERO: Self = Self {
33        tv_sec: 0,
34        tv_nsec: 0,
35    };
36    pub const SECOND: Self = Self {
37        tv_sec: 1,
38        tv_nsec: 0,
39    };
40    pub const MILLSECOND: Self = Self {
41        tv_sec: 0,
42        tv_nsec: 1_000_000,
43    };
44    pub const MICROSECOND: Self = Self {
45        tv_sec: 0,
46        tv_nsec: 1_000,
47    };
48    pub const NANOSECOND: Self = Self {
49        tv_sec: 0,
50        tv_nsec: 1,
51    };
52    pub fn from_millsecond(millsecond: usize) -> Self {
53        Self {
54            tv_sec: millsecond / 1_000,
55            tv_nsec: millsecond % 1_000 * 1_000_000,
56        }
57    }
58}
59
60impl core::ops::Add<TimeSpec> for TimeSpec {
61    type Output = Self;
62    fn add(self, rhs: Self) -> Self::Output {
63        let mut ans = Self {
64            tv_sec: self.tv_sec + rhs.tv_sec,
65            tv_nsec: self.tv_nsec + rhs.tv_nsec,
66        };
67        if ans.tv_nsec > 1_000_000_000 {
68            ans.tv_sec += 1;
69            ans.tv_nsec -= 1_000_000_000;
70        }
71        ans
72    }
73}
74
75impl core::fmt::Display for TimeSpec {
76    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
77        write!(f, "TimeSpec({}.{:09})", self.tv_sec, self.tv_nsec)
78    }
79}