Skip to main content

leodos_libcfs/cfe/
duration.rs

1//! A simple duration struct similar to `core::time::Duration`.
2//! Uses 32-bit unsigned integers for seconds and nanoseconds instead of 64-bit.
3
4use crate::cfe::time::SysTime;
5
6/// A simple duration struct similar to `std::time::Duration`.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
8pub struct Duration {
9    secs: u32,
10    nanos: u32,
11}
12
13impl From<SysTime> for Duration {
14    fn from(time: SysTime) -> Self {
15        Self {
16            secs: time.seconds(),
17            nanos: time.subseconds(),
18        }
19    }
20}
21
22impl Duration {
23    /// Creates a new `Duration` from seconds and nanoseconds.
24    pub fn new(secs: u32, nanos: u32) -> Self {
25        Self { secs, nanos }
26    }
27
28    /// Creates a new `Duration` from hours.
29    pub fn from_hours(hours: u32) -> Self {
30        Self {
31            secs: hours * 60 * 60,
32            nanos: 0,
33        }
34    }
35
36    /// Creates a new `Duration` from minutes.
37    pub fn from_mins(mins: u32) -> Self {
38        Self {
39            secs: mins * 60,
40            nanos: 0,
41        }
42    }
43
44    /// Creates a new `Duration` from seconds.
45    pub fn from_secs(secs: u32) -> Self {
46        Self { secs, nanos: 0 }
47    }
48
49    /// Creates a new `Duration` from milliseconds.
50    pub fn from_millis(millis: u32) -> Self {
51        Self {
52            secs: millis / 1_000,
53            nanos: (millis % 1_000) * 1_000_000,
54        }
55    }
56
57    /// Creates a new `Duration` from microseconds.
58    pub fn from_micros(micros: u32) -> Self {
59        Self {
60            secs: micros / 1_000_000,
61            nanos: (micros % 1_000_000) * 1_000,
62        }
63    }
64
65    /// Creates a new `Duration` from nanoseconds.
66    pub fn from_nanos(nanos: u32) -> Self {
67        Self { secs: 0, nanos }
68    }
69
70    /// Returns the seconds component of the duration.
71    pub fn secs(&self) -> u32 {
72        self.secs
73    }
74
75    /// Returns the nanoseconds component of the duration.
76    pub fn nanos(&self) -> u32 {
77        self.nanos
78    }
79
80    /// Returns the total duration in milliseconds.
81    pub fn millis(&self) -> u32 {
82        self.secs * 1_000 + self.nanos / 1_000_000
83    }
84
85    /// Returns a zero duration.
86    pub fn zero() -> Self {
87        Self { secs: 0, nanos: 0 }
88    }
89}