Skip to content

Commit 825db55

Browse files
committed
time: Eliminate panics from Instant arithmetic
`Instant::duration_since`, `Instant::elapsed`, and `Instant::sub` may panic. This is especially dangerous when `Instant::now` travels back in time. While this isn't supposed to happen, this behavior is highly platform-dependent (e.g., rust-lang/rust#86470). This change modifies the behavior of `tokio::time::Instant` to prevent this class of panic, as proposed for `std::time::Instant` in rust-lang/rust#89926.
1 parent 49fff47 commit 825db55

File tree

1 file changed

+7
-15
lines changed

1 file changed

+7
-15
lines changed

tokio/src/time/instant.rs

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -67,13 +67,10 @@ impl Instant {
6767
self.std
6868
}
6969

70-
/// Returns the amount of time elapsed from another instant to this one.
71-
///
72-
/// # Panics
73-
///
74-
/// This function will panic if `earlier` is later than `self`.
70+
/// Returns the amount of time elapsed from another instant to this one, or
71+
/// zero duration if that instant is later than this one.
7572
pub fn duration_since(&self, earlier: Instant) -> Duration {
76-
self.std.duration_since(earlier.std)
73+
self.std.saturating_duration_since(earlier.std)
7774
}
7875

7976
/// Returns the amount of time elapsed from another instant to this one, or
@@ -118,13 +115,8 @@ impl Instant {
118115
self.std.saturating_duration_since(earlier.std)
119116
}
120117

121-
/// Returns the amount of time elapsed since this instant was created.
122-
///
123-
/// # Panics
124-
///
125-
/// This function may panic if the current time is earlier than this
126-
/// instant, which is something that can happen if an `Instant` is
127-
/// produced synthetically.
118+
/// Returns the amount of time elapsed since this instant was created,
119+
/// or zero duration if that this instant is in the future.
128120
///
129121
/// # Examples
130122
///
@@ -140,7 +132,7 @@ impl Instant {
140132
/// }
141133
/// ```
142134
pub fn elapsed(&self) -> Duration {
143-
Instant::now() - *self
135+
Instant::now().saturating_duration_since(*self)
144136
}
145137

146138
/// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be
@@ -188,7 +180,7 @@ impl ops::Sub for Instant {
188180
type Output = Duration;
189181

190182
fn sub(self, rhs: Instant) -> Duration {
191-
self.std - rhs.std
183+
self.std.saturating_duration_since(rhs.std)
192184
}
193185
}
194186

0 commit comments

Comments
 (0)