ambient_sys/native/
time.rs1#![allow(clippy::disallowed_types)]
2use std::{
3 ops::{Add, AddAssign, Sub},
4 time::{Duration, SystemTimeError},
5};
6
7#[derive(From, Into, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
12pub struct Instant(pub(crate) std::time::Instant);
13
14impl Sub<Instant> for Instant {
15 type Output = Duration;
16
17 fn sub(self, rhs: Instant) -> Self::Output {
18 self.0 - rhs.0
19 }
20}
21
22impl Sub<Duration> for Instant {
23 type Output = Instant;
24
25 fn sub(self, rhs: Duration) -> Self::Output {
26 Self(self.0.checked_sub(rhs).unwrap())
27 }
28}
29
30impl Add<Duration> for Instant {
31 type Output = Instant;
32
33 fn add(self, rhs: Duration) -> Self::Output {
34 Self(self.0 + rhs)
35 }
36}
37
38impl AddAssign<Duration> for Instant {
39 fn add_assign(&mut self, rhs: Duration) {
40 *self = *self + rhs;
41 }
42}
43
44impl Instant {
45 pub fn from_tokio(instant: tokio::time::Instant) -> Self {
46 Self(instant.into())
47 }
48
49 pub fn now() -> Self {
50 Self(std::time::Instant::now())
51 }
52
53 pub fn elapsed(&self) -> Duration {
54 self.0.elapsed()
55 }
56
57 pub fn duration_since(&self, earlier: Self) -> Duration {
58 self.0.duration_since(earlier.0)
59 }
60}
61
62#[derive(From, Into, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
68pub struct SystemTime(pub(crate) std::time::SystemTime);
69
70impl Add<Duration> for SystemTime {
71 type Output = SystemTime;
72
73 fn add(self, rhs: Duration) -> Self::Output {
74 Self(self.0 + rhs)
75 }
76}
77
78impl Sub<Duration> for SystemTime {
79 type Output = SystemTime;
80
81 fn sub(self, rhs: Duration) -> Self::Output {
82 Self(self.0 - rhs)
83 }
84}
85
86impl SystemTime {
87 pub const UNIX_EPOCH: Self = SystemTime(std::time::SystemTime::UNIX_EPOCH);
88 pub fn now() -> Self {
89 Self(std::time::SystemTime::now())
90 }
91
92 pub fn duration_since(&self, earlier: Self) -> Result<Duration, SystemTimeError> {
93 self.0.duration_since(earlier.0)
94 }
95}
96
97use derive_more::{From, Into};