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

Add saturating_add and saturating_sub to Instant #3846

Merged
merged 2 commits into from
Feb 4, 2025
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
12 changes: 12 additions & 0 deletions embassy-time/src/instant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,18 @@ impl Instant {
pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
self.ticks.checked_sub(duration.ticks).map(|ticks| Instant { ticks })
}

/// Adds a Duration to self. In case of overflow, the maximum value is returned.
pub fn saturating_add(mut self, duration: Duration) -> Self {
self.ticks = self.ticks.saturating_add(duration.ticks);
Copy link
Member

Choose a reason for hiding this comment

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

Mutating self is a bit strange. could you do Self::from_ticks(self.ticks.saturating_add(duration.ticks))?

same for sub.

Copy link
Member

Choose a reason for hiding this comment

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

lol already merged

self
}

/// Subtracts a Duration from self. In case of overflow, the minimum value is returned.
pub fn saturating_sub(mut self, duration: Duration) -> Self {
self.ticks = self.ticks.saturating_sub(duration.ticks);
self
}
}

impl Add<Duration> for Instant {
Expand Down