Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

time: Eliminate panics from Instant arithmetic #4461

Merged
merged 1 commit into from
Feb 6, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 7 additions & 15 deletions tokio/src/time/instant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,10 @@ impl Instant {
self.std
}

/// Returns the amount of time elapsed from another instant to this one.
///
/// # Panics
///
/// This function will panic if `earlier` is later than `self`.
Comment on lines -72 to -74
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it maybe worth explicitly noting somewhere that "unlike the std::time::Instant equivalent, this function does not panic" or similar? not a blocker.

/// Returns the amount of time elapsed from another instant to this one, or
/// zero duration if that instant is later than this one.
pub fn duration_since(&self, earlier: Instant) -> Duration {
self.std.duration_since(earlier.std)
self.std.saturating_duration_since(earlier.std)
}

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

/// Returns the amount of time elapsed since this instant was created.
///
/// # Panics
///
/// This function may panic if the current time is earlier than this
/// instant, which is something that can happen if an `Instant` is
/// produced synthetically.
/// Returns the amount of time elapsed since this instant was created,
/// or zero duration if that this instant is in the future.
///
/// # Examples
///
Expand All @@ -140,7 +132,7 @@ impl Instant {
/// }
/// ```
pub fn elapsed(&self) -> Duration {
Instant::now() - *self
Instant::now().saturating_duration_since(*self)
}

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

fn sub(self, rhs: Instant) -> Duration {
self.std - rhs.std
self.std.saturating_duration_since(rhs.std)
}
}

Expand Down