1use crate::{
2SignedDuration, Unit,
3 error::{
4Error, ErrorContext,
5 unit::{MustDivide, UnitConfigError},
6util::RoundingIncrementError,
7 },
8util::b,
9};
1011/// A representation of a rounding increment in a particular unit.
12///
13/// This implements the core rounding interface of Jiff, shared across all
14/// types. The constructors on `Increment` know which units *and* increments
15/// are valid for a particular rounding configuration. For example, only
16/// `Increment::for_span` supports any `unit` value. All other constructors
17/// have some kind of limitation (e.g., you can't round a date to the nearest
18/// month).
19///
20/// For most cases, rounding is done via `Increment::round`. This takes a
21/// quantity in a number of nanoseconds and rounds it to the nearest increment
22/// (after converting the increment to nanoseconds as well, based on the unit
23/// provided). This API makes it difficult for callers to get rounding wrong.
24/// They just need to use the right constructor and provide a quantity in units
25/// of nanoseconds.
26///
27/// For lower level needs, one can use `RoundMode::round_by_duration` directly.
28/// This doesn't know about any units other than nanoseconds. It's useful in
29/// contexts when dealing with variable length units and there are no rules
30/// for what is a valid increment.
31#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Increment {
}
#[automatically_derived]impl ::core::clone::Clone for Increment {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Unit>;
let _: ::core::clone::AssertParamIsClone<i32>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for Increment { }Copy, #[automatically_derived]impl ::core::fmt::Debug for Increment {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Increment unit value", &self.unit, &&self.value)
}
}Debug)]
32pub(crate) struct Increment {
33 unit: Unit,
34 value: i32,
35}
3637impl Increment {
38/// Return a rounding increment suitable for use when rounding a `Span`.
39pub(crate) fn for_span(
40 unit: Unit,
41 value: i64,
42 ) -> Result<Increment, Error> {
43// Indexed by `Unit`.
44static LIMITS: &[MustDivide] = &[
45 MustDivide::NanosPerMicro,
46 MustDivide::MicrosPerMilli,
47 MustDivide::MillisPerSec,
48 MustDivide::SecsPerMin,
49 MustDivide::MinsPerHour,
50 MustDivide::HoursPerCivilDay,
51 ];
5253// We allow any kind of increment for calendar units, but for time
54 // units, they have to divide evenly into the next highest unit (and
55 // also be less than that). The reason for this is that calendar
56 // units vary, where as for time units, given a balanced span, you
57 // know that time units will always spill over into days so that
58 // hours/minutes/... will never exceed 24/60/...
59if unit < Unit::Day {
60Increment::for_limits(unit, value, LIMITS)
61 .context(RoundingIncrementError::ForSpan)
62 } else {
63// For calendar units, just verify that the increment is in the
64 // correct range.
65let value = b::Increment32::check(value)
66 .context(RoundingIncrementError::ForSpan)?;
67Ok(Increment { unit, value })
68 }
69 }
7071/// Return a rounding increment suitable for use when rounding a
72 /// `SignedDuration`.
73pub(crate) fn for_signed_duration(
74 unit: Unit,
75 value: i64,
76 ) -> Result<Increment, Error> {
77if unit > Unit::Hour {
78return Err(Error::from(
79 UnitConfigError::SignedDurationCalendarUnit { smallest: unit },
80 ));
81 }
8283// For signed durations, we allow any increment that is within range.
84let value = b::Increment32::check(value)
85 .context(RoundingIncrementError::ForSignedDuration)?;
86Ok(Increment { unit, value })
87 }
8889/// Return a rounding increment suitable for use when rounding a
90 /// `tz::Offset`.
91pub(crate) fn for_offset(
92 unit: Unit,
93 value: i64,
94 ) -> Result<Increment, Error> {
95if !(Unit::Second <= unit && unit <= Unit::Hour) {
96return Err(Error::from(UnitConfigError::TimeZoneOffset {
97 given: unit,
98 }));
99 }
100101// For time zone offsets, we allow any increment that is within range.
102let value = b::Increment32::check(value)
103 .context(RoundingIncrementError::ForOffset)?;
104Ok(Increment { unit, value })
105 }
106107/// Return a rounding increment suitable for use when rounding a
108 /// `civil::DateTime` or a `ZonedDateTime`.
109pub(crate) fn for_datetime(
110 unit: Unit,
111 value: i64,
112 ) -> Result<Increment, Error> {
113// Indexed by `Unit`.
114static LIMITS: &[MustDivide] = &[
115 MustDivide::NanosPerMicro,
116 MustDivide::MicrosPerMilli,
117 MustDivide::MillisPerSec,
118 MustDivide::SecsPerMin,
119 MustDivide::MinsPerHour,
120 MustDivide::HoursPerCivilDay,
121 MustDivide::Days,
122 ];
123Increment::for_limits(unit, value, LIMITS)
124 .context(RoundingIncrementError::ForDateTime)
125 }
126127/// Return a rounding increment suitable for use when rounding a
128 /// `civil::Time`.
129pub(crate) fn for_time(
130 unit: Unit,
131 value: i64,
132 ) -> Result<Increment, Error> {
133// Indexed by `Unit`.
134static LIMITS: &[MustDivide] = &[
135 MustDivide::NanosPerMicro,
136 MustDivide::MicrosPerMilli,
137 MustDivide::MillisPerSec,
138 MustDivide::SecsPerMin,
139 MustDivide::MinsPerHour,
140 MustDivide::HoursPerCivilDay,
141 ];
142Increment::for_limits(unit, value, LIMITS)
143 .context(RoundingIncrementError::ForTime)
144 }
145146/// Return a rounding increment suitable for use when rounding a
147 /// `civil::Timestamp`.
148pub(crate) fn for_timestamp(
149 unit: Unit,
150 value: i64,
151 ) -> Result<Increment, Error> {
152// Indexed by `Unit`.
153static MAXIMUMS: &[MustDivide] = &[
154 MustDivide::NanosPerCivilDay,
155 MustDivide::MicrosPerCivilDay,
156 MustDivide::MillisPerCivilDay,
157 MustDivide::SecsPerCivilDay,
158 MustDivide::MinsPerCivilDay,
159 MustDivide::HoursPerCivilDay,
160 ];
161Increment::for_maximums(unit, value, MAXIMUMS)
162 .context(RoundingIncrementError::ForTimestamp)
163 }
164165/// Rounds the given quantity to the nearest increment value (in terms of
166 /// the units given to this increment's constructor). Rounding down or up
167 /// is determined by the mode given.
168pub(crate) fn round(
169&self,
170 mode: RoundMode,
171 quantity: SignedDuration,
172 ) -> Result<SignedDuration, Error> {
173// OK because the max for the number of nanoseconds in a unit
174 // is weeks at `604_800_000_000_000` and `increment` cannot be
175 // any larger than `1_000_000_000`. The multiplication of these two
176 // values does not exceed `SignedDuration::MAX`.
177let increment = self.value() * self.unit().duration();
178mode.round_by_duration(quantity, increment)
179 }
180181/// Returns this increment's unit.
182 ///
183 /// The increment value is always in terms of this unit.
184pub(crate) fn unit(&self) -> Unit {
185self.unit
186 }
187188/// Returns this increment's value.
189 ///
190 /// e.g., "round to the nearest 15th minute" is expressed with an increment
191 /// value of `15` and a unit of `Unit::Minute`.
192 ///
193 /// The value returned is guaranteed to be in the range
194 /// `1..=1_000_000_000`.
195pub(crate) fn value(&self) -> i32 {
196self.value
197 }
198}
199200/// Lower level constructors that require the caller to know the precise
201/// limits or maximums. These should generally stay unexported.
202impl Increment {
203/// Validate the `increment` value for the given `unit` and limits.
204 ///
205 /// Specifically, this ensures that rounding to the given `unit` is
206 /// supported and that the specific value is *less than* to the
207 /// corresponding limit.
208fn for_limits(
209 unit: Unit,
210 value: i64,
211 limits: &[MustDivide],
212 ) -> Result<Increment, Error> {
213let Some(&must_divide) = limits.get(unitas usize) else {
214return Err(Error::from(
215 UnitConfigError::RoundToUnitUnsupported { unit },
216 ));
217 };
218219let value32 = b::Increment32::check(value)?;
220let must_divide_i64 = must_divide.as_i64();
221if value < must_divide_i64 && must_divide_i64 % value == 0 {
222return Ok(Increment { unit, value: value32 });
223 }
224Err(Error::from(UnitConfigError::IncrementDivide {
225unit,
226must_divide,
227 }))
228 }
229230/// Validate the `increment` value for the given `unit` and maximums.
231 ///
232 /// Specifically, this ensures that rounding to the given `unit` is
233 /// supported and that the specific value is *less than or equal* to the
234 /// corresponding maximum.
235fn for_maximums(
236 unit: Unit,
237 value: i64,
238 maximums: &[MustDivide],
239 ) -> Result<Increment, Error> {
240let Some(&must_divide) = maximums.get(unitas usize) else {
241return Err(Error::from(
242 UnitConfigError::RoundToUnitUnsupported { unit },
243 ));
244 };
245246let value32 = b::Increment32::check(value)?;
247let must_divide_i64 = must_divide.as_i64();
248if value <= must_divide_i64 && must_divide_i64 % value == 0 {
249return Ok(Increment { unit, value: value32 });
250 }
251Err(Error::from(UnitConfigError::IncrementDivide {
252unit,
253must_divide,
254 }))
255 }
256}
257258/// The mode for dealing with the remainder when rounding datetimes or spans.
259///
260/// This is used in APIs like [`Span::round`](crate::Span::round) for rounding
261/// spans, and APIs like [`ZonedDateTime::round`](crate::ZonedDateTime::round)
262/// for rounding datetimes.
263///
264/// In the documentation for each variant, we refer to concepts like the
265/// "smallest" unit and the "rounding increment." These are best described
266/// in the documentation for what you're rounding. For example,
267/// [`SpanRound::smallest`](crate::SpanRound::smallest)
268/// and [`SpanRound::increment`](crate::SpanRound::increment).
269///
270/// # Example
271///
272/// This shows how to round a span with a different rounding mode than the
273/// default:
274///
275/// ```
276/// use jiff::{RoundMode, SpanRound, ToSpan, Unit};
277///
278/// // The default rounds like how you were taught in school:
279/// assert_eq!(
280/// 1.hour().minutes(59).round(Unit::Hour)?,
281/// 2.hours().fieldwise(),
282/// );
283/// // But we can change the mode, e.g., truncation:
284/// let options = SpanRound::new().smallest(Unit::Hour).mode(RoundMode::Trunc);
285/// assert_eq!(
286/// 1.hour().minutes(59).round(options)?,
287/// 1.hour().fieldwise(),
288/// );
289///
290/// # Ok::<(), Box<dyn std::error::Error>>(())
291/// ```
292#[non_exhaustive]
293#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for RoundMode {
}
#[automatically_derived]impl ::core::clone::Clone for RoundMode {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for RoundMode { }Copy, #[automatically_derived]impl ::core::fmt::Debug for RoundMode {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_c_like_enum_write_str(f,
"Ceil Floor Expand Trunc HalfCeil HalfFloor HalfExpand HalfTrunc HalfEven",
match self {
RoundMode::Ceil => 0usize,
RoundMode::Floor => 5usize,
RoundMode::Expand => 11usize,
RoundMode::Trunc => 18usize,
RoundMode::HalfCeil => 24usize,
RoundMode::HalfFloor => 33usize,
RoundMode::HalfExpand => 43usize,
RoundMode::HalfTrunc => 54usize,
RoundMode::HalfEven => 64usize,
})
}
}Debug, #[automatically_derived]impl ::core::cmp::Eq for RoundMode { }Eq, #[automatically_derived]impl ::core::hash::Hash for RoundMode {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state)
}
}Hash, #[automatically_derived]impl ::core::marker::StructuralPartialEq for RoundMode
{
}
#[automatically_derived]impl ::core::cmp::PartialEq for RoundMode {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
294#[cfg_attr(feature = "defmt", derive(defmt::Format))]
295pub enum RoundMode {
296/// Rounds toward positive infinity.
297 ///
298 /// For negative spans and datetimes, this option will make the absolute
299 /// value smaller, which could be unexpected. To round away from zero, use
300 /// `Expand`.
301Ceil,
302/// Rounds toward negative infinity.
303 ///
304 /// This mode acts like `Trunc` for positive spans and datetimes, but
305 /// for negative values, it will make the absolute value larger, which
306 /// could be unexpected. To round towards zero, use `Trunc`.
307Floor,
308/// Rounds away from zero like `Ceil` for positive spans and datetimes,
309 /// and like `Floor` for negative spans and datetimes.
310Expand,
311/// Rounds toward zero, chopping off any fractional part of a unit.
312 ///
313 /// This is the default when rounding spans returned from
314 /// datetime arithmetic. (But it is not the default for
315 /// [`Span::round`](crate::Span::round).)
316Trunc,
317/// Rounds to the nearest allowed value like `HalfExpand`, but when there
318 /// is a tie, round towards positive infinity like `Ceil`.
319HalfCeil,
320/// Rounds to the nearest allowed value like `HalfExpand`, but when there
321 /// is a tie, round towards negative infinity like `Floor`.
322HalfFloor,
323/// Rounds to the nearest value allowed by the rounding increment and the
324 /// smallest unit. When there is a tie, round away from zero like `Ceil`
325 /// for positive spans and datetimes and like `Floor` for negative spans
326 /// and datetimes.
327 ///
328 /// This corresponds to how rounding is often taught in school.
329 ///
330 /// This is the default for rounding spans and datetimes.
331HalfExpand,
332/// Rounds to the nearest allowed value like `HalfExpand`, but when there
333 /// is a tie, round towards zero like `Trunc`.
334HalfTrunc,
335/// Rounds to the nearest allowed value like `HalfExpand`, but when there
336 /// is a tie, round towards the value that is an even multiple of the
337 /// rounding increment. For example, with a rounding increment of `3`,
338 /// the number `10` would round up to `12` instead of down to `9`, because
339 /// `12` is an even multiple of `3`, where as `9` is is an odd multiple.
340HalfEven,
341}
342343impl RoundMode {
344/// Round `quantity` to the nearest `increment` using this rounding mode.
345 ///
346 /// If this the rounding result would overflow `SignedDuration`, then an
347 /// error is returned.
348 ///
349 /// Callers should generally prefer higher level APIs. But this one is
350 /// unavoidable when the increment isn't tied to an invariant length and
351 /// can vary.
352 ///
353 /// # Panics
354 ///
355 /// Callers must ensure that `increment` has a number of nanoseconds
356 /// greater than or equal to `1`.
357pub(crate) fn round_by_duration(
358self,
359 quantity: SignedDuration,
360 increment: SignedDuration,
361 ) -> Result<SignedDuration, Error> {
362let quantity = quantity.as_nanos();
363let increment = increment.as_nanos();
364if !(increment >= 1) {
::core::panicking::panic("assertion failed: increment >= 1")
};assert!(increment >= 1);
365let rounded = self.round_by_i128(quantity, increment);
366// This can fail in the case where `quantity` is somehow rounded to a
367 // value above/below a signed duration's max/min. This cannot *usually*
368 // happen in practice because our `quantity` is typically limited by
369 // the maximum Jiff datetime span. Even spanning from -9999 to 9999, a
370 // 96-bit integer number of nanoseconds still can't cause an overflow.
371 // Moreover, `increment` is usually capped to `1_000_000_000`. The only
372 // case where it isn't is when we're rounding based on variable length
373 // units (in which case, this lower level rounding routine is called
374 // directly). For example, when rounding to years with an increment
375 // (set by the user) to `15_000`. That will get translated to 15,000
376 // years *in nanoseconds*.
377 //
378 // Even still, the complete span of time supported by Jiff can
379 // comfortably fit into a `SignedDuration`. And because of the limit
380 // placed on `increment`, I don't believe this error can ever actually
381 // occur.
382SignedDuration::try_from_nanos_i128(rounded)
383 .ok_or_else(|| Error::from(b::SignedDurationSeconds::error()))
384 }
385386/// The internal API that does the actual rounding.
387 ///
388 /// This does not error on overflow because callers can never use values
389 /// close to the `i128` limits. If an overflow would otherwise occur due to
390 /// rounding, then it saturates instead of panicking or returning an error.
391 ///
392 /// I wish we could do modulus on `SignedDuration` directly. Then we
393 /// wouldn't need 128-bit arithmetic at all. But I looked into making
394 /// `SignedDuration % SignedDuration` work, and it was quite involved? So I
395 /// guess we should just let the compiler handle it for `i128`. We'd also
396 /// need division.
397 ///
398 /// # Panics
399 ///
400 /// When `increment < 1`.
401fn round_by_i128(self, quantity: i128, increment: i128) -> i128 {
402if !(increment >= 1) {
::core::panicking::panic("assertion failed: increment >= 1")
};assert!(increment >= 1);
403// ref: https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
404let mode = self;
405let mut quotient = quantity / increment;
406let remainder = quantity % increment;
407if remainder == 0 {
408return quantity;
409 }
410let sign = if remainder < 0 { -1 } else { 1 };
411let tiebreaker = (remainder * 2).abs();
412let tie = tiebreaker == increment;
413let expand_is_nearer = tiebreaker > increment;
414// ref: https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
415match mode {
416 RoundMode::Ceil => {
417if sign > 0 {
418quotient += sign;
419 }
420 }
421 RoundMode::Floor => {
422if sign < 0 {
423quotient += sign;
424 }
425 }
426 RoundMode::Expand => {
427quotient += sign;
428 }
429 RoundMode::Trunc => {}
430 RoundMode::HalfCeil => {
431if expand_is_nearer || (tie && sign > 0) {
432quotient += sign;
433 }
434 }
435 RoundMode::HalfFloor => {
436if expand_is_nearer || (tie && sign < 0) {
437quotient += sign;
438 }
439 }
440 RoundMode::HalfExpand => {
441if expand_is_nearer || tie {
442quotient += sign;
443 }
444 }
445 RoundMode::HalfTrunc => {
446if expand_is_nearer {
447quotient += sign;
448 }
449 }
450 RoundMode::HalfEven => {
451if expand_is_nearer || (tie && quotient.rem_euclid(2) == 1) {
452quotient += sign;
453 }
454 }
455 }
456// We use saturating arithmetic here because this can overflow when
457 // `quantity` is the max value. Since we're rounding, we just refuse to
458 // go over the maximum. This can't happen in practice because this is
459 // a private API and all paths to this API enforce that we are never
460 // going to round over the `i128` maximum.
461quotient.saturating_mul(increment)
462 }
463}
464465#[cfg(test)]
466mod tests {
467use super::*;
468469#[test]
470fn for_span() {
471let get = |unit, value| Increment::for_span(unit, value);
472473assert!(get(Unit::Nanosecond, 1).is_ok());
474assert!(get(Unit::Nanosecond, 500).is_ok());
475assert!(get(Unit::Nanosecond, -1).is_err());
476assert!(get(Unit::Nanosecond, 0).is_err());
477assert!(get(Unit::Nanosecond, 7).is_err());
478assert!(get(Unit::Nanosecond, 1_000).is_err());
479assert!(get(Unit::Nanosecond, i64::MIN).is_err());
480assert!(get(Unit::Nanosecond, i64::MAX).is_err());
481482assert!(get(Unit::Microsecond, 1).is_ok());
483assert!(get(Unit::Microsecond, 500).is_ok());
484assert!(get(Unit::Microsecond, -1).is_err());
485assert!(get(Unit::Microsecond, 0).is_err());
486assert!(get(Unit::Microsecond, 7).is_err());
487assert!(get(Unit::Microsecond, 1_000).is_err());
488assert!(get(Unit::Microsecond, i64::MIN).is_err());
489assert!(get(Unit::Microsecond, i64::MAX).is_err());
490491assert!(get(Unit::Millisecond, 1).is_ok());
492assert!(get(Unit::Millisecond, 500).is_ok());
493assert!(get(Unit::Millisecond, -1).is_err());
494assert!(get(Unit::Millisecond, 0).is_err());
495assert!(get(Unit::Millisecond, 7).is_err());
496assert!(get(Unit::Millisecond, 1_000).is_err());
497assert!(get(Unit::Millisecond, i64::MIN).is_err());
498assert!(get(Unit::Millisecond, i64::MAX).is_err());
499500assert!(get(Unit::Second, 1).is_ok());
501assert!(get(Unit::Second, 15).is_ok());
502assert!(get(Unit::Second, -1).is_err());
503assert!(get(Unit::Second, 0).is_err());
504assert!(get(Unit::Second, 7).is_err());
505assert!(get(Unit::Second, 1_000).is_err());
506assert!(get(Unit::Second, i64::MIN).is_err());
507assert!(get(Unit::Second, i64::MAX).is_err());
508509assert!(get(Unit::Minute, 1).is_ok());
510assert!(get(Unit::Minute, 15).is_ok());
511assert!(get(Unit::Minute, -1).is_err());
512assert!(get(Unit::Minute, 0).is_err());
513assert!(get(Unit::Minute, 7).is_err());
514assert!(get(Unit::Minute, 1_000).is_err());
515assert!(get(Unit::Minute, i64::MIN).is_err());
516assert!(get(Unit::Minute, i64::MAX).is_err());
517518assert!(get(Unit::Hour, 1).is_ok());
519assert!(get(Unit::Hour, 6).is_ok());
520assert!(get(Unit::Hour, 12).is_ok());
521assert!(get(Unit::Hour, -1).is_err());
522assert!(get(Unit::Hour, 0).is_err());
523assert!(get(Unit::Hour, 15).is_err());
524assert!(get(Unit::Hour, 18).is_err());
525assert!(get(Unit::Hour, 23).is_err());
526assert!(get(Unit::Hour, 24).is_err());
527assert!(get(Unit::Hour, i64::MIN).is_err());
528assert!(get(Unit::Hour, i64::MAX).is_err());
529530assert!(get(Unit::Day, 1).is_ok());
531assert!(get(Unit::Day, 6).is_ok());
532assert!(get(Unit::Day, 7).is_ok());
533assert!(get(Unit::Day, 12).is_ok());
534assert!(get(Unit::Day, 30).is_ok());
535assert!(get(Unit::Day, 31).is_ok());
536assert!(get(Unit::Day, 100).is_ok());
537assert!(get(Unit::Day, 10_000_000).is_ok());
538assert!(get(Unit::Day, 1_000_000_000).is_ok());
539assert!(get(Unit::Day, -1).is_err());
540assert!(get(Unit::Day, 0).is_err());
541assert!(get(Unit::Day, 1_000_000_001).is_err());
542assert!(get(Unit::Day, i64::MIN).is_err());
543assert!(get(Unit::Day, i64::MAX).is_err());
544545assert!(get(Unit::Week, 1).is_ok());
546assert!(get(Unit::Week, 6).is_ok());
547assert!(get(Unit::Week, 7).is_ok());
548assert!(get(Unit::Week, 12).is_ok());
549assert!(get(Unit::Week, 30).is_ok());
550assert!(get(Unit::Week, 31).is_ok());
551assert!(get(Unit::Week, 100).is_ok());
552assert!(get(Unit::Week, 2_000_000).is_ok());
553assert!(get(Unit::Week, 1_000_000_000).is_ok());
554assert!(get(Unit::Week, -1).is_err());
555assert!(get(Unit::Week, 0).is_err());
556assert!(get(Unit::Week, 1_000_000_001).is_err());
557assert!(get(Unit::Week, i64::MIN).is_err());
558assert!(get(Unit::Week, i64::MAX).is_err());
559560assert!(get(Unit::Month, 1).is_ok());
561assert!(get(Unit::Month, 6).is_ok());
562assert!(get(Unit::Month, 7).is_ok());
563assert!(get(Unit::Month, 12).is_ok());
564assert!(get(Unit::Month, 30).is_ok());
565assert!(get(Unit::Month, 31).is_ok());
566assert!(get(Unit::Month, 100).is_ok());
567assert!(get(Unit::Month, 300_000).is_ok());
568assert!(get(Unit::Month, 1_000_000_000).is_ok());
569assert!(get(Unit::Month, -1).is_err());
570assert!(get(Unit::Month, 0).is_err());
571assert!(get(Unit::Month, 1_000_000_001).is_err());
572assert!(get(Unit::Month, i64::MIN).is_err());
573assert!(get(Unit::Month, i64::MAX).is_err());
574575assert!(get(Unit::Year, 1).is_ok());
576assert!(get(Unit::Year, 6).is_ok());
577assert!(get(Unit::Year, 7).is_ok());
578assert!(get(Unit::Year, 12).is_ok());
579assert!(get(Unit::Year, 30).is_ok());
580assert!(get(Unit::Year, 31).is_ok());
581assert!(get(Unit::Year, 100).is_ok());
582assert!(get(Unit::Year, 50_000).is_ok());
583assert!(get(Unit::Year, 1_000_000_000).is_ok());
584assert!(get(Unit::Year, -1).is_err());
585assert!(get(Unit::Year, 0).is_err());
586assert!(get(Unit::Year, 1_000_000_001).is_err());
587assert!(get(Unit::Year, i64::MIN).is_err());
588assert!(get(Unit::Year, i64::MAX).is_err());
589 }
590591#[test]
592fn for_datetime() {
593let get = |unit, value| Increment::for_datetime(unit, value);
594595assert!(get(Unit::Nanosecond, 1).is_ok());
596assert!(get(Unit::Nanosecond, 500).is_ok());
597assert!(get(Unit::Nanosecond, -1).is_err());
598assert!(get(Unit::Nanosecond, 0).is_err());
599assert!(get(Unit::Nanosecond, 7).is_err());
600assert!(get(Unit::Nanosecond, 1_000).is_err());
601assert!(get(Unit::Nanosecond, i64::MIN).is_err());
602assert!(get(Unit::Nanosecond, i64::MAX).is_err());
603604assert!(get(Unit::Microsecond, 1).is_ok());
605assert!(get(Unit::Microsecond, 500).is_ok());
606assert!(get(Unit::Microsecond, -1).is_err());
607assert!(get(Unit::Microsecond, 0).is_err());
608assert!(get(Unit::Microsecond, 7).is_err());
609assert!(get(Unit::Microsecond, 1_000).is_err());
610assert!(get(Unit::Microsecond, i64::MIN).is_err());
611assert!(get(Unit::Microsecond, i64::MAX).is_err());
612613assert!(get(Unit::Millisecond, 1).is_ok());
614assert!(get(Unit::Millisecond, 500).is_ok());
615assert!(get(Unit::Millisecond, -1).is_err());
616assert!(get(Unit::Millisecond, 0).is_err());
617assert!(get(Unit::Millisecond, 7).is_err());
618assert!(get(Unit::Millisecond, 1_000).is_err());
619assert!(get(Unit::Millisecond, i64::MIN).is_err());
620assert!(get(Unit::Millisecond, i64::MAX).is_err());
621622assert!(get(Unit::Second, 1).is_ok());
623assert!(get(Unit::Second, 15).is_ok());
624assert!(get(Unit::Second, -1).is_err());
625assert!(get(Unit::Second, 0).is_err());
626assert!(get(Unit::Second, 7).is_err());
627assert!(get(Unit::Second, 1_000).is_err());
628assert!(get(Unit::Second, i64::MIN).is_err());
629assert!(get(Unit::Second, i64::MAX).is_err());
630631assert!(get(Unit::Minute, 1).is_ok());
632assert!(get(Unit::Minute, 15).is_ok());
633assert!(get(Unit::Minute, -1).is_err());
634assert!(get(Unit::Minute, 0).is_err());
635assert!(get(Unit::Minute, 7).is_err());
636assert!(get(Unit::Minute, 1_000).is_err());
637assert!(get(Unit::Minute, i64::MIN).is_err());
638assert!(get(Unit::Minute, i64::MAX).is_err());
639640assert!(get(Unit::Hour, 1).is_ok());
641assert!(get(Unit::Hour, 6).is_ok());
642assert!(get(Unit::Hour, 12).is_ok());
643assert!(get(Unit::Hour, -1).is_err());
644assert!(get(Unit::Hour, 0).is_err());
645assert!(get(Unit::Hour, 15).is_err());
646assert!(get(Unit::Hour, 18).is_err());
647assert!(get(Unit::Hour, 23).is_err());
648assert!(get(Unit::Hour, 24).is_err());
649assert!(get(Unit::Hour, i64::MIN).is_err());
650assert!(get(Unit::Hour, i64::MAX).is_err());
651652assert!(get(Unit::Day, 1).is_ok());
653assert!(get(Unit::Day, -1).is_err());
654assert!(get(Unit::Day, 0).is_err());
655assert!(get(Unit::Day, 2).is_err());
656assert!(get(Unit::Day, 4).is_err());
657assert!(get(Unit::Day, 7).is_err());
658assert!(get(Unit::Day, i64::MIN).is_err());
659assert!(get(Unit::Day, i64::MAX).is_err());
660 }
661662#[test]
663fn for_time() {
664let get = |unit, value| Increment::for_time(unit, value);
665666assert!(get(Unit::Nanosecond, 1).is_ok());
667assert!(get(Unit::Nanosecond, 500).is_ok());
668assert!(get(Unit::Nanosecond, -1).is_err());
669assert!(get(Unit::Nanosecond, 0).is_err());
670assert!(get(Unit::Nanosecond, 7).is_err());
671assert!(get(Unit::Nanosecond, 1_000).is_err());
672assert!(get(Unit::Nanosecond, i64::MIN).is_err());
673assert!(get(Unit::Nanosecond, i64::MAX).is_err());
674675assert!(get(Unit::Microsecond, 1).is_ok());
676assert!(get(Unit::Microsecond, 500).is_ok());
677assert!(get(Unit::Microsecond, -1).is_err());
678assert!(get(Unit::Microsecond, 0).is_err());
679assert!(get(Unit::Microsecond, 7).is_err());
680assert!(get(Unit::Microsecond, 1_000).is_err());
681assert!(get(Unit::Microsecond, i64::MIN).is_err());
682assert!(get(Unit::Microsecond, i64::MAX).is_err());
683684assert!(get(Unit::Millisecond, 1).is_ok());
685assert!(get(Unit::Millisecond, 500).is_ok());
686assert!(get(Unit::Millisecond, -1).is_err());
687assert!(get(Unit::Millisecond, 0).is_err());
688assert!(get(Unit::Millisecond, 7).is_err());
689assert!(get(Unit::Millisecond, 1_000).is_err());
690assert!(get(Unit::Millisecond, i64::MIN).is_err());
691assert!(get(Unit::Millisecond, i64::MAX).is_err());
692693assert!(get(Unit::Second, 1).is_ok());
694assert!(get(Unit::Second, 15).is_ok());
695assert!(get(Unit::Second, -1).is_err());
696assert!(get(Unit::Second, 0).is_err());
697assert!(get(Unit::Second, 7).is_err());
698assert!(get(Unit::Second, 1_000).is_err());
699assert!(get(Unit::Second, i64::MIN).is_err());
700assert!(get(Unit::Second, i64::MAX).is_err());
701702assert!(get(Unit::Minute, 1).is_ok());
703assert!(get(Unit::Minute, 15).is_ok());
704assert!(get(Unit::Minute, -1).is_err());
705assert!(get(Unit::Minute, 0).is_err());
706assert!(get(Unit::Minute, 7).is_err());
707assert!(get(Unit::Minute, 1_000).is_err());
708assert!(get(Unit::Minute, i64::MIN).is_err());
709assert!(get(Unit::Minute, i64::MAX).is_err());
710711assert!(get(Unit::Hour, 1).is_ok());
712assert!(get(Unit::Hour, 6).is_ok());
713assert!(get(Unit::Hour, 12).is_ok());
714assert!(get(Unit::Hour, -1).is_err());
715assert!(get(Unit::Hour, 0).is_err());
716assert!(get(Unit::Hour, 15).is_err());
717assert!(get(Unit::Hour, 18).is_err());
718assert!(get(Unit::Hour, 23).is_err());
719assert!(get(Unit::Hour, 24).is_err());
720assert!(get(Unit::Hour, i64::MIN).is_err());
721assert!(get(Unit::Hour, i64::MAX).is_err());
722723assert!(get(Unit::Day, 1).is_err());
724assert!(get(Unit::Day, -1).is_err());
725assert!(get(Unit::Day, 0).is_err());
726assert!(get(Unit::Day, 2).is_err());
727assert!(get(Unit::Day, 4).is_err());
728assert!(get(Unit::Day, 7).is_err());
729assert!(get(Unit::Day, i64::MIN).is_err());
730assert!(get(Unit::Day, i64::MAX).is_err());
731 }
732733#[test]
734fn for_timestamp() {
735let get = |unit, value| Increment::for_timestamp(unit, value);
736737assert!(get(Unit::Nanosecond, 1).is_ok());
738assert!(get(Unit::Nanosecond, 500).is_ok());
739assert!(get(Unit::Nanosecond, 1_000).is_ok());
740assert!(get(Unit::Nanosecond, 1_000_000_000).is_ok());
741assert!(get(Unit::Nanosecond, -1).is_err());
742assert!(get(Unit::Nanosecond, 0).is_err());
743assert!(get(Unit::Nanosecond, 7).is_err());
744assert!(get(Unit::Nanosecond, 1_000_000_001).is_err());
745assert!(get(Unit::Nanosecond, i64::MIN).is_err());
746assert!(get(Unit::Nanosecond, i64::MAX).is_err());
747748assert!(get(Unit::Microsecond, 1).is_ok());
749assert!(get(Unit::Microsecond, 500).is_ok());
750assert!(get(Unit::Microsecond, 1_000).is_ok());
751assert!(get(Unit::Microsecond, 2_000).is_ok());
752assert!(get(Unit::Microsecond, -1).is_err());
753assert!(get(Unit::Microsecond, 0).is_err());
754assert!(get(Unit::Microsecond, 7).is_err());
755assert!(get(Unit::Microsecond, 1_000_000_000).is_err());
756assert!(get(Unit::Microsecond, 1_000_000_001).is_err());
757assert!(get(Unit::Microsecond, i64::MIN).is_err());
758assert!(get(Unit::Microsecond, i64::MAX).is_err());
759760assert!(get(Unit::Millisecond, 1).is_ok());
761assert!(get(Unit::Millisecond, 500).is_ok());
762assert!(get(Unit::Millisecond, 1_000).is_ok());
763assert!(get(Unit::Millisecond, 2_000).is_ok());
764assert!(get(Unit::Millisecond, 86_400_000).is_ok());
765assert!(get(Unit::Millisecond, -1).is_err());
766assert!(get(Unit::Millisecond, 0).is_err());
767assert!(get(Unit::Millisecond, 7).is_err());
768assert!(get(Unit::Millisecond, 1_000_000_000).is_err());
769assert!(get(Unit::Millisecond, 1_000_000_001).is_err());
770assert!(get(Unit::Millisecond, i64::MIN).is_err());
771assert!(get(Unit::Millisecond, i64::MAX).is_err());
772773assert!(get(Unit::Second, 1).is_ok());
774assert!(get(Unit::Second, 15).is_ok());
775assert!(get(Unit::Second, 3_600).is_ok());
776assert!(get(Unit::Second, 86_400).is_ok());
777assert!(get(Unit::Second, -1).is_err());
778assert!(get(Unit::Second, 0).is_err());
779assert!(get(Unit::Second, 7).is_err());
780assert!(get(Unit::Second, 1_000).is_err());
781assert!(get(Unit::Second, 86_401).is_err());
782assert!(get(Unit::Second, 172_800).is_err());
783assert!(get(Unit::Second, 1_000_000_000).is_err());
784assert!(get(Unit::Second, 1_000_000_001).is_err());
785assert!(get(Unit::Second, i64::MIN).is_err());
786assert!(get(Unit::Second, i64::MAX).is_err());
787788assert!(get(Unit::Minute, 1).is_ok());
789assert!(get(Unit::Minute, 15).is_ok());
790assert!(get(Unit::Minute, 1_440).is_ok());
791assert!(get(Unit::Minute, -1).is_err());
792assert!(get(Unit::Minute, 0).is_err());
793assert!(get(Unit::Minute, 7).is_err());
794assert!(get(Unit::Minute, 1_000).is_err());
795assert!(get(Unit::Minute, 1_441).is_err());
796assert!(get(Unit::Minute, 2_880).is_err());
797assert!(get(Unit::Minute, 1_000_000_000).is_err());
798assert!(get(Unit::Minute, 1_000_000_001).is_err());
799assert!(get(Unit::Minute, i64::MIN).is_err());
800assert!(get(Unit::Minute, i64::MAX).is_err());
801802assert!(get(Unit::Hour, 1).is_ok());
803assert!(get(Unit::Hour, 6).is_ok());
804assert!(get(Unit::Hour, 12).is_ok());
805assert!(get(Unit::Hour, 24).is_ok());
806assert!(get(Unit::Hour, -1).is_err());
807assert!(get(Unit::Hour, 0).is_err());
808assert!(get(Unit::Hour, 15).is_err());
809assert!(get(Unit::Hour, 18).is_err());
810assert!(get(Unit::Hour, 23).is_err());
811assert!(get(Unit::Hour, 25).is_err());
812assert!(get(Unit::Hour, 1_000_000_000).is_err());
813assert!(get(Unit::Hour, 1_000_000_001).is_err());
814assert!(get(Unit::Hour, i64::MIN).is_err());
815assert!(get(Unit::Hour, i64::MAX).is_err());
816817assert!(get(Unit::Day, 1).is_err());
818assert!(get(Unit::Day, -1).is_err());
819assert!(get(Unit::Day, 0).is_err());
820assert!(get(Unit::Day, 2).is_err());
821assert!(get(Unit::Day, 4).is_err());
822assert!(get(Unit::Day, 7).is_err());
823assert!(get(Unit::Day, i64::MIN).is_err());
824assert!(get(Unit::Day, i64::MAX).is_err());
825826assert!(get(Unit::Week, 1).is_err());
827assert!(get(Unit::Week, -1).is_err());
828assert!(get(Unit::Week, 0).is_err());
829assert!(get(Unit::Week, 2).is_err());
830assert!(get(Unit::Week, 4).is_err());
831assert!(get(Unit::Week, 7).is_err());
832assert!(get(Unit::Week, i64::MIN).is_err());
833assert!(get(Unit::Week, i64::MAX).is_err());
834835assert!(get(Unit::Month, 1).is_err());
836assert!(get(Unit::Month, -1).is_err());
837assert!(get(Unit::Month, 0).is_err());
838assert!(get(Unit::Month, 2).is_err());
839assert!(get(Unit::Month, 4).is_err());
840assert!(get(Unit::Month, 7).is_err());
841assert!(get(Unit::Month, i64::MIN).is_err());
842assert!(get(Unit::Month, i64::MAX).is_err());
843844assert!(get(Unit::Year, 1).is_err());
845assert!(get(Unit::Year, -1).is_err());
846assert!(get(Unit::Year, 0).is_err());
847assert!(get(Unit::Year, 2).is_err());
848assert!(get(Unit::Year, 4).is_err());
849assert!(get(Unit::Year, 7).is_err());
850assert!(get(Unit::Year, i64::MIN).is_err());
851assert!(get(Unit::Year, i64::MAX).is_err());
852 }
853854// Some ad hoc tests I wrote while writing the rounding increment code.
855#[test]
856fn round_to_increment_half_expand_ad_hoc() {
857let round = |quantity: i128, increment: i128| -> i128 {
858 RoundMode::HalfExpand.round_by_i128(quantity, increment)
859 };
860assert_eq!(26, round(20, 13));
861862assert_eq!(0, round(29, 60));
863assert_eq!(60, round(30, 60));
864assert_eq!(60, round(31, 60));
865866assert_eq!(0, round(3, 7));
867assert_eq!(7, round(4, 7));
868 }
869870// The Temporal tests are inspired by the table from here:
871 // https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
872 //
873 // The main difference is that our rounding function specifically does not
874 // use floating point, so we tweak the values a bit.
875876#[test]
877fn round_to_increment_temporal_table_ceil() {
878let round = |quantity: i128, increment: i128| -> i128 {
879 RoundMode::Ceil.round_by_i128(quantity, increment)
880 };
881assert_eq!(-10, round(-15, 10));
882assert_eq!(0, round(-5, 10));
883assert_eq!(10, round(4, 10));
884assert_eq!(10, round(5, 10));
885assert_eq!(10, round(6, 10));
886assert_eq!(20, round(15, 10));
887888assert_eq!(i128::MAX, round(i128::MAX, 1));
889assert_eq!(i128::MAX, round(i128::MAX, i128::MAX));
890891// TODO: This test currently panics on overflow.
892 // We should overall scrutinize the input constraints
893 // for our rounding routines and align with their call
894 // sites. We were previously relying on ranged integers
895 // to holistically verify we weren't doing anything that
896 // could result in overflow. I suspect that we can't
897 // actually support the i128 quantity range (and I don't
898 // think we need to). The question is whether we should
899 // make the rounding interface fallible or if this
900 // should just document panicking conditions.
901 //
902 // Oh, we should introduce a new internal `Increment`
903 // wrapper that provides guarantees about its range.
904 // assert_eq!(i128::MIN, round(i128::MIN, -1));
905 // assert_eq!(i128::MIN, round(i128::MIN, i128::MIN));
906}
907908#[test]
909fn round_to_increment_temporal_table_floor() {
910let round = |quantity: i128, increment: i128| -> i128 {
911 RoundMode::Floor.round_by_i128(quantity, increment)
912 };
913assert_eq!(-20, round(-15, 10));
914assert_eq!(-10, round(-5, 10));
915assert_eq!(0, round(4, 10));
916assert_eq!(0, round(5, 10));
917assert_eq!(0, round(6, 10));
918assert_eq!(10, round(15, 10));
919 }
920921#[test]
922fn round_to_increment_temporal_table_expand() {
923let round = |quantity: i128, increment: i128| -> i128 {
924 RoundMode::Expand.round_by_i128(quantity, increment)
925 };
926assert_eq!(-20, round(-15, 10));
927assert_eq!(-10, round(-5, 10));
928assert_eq!(10, round(4, 10));
929assert_eq!(10, round(5, 10));
930assert_eq!(10, round(6, 10));
931assert_eq!(20, round(15, 10));
932 }
933934#[test]
935fn round_to_increment_temporal_table_trunc() {
936let round = |quantity: i128, increment: i128| -> i128 {
937 RoundMode::Trunc.round_by_i128(quantity, increment)
938 };
939assert_eq!(-10, round(-15, 10));
940assert_eq!(0, round(-5, 10));
941assert_eq!(0, round(4, 10));
942assert_eq!(0, round(5, 10));
943assert_eq!(0, round(6, 10));
944assert_eq!(10, round(15, 10));
945 }
946947#[test]
948fn round_to_increment_temporal_table_half_ceil() {
949let round = |quantity: i128, increment: i128| -> i128 {
950 RoundMode::HalfCeil.round_by_i128(quantity, increment)
951 };
952assert_eq!(-10, round(-15, 10));
953assert_eq!(0, round(-5, 10));
954assert_eq!(0, round(4, 10));
955assert_eq!(10, round(5, 10));
956assert_eq!(10, round(6, 10));
957assert_eq!(20, round(15, 10));
958 }
959960#[test]
961fn round_to_increment_temporal_table_half_floor() {
962let round = |quantity: i128, increment: i128| -> i128 {
963 RoundMode::HalfFloor.round_by_i128(quantity, increment)
964 };
965assert_eq!(-20, round(-15, 10));
966assert_eq!(-10, round(-5, 10));
967assert_eq!(0, round(4, 10));
968assert_eq!(0, round(5, 10));
969assert_eq!(10, round(6, 10));
970assert_eq!(10, round(15, 10));
971 }
972973#[test]
974fn round_to_increment_temporal_table_half_expand() {
975let round = |quantity: i128, increment: i128| -> i128 {
976 RoundMode::HalfExpand.round_by_i128(quantity, increment)
977 };
978assert_eq!(-20, round(-15, 10));
979assert_eq!(-10, round(-5, 10));
980assert_eq!(0, round(4, 10));
981assert_eq!(10, round(5, 10));
982assert_eq!(10, round(6, 10));
983assert_eq!(20, round(15, 10));
984 }
985986#[test]
987fn round_to_increment_temporal_table_half_trunc() {
988let round = |quantity: i128, increment: i128| -> i128 {
989 RoundMode::HalfTrunc.round_by_i128(quantity, increment)
990 };
991assert_eq!(-10, round(-15, 10));
992assert_eq!(0, round(-5, 10));
993assert_eq!(0, round(4, 10));
994assert_eq!(0, round(5, 10));
995assert_eq!(10, round(6, 10));
996assert_eq!(10, round(15, 10));
997 }
998999#[test]
1000fn round_to_increment_temporal_table_half_even() {
1001let round = |quantity: i128, increment: i128| -> i128 {
1002 RoundMode::HalfEven.round_by_i128(quantity, increment)
1003 };
1004assert_eq!(-20, round(-15, 10));
1005assert_eq!(0, round(-5, 10));
1006assert_eq!(0, round(4, 10));
1007assert_eq!(0, round(5, 10));
1008assert_eq!(10, round(6, 10));
1009assert_eq!(20, round(15, 10));
1010 }
10111012// Tests that the maximum possible increment, in units of nanoseconds,
1013 // fits into a `SignedDuration`.
1014#[test]
1015fn maximum_increment_nanos() {
1016assert!(Increment::for_span(Unit::Week, 1_000_000_000).is_ok());
1017assert!(Increment::for_span(Unit::Week, 1_000_000_001).is_err());
1018assert_eq!(
1019 Unit::Week.duration() * 1_000_000_000,
1020 SignedDuration::from_secs(168_000_000_000 * 60 * 60)
1021 );
1022 }
10231024// Tests some edge cases where rounding can actually overflow. We ensure
1025 // that an error is returned instead of panicking.
1026 //
1027 // I do not believe it's possible for these overflows to be observed using
1028 // Jiff's public API however.
1029#[test]
1030fn round_by_duration_overflow() {
1031let mode = RoundMode::Expand;
1032let quantity = SignedDuration::MAX;
1033let increment = SignedDuration::MAX - SignedDuration::from_secs(1);
1034assert!(mode.round_by_duration(quantity, increment).is_err());
10351036let mode = RoundMode::Expand;
1037let quantity = SignedDuration::MIN;
1038let increment = SignedDuration::MAX;
1039assert!(mode.round_by_duration(quantity, increment).is_err());
1040 }
1041}