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

Conversation

abreis
Copy link
Contributor

@abreis abreis commented May 4, 2020

This PR adds a method to get the absolute (modulus) of a Duration.

It is useful for checking how much two DateTimes diverge without having to fall back to i64s.

@quodlibetor quodlibetor merged commit ce62f91 into chronotope:master Jun 17, 2020
@quodlibetor
Copy link
Contributor

Thanks!

/// 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants