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