sel4_async_time/
instant.rs

1//
2// Copyright 2023, Colias Group, LLC
3//
4// SPDX-License-Identifier: BSD-2-Clause
5//
6
7use core::ops::{Add, AddAssign, Sub, SubAssign};
8use core::time::Duration;
9
10#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
11pub struct Instant {
12    since_zero: Duration,
13}
14
15impl Instant {
16    pub const ZERO: Self = Self::new(Duration::ZERO);
17
18    pub const fn new(since_zero: Duration) -> Self {
19        Self { since_zero }
20    }
21
22    pub const fn since_zero(&self) -> Duration {
23        self.since_zero
24    }
25
26    pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
27        self.since_zero.checked_sub(earlier.since_zero)
28    }
29
30    pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
31        self.checked_duration_since(earlier).unwrap_or_default()
32    }
33
34    pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
35        self.since_zero.checked_add(duration).map(Self::new)
36    }
37
38    pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
39        self.since_zero.checked_sub(duration).map(Self::new)
40    }
41}
42
43impl Add<Duration> for Instant {
44    type Output = Instant;
45
46    fn add(self, other: Duration) -> Instant {
47        self.checked_add(other)
48            .expect("overflow when adding duration to instant")
49    }
50}
51
52impl AddAssign<Duration> for Instant {
53    fn add_assign(&mut self, other: Duration) {
54        *self = *self + other;
55    }
56}
57
58impl Sub<Duration> for Instant {
59    type Output = Instant;
60
61    fn sub(self, other: Duration) -> Instant {
62        self.checked_sub(other)
63            .expect("overflow when subtracting duration from instant")
64    }
65}
66
67impl SubAssign<Duration> for Instant {
68    fn sub_assign(&mut self, other: Duration) {
69        *self = *self - other;
70    }
71}
72
73impl Sub<Instant> for Instant {
74    type Output = Duration;
75
76    fn sub(self, other: Instant) -> Duration {
77        self.checked_duration_since(other)
78            .expect("overflow when instant from instant")
79    }
80}