hifitime 4.3.1

Ultra-precise date and time handling in Rust for scientific applications with leap second support
Documentation
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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
use hifitime::{
    Duration, DurationError, Freq, Frequencies, HifitimeError, TimeUnits, Unit,
    NANOSECONDS_PER_CENTURY, NANOSECONDS_PER_MINUTE,
};

#[test]
fn time_unit() {
    // Check that the same number is created for different types
    assert_eq!(Unit::Day * 10.0, Unit::Day * 10);
    assert_eq!(Unit::Hour * -7.0, Unit::Hour * -7);
    assert_eq!(Unit::Minute * -2.0, Unit::Minute * -2);
    assert_eq!(Unit::Second * 3.0, Unit::Second * 3);
    assert_eq!(Unit::Millisecond * 4.0, Unit::Millisecond * 4);
    assert_eq!(Unit::Nanosecond * 5.0, Unit::Nanosecond * 5);

    // Check the LHS multiplications match the RHS ones
    assert_eq!(10.0 * Unit::Day, Unit::Day * 10);
    assert_eq!(-7 * Unit::Hour, Unit::Hour * -7.0);
    assert_eq!(-2.0 * Unit::Minute, Unit::Minute * -2);
    assert_eq!(3.0 * Unit::Second, Unit::Second * 3);
    assert_eq!(4.0 * Unit::Millisecond, Unit::Millisecond * 4);
    assert_eq!(5.0 * Unit::Nanosecond, Unit::Nanosecond * 5);

    let d: Duration = 1.0 * Unit::Hour / 3 - 20 * Unit::Minute;
    assert!(d.abs() < Unit::Nanosecond);
    assert_eq!(3 * (20 * Unit::Minute), Unit::Hour);

    // Test operations
    let seven_hours = Unit::Hour * 7;
    let six_minutes = Unit::Minute * 6;
    // let five_seconds = Unit::Second * 5.0;
    let five_seconds = 5.0.seconds();
    let sum: Duration = seven_hours + six_minutes + five_seconds;
    assert!((sum.to_seconds() - 25565.0).abs() < f64::EPSILON);

    let neg_sum = -sum;
    assert!((neg_sum.to_seconds() + 25565.0).abs() < f64::EPSILON);

    assert_eq!(neg_sum.abs(), sum, "abs failed");

    let sub: Duration = seven_hours - six_minutes - five_seconds;
    assert!((sub.to_seconds() - 24835.0).abs() < f64::EPSILON);

    // Test fractional
    let quarter_hour = 0.25 * Unit::Hour;
    let third_hour = (1.0 / 3.0) * Unit::Hour;
    let sum: Duration = quarter_hour + third_hour;
    assert!((sum.to_unit(Unit::Minute) - 35.0).abs() < f64::EPSILON);

    let quarter_hour = -0.25 * Unit::Hour;
    let third_hour: Duration = -1 * Unit::Hour / 3;
    let sum: Duration = quarter_hour + third_hour;
    let delta = sum.to_unit(Unit::Millisecond).floor() - sum.to_unit(Unit::Second).floor() * 1000.0;
    assert!(delta < f64::EPSILON);
    assert!((sum.to_unit(Unit::Minute) + 35.0).abs() < f64::EPSILON);
}

#[test]
fn duration_format() {
    // Check printing adds precision
    assert_eq!(
        format!("{}", Unit::Day * 10.0 + Unit::Hour * 5),
        "10 days 5 h"
    );

    assert_eq!(
        format!("{}", Unit::Hour * 5 + Unit::Millisecond * 256),
        "5 h 256 ms"
    );

    assert_eq!(
        format!(
            "{}",
            Unit::Hour * 5 + Unit::Millisecond * 256 + Unit::Nanosecond
        ),
        "5 h 256 ms 1 ns"
    );

    assert_eq!(format!("{}", Unit::Hour + Unit::Second), "1 h 1 s");

    // NOTE: We _try_ to specify down to a half of a nanosecond, but duration is NOT
    // more precise than that, so it only actually stores to that number.
    assert_eq!(
        format!(
            "{}",
            Unit::Hour * 5 + Unit::Millisecond * 256 + Unit::Microsecond + Unit::Nanosecond * 3.5
        ),
        "5 h 256 ms 1 μs 3 ns"
    );

    // Check printing negative durations only shows one negative sign
    assert_eq!(
        format!("{}", Unit::Hour * -5 + Unit::Millisecond * -256),
        "-5 h 256 ms"
    );

    assert_eq!(
        format!(
            "{}",
            Unit::Hour * -5 + Unit::Millisecond * -256 + Unit::Nanosecond * -3
        ),
        "-5 h 256 ms 3 ns"
    );

    assert_eq!(
        format!(
            "{}",
            (Unit::Hour * -5 + Unit::Millisecond * -256)
                - (Unit::Hour * -5 + Unit::Millisecond * -256 + Unit::Nanosecond * 2)
        ),
        "-2 ns"
    );

    assert_eq!(format!("{}", Unit::Nanosecond * 2), "2 ns");

    // Check that we support nanoseconds pas GPS time
    let now = Unit::Nanosecond * 1286495254000000123;
    assert_eq!(format!("{now}"), "14889 days 23 h 47 min 34 s 123 ns");

    let arbitrary = 14889.days()
        + 23.hours()
        + 47.minutes()
        + 34.seconds()
        + 0.milliseconds()
        + 123.nanoseconds();
    assert_eq!(format!("{arbitrary}"), "14889 days 23 h 47 min 34 s 123 ns");

    assert_eq!(
        arbitrary,
        Duration::compose(0, 14889, 23, 47, 34, 0, 0, 123)
    );

    // Test fractional
    let quarter_hour = 0.25 * Unit::Hour;
    let third_hour = (1.0 / 3.0) * Unit::Hour;
    let sum: Duration = quarter_hour + third_hour;

    println!(
        "Proof that Duration is more precise than f64: {} vs {}",
        sum.to_unit(Unit::Minute),
        (1.0 / 4.0 + 1.0 / 3.0) * 60.0
    );
    assert_eq!(format!("{sum}"), "35 min");

    let quarter_hour = -0.25 * Unit::Hour;
    let third_hour: Duration = -1 * Unit::Hour / 3;
    let sum: Duration = quarter_hour + third_hour;
    let delta = sum.to_unit(Unit::Millisecond).floor() - sum.to_unit(Unit::Second).floor() * 1000.0;
    assert_eq!(-delta, 0.0);
    assert_eq!(format!("{sum}"), "-35 min");

    assert_eq!(format!("{}", Duration::MAX), "1196851200 days");
    assert_eq!(format!("{}", Duration::MIN), "-1196851200 days");
    assert_eq!(format!("{}", Duration::ZERO), "0 ns");

    // The `e` format will print this as a floating point value.
    let mut sum2 = sum;
    sum2 -= 1 * Unit::Nanosecond;
    assert_eq!(sum2, sum - 1 * Unit::Nanosecond);
    assert_eq!(sum2, sum - Unit::Nanosecond);
    assert_eq!(format!("{sum2:e}"), "-35.00000000001667 min");
}

#[test]
fn test_ops() {
    assert_eq!(
        (0.25 * Unit::Hour).total_nanoseconds(),
        (15 * NANOSECONDS_PER_MINUTE).into()
    );

    assert_eq!(
        (-0.25 * Unit::Hour).total_nanoseconds(),
        -i128::from(15 * NANOSECONDS_PER_MINUTE)
    );

    assert_eq!(
        (-0.25 * Unit::Hour - 0.25 * Unit::Hour).total_nanoseconds(),
        -i128::from(30 * NANOSECONDS_PER_MINUTE)
    );

    #[cfg(feature = "std")]
    println!("{}", -0.25 * Unit::Hour + (-0.25 * Unit::Hour));

    assert_eq!(
        Duration::MIN_POSITIVE + 4 * Duration::MIN_POSITIVE,
        5 * Unit::Nanosecond
    );

    assert_eq!(
        Duration::MIN_NEGATIVE + 4 * Duration::MIN_NEGATIVE,
        -5 * Unit::Nanosecond
    );

    let half_hour = 0.5.hours();
    let quarter_hour = 0.5 * half_hour;
    assert_eq!(quarter_hour, 15.minutes());
    #[cfg(feature = "std")]
    println!("{quarter_hour}");

    let min_quarter_hour = -0.5 * half_hour;
    assert_eq!(min_quarter_hour, -15.minutes());
    #[cfg(feature = "std")]
    println!("{min_quarter_hour}");
}

#[test]
fn test_ops_near_bounds() {
    assert_eq!(Duration::MAX - Duration::MAX, 0 * Unit::Nanosecond);
    assert_eq!(Duration::MIN - Duration::MIN, 0 * Unit::Nanosecond);

    // Check that the special cases of the bounds themselves don't prevent correct math.
    assert_eq!(
        (Duration::MIN - 1 * Unit::Nanosecond) - (Duration::MIN - 1 * Unit::Nanosecond),
        0 * Unit::Nanosecond
    );

    let tt_offset_ns: u64 = 32_184_000_000;
    let duration = Duration::from_parts(-32767, 0);
    let exp = Duration::from_parts(-32768, NANOSECONDS_PER_CENTURY - tt_offset_ns);
    assert_eq!(
        duration - Duration::from_total_nanoseconds(tt_offset_ns.into()),
        exp
    );

    // Test the zero crossing with a large negative value
    assert_eq!(
        2 * Unit::Nanosecond - (-1 * Unit::Century),
        1 * Unit::Century + 2 * Unit::Nanosecond
    );

    // Check that we saturate one way but not the other for MIN
    assert_eq!(Duration::MIN - 1 * Unit::Nanosecond, Duration::MIN);
    assert_ne!(Duration::MIN + 1 * Unit::Nanosecond, Duration::MIN);

    // Check that we saturate one way but not the other for MAX
    assert_eq!(Duration::MAX + 1 * Unit::Nanosecond, Duration::MAX);
    assert_ne!(Duration::MAX - 1 * Unit::Nanosecond, Duration::MAX);
}

/// Regression test for https://github.com/nyx-space/hifitime/issues/494
#[test]
fn test_subtraction_saturates_in_the_result_direction() {
    assert_eq!(Duration::ZERO - Duration::MIN, Duration::MAX);
    assert_eq!(Duration::MAX - Duration::MIN, Duration::MAX);
    assert_eq!(Duration::ZERO - Duration::MAX, Duration::MIN);
    assert_eq!(Duration::MIN - Duration::MAX, Duration::MIN);
    assert_eq!(
        Duration::ZERO - (Duration::MIN + Duration::EPSILON),
        Duration::MAX - Duration::EPSILON
    );
    assert_eq!(
        Duration::ZERO - (Duration::MAX - Duration::EPSILON),
        Duration::MIN + Duration::EPSILON
    );
    assert_eq!(
        Duration::MAX - 1 * Unit::Century,
        Duration::from_parts(i16::MAX, 0)
    );
}

/// Regression test for https://github.com/nyx-space/hifitime/issues/469
/// Duration::PartialEq previously treated opposite-sign durations as equal
/// (-15min == 15min), which violated Rust's Eq/Ord contract since the derived
/// Ord did not have this special case.
#[test]
fn test_duration_eq_ord_consistency() {
    use hifitime::prelude::*;

    // Opposite-sign durations must NOT be equal
    assert_ne!(15.minutes(), -15.minutes());
    assert_ne!(1.seconds(), -1.seconds());
    assert_ne!(Duration::MIN_POSITIVE, Duration::MIN_NEGATIVE);

    // Positive > Negative
    assert!(15.minutes() > -15.minutes());
    assert!(1.nanoseconds() > -1.nanoseconds());

    // Eq and Ord must be consistent
    let pos = Duration::from_parts(0, 1);
    let neg = Duration::from_parts(-1, NANOSECONDS_PER_CENTURY - 1);
    assert_ne!(pos, neg, "+1ns and -1ns must not be equal");
    assert!(pos > neg, "+1ns must be greater than -1ns");

    // Same-value durations are still equal
    assert_eq!(15.minutes(), 15.minutes());
    assert_eq!(-15.minutes(), -15.minutes());
    assert_eq!(Duration::ZERO, Duration::ZERO);
}

#[test]
fn test_neg() {
    assert_eq!(Duration::MIN_NEGATIVE, -Duration::MIN_POSITIVE);
    assert_eq!(Duration::MIN_POSITIVE, -Duration::MIN_NEGATIVE);
    assert_eq!(2.nanoseconds(), -(-(2.0.nanoseconds()))); // double negation is identity
    assert_ne!(2.nanoseconds(), -(2.0.nanoseconds())); // 2ns != -2ns
    assert_eq!(Duration::MIN, -Duration::MAX);
    assert_eq!(Duration::MAX, -Duration::MIN);
    assert_eq!(
        -(Duration::MIN + Unit::Nanosecond),
        Duration::MAX - Unit::Nanosecond
    );
}

#[test]
fn test_extremes() {
    let d = Duration::from_total_nanoseconds(i128::MAX);

    assert_eq!(Duration::from_total_nanoseconds(d.total_nanoseconds()), d);
    let d = Duration::from_total_nanoseconds(i128::MIN + 1);
    assert_eq!(d, Duration::MIN);
    // Test min positive
    let d_min = Duration::from_total_nanoseconds(Duration::MIN_POSITIVE.total_nanoseconds());
    assert_eq!(d_min, Duration::MIN_POSITIVE);
    // Test difference between min durations
    assert_eq!(
        Duration::MIN_POSITIVE - Duration::MIN_NEGATIVE,
        2 * Unit::Nanosecond
    );
    assert_eq!(
        Duration::MIN_NEGATIVE - Duration::MIN_POSITIVE,
        -2 * Unit::Nanosecond
    );
    assert_eq!(Duration::from_total_nanoseconds(2), 2 * Unit::Nanosecond);
    // Check that we do not support more precise than nanosecond
    assert_eq!(Unit::Nanosecond * 3.5, Unit::Nanosecond * 3);

    assert_eq!(
        Duration::MIN_POSITIVE + Duration::MIN_NEGATIVE,
        Duration::ZERO
    );

    assert_eq!(
        Duration::MIN_NEGATIVE + Duration::MIN_NEGATIVE,
        -2 * Unit::Nanosecond
    );

    // Add i64 tests
    let d = Duration::from_truncated_nanoseconds(i64::MAX);
    #[cfg(feature = "std")]
    println!("{d}");
    assert_eq!(
        Duration::from_truncated_nanoseconds(d.truncated_nanoseconds()),
        d
    );

    let past_min = Duration::from_total_nanoseconds(i128::MIN);
    assert_eq!(past_min, Duration::MIN);
}

#[test]
fn duration_enum_eq() {
    // Check the equality compiles (if one compiles, then all asserts will work)
    assert!(Freq::GigaHertz == Freq::GigaHertz);
    assert!(Unit::Century == Unit::Century);
    assert!(1 * Unit::Century == Unit::Century);
    assert!(1 * Unit::Century >= Unit::Century);
    assert!(1 * Unit::Century <= Unit::Century);
    assert!(1 * Unit::Century > Unit::Day);
}

#[test]
fn duration_enum_orq() {
    // Check the equality compiles (if one compiles, then all asserts will work)
    assert!(Unit::Century > Unit::Day);
    assert_eq!(Unit::Century.min(Unit::Day), Unit::Day);
    assert_eq!(Unit::Century.max(Unit::Day), Unit::Century);
    // Frequencies are converted to durations, and that's what compared!
    assert!(Freq::GigaHertz < Freq::MegaHertz);
}

#[test]
fn freq_mul() {
    assert_eq!(1_000 * Freq::MegaHertz, Unit::Nanosecond);
    assert_eq!(1_000 * Freq::KiloHertz, Unit::Microsecond);
    assert_eq!(1_000 * Freq::Hertz, Unit::Millisecond);

    assert_eq!(Freq::MegaHertz * 1_000, Unit::Nanosecond);
    assert_eq!(Freq::KiloHertz * 1_000, Unit::Microsecond);
    assert_eq!(Freq::Hertz * 1_000, Unit::Millisecond);

    assert_eq!(1_000.MHz(), Unit::Nanosecond);
    assert_eq!(1_000.kHz(), Unit::Microsecond);
    assert_eq!(1_000.Hz(), Unit::Millisecond);
}

#[test]
fn duration_recip() {
    // Ensure that for arbitrary durations and constant ones, the from and to total nanoseconds is reciprocal.
    let arbitrary = 14889.days()
        + 23.hours()
        + 47.minutes()
        + 34.seconds()
        + 0.milliseconds()
        + 123.nanoseconds();

    for duration in [
        arbitrary,
        Duration::ZERO,
        Duration::MAX,
        Duration::MIN,
        Duration::MIN_NEGATIVE,
        Duration::MIN_POSITIVE,
    ] {
        assert_eq!(
            duration,
            Duration::from_total_nanoseconds(duration.total_nanoseconds()),
        );
    }
}

#[test]
fn duration_century_range_is_exact() {
    let one_side_range_ns = 32_768_i128 * i128::from(NANOSECONDS_PER_CENTURY);

    assert_eq!(Duration::MAX.total_nanoseconds(), one_side_range_ns);
    assert_eq!(Duration::MIN.total_nanoseconds(), -one_side_range_ns);

    assert_eq!(
        Duration::from_total_nanoseconds(one_side_range_ns),
        Duration::MAX
    );
    assert_eq!(
        Duration::from_total_nanoseconds(-one_side_range_ns),
        Duration::MIN
    );

    assert_eq!(
        Duration::from_total_nanoseconds(one_side_range_ns + 1),
        Duration::MAX
    );
    assert_eq!(
        Duration::from_total_nanoseconds(-one_side_range_ns - 1),
        Duration::MIN
    );
}

#[test]
fn duration_floor_ceil_round() {
    // These are from here: https://www.geeksforgeeks.org/time-round-function-in-golang-with-examples/
    let d = 5.minutes() + 7.seconds();
    assert_eq!(d.floor(6.seconds()), 5.minutes() + 6.seconds());
    assert_eq!(d.floor(-6.seconds()), 5.minutes() + 6.seconds());
    assert_eq!(d.ceil(6.seconds()), 5.minutes() + 12.seconds());
    println!("{}", d.ceil(-6.seconds()));
    println!("{}", 5.minutes() + 12.seconds());
    assert_eq!(d.ceil(-6.seconds()), 5.minutes() + 12.seconds());

    let d = 3.minutes() + 73.671.seconds();
    assert_eq!(d, 4.minutes() + 13.seconds() + 671.milliseconds());

    // Floor
    // Rounding to the closest microsecond should return the same duration
    assert_eq!(d.floor(1.microseconds()), d);
    assert_eq!(d.floor(1.seconds()), 4.minutes() + 13.seconds());
    assert_eq!(d.floor(3.seconds()), 4.minutes() + 12.seconds());
    assert_eq!(d.floor(9.minutes()), 0.minutes());
    assert_eq!(
        (Duration::MIN + 10.seconds()).floor(10.seconds()),
        Duration::MIN + 10.seconds()
    );

    // Ceil
    assert_eq!(d.ceil(1.minutes()), 5.minutes());
    assert_eq!(d.ceil(30.seconds()), 4.minutes() + 30.seconds());
    assert_eq!(d.ceil(4.minutes()), 8.minutes());
    assert_eq!(d.ceil(1.seconds()), 4.minutes() + 14.seconds());
    assert_eq!(Duration::MAX.ceil(1.seconds()), Duration::MAX);

    // Round
    assert_eq!(d.round(1.minutes()), 4.minutes());
    assert_eq!(d.round(30.seconds()), 4.minutes());
    assert_eq!(d.round(4.minutes()), 4.minutes());
    assert_eq!(d.round(1.seconds()), 4.minutes() + 14.seconds());
}

#[test]
fn duration_from_str() {
    use core::str::FromStr;
    use hifitime::{Duration, Unit};

    assert_eq!(Duration::from_str("1 d").unwrap(), Unit::Day * 1);
    assert_eq!(
        Duration::from_str("10.598 days").unwrap(),
        Unit::Day * 10.598
    );
    assert_eq!(
        Duration::from_str("10.598 min").unwrap(),
        Unit::Minute * 10.598
    );
    assert_eq!(
        Duration::from_str("10.598 us").unwrap(),
        Unit::Microsecond * 10.598
    );
    assert_eq!(
        Duration::from_str("10.598 seconds").unwrap(),
        Unit::Second * 10.598
    );
    assert_eq!(
        Duration::from_str("10.598 nanosecond").unwrap(),
        Unit::Nanosecond * 10.598
    );

    assert_eq!(
        Duration::from_str("1 d 15.5 hours 25 ns").unwrap(),
        Unit::Day * 1 + 15.5 * Unit::Hour + 25 * Unit::Nanosecond
    );

    assert_eq!(
        Duration::from_str("5 h 256 ms 1 ns").unwrap(),
        5 * Unit::Hour + 256 * Unit::Millisecond + Unit::Nanosecond
    );

    // It supports extra white spaces before and after the duration
    assert_eq!(
        Duration::from_str("  5 days 1 ns ").unwrap(),
        5 * Unit::Day + 1 * Unit::Nanosecond
    );

    assert!(
        Duration::from_str("5 days 1").is_err(),
        "should return an unknown unit error"
    );

    assert!(
        Duration::from_str("5 days 1 ").is_err(),
        "should return an unknown unit error"
    );

    // Test the offset initialization
    assert_eq!(
        Duration::from_str("-01:15:30").unwrap(),
        -(1 * Unit::Hour + 15 * Unit::Minute + 30 * Unit::Second)
    );

    assert_eq!(
        Duration::from_str("+01:15:30").unwrap(),
        1 * Unit::Hour + 15 * Unit::Minute + 30 * Unit::Second
    );

    assert_eq!(
        Duration::from_str("-01:15").unwrap(),
        -(1 * Unit::Hour + 15 * Unit::Minute)
    );

    assert_eq!(Duration::from_str("-05:00").unwrap(), -5 * Unit::Hour);

    assert_eq!(
        Duration::from_str("+01:15").unwrap(),
        1 * Unit::Hour + 15 * Unit::Minute
    );

    // Test offsets without colon
    assert_eq!(
        Duration::from_str("-011530").unwrap(),
        -(1 * Unit::Hour + 15 * Unit::Minute + 30 * Unit::Second)
    );

    assert_eq!(
        Duration::from_str("+011530").unwrap(),
        1 * Unit::Hour + 15 * Unit::Minute + 30 * Unit::Second
    );

    assert_eq!(
        Duration::from_str("-0115").unwrap(),
        -(1 * Unit::Hour + 15 * Unit::Minute)
    );

    assert_eq!(
        Duration::from_str("+0115").unwrap(),
        1 * Unit::Hour + 15 * Unit::Minute
    );

    assert_eq!(
        Duration::from_str("+2515").unwrap(),
        25 * Unit::Hour + 15 * Unit::Minute
    );

    assert_eq!(
        Duration::from_tz_offset(1, 1, 15),
        1 * Unit::Hour + 15 * Unit::Minute
    );

    assert_eq!(
        Duration::from_tz_offset(-1, 1, 15),
        -(1 * Unit::Hour + 15 * Unit::Minute)
    );

    assert!(Duration::from_str("").is_err(),);
    assert!(Duration::from_str("+").is_err(),);

    assert_eq!(Duration::from_str("  -5 days ").unwrap(), -5 * Unit::Day);

    assert_eq!(
        Duration::from_str("-5 h 256 ms 1 ns").unwrap(),
        -(5 * Unit::Hour + 256 * Unit::Millisecond + Unit::Nanosecond)
    );

    assert_eq!(
        Duration::from_str("  -5 days 1 ns ").unwrap(),
        -(5 * Unit::Day + 1 * Unit::Nanosecond)
    );

    assert_eq!(
        Duration::from_str("  -145 ns ").unwrap(),
        -145 * Unit::Nanosecond
    );

    assert_eq!(
        Duration::from_str("-123 μs").unwrap(),
        -123 * Unit::Microsecond
    );

    assert_eq!(
        Duration::from_str("-1 μs 99 ns").unwrap(),
        -(1 * Unit::Microsecond + 99 * Unit::Nanosecond)
    );
}

#[cfg(feature = "std")]
#[test]
fn std_time_duration() {
    use std::time::Duration as StdDuration;

    let hf_duration = 5 * Unit::Day + 1 * Unit::Nanosecond;
    let std_duration: StdDuration = hf_duration.into();
    assert_eq!(std_duration, StdDuration::new(432_000, 1));

    let hf_return: Duration = std_duration.into();
    assert_eq!(hf_return, hf_duration);

    // Check that a negative hifitime duration is zero in std time
    let std_duration: StdDuration = (-hf_duration).into();
    assert_eq!(std_duration, StdDuration::ZERO);

    // Check that a StdDuration::MAX, which is a longer duration than
    // hifitime::Duration, is hifitime::Duration::MAX on conversion
    assert_eq!(Duration::MAX, Into::<Duration>::into(StdDuration::MAX));

    // Check that when Duration::MAX is converteed into StdDuration,
    // its conversion is equivalent to a StdDuration of
    // 103407943680000 seconds
    assert_eq!(
        StdDuration::from_secs(103407943680000),
        Into::<StdDuration>::into(Duration::MAX)
    );

    // Check that conversions are in fact lossless at large durations.
    // This tests large numbers below the seconds equivalent when converting
    // Duration::MAX into a StdDuration
    let std_duration: StdDuration = StdDuration::from_secs(100000000000000);
    let hf_duration: Duration = std_duration.into();
    assert_eq!(StdDuration::from_secs(100000000000000), hf_duration.into());

    let std_duration: StdDuration = StdDuration::from_secs(103407943680000 - 1);
    let hf_duration: Duration = std_duration.into();
    assert_eq!(
        StdDuration::from_secs(103407943680000 - 1),
        hf_duration.into()
    );
}

#[test]
fn test_decompose() {
    let pos = 5 * Unit::Hour + 256 * Unit::Millisecond + Unit::Nanosecond;

    let (sign, days, hours, minutes, seconds, milliseconds, microseconds, nanos) = pos.decompose();
    assert_eq!(sign, 0);
    assert_eq!(days, 0);
    assert_eq!(hours, 5);
    assert_eq!(minutes, 0);
    assert_eq!(seconds, 0);
    assert_eq!(milliseconds, 256);
    assert_eq!(microseconds, 0);
    assert_eq!(nanos, 1);

    // A negative duration works in the same way, only the sign is different.
    let neg = -(5 * Unit::Hour + 256 * Unit::Millisecond + Unit::Nanosecond);
    assert_eq!(neg, -pos);
    assert_eq!(neg.abs(), pos);
    assert!(neg.is_negative());

    let (sign, days, hours, minutes, seconds, milliseconds, microseconds, nanos) = neg.decompose();
    assert_eq!(sign, -1);
    assert_eq!(days, 0);
    assert_eq!(hours, 5);
    assert_eq!(minutes, 0);
    assert_eq!(seconds, 0);
    assert_eq!(milliseconds, 256);
    assert_eq!(microseconds, 0);
    assert_eq!(nanos, 1);
}

#[test]
fn test_min_max() {
    use hifitime::TimeUnits;

    let d0 = 20.seconds();
    let d1 = 21.seconds();

    assert_eq!(d0, d1.min(d0));
    assert_eq!(d0, d0.min(d1));

    assert_eq!(d1, d1.max(d0));
    assert_eq!(d1, d0.max(d1));
}

#[test]
fn regression_test_gh_244() {
    let zero = Duration::ZERO;
    // Test that the ceil of a zero duration is still zero.
    assert_eq!(zero.ceil(zero), zero);
    let non_zero = Duration::from_parts(1, 23456);
    // Test that the ceil of a non-zero duration by zero is still zero.
    assert_eq!(non_zero.ceil(zero), zero);
    // Test that the ceil of a zero duration by a non-zero is non-zero duration.
    assert_eq!(zero.ceil(non_zero), non_zero);
}

#[test]
fn regression_test_gh_475() {
    assert_eq!(
        Duration::from_parts(3, 0).try_truncated_nanoseconds(),
        Err(HifitimeError::Duration {
            source: DurationError::Overflow,
        })
    );
    assert_eq!(
        Duration::from_parts(i16::MIN, 0).try_truncated_nanoseconds(),
        Err(HifitimeError::Duration {
            source: DurationError::Underflow,
        })
    );
    assert_eq!(
        Duration::from_parts(i16::MAX, 0).try_truncated_nanoseconds(),
        Err(HifitimeError::Duration {
            source: DurationError::Overflow,
        })
    );
    assert_eq!(
        Duration::from_parts(-3, 0).try_truncated_nanoseconds(),
        Err(HifitimeError::Duration {
            source: DurationError::Underflow,
        })
    );
    assert_eq!(
        Duration::from_truncated_nanoseconds(i64::MIN).try_truncated_nanoseconds(),
        Ok(i64::MIN)
    );
    assert_eq!(
        Duration::from_truncated_nanoseconds(i64::MAX).try_truncated_nanoseconds(),
        Ok(i64::MAX)
    );
    assert!(Duration::from_parts(2, 0)
        .try_truncated_nanoseconds()
        .is_ok());
}