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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

//! A time interval abstract data type.

use std::fmt::{self, Write};
use std::time::Duration;

use anyhow::bail;
use serde::{Deserialize, Serialize};

use crate::adt::datetime::DateTimeField;
use crate::adt::numeric::DecimalLike;

/// An interval of time meant to express SQL intervals.
///
/// Obtained by parsing an `INTERVAL '<value>' <unit> [TO <precision>]`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Hash, Deserialize)]
pub struct Interval {
    /// A possibly negative number of months for field types like `YEAR`
    pub months: i32,
    /// A timespan represented in nanoseconds.
    ///
    /// Irrespective of values, `duration` will not be carried over into
    /// `months`.
    pub duration: i128,
}

impl Default for Interval {
    fn default() -> Self {
        Self {
            months: 0,
            duration: 0,
        }
    }
}

impl std::ops::Neg for Interval {
    type Output = Self;
    fn neg(self) -> Self {
        Self {
            months: -self.months,
            duration: -self.duration,
        }
    }
}

impl Interval {
    /// Constructs a new `Interval` with the specified units of time.
    ///
    /// `nanos` in excess of `999_999_999` are carried over into seconds.
    pub fn new(months: i32, seconds: i64, nanos: i64) -> Result<Interval, anyhow::Error> {
        let i = Interval {
            months,
            duration: i128::from(seconds) * 1_000_000_000 + i128::from(nanos),
        };
        // Don't let our duration exceed Postgres' min/max for those same fields,
        // equivalent to:
        // ```
        // SELECT INTERVAL '2147483647 days 2147483647 hours 59 minutes 59.999999 seconds';
        // SELECT INTERVAL '-2147483647 days -2147483647 hours -59 minutes -59.999999 seconds';
        // ```
        if i.duration > 193_273_528_233_599_999_999_000
            || i.duration < -193_273_528_233_599_999_999_000
        {
            bail!(
                "exceeds min/max interval duration +/-(2147483647 days 2147483647 hours \
                59 minutes 59.999999 seconds)"
            )
        } else {
            Ok(i)
        }
    }

    pub fn checked_add(&self, other: &Self) -> Option<Self> {
        let months = match self.months.checked_add(other.months) {
            Some(m) => m,
            None => return None,
        };
        let seconds = match self.dur_as_secs().checked_add(other.dur_as_secs()) {
            Some(s) => s,
            None => return None,
        };

        match Self::new(
            months,
            seconds,
            i64::from(self.nanoseconds() + other.nanoseconds()),
        ) {
            Ok(i) => Some(i),
            Err(_) => None,
        }
    }

    pub fn checked_mul(&self, other: f64) -> Option<Self> {
        let months = self.months as f64 * other;
        if months.is_nan() || months < i32::MIN as f64 || months > i32::MAX as f64 {
            return None;
        }

        let seconds =
            self.dur_as_secs() as f64 * other + months.fract() * 60.0 * 60.0 * 24.0 * 30.0;
        if seconds.is_nan() || seconds < i64::MIN as f64 || seconds > i64::MAX as f64 {
            return None;
        }

        let nanos = self.nanoseconds() as f64 * other + seconds.fract() * 1e9;
        if nanos.is_nan() || nanos < i64::MIN as f64 || nanos > i64::MAX as f64 {
            return None;
        }

        Self::new(months as i32, seconds as i64, nanos as i64).ok()
    }

    pub fn checked_div(&self, other: f64) -> Option<Self> {
        let months = self.months as f64 / other;
        if months.is_nan() || months < i32::MIN as f64 || months > i32::MAX as f64 {
            return None;
        }

        let seconds =
            self.dur_as_secs() as f64 / other + months.fract() * 60.0 * 60.0 * 24.0 * 30.0;
        if seconds.is_nan() || seconds < i64::MIN as f64 || seconds > i64::MAX as f64 {
            return None;
        }

        let nanos = self.nanoseconds() as f64 / other + seconds.fract() * 1e9;
        if nanos.is_nan() || nanos < i64::MIN as f64 || nanos > i64::MAX as f64 {
            return None;
        }

        Self::new(months as i32, seconds as i64, nanos as i64).ok()
    }

    /// Returns the total number of whole seconds in the `Interval`'s duration.
    pub fn dur_as_secs(&self) -> i64 {
        (self.duration / 1_000_000_000) as i64
    }

    /// Computes the millennium part of the interval.
    ///
    /// The millennium part is the number of whole millennia in the interval. For example,
    /// this function returns `3` for the interval `3400 years`.
    pub fn millennia(&self) -> i32 {
        self.months / 12_000
    }

    /// Computes the century part of the interval.
    ///
    /// The century part is the number of whole centuries in the interval. For example,
    /// this function returns `3` for the interval `340 years`.
    pub fn centuries(&self) -> i32 {
        self.months / 1_200
    }

    /// Computes the decade part of the interval.
    ///
    /// The decade part is the number of whole decades in the interval. For example,
    /// this function returns `3` for the interval `34 years`.
    pub fn decades(&self) -> i32 {
        self.months / 120
    }

    /// Computes the year part of the interval.
    ///
    /// The year part is the number of whole years in the interval. For example,
    /// this function returns `3` for the interval `3 years 4 months`.
    pub fn years(&self) -> i32 {
        self.months / 12
    }

    /// Computes the quarter part of the interval.
    ///
    /// The quarter part is obtained from taking the number of whole months modulo 12,
    /// and assigning quarter #1 for months 0-2, #2 for 3-5, #3 for 6-8 and #4 for 9-11.
    /// For example, this function returns `4` for the interval `11 months`.
    pub fn quarters(&self) -> i32 {
        (self.months % 12) / 3 + 1
    }

    /// Computes the month part of the interval.
    ///
    /// The month part is the number of whole months in the interval, modulo 12.
    /// For example, this function returns `4` for the interval `3 years 4
    /// months`.
    pub fn months(&self) -> i32 {
        self.months % 12
    }

    /// Computes the day part of the interval.
    ///
    /// The day part is the number of whole days in the interval. For example,
    /// this function returns `5` for the interval `5 days 4 hours 3 minutes
    /// 2.1 seconds`.
    pub fn days(&self) -> i64 {
        self.dur_as_secs() / (60 * 60 * 24)
    }

    /// Computes the hour part of the interval.
    ///
    /// The hour part is the number of whole hours in the interval, modulo 24.
    /// For example, this function returns `4` for the interval `5 days 4
    /// hours 3 minutes 2.1 seconds`.
    pub fn hours(&self) -> i64 {
        (self.dur_as_secs() / (60 * 60)) % 24
    }

    /// Computes the minute part of the interval.
    ///
    /// The minute part is the number of whole minutes in the interval, modulo
    /// 60. For example, this function returns `3` for the interval `5 days 4
    /// hours 3 minutes 2.1 seconds`.
    pub fn minutes(&self) -> i64 {
        (self.dur_as_secs() / 60) % 60
    }

    /// Computes the second part of the interval.
    ///
    /// The second part is the number of fractional seconds in the interval,
    /// modulo 60.0.
    pub fn seconds<T>(&self) -> T
    where
        T: DecimalLike,
    {
        T::lossy_from((self.duration % 60_000_000_000) as i64) / T::from(1e9)
    }

    /// Computes the second part of the interval displayed in milliseconds.
    ///
    /// The second part is the number of fractional seconds in the interval,
    /// modulo 60.0.
    pub fn milliseconds<T>(&self) -> T
    where
        T: DecimalLike,
    {
        T::lossy_from((self.duration % 60_000_000_000) as i64) / T::from(1e6)
    }

    /// Computes the second part of the interval displayed in microseconds.
    ///
    /// The second part is the number of fractional seconds in the interval,
    /// modulo 60.0.
    pub fn microseconds<T>(&self) -> T
    where
        T: DecimalLike,
    {
        T::lossy_from((self.duration % 60_000_000_000) as i64) / T::from(1e3)
    }

    /// Computes the nanosecond part of the interval.
    pub fn nanoseconds(&self) -> i32 {
        (self.duration % 1_000_000_000) as i32
    }

    /// Computes the total number of seconds in the interval.
    pub fn as_seconds<T>(&self) -> T
    where
        T: DecimalLike,
    {
        T::from(self.years() * 60 * 60 * 24) * T::from(365.25)
            + T::from(self.months() * 60 * 60 * 24 * 30)
            + T::lossy_from(self.dur_as_secs())
            + T::from(self.nanoseconds()) / T::from(1e9)
    }

    /// Truncate the "head" of the interval, removing all time units greater than `f`.
    pub fn truncate_high_fields(&mut self, f: DateTimeField) {
        match f {
            DateTimeField::Year => {}
            DateTimeField::Month => self.months %= 12,
            DateTimeField::Day => self.months = 0,
            DateTimeField::Hour | DateTimeField::Minute | DateTimeField::Second => {
                self.months = 0;
                self.duration %= f.next_largest().nanos_multiplier() as i128
            }
            DateTimeField::Millennium
            | DateTimeField::Century
            | DateTimeField::Decade
            | DateTimeField::Milliseconds
            | DateTimeField::Microseconds => {
                unreachable!(format!("Cannot truncate interval by {}", f))
            }
        }
    }

    /// Converts this `Interval`'s duration into `chrono::Duration`.
    pub fn duration_as_chrono(&self) -> chrono::Duration {
        use chrono::Duration;
        // This can be converted into a single call with
        // https://github.com/chronotope/chrono/pull/426
        Duration::seconds(self.dur_as_secs() as i64)
            + Duration::nanoseconds(self.nanoseconds() as i64)
    }

    pub fn duration(&self) -> Result<Duration, anyhow::Error> {
        if self.duration < 0 {
            bail!("cannot convert negative interval to duration");
        }
        if self.months != 0 {
            bail!("cannot convert interval with months to duration");
        }
        Ok(Duration::new(
            self.dur_as_secs() as u64,
            self.nanoseconds() as u32,
        ))
    }

    /// Truncate the "tail" of the interval, removing all time units less than `f`.
    /// # Arguments
    /// - `f`: Round the interval down to the specified time unit.
    /// - `fsec_max_precision`: If `Some(x)`, keep only `x` places of nanosecond precision.
    ///    Must be `(0,6)`.
    ///
    /// # Errors
    /// - If `fsec_max_precision` is not None or within (0,6).
    pub fn truncate_low_fields(
        &mut self,
        f: DateTimeField,
        fsec_max_precision: Option<u64>,
    ) -> Result<(), anyhow::Error> {
        use DateTimeField::*;
        match f {
            Year => {
                self.months -= self.months % 12;
                self.duration = 0;
            }
            Month => {
                self.duration = 0;
            }
            // Round nanoseconds.
            Second => {
                let default_precision = 6;
                let precision = match fsec_max_precision {
                    Some(p) => p,
                    None => default_precision,
                };

                if precision > default_precision {
                    bail!(
                        "SECOND precision must be (0, 6), have SECOND({})",
                        precision
                    )
                }

                // Check if value should round up to nearest fractional place.
                let remainder = self.duration % 10_i128.pow(9 - precision as u32);
                if remainder / 10_i128.pow(8 - precision as u32) > 4 {
                    self.duration += 10_i128.pow(9 - precision as u32);
                }

                self.duration -= remainder;
            }
            Day | Hour | Minute => {
                self.duration -= self.duration % f.nanos_multiplier() as i128;
            }
            Millennium | Century | Decade | Milliseconds | Microseconds => {
                unreachable!(format!("Cannot truncate interval by {}", f))
            }
        }
        Ok(())
    }
}

/// Format an interval in a human form
///
/// Example outputs:
///
/// * 1 year 2 months 5 days 03:04:00
/// * -1 year +5 days +18:59:29.3
/// * 00:00:00
impl fmt::Display for Interval {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut months = self.months;
        let neg_mos = months < 0;
        months = months.abs();
        let years = months / 12;
        months %= 12;
        let mut secs = self.dur_as_secs().abs();
        let mut nanos = self.nanoseconds().abs();
        let days = secs / (24 * 60 * 60);
        secs %= 24 * 60 * 60;
        let hours = secs / (60 * 60);
        secs %= 60 * 60;
        let minutes = secs / 60;
        secs %= 60;

        if years > 0 {
            if neg_mos {
                f.write_char('-')?;
            }
            write!(f, "{} year", years)?;
            if years > 1 {
                f.write_char('s')?;
            }
        }

        if months > 0 {
            if years != 0 {
                f.write_char(' ')?;
            }
            if neg_mos {
                f.write_char('-')?;
            }
            write!(f, "{} month", months)?;
            if months > 1 {
                f.write_char('s')?;
            }
        }

        if days > 0 {
            if years > 0 || months > 0 {
                f.write_char(' ')?;
            }
            if self.duration < 0 {
                f.write_char('-')?;
            } else if neg_mos {
                f.write_char('+')?;
            }
            write!(f, "{} day", days)?;
            if days != 1 {
                f.write_char('s')?;
            }
        }

        let non_zero_hmsn = hours > 0 || minutes > 0 || secs > 0 || nanos > 0;

        if (years == 0 && months == 0 && days == 0) || non_zero_hmsn {
            if years > 0 || months > 0 || days > 0 {
                f.write_char(' ')?;
            }
            if self.duration < 0 && non_zero_hmsn {
                f.write_char('-')?;
            } else if neg_mos {
                f.write_char('+')?;
            }
            write!(f, "{:02}:{:02}:{:02}", hours, minutes, secs)?;
            if nanos > 0 {
                let mut width = 9;
                while nanos % 10 == 0 {
                    width -= 1;
                    nanos /= 10;
                }
                write!(f, ".{:0width$}", nanos, width = width)?;
            }
        }

        Ok(())
    }
}

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

    #[test]
    fn interval_fmt() {
        fn mon(mon: i32) -> String {
            Interval {
                months: mon,
                ..Default::default()
            }
            .to_string()
        }

        assert_eq!(mon(1), "1 month");
        assert_eq!(mon(12), "1 year");
        assert_eq!(mon(13), "1 year 1 month");
        assert_eq!(mon(24), "2 years");
        assert_eq!(mon(25), "2 years 1 month");
        assert_eq!(mon(26), "2 years 2 months");

        fn dur(d: i64) -> String {
            Interval::new(0, d, 0).unwrap().to_string()
        }
        assert_eq!(&dur(86_400 * 2), "2 days");
        assert_eq!(&dur(86_400 * 2 + 3_600 * 3), "2 days 03:00:00");
        assert_eq!(
            &dur(86_400 * 2 + 3_600 * 3 + 60 * 45 + 6),
            "2 days 03:45:06"
        );
        assert_eq!(&dur(86_400 * 2 + 3_600 * 3 + 60 * 45), "2 days 03:45:00");
        assert_eq!(&dur(86_400 * 2 + 6), "2 days 00:00:06");
        assert_eq!(&dur(86_400 * 2 + 60 * 45 + 6), "2 days 00:45:06");
        assert_eq!(&dur(86_400 * 2 + 3_600 * 3 + 6), "2 days 03:00:06");
        assert_eq!(&dur(3_600 * 3 + 60 * 45 + 6), "03:45:06");
        assert_eq!(&dur(3_600 * 3 + 6), "03:00:06");
        assert_eq!(&dur(3_600 * 3), "03:00:00");
        assert_eq!(&dur(60 * 45 + 6), "00:45:06");
        assert_eq!(&dur(60 * 45), "00:45:00");
        assert_eq!(&dur(6), "00:00:06");

        assert_eq!(&dur(-(86_400 * 2 + 6)), "-2 days -00:00:06");
        assert_eq!(&dur(-(86_400 * 2 + 60 * 45 + 6)), "-2 days -00:45:06");
        assert_eq!(&dur(-(86_400 * 2 + 3_600 * 3 + 6)), "-2 days -03:00:06");
        assert_eq!(&dur(-(3_600 * 3 + 60 * 45 + 6)), "-03:45:06");
        assert_eq!(&dur(-(3_600 * 3 + 6)), "-03:00:06");
        assert_eq!(&dur(-(3_600 * 3)), "-03:00:00");
        assert_eq!(&dur(-(60 * 45 + 6)), "-00:45:06");
        assert_eq!(&dur(-(60 * 45)), "-00:45:00");
        assert_eq!(&dur(-6), "-00:00:06");

        fn mon_dur(mon: i32, d: i64) -> String {
            Interval::new(mon, d, 0).unwrap().to_string()
        }
        assert_eq!(&mon_dur(1, 86_400 * 2 + 6), "1 month 2 days 00:00:06");
        assert_eq!(
            &mon_dur(1, 86_400 * 2 + 60 * 45 + 6),
            "1 month 2 days 00:45:06"
        );
        assert_eq!(
            &mon_dur(1, 86_400 * 2 + 3_600 * 3 + 6),
            "1 month 2 days 03:00:06"
        );
        assert_eq!(
            &mon_dur(26, 3_600 * 3 + 60 * 45 + 6),
            "2 years 2 months 03:45:06"
        );
        assert_eq!(&mon_dur(26, 3_600 * 3 + 6), "2 years 2 months 03:00:06");
        assert_eq!(&mon_dur(26, 3_600 * 3), "2 years 2 months 03:00:00");
        assert_eq!(&mon_dur(26, 60 * 45 + 6), "2 years 2 months 00:45:06");
        assert_eq!(&mon_dur(26, 60 * 45), "2 years 2 months 00:45:00");
        assert_eq!(&mon_dur(26, 6), "2 years 2 months 00:00:06");

        assert_eq!(
            &mon_dur(26, -(86_400 * 2 + 6)),
            "2 years 2 months -2 days -00:00:06"
        );
        assert_eq!(
            &mon_dur(26, -(86_400 * 2 + 60 * 45 + 6)),
            "2 years 2 months -2 days -00:45:06"
        );
        assert_eq!(
            &mon_dur(26, -(86_400 * 2 + 3_600 * 3 + 6)),
            "2 years 2 months -2 days -03:00:06"
        );
        assert_eq!(
            &mon_dur(26, -(3_600 * 3 + 60 * 45 + 6)),
            "2 years 2 months -03:45:06"
        );
        assert_eq!(&mon_dur(26, -(3_600 * 3 + 6)), "2 years 2 months -03:00:06");
        assert_eq!(&mon_dur(26, -(3_600 * 3)), "2 years 2 months -03:00:00");
        assert_eq!(&mon_dur(26, -(60 * 45 + 6)), "2 years 2 months -00:45:06");
        assert_eq!(&mon_dur(26, -(60 * 45)), "2 years 2 months -00:45:00");
        assert_eq!(&mon_dur(26, -6), "2 years 2 months -00:00:06");

        assert_eq!(&mon_dur(-1, 86_400 * 2 + 6), "-1 month +2 days +00:00:06");
        assert_eq!(
            &mon_dur(-1, 86_400 * 2 + 60 * 45 + 6),
            "-1 month +2 days +00:45:06"
        );
        assert_eq!(
            &mon_dur(-1, 86_400 * 2 + 3_600 * 3 + 6),
            "-1 month +2 days +03:00:06"
        );
        assert_eq!(
            &mon_dur(-26, 3_600 * 3 + 60 * 45 + 6),
            "-2 years -2 months +03:45:06"
        );
        assert_eq!(&mon_dur(-26, 3_600 * 3 + 6), "-2 years -2 months +03:00:06");
        assert_eq!(&mon_dur(-26, 3_600 * 3), "-2 years -2 months +03:00:00");
        assert_eq!(&mon_dur(-26, 60 * 45 + 6), "-2 years -2 months +00:45:06");
        assert_eq!(&mon_dur(-26, 60 * 45), "-2 years -2 months +00:45:00");
        assert_eq!(&mon_dur(-26, 6), "-2 years -2 months +00:00:06");

        assert_eq!(
            &mon_dur(-26, -(86_400 * 2 + 6)),
            "-2 years -2 months -2 days -00:00:06"
        );
        assert_eq!(
            &mon_dur(-26, -(86_400 * 2 + 60 * 45 + 6)),
            "-2 years -2 months -2 days -00:45:06"
        );
        assert_eq!(
            &mon_dur(-26, -(86_400 * 2 + 3_600 * 3 + 6)),
            "-2 years -2 months -2 days -03:00:06"
        );
        assert_eq!(
            &mon_dur(-26, -(3_600 * 3 + 60 * 45 + 6)),
            "-2 years -2 months -03:45:06"
        );
        assert_eq!(
            &mon_dur(-26, -(3_600 * 3 + 6)),
            "-2 years -2 months -03:00:06"
        );
        assert_eq!(&mon_dur(-26, -(3_600 * 3)), "-2 years -2 months -03:00:00");
        assert_eq!(
            &mon_dur(-26, -(60 * 45 + 6)),
            "-2 years -2 months -00:45:06"
        );
        assert_eq!(&mon_dur(-26, -(60 * 45)), "-2 years -2 months -00:45:00");
        assert_eq!(&mon_dur(-26, -6), "-2 years -2 months -00:00:06");
    }

    #[test]
    fn test_interval_value_truncate_low_fields() {
        use DateTimeField::*;

        let mut test_cases = [
            (Year, None, (321, 654_321, 321_000_000), (26 * 12, 0, 0)),
            (Month, None, (321, 654_321, 321_000_000), (321, 0, 0)),
            (
                Day,
                None,
                (321, 654_321, 321_000_000),
                (321, 7 * 60 * 60 * 24, 0), // months: 321, duration: 604800s, is_positive_dur: true
            ),
            (
                Hour,
                None,
                (321, 654_321, 321_000_000),
                (321, 181 * 60 * 60, 0),
            ),
            (
                Minute,
                None,
                (321, 654_321, 321_000_000),
                (321, 10905 * 60, 0),
            ),
            (
                Second,
                None,
                (321, 654_321, 321_000_000),
                (321, 654_321, 321_000_000),
            ),
            (
                Second,
                Some(1),
                (321, 654_321, 321_000_000),
                (321, 654_321, 300_000_000),
            ),
            (
                Second,
                Some(0),
                (321, 654_321, 321_000_000),
                (321, 654_321, 0),
            ),
        ];

        for test in test_cases.iter_mut() {
            let mut i = Interval::new((test.2).0, (test.2).1, (test.2).2).unwrap();
            let j = Interval::new((test.3).0, (test.3).1, (test.3).2).unwrap();

            i.truncate_low_fields(test.0, test.1).unwrap();

            if i != j {
                panic!(
                "test_interval_value_truncate_low_fields failed on {} \n actual: {:?} \n expected: {:?}",
                test.0, i, j
            );
            }
        }
    }

    #[test]
    fn test_interval_value_truncate_high_fields() {
        use DateTimeField::*;

        let mut test_cases = [
            (Year, (321, 654_321), (321, 654_321)),
            (Month, (321, 654_321), (9, 654_321)),
            (Day, (321, 654_321), (0, 654_321)),
            (Hour, (321, 654_321), (0, 654_321 % (60 * 60 * 24))),
            (Minute, (321, 654_321), (0, 654_321 % (60 * 60))),
            (Second, (321, 654_321), (0, 654_321 % 60)),
        ];

        for test in test_cases.iter_mut() {
            let mut i = Interval::new((test.1).0, (test.1).1, 123).unwrap();
            let j = Interval::new((test.2).0, (test.2).1, 123).unwrap();

            i.truncate_high_fields(test.0);

            if i != j {
                panic!(
                    "test_interval_value_truncate_high_fields failed on {} \n actual: {:?} \n expected: {:?}",
                    test.0, i, j
                );
            }
        }
    }
}