Skip to content

Commit

Permalink
signed_duration: add round method
Browse files Browse the repository at this point in the history
This adds a new `SignedDuration::round` method that behaves like `Span`,
but for time (non-calendar) units only.

For the most part, we just copy `Span::round` as-is, but without the
`largest` unit knob (which doesn't make sense for something like
`SignedDuration`) or the `relative` datetime knob (which isn't needed
for a duration with all invariant units, as is the case for
`SignedDuration`). We can even reuse the same implementation for `Span`
rounding: we convert the duration to a 128-bit signed integer of
nanoseconds, do the rounding and then convert back (and check for
overflow).

Note that we specifically don't both with adding rounding functionality
built into APIs like `Zoned::duration_since` or
`civil::DateTime::duration_until`, unlike what we do for `Span`, since
composition works better for `SignedDuration` than it does for `Span`.
Namely, in order to round a `Span` with calendar units, you need to
provide a relative datetime. By building rounding into the datetime
arithmetic routines, we absolve the caller of needing to manage this
carefully across two distinct operations. Since `SignedDuration` only
supports invariant units, there is no purpose to providing a relative
datetime and rounding is thus fully orthogonal. Moreover, if we
overloaded methods like `Zoned::duration_since`, then they would go from
infallible to fallible, which is kind of a bummer.

Closes #187
  • Loading branch information
BurntSushi committed Jan 1, 2025
1 parent 2f57df3 commit 21218a0
Show file tree
Hide file tree
Showing 4 changed files with 365 additions and 12 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ Enhancements:

* [#130](https://github.com/BurntSushi/jiff/issues/130):
Document value ranges for methods like `year`, `day`, `hour` and so on.
* [#187](https://github.com/BurntSushi/jiff/issues/187):
Add a rounding API (for time units only) on `SignedDuration`.

Bug fixes:

Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -691,7 +691,7 @@ extern crate alloc;

pub use crate::{
error::Error,
signed_duration::SignedDuration,
signed_duration::{SignedDuration, SignedDurationRound},
span::{
Span, SpanArithmetic, SpanCompare, SpanRelativeTo, SpanRound,
SpanTotal, ToSpan, Unit,
Expand Down
Loading

0 comments on commit 21218a0

Please sign in to comment.