Skip to main content

futures_time/time/
instant.rs

1use crate::{future::IntoFuture, task::SleepUntil};
2
3use std::ops::{Add, AddAssign, Sub, SubAssign};
4
5use super::Duration;
6
7#[cfg(not(feature = "web"))]
8use std::time::Instant as HostInstant;
9
10#[cfg(feature = "web")]
11use web_time::Instant as HostInstant;
12
13/// A measurement of a monotonically nondecreasing clock. Opaque and useful only
14/// with Duration.
15///
16/// This type wraps `std::time::Duration` so we can implement traits on it
17/// without coherence issues, just like if we were implementing this in the
18/// stdlib.
19#[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash, Clone, Copy)]
20pub struct Instant(pub(crate) HostInstant);
21
22impl Instant {
23    /// Returns an instant corresponding to "now".
24    ///
25    /// # Examples
26    ///
27    /// ```
28    /// use futures_time::time::Instant;
29    ///
30    /// let now = Instant::now();
31    /// ```
32    #[must_use]
33    pub fn now() -> Self {
34        HostInstant::now().into()
35    }
36}
37
38impl Add<Duration> for Instant {
39    type Output = Self;
40
41    fn add(self, rhs: Duration) -> Self::Output {
42        (self.0 + rhs.0).into()
43    }
44}
45
46impl AddAssign<Duration> for Instant {
47    fn add_assign(&mut self, rhs: Duration) {
48        *self = (self.0 + rhs.0).into()
49    }
50}
51
52impl Sub<Duration> for Instant {
53    type Output = Self;
54
55    fn sub(self, rhs: Duration) -> Self::Output {
56        (self.0 - rhs.0).into()
57    }
58}
59
60impl SubAssign<Duration> for Instant {
61    fn sub_assign(&mut self, rhs: Duration) {
62        *self = (self.0 - rhs.0).into()
63    }
64}
65
66impl std::ops::Deref for Instant {
67    type Target = HostInstant;
68
69    fn deref(&self) -> &Self::Target {
70        &self.0
71    }
72}
73
74impl std::ops::DerefMut for Instant {
75    fn deref_mut(&mut self) -> &mut Self::Target {
76        &mut self.0
77    }
78}
79
80impl From<HostInstant> for Instant {
81    fn from(inner: HostInstant) -> Self {
82        Self(inner)
83    }
84}
85
86impl Into<HostInstant> for Instant {
87    fn into(self) -> HostInstant {
88        self.0
89    }
90}
91
92impl IntoFuture for Instant {
93    type Output = Instant;
94
95    type IntoFuture = SleepUntil;
96
97    fn into_future(self) -> Self::IntoFuture {
98        crate::task::sleep_until(self)
99    }
100}