jiff/util/round/
mode.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
use crate::{
    util::{
        rangeint::{RFrom, RInto},
        t::{NoUnits, NoUnits128, C, C128},
    },
    Unit,
};

/// The mode for dealing with the remainder when rounding datetimes or spans.
///
/// This is used in APIs like [`Span::round`](crate::Span::round) for rounding
/// spans, and APIs like [`Zoned::round`](crate::Zoned::round) for rounding
/// datetimes.
///
/// In the documentation for each variant, we refer to concepts like the
/// "smallest" unit and the "rounding increment." These are best described
/// in the documentation for what you're rounding. For example,
/// [`SpanRound::smallest`](crate::SpanRound::smallest)
/// and [`SpanRound::increment`](crate::SpanRound::increment).
///
/// # Example
///
/// This shows how to round a span with a different rounding mode than the
/// default:
///
/// ```
/// use jiff::{RoundMode, SpanRound, ToSpan, Unit};
///
/// // The default rounds like how you were taught in school:
/// assert_eq!(
///     1.hour().minutes(59).round(Unit::Hour)?,
///     2.hours().fieldwise(),
/// );
/// // But we can change the mode, e.g., truncation:
/// let options = SpanRound::new().smallest(Unit::Hour).mode(RoundMode::Trunc);
/// assert_eq!(
///     1.hour().minutes(59).round(options)?,
///     1.hour().fieldwise(),
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum RoundMode {
    /// Rounds toward positive infinity.
    ///
    /// For negative spans and datetimes, this option will make the value
    /// smaller, which could be unexpected. To round away from zero, use
    /// `Expand`.
    Ceil,
    /// Rounds toward negative infinity.
    ///
    /// This mode acts like `Trunc` for positive spans and datetimes, but
    /// for negative values it will make the value larger, which could be
    /// unexpected. To round towards zero, use `Trunc`.
    Floor,
    /// Rounds away from zero like `Ceil` for positive spans and datetimes,
    /// and like `Floor` for negative spans and datetimes.
    Expand,
    /// Rounds toward zero, chopping off any fractional part of a unit.
    ///
    /// This is the default when rounding spans returned from
    /// datetime arithmetic. (But it is not the default for
    /// [`Span::round`](crate::Span::round).)
    Trunc,
    /// Rounds to the nearest allowed value like `HalfExpand`, but when there
    /// is a tie, round towards positive infinity like `Ceil`.
    HalfCeil,
    /// Rounds to the nearest allowed value like `HalfExpand`, but when there
    /// is a tie, round towards negative infinity like `Floor`.
    HalfFloor,
    /// Rounds to the nearest value allowed by the rounding increment and the
    /// smallest unit. When there is a tie, round away from zero like `Ceil`
    /// for positive spans and datetimes and like `Floor` for negative spans
    /// and datetimes.
    ///
    /// This corresponds to how rounding is often taught in school.
    ///
    /// This is the default for rounding spans and datetimes.
    HalfExpand,
    /// Rounds to the nearest allowed value like `HalfExpand`, but when there
    /// is a tie, round towards zero like `Trunc`.
    HalfTrunc,
    /// Rounds to the nearest allowed value like `HalfExpand`, but when there
    /// is a tie, round towards the value that is an even multiple of the
    /// rounding increment. For example, with a rounding increment of `3`,
    /// the number `10` would round up to `12` instead of down to `9`, because
    /// `12` is an even multiple of `3`, where as `9` is is an odd multiple.
    HalfEven,
}

impl RoundMode {
    /// Given a `quantity` in nanoseconds and an `increment` in units of
    /// `unit`, this rounds it according to this mode and returns the result
    /// in nanoseconds.
    pub(crate) fn round_by_unit_in_nanoseconds(
        self,
        quantity: impl RInto<NoUnits128>,
        unit: Unit,
        increment: impl RInto<NoUnits128>,
    ) -> NoUnits128 {
        let quantity = quantity.rinto();
        let increment = unit.nanoseconds() * increment.rinto();
        let rounded = self.round(quantity, increment);
        rounded
    }

    fn round(
        self,
        quantity: impl RInto<NoUnits128>,
        increment: impl RInto<NoUnits128>,
    ) -> NoUnits128 {
        // ref: https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
        fn inner(
            mode: RoundMode,
            quantity: NoUnits128,
            increment: NoUnits128,
        ) -> NoUnits128 {
            let mut quotient = quantity.div_ceil(increment);
            let remainder = quantity.rem_ceil(increment);
            if remainder == 0 {
                return quantity;
            }
            let sign = if remainder < 0 { C128(-1) } else { C128(1) };
            let tiebreaker = (remainder * C128(2)).abs();
            let tie = tiebreaker == increment;
            let expand_is_nearer = tiebreaker > increment;
            // ref: https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
            match mode {
                RoundMode::Ceil => {
                    if sign > 0 {
                        quotient += sign;
                    }
                }
                RoundMode::Floor => {
                    if sign < 0 {
                        quotient += sign;
                    }
                }
                RoundMode::Expand => {
                    quotient += sign;
                }
                RoundMode::Trunc => {}
                RoundMode::HalfCeil => {
                    if expand_is_nearer || (tie && sign > 0) {
                        quotient += sign;
                    }
                }
                RoundMode::HalfFloor => {
                    if expand_is_nearer || (tie && sign < 0) {
                        quotient += sign;
                    }
                }
                RoundMode::HalfExpand => {
                    if expand_is_nearer || tie {
                        quotient += sign;
                    }
                }
                RoundMode::HalfTrunc => {
                    if expand_is_nearer {
                        quotient += sign;
                    }
                }
                RoundMode::HalfEven => {
                    if expand_is_nearer || (tie && quotient % C(2) == 1) {
                        quotient += sign;
                    }
                }
            }
            // We use saturating arithmetic here because this can overflow
            // when `quantity` is the max value. Since we're rounding, we just
            // refuse to go over the maximum. I'm not 100% convinced this is
            // correct, but I think the only alternative is to return an error,
            // and I'm not sure that's ideal either.
            quotient.saturating_mul(increment)
        }
        inner(self, quantity.rinto(), increment.rinto())
    }

    pub(crate) fn round_float(
        self,
        quantity: f64,
        increment: NoUnits128,
    ) -> NoUnits128 {
        #[cfg(not(feature = "std"))]
        use crate::util::libm::Float;

        let quotient = quantity / (increment.get() as f64);
        let rounded = match self {
            RoundMode::Ceil => quotient.ceil(),
            RoundMode::Floor => quotient.floor(),
            RoundMode::Expand => {
                if quotient < 0.0 {
                    quotient.floor()
                } else {
                    quotient.ceil()
                }
            }
            RoundMode::Trunc => quotient.trunc(),
            RoundMode::HalfCeil => {
                if quotient % 1.0 == 0.5 {
                    quotient.ceil()
                } else {
                    quotient.round()
                }
            }
            RoundMode::HalfFloor => {
                if quotient % 1.0 == 0.5 {
                    quotient.floor()
                } else {
                    quotient.round()
                }
            }
            RoundMode::HalfExpand => {
                quotient.signum() * quotient.abs().round()
            }
            RoundMode::HalfTrunc => {
                if quotient % 1.0 == 0.5 {
                    quotient.trunc()
                } else {
                    quotient.round()
                }
            }
            RoundMode::HalfEven => {
                if quotient % 1.0 == 0.5 {
                    quotient.trunc() + (quotient % 2.0)
                } else {
                    quotient.round()
                }
            }
        };
        let rounded = NoUnits::new(rounded as i64).unwrap();
        NoUnits128::rfrom(rounded.saturating_mul(increment))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Some ad hoc tests I wrote while writing the rounding increment code.
    #[test]
    fn round_to_increment_half_expand_ad_hoc() {
        let round = |quantity: i64, increment: i64| -> i64 {
            let quantity = NoUnits::new(quantity).unwrap();
            let increment = NoUnits::new(increment).unwrap();
            i64::from(RoundMode::HalfExpand.round(quantity, increment))
        };
        assert_eq!(26, round(20, 13));

        assert_eq!(0, round(29, 60));
        assert_eq!(60, round(30, 60));
        assert_eq!(60, round(31, 60));

        assert_eq!(0, round(3, 7));
        assert_eq!(7, round(4, 7));
    }

    // The Temporal tests are inspired by the table from here:
    // https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
    //
    // The main difference is that our rounding function specifically does not
    // use floating point, so we tweak the values a bit.

    #[test]
    fn round_to_increment_temporal_table_ceil() {
        let round = |quantity: i64, increment: i64| -> i64 {
            let quantity = NoUnits::new(quantity).unwrap();
            let increment = NoUnits::new(increment).unwrap();
            RoundMode::Ceil.round(quantity, increment).into()
        };
        assert_eq!(-10, round(-15, 10));
        assert_eq!(0, round(-5, 10));
        assert_eq!(10, round(4, 10));
        assert_eq!(10, round(5, 10));
        assert_eq!(10, round(6, 10));
        assert_eq!(20, round(15, 10));
    }

    #[test]
    fn round_to_increment_temporal_table_floor() {
        let round = |quantity: i64, increment: i64| -> i64 {
            let quantity = NoUnits::new(quantity).unwrap();
            let increment = NoUnits::new(increment).unwrap();
            RoundMode::Floor.round(quantity, increment).into()
        };
        assert_eq!(-20, round(-15, 10));
        assert_eq!(-10, round(-5, 10));
        assert_eq!(0, round(4, 10));
        assert_eq!(0, round(5, 10));
        assert_eq!(0, round(6, 10));
        assert_eq!(10, round(15, 10));
    }

    #[test]
    fn round_to_increment_temporal_table_expand() {
        let round = |quantity: i64, increment: i64| -> i64 {
            let quantity = NoUnits::new(quantity).unwrap();
            let increment = NoUnits::new(increment).unwrap();
            RoundMode::Expand.round(quantity, increment).into()
        };
        assert_eq!(-20, round(-15, 10));
        assert_eq!(-10, round(-5, 10));
        assert_eq!(10, round(4, 10));
        assert_eq!(10, round(5, 10));
        assert_eq!(10, round(6, 10));
        assert_eq!(20, round(15, 10));
    }

    #[test]
    fn round_to_increment_temporal_table_trunc() {
        let round = |quantity: i64, increment: i64| -> i64 {
            let quantity = NoUnits::new(quantity).unwrap();
            let increment = NoUnits::new(increment).unwrap();
            RoundMode::Trunc.round(quantity, increment).into()
        };
        assert_eq!(-10, round(-15, 10));
        assert_eq!(0, round(-5, 10));
        assert_eq!(0, round(4, 10));
        assert_eq!(0, round(5, 10));
        assert_eq!(0, round(6, 10));
        assert_eq!(10, round(15, 10));
    }

    #[test]
    fn round_to_increment_temporal_table_half_ceil() {
        let round = |quantity: i64, increment: i64| -> i64 {
            let quantity = NoUnits::new(quantity).unwrap();
            let increment = NoUnits::new(increment).unwrap();
            RoundMode::HalfCeil.round(quantity, increment).into()
        };
        assert_eq!(-10, round(-15, 10));
        assert_eq!(0, round(-5, 10));
        assert_eq!(0, round(4, 10));
        assert_eq!(10, round(5, 10));
        assert_eq!(10, round(6, 10));
        assert_eq!(20, round(15, 10));
    }

    #[test]
    fn round_to_increment_temporal_table_half_floor() {
        let round = |quantity: i64, increment: i64| -> i64 {
            let quantity = NoUnits::new(quantity).unwrap();
            let increment = NoUnits::new(increment).unwrap();
            RoundMode::HalfFloor.round(quantity, increment).into()
        };
        assert_eq!(-20, round(-15, 10));
        assert_eq!(-10, round(-5, 10));
        assert_eq!(0, round(4, 10));
        assert_eq!(0, round(5, 10));
        assert_eq!(10, round(6, 10));
        assert_eq!(10, round(15, 10));
    }

    #[test]
    fn round_to_increment_temporal_table_half_expand() {
        let round = |quantity: i64, increment: i64| -> i64 {
            let quantity = NoUnits::new(quantity).unwrap();
            let increment = NoUnits::new(increment).unwrap();
            RoundMode::HalfExpand.round(quantity, increment).into()
        };
        assert_eq!(-20, round(-15, 10));
        assert_eq!(-10, round(-5, 10));
        assert_eq!(0, round(4, 10));
        assert_eq!(10, round(5, 10));
        assert_eq!(10, round(6, 10));
        assert_eq!(20, round(15, 10));
    }

    #[test]
    fn round_to_increment_temporal_table_half_trunc() {
        let round = |quantity: i64, increment: i64| -> i64 {
            let quantity = NoUnits::new(quantity).unwrap();
            let increment = NoUnits::new(increment).unwrap();
            RoundMode::HalfTrunc.round(quantity, increment).into()
        };
        assert_eq!(-10, round(-15, 10));
        assert_eq!(0, round(-5, 10));
        assert_eq!(0, round(4, 10));
        assert_eq!(0, round(5, 10));
        assert_eq!(10, round(6, 10));
        assert_eq!(10, round(15, 10));
    }

    #[test]
    fn round_to_increment_temporal_table_half_even() {
        let round = |quantity: i64, increment: i64| -> i64 {
            let quantity = NoUnits::new(quantity).unwrap();
            let increment = NoUnits::new(increment).unwrap();
            RoundMode::HalfEven.round(quantity, increment).into()
        };
        assert_eq!(-20, round(-15, 10));
        assert_eq!(0, round(-5, 10));
        assert_eq!(0, round(4, 10));
        assert_eq!(0, round(5, 10));
        assert_eq!(10, round(6, 10));
        assert_eq!(20, round(15, 10));
    }
}