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

Implement .abs() for Duration #418

Merged
merged 1 commit into from Jun 17, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/oldtime.rs
Expand Up @@ -229,6 +229,12 @@ impl Duration {
if d < MIN || d > MAX { None } else { Some(d) }
}

/// Returns the duration as an absolute (non-negative) value.
#[inline]
pub fn abs(&self) -> Duration {
Duration { secs: self.secs.abs(), nanos: self.nanos }

Choose a reason for hiding this comment

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

This seems like it doesn't handle nanos properly; -1s + .5s is -0.5s which should have an absolute value of .5s not 1.5s

Copy link
Contributor Author

Choose a reason for hiding this comment

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

You're correct: I didn't realize at the time that the nanos field always 'adds' to the secs field (which makes sense since you can't store -0 in the secs field).

Copy link
Contributor Author

@abreis abreis Jul 14, 2022

Choose a reason for hiding this comment

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

This should do it:

    /// Returns the duration as an absolute (non-negative) value.
    #[inline]
    pub fn abs(&self) -> Duration {
        if self.secs < 0 && self.nanos != 0 {
            Duration { secs: (self.secs+1).abs(), nanos: NANOS_PER_SEC-self.nanos }
        } else {
            Duration { secs: self.secs.abs(), nanos: self.nanos }
        }
    }

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I submitted #734.

}

/// The minimum possible `Duration`: `i64::MIN` milliseconds.
#[inline]
pub fn min_value() -> Duration { MIN }
Expand Down