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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
// Copyright 2020 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.

// Trait Implementations for `ComplexTime`
pub mod complex_time_impls {
    use super::super::{ComplexTime, ReadableSystemTime};
    use std::fmt::Display;
    use std::ops::{Add, AddAssign, Sub, SubAssign};
    use std::time::Duration;

    /// `ComplexTime` implements `Display` to provide a human-readable, detailed, format for its
    /// values. It uses the `ReadableSystemTime` struct for its `SystemTime` component, and the
    /// `Debug` trait implementation of `Instant`, as that type's internals are not accessible, and
    /// it only implements `Debug`.
    ///
    /// # Example
    /// ```no_run
    /// use omaha_client::time::ComplexTime;
    /// use std::time::{Duration, Instant, SystemTime};
    /// assert_eq!(
    ///     format!("{}", ComplexTime{
    ///                       wall: SystemTime::UNIX_EPOCH + Duration::from_nanos(994610096026420000),
    ///                       mono: Instant::now(),
    ///                   }),
    ///     "2001-07-08 16:34:56.026 UTC (994610096.026420000) at Instant{ tv_sec: SEC, tv_nsec: NSEC }"
    /// );
    ///```
    impl Display for ComplexTime {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{} at {:?}", &ReadableSystemTime(self.wall), self.mono)
        }
    }

    impl Add<Duration> for ComplexTime {
        type Output = Self;

        fn add(self, dur: Duration) -> Self {
            Self {
                wall: self.wall + dur,
                mono: self.mono + dur,
            }
        }
    }

    /// AddAssign implementation that relies on the above Add implementation.
    impl AddAssign<Duration> for ComplexTime {
        fn add_assign(&mut self, other: Duration) {
            *self = *self + other;
        }
    }

    /// A `Sub` implementation for ComplexTime that subtracts the duration from both times that
    /// the ComplexTime holds.
    impl Sub<Duration> for ComplexTime {
        type Output = Self;

        fn sub(self, dur: Duration) -> Self {
            Self {
                wall: self.wall.checked_sub(dur).unwrap(),
                mono: self.mono.checked_sub(dur).unwrap(),
            }
        }
    }

    /// AddAssign implementation that relies on the above Add implementation.
    impl SubAssign<Duration> for ComplexTime {
        fn sub_assign(&mut self, other: Duration) {
            *self = *self - other;
        }
    }

    #[cfg(test)]
    mod tests {
        use super::super::super::PartialComplexTime;
        use super::super::system_time_conversion;
        use super::*;
        use std::time::{Duration, Instant, SystemTime};

        #[test]
        fn test_truncate_submicrosecond_walltime() {
            let time = ComplexTime {
                wall: SystemTime::now(),
                mono: Instant::now(),
            };
            assert_eq!(
                time.truncate_submicrosecond_walltime().wall,
                system_time_conversion::micros_from_epoch_to_system_time(
                    system_time_conversion::checked_system_time_to_micros_from_epoch(time.wall)
                        .unwrap()
                )
            );
        }

        #[test]
        fn test_wall_duration_since() {
            let early = ComplexTime {
                wall: SystemTime::now(),
                mono: Instant::now(),
            };
            let later = ComplexTime {
                wall: early.wall + Duration::from_secs(200),
                ..early
            };
            assert_eq!(
                later.wall_duration_since(early).unwrap(),
                Duration::from_secs(200)
            )
        }

        #[test]
        fn test_is_after_or_eq_any() {
            let wall = SystemTime::now();
            let mono = Instant::now();
            let comp = ComplexTime { wall, mono };

            let dur = Duration::from_secs(60);
            let wall_after = wall + dur;
            let mono_after = mono + dur;
            let comp_after = comp + dur;

            let comp_wall_after_mono_not = ComplexTime::from((wall_after, mono));
            let comp_mono_after_wall_not = ComplexTime::from((wall, mono_after));

            // strictly after cases
            assert!(comp_after.is_after_or_eq_any(comp));
            assert!(comp_after.is_after_or_eq_any(PartialComplexTime::Wall(wall)));
            assert!(comp_after.is_after_or_eq_any(PartialComplexTime::Monotonic(mono)));
            assert!(comp_after.is_after_or_eq_any(PartialComplexTime::Complex(comp)));

            // reversed (note these are all negated)
            assert!(!comp.is_after_or_eq_any(comp_after));
            assert!(!comp.is_after_or_eq_any(PartialComplexTime::Wall(wall_after)));
            assert!(!comp.is_after_or_eq_any(PartialComplexTime::Monotonic(mono_after)));
            assert!(!comp.is_after_or_eq_any(PartialComplexTime::Complex(comp_after)));

            // strictly equal cases
            assert!(comp_after.is_after_or_eq_any(comp_after));
            assert!(comp_after.is_after_or_eq_any(PartialComplexTime::Wall(wall_after)));
            assert!(comp_after.is_after_or_eq_any(PartialComplexTime::Monotonic(mono_after)));
            assert!(comp_after.is_after_or_eq_any(PartialComplexTime::Complex(comp_after)));

            // wall is after, mono is not
            assert!(comp_wall_after_mono_not.is_after_or_eq_any(comp));

            // mono is after, wall is not
            assert!(comp_mono_after_wall_not.is_after_or_eq_any(comp));
        }

        #[test]
        fn test_complex_time_impl_add() {
            let earlier = ComplexTime {
                wall: SystemTime::now(),
                mono: Instant::now(),
            };
            let dur = Duration::from_secs(60 * 60);

            let later = earlier + dur;

            let wall_duration_added = later.wall.duration_since(earlier.wall).unwrap();
            let mono_duration_added = later.mono.duration_since(earlier.mono);

            assert_eq!(wall_duration_added, dur);
            assert_eq!(mono_duration_added, dur);
        }

        #[test]
        fn test_complex_time_impl_add_assign() {
            let mut time = ComplexTime {
                wall: SystemTime::now(),
                mono: Instant::now(),
            };
            let earlier = time;
            let dur = Duration::from_secs(60 * 60);

            time += dur;

            let wall_duration_added = time.wall.duration_since(earlier.wall).unwrap();
            let mono_duration_added = time.mono.duration_since(earlier.mono);

            assert_eq!(wall_duration_added, dur);
            assert_eq!(mono_duration_added, dur);
        }

        #[test]
        fn test_complex_time_impl_sub() {
            // If this test was executed early after boot, it's possible `Instant::now()` could be
            // less than 60*60 seconds. To make the tests more deterministic, we'll create a
            // synthetic now we'll use in tests that's at least 24 hours from the real `now()`
            // value.
            let mono = Instant::now() + Duration::from_secs(24 * 60 * 60);
            let time = ComplexTime {
                wall: SystemTime::now(),
                mono,
            };
            let dur = Duration::from_secs(60 * 60);
            let earlier = time - dur;

            let wall_duration_subtracted = time.wall.duration_since(earlier.wall).unwrap();
            let mono_duration_subtracted = time.mono.duration_since(earlier.mono);

            assert_eq!(wall_duration_subtracted, dur);
            assert_eq!(mono_duration_subtracted, dur);
        }

        #[test]
        fn test_complex_time_impl_sub_assign() {
            // If this test was executed early after boot, it's possible `Instant::now()` could be
            // less than 60*60 seconds. To make the tests more deterministic, we'll create a
            // synthetic now we'll use in tests that's at least 24 hours from the real `now()`
            // value.
            let mono = Instant::now() + Duration::from_secs(24 * 60 * 60);
            let mut time = ComplexTime {
                wall: SystemTime::now(),
                mono,
            };
            let before_sub = time;
            let dur = Duration::from_secs(60 * 60);

            time -= dur;

            let wall_duration_subtracted = before_sub.wall.duration_since(time.wall).unwrap();
            let mono_duration_subtracted = before_sub.mono.duration_since(time.mono);

            assert_eq!(wall_duration_subtracted, dur);
            assert_eq!(mono_duration_subtracted, dur);
        }
    }
}

/// Conversions for `ComplexTime`.
///
/// This implements `From<T> for ComplexTime` for many T.
/// This implements `From<ComplexTime> for U` for many U (which are outside this module)
pub mod complex_time_type_conversions {
    use super::super::ComplexTime;
    use std::time::{Instant, SystemTime};

    // `From<T> for ComplexTime`

    impl From<(SystemTime, Instant)> for ComplexTime {
        fn from(t: (SystemTime, Instant)) -> ComplexTime {
            ComplexTime {
                wall: t.0,
                mono: t.1,
            }
        }
    }

    // `From<ComplexTime> for ...`

    impl From<ComplexTime> for SystemTime {
        fn from(complex: ComplexTime) -> SystemTime {
            complex.wall
        }
    }
    impl From<ComplexTime> for Instant {
        fn from(complex: ComplexTime) -> Instant {
            complex.mono
        }
    }

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

        /// Test that the `ComplexTime` `From` implementations work correctly.
        #[test]
        fn test_from_std_time_tuple_for_complex_time() {
            let system_time = SystemTime::now();
            let instant = Instant::now();
            assert_eq!(
                ComplexTime::from((system_time, instant)),
                ComplexTime {
                    wall: system_time,
                    mono: instant
                }
            );
        }

        #[test]
        fn test_from_complex_time_for_instant() {
            let time = ComplexTime {
                wall: SystemTime::now(),
                mono: Instant::now(),
            };
            let instant_from_time: Instant = Instant::from(time);
            let time_into_instant: Instant = time.into();

            assert_eq!(instant_from_time, time_into_instant);
            assert_eq!(instant_from_time, time.mono);
            assert_eq!(time_into_instant, time.mono);
        }

        #[test]
        fn test_from_complex_time_for_system_time() {
            let time = ComplexTime {
                wall: SystemTime::now(),
                mono: Instant::now(),
            };
            let system_from_time: SystemTime = SystemTime::from(time);
            let time_into_system: SystemTime = time.into();

            assert_eq!(system_from_time, time_into_system);
            assert_eq!(system_from_time, time.wall);
            assert_eq!(time_into_system, time.wall);
        }
    }
}

/// Trait Implementations for `PartialComplexTime`
pub mod partial_complex_time_impls {
    use super::super::{PartialComplexTime, ReadableSystemTime};
    use std::fmt::Display;
    use std::ops::{Add, AddAssign, Sub, SubAssign};
    use std::time::Duration;

    /// `PartialComplexTime` implements `Display` to provide a human-readable, detailed, format for
    /// its values. It uses the `ReadableSystemTime` struct for its `SystemTime` component, and the
    /// `Debug` trait implementation of `Instant`, as that type's internals are not accessible, and
    /// it only implements `Debug`.
    ///
    /// # Example
    /// ```no_run
    /// use std::time::{Duration, Instant, SystemTime};
    /// use omaha_client::time::{ComplexTime, PartialComplexTime};
    ///
    /// assert_eq!(
    ///     format!("{}", PartialComplexTime::Complex(ComplexTime{
    ///                       wall: SystemTime::UNIX_EPOCH + Duration::from_nanos(994610096026420000),
    ///                       mono: Instant::now()
    ///                   })),
    ///     "2001-07-08 16:34:56.026 UTC (994610096.026420000) and Instant{ tv_sec: SEC, tv_nsec: NSEC }"
    /// );
    ///
    /// assert_eq!(
    ///     format!("{}", PartialComplexTime::Wall(
    ///                       SystemTime::UNIX_EPOCH + Duration::from_nanos(994610096026420000),
    ///                   )),
    ///     "2001-07-08 16:34:56.026 UTC (994610096.026420000) and Instant{ tv_sec: SEC, tv_nsec: NSEC }"
    /// );
    ///
    /// assert_eq!(
    ///     format!("{}", PartialComplexTime::Monotonic(Instant::now())),
    ///     "2001-07-08 16:34:56.026 UTC (994610096.026420000) and Instant{ tv_sec: SEC, tv_nsec: NSEC }"
    /// );
    ///```
    impl Display for PartialComplexTime {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                Self::Wall(w) => write!(f, "{} and No Monotonic", &ReadableSystemTime(*w)),
                Self::Monotonic(m) => write!(f, "No Wall and {m:?}"),
                Self::Complex(t) => Display::fmt(t, f),
            }
        }
    }

    /// An `Add` implementation for PartialComplexTime that adds the duration to each of the time
    /// values it holds.
    ///
    /// # Panics
    ///
    /// The Add<Duration> implementations for both SystemTime and Instant, which this uses, will
    /// panic on overflow.
    impl Add<Duration> for PartialComplexTime {
        type Output = Self;

        fn add(self, dur: Duration) -> Self {
            match self {
                Self::Wall(w) => Self::Wall(w + dur),
                Self::Monotonic(m) => Self::Monotonic(m + dur),
                Self::Complex(c) => Self::Complex(c + dur),
            }
        }
    }

    /// AddAssign implementation that relies on the above Add implementation.
    impl AddAssign<Duration> for PartialComplexTime {
        fn add_assign(&mut self, other: Duration) {
            *self = *self + other;
        }
    }

    /// A `Sub` implementation for PartialComplexTime that subtracts the duration to each of the time
    /// values it holds.
    ///
    /// # Panics
    ///
    /// Panics when the result cannot be expressed in the underlying representation.
    /// Specifically, SystemTime, Instant, and ComplexTime may not be able to represent the
    /// resulting time.
    impl Sub<Duration> for PartialComplexTime {
        type Output = Self;
        fn sub(self, dur: Duration) -> Self {
            match self {
                Self::Wall(w) => Self::Wall(w.checked_sub(dur).unwrap()),
                Self::Monotonic(m) => Self::Monotonic(m.checked_sub(dur).unwrap()),
                Self::Complex(c) => Self::Complex(c - dur),
            }
        }
    }

    /// SubAssign implementation that relies on the above Add implementation.
    impl SubAssign<Duration> for PartialComplexTime {
        fn sub_assign(&mut self, other: Duration) {
            *self = *self - other;
        }
    }
    #[cfg(test)]
    mod tests {
        use super::super::super::ComplexTime;
        use super::*;
        use std::time::{Instant, SystemTime};

        #[test]
        fn test_partial_complex_time_impl_add() {
            let wall = SystemTime::now();
            let mono = Instant::now();
            let comp = ComplexTime { wall, mono };

            let partial_wall = PartialComplexTime::Wall(wall);
            let partial_mono = PartialComplexTime::Monotonic(mono);
            let partial_comp = PartialComplexTime::Complex(comp);

            let dur = Duration::from_secs(60 * 60);

            let later_partial_wall = partial_wall + dur;
            let later_partial_mono = partial_mono + dur;
            let later_partial_comp = partial_comp + dur;

            match later_partial_wall {
                PartialComplexTime::Wall(w) => assert_eq!(w.duration_since(wall).unwrap(), dur),
                x => panic!("{x:?} is not a PartialComplexTime::Wall"),
            };
            match later_partial_mono {
                PartialComplexTime::Monotonic(m) => assert_eq!(m.duration_since(mono), dur),
                x => panic!("{x:?} is not a PartialComplexTime::Monotonic"),
            };
            match later_partial_comp {
                PartialComplexTime::Complex(c) => {
                    assert_eq!(c.wall.duration_since(wall).unwrap(), dur);
                    assert_eq!(c.mono.duration_since(mono), dur);
                }
                x => panic!("{x:?} is not a PartialComplexTime::Complex"),
            };
        }

        #[test]
        fn test_partial_complex_time_impl_add_assign() {
            let wall = SystemTime::now();
            let mono = Instant::now();
            let comp = ComplexTime { wall, mono };

            let mut partial_wall = PartialComplexTime::Wall(wall);
            let mut partial_mono = PartialComplexTime::Monotonic(mono);
            let mut partial_comp = PartialComplexTime::Complex(comp);

            let dur = Duration::from_secs(60 * 60);

            // perform the add-assign
            partial_wall += dur;
            partial_mono += dur;
            partial_comp += dur;

            match partial_wall {
                PartialComplexTime::Wall(w) => assert_eq!(w.duration_since(wall).unwrap(), dur),
                x => panic!("{x:?} is not a PartialComplexTime::Wall"),
            };
            match partial_mono {
                PartialComplexTime::Monotonic(m) => assert_eq!(m.duration_since(mono), dur),
                x => panic!("{x:?} is not a PartialComplexTime::Monotonic"),
            };
            match partial_comp {
                PartialComplexTime::Complex(c) => {
                    assert_eq!(c.wall.duration_since(comp.wall).unwrap(), dur);
                    assert_eq!(c.mono.duration_since(comp.mono), dur);
                }
                x => panic!("{x:?} is not a PartialComplexTime::Complex"),
            };
        }

        #[test]
        fn test_partial_complex_time_impl_sub() {
            let wall = SystemTime::now();
            // If this test was executed early after boot, it's possible `Instant::now()` could be
            // less than 60*60 seconds. To make the tests more deterministic, we'll create a
            // synthetic now we'll use in tests that's at least 24 hours from the real `now()`
            // value.
            let mono = Instant::now() + Duration::from_secs(24 * 60 * 60);
            let comp = ComplexTime { wall, mono };

            let partial_wall = PartialComplexTime::Wall(wall);
            let partial_mono = PartialComplexTime::Monotonic(mono);
            let partial_comp = PartialComplexTime::Complex(comp);

            let dur = Duration::from_secs(60 * 60);

            let earlier_partial_wall = partial_wall - dur;
            let earlier_partial_mono = partial_mono - dur;
            let earlier_partial_comp = partial_comp - dur;

            match earlier_partial_wall {
                PartialComplexTime::Wall(w) => assert_eq!(wall.duration_since(w).unwrap(), dur),
                x => panic!("{x:?} is not a PartialComplexTime::Wall"),
            };
            match earlier_partial_mono {
                PartialComplexTime::Monotonic(m) => assert_eq!(mono.duration_since(m), dur),
                x => panic!("{x:?} is not a PartialComplexTime::Monotonic"),
            };
            match earlier_partial_comp {
                PartialComplexTime::Complex(c) => {
                    assert_eq!(wall.duration_since(c.wall).unwrap(), dur);
                    assert_eq!(mono.duration_since(c.mono), dur);
                }
                x => panic!("{x:?} is not a PartialComplexTime::Complex"),
            };
        }

        #[test]
        fn test_partial_complex_time_impl_sub_assign() {
            let wall = SystemTime::now();
            // If this test was executed early after boot, it's possible `Instant::now()` could be
            // less than 60*60 seconds. To make the tests more deterministic, we'll create a
            // synthetic now we'll use in tests that's at least 24 hours from the real `now()`
            // value.
            let mono = Instant::now() + Duration::from_secs(24 * 60 * 60);
            let comp = ComplexTime { wall, mono };

            let mut partial_wall = PartialComplexTime::Wall(wall);
            let mut partial_mono = PartialComplexTime::Monotonic(mono);
            let mut partial_comp = PartialComplexTime::Complex(comp);

            let dur = Duration::from_secs(60 * 60);

            // perform the add-assign
            partial_wall -= dur;
            partial_mono -= dur;
            partial_comp -= dur;

            match partial_wall {
                PartialComplexTime::Wall(w) => assert_eq!(wall.duration_since(w).unwrap(), dur),
                x => panic!("{x:?} is not a PartialComplexTime::Wall"),
            };
            match partial_mono {
                PartialComplexTime::Monotonic(m) => assert_eq!(mono.duration_since(m), dur),
                x => panic!("{x:?} is not a PartialComplexTime::Monotonic"),
            };
            match partial_comp {
                PartialComplexTime::Complex(c) => {
                    assert_eq!(wall.duration_since(c.wall).unwrap(), dur);
                    assert_eq!(mono.duration_since(c.mono), dur);
                }
                x => panic!("{x:?} is not a PartialComplexTime::Complex"),
            };
        }
    }
}

/// Conversions for `PartialComplexTime`.
///
/// This implements `From<T> for PartialComplexTime` for many T.
/// This implements `From<PartialComplexTime> for U` for many U (which are outside this module)
pub mod partial_complex_time_type_conversions {
    use super::super::{ComplexTime, PartialComplexTime};
    use std::time::{Instant, SystemTime};

    // `From<T> for PartialComplexTime`

    impl From<ComplexTime> for PartialComplexTime {
        fn from(t: ComplexTime) -> Self {
            PartialComplexTime::Complex(t)
        }
    }

    // Provided so that fn's that take `impl Into<Option<PartialComplexTime>>` can easily take a
    // ComplexTime without spelling out the whole conversion (mostly applies to builders)
    impl From<ComplexTime> for Option<PartialComplexTime> {
        fn from(t: ComplexTime) -> Self {
            Some(PartialComplexTime::from(t))
        }
    }

    impl From<SystemTime> for PartialComplexTime {
        fn from(w: SystemTime) -> PartialComplexTime {
            PartialComplexTime::Wall(w)
        }
    }

    impl From<Instant> for PartialComplexTime {
        fn from(m: Instant) -> PartialComplexTime {
            PartialComplexTime::Monotonic(m)
        }
    }

    impl From<(SystemTime, Instant)> for PartialComplexTime {
        fn from(t: (SystemTime, Instant)) -> PartialComplexTime {
            PartialComplexTime::Complex(ComplexTime::from(t))
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use std::time::{Duration, Instant, SystemTime};

        #[test]
        fn test_from_complex_time_for_partial_complex_time() {
            let complex = ComplexTime {
                wall: SystemTime::now(),
                mono: Instant::now(),
            };
            assert_eq!(
                PartialComplexTime::from(complex),
                PartialComplexTime::Complex(complex)
            );
        }

        #[test]
        fn test_from_complex_time_for_option_partial_complex_time() {
            let complex = ComplexTime {
                wall: SystemTime::now(),
                mono: Instant::now(),
            };
            assert_eq!(
                Option::<PartialComplexTime>::from(complex),
                Some(PartialComplexTime::Complex(complex))
            );
        }

        #[test]
        fn test_from_system_time_for_partial_complex_time() {
            let system_time = SystemTime::now();
            assert_eq!(
                PartialComplexTime::from(system_time),
                PartialComplexTime::Wall(system_time)
            );
        }

        #[test]
        fn test_from_instant_for_partial_complex_time() {
            let instant = Instant::now();
            assert_eq!(
                PartialComplexTime::from(instant),
                PartialComplexTime::Monotonic(instant)
            );
        }

        #[test]
        fn test_from_std_time_tuple_for_partial_complex_time() {
            let system_time = SystemTime::now();
            let instant = Instant::now();

            assert_eq!(
                PartialComplexTime::from(system_time),
                PartialComplexTime::Wall(system_time)
            );
            assert_eq!(
                PartialComplexTime::from(instant),
                PartialComplexTime::Monotonic(instant)
            );
            assert_eq!(
                PartialComplexTime::from((system_time, instant)),
                PartialComplexTime::Complex(ComplexTime {
                    wall: system_time,
                    mono: instant
                })
            );
        }

        // `From<PartialComplexTime> for ...`

        #[test]
        fn test_checked_to_system_time() {
            let system_time = SystemTime::now();
            let instant = Instant::now();

            assert_eq!(
                PartialComplexTime::Wall(system_time).checked_to_system_time(),
                Some(system_time)
            );
            assert_eq!(
                PartialComplexTime::Monotonic(instant).checked_to_system_time(),
                None
            );
            assert_eq!(
                PartialComplexTime::Complex((system_time, instant).into()).checked_to_system_time(),
                Some(system_time)
            );
        }

        #[test]
        fn test_checked_to_micros_from_partial_complex_time() {
            let system_time = SystemTime::UNIX_EPOCH + Duration::from_micros(123456789);
            let instant = Instant::now();

            assert_eq!(
                123456789,
                PartialComplexTime::Wall(system_time)
                    .checked_to_micros_since_epoch()
                    .unwrap()
            );
            assert_eq!(
                123456789,
                PartialComplexTime::Complex(ComplexTime::from((system_time, instant)))
                    .checked_to_micros_since_epoch()
                    .unwrap()
            );
            assert_eq!(
                None,
                PartialComplexTime::Monotonic(instant).checked_to_micros_since_epoch()
            );
        }

        #[test]
        fn test_checked_to_micros_from_partial_complex_time_before_epoch() {
            let system_time = SystemTime::UNIX_EPOCH - Duration::from_micros(123456789);
            let instant = Instant::now();

            assert_eq!(
                -123456789,
                PartialComplexTime::Wall(system_time)
                    .checked_to_micros_since_epoch()
                    .unwrap()
            );
            assert_eq!(
                -123456789,
                PartialComplexTime::Complex(ComplexTime::from((system_time, instant)))
                    .checked_to_micros_since_epoch()
                    .unwrap()
            );
            assert_eq!(
                None,
                PartialComplexTime::Monotonic(instant).checked_to_micros_since_epoch()
            );
        }

        #[test]
        fn test_checked_to_micros_from_partial_complex_time_overflow_is_none() {
            let system_time = SystemTime::UNIX_EPOCH + 2 * Duration::from_micros(u64::MAX);
            assert_eq!(
                None,
                PartialComplexTime::Wall(system_time).checked_to_micros_since_epoch()
            );
        }

        #[test]
        fn test_checked_to_micros_from_partial_complex_time_negative_overflow_is_none() {
            let system_time = SystemTime::UNIX_EPOCH - 2 * Duration::from_micros(u64::MAX);
            assert_eq!(
                None,
                PartialComplexTime::Wall(system_time).checked_to_micros_since_epoch()
            );
        }

        #[test]
        fn test_complete_with() {
            let system_time = SystemTime::UNIX_EPOCH - Duration::from_micros(100);
            let instant = Instant::now();
            let complex = ComplexTime::from((system_time, instant));

            let wall = PartialComplexTime::Wall(system_time);
            let mono = PartialComplexTime::Monotonic(instant);
            let comp = PartialComplexTime::Complex(complex);

            let other = complex + Duration::from_micros(500);

            assert_eq!(
                wall.complete_with(other),
                ComplexTime::from((system_time, other.mono))
            );
            assert_eq!(
                mono.complete_with(other),
                ComplexTime::from((other.wall, instant))
            );
            assert_eq!(comp.complete_with(other), complex);
        }

        #[test]
        fn test_destructure() {
            let system_time = SystemTime::now();
            let instant = Instant::now();
            let complex = ComplexTime::from((system_time, instant));

            let wall = PartialComplexTime::Wall(system_time);
            let mono = PartialComplexTime::Monotonic(instant);
            let comp = PartialComplexTime::Complex(complex);

            assert_eq!(wall.destructure(), (Some(system_time), None));
            assert_eq!(mono.destructure(), (None, Some(instant)));
            assert_eq!(comp.destructure(), (Some(system_time), Some(instant)));
        }
    }
}

/// Module to ease the conversion betwee SystemTime and i64 microseconds from the from UNIX Epoch.
pub mod system_time_conversion {
    use std::convert::TryFrom;
    use std::time::{Duration, SystemTime};

    /// Convert a SystemTime into microseconds from the unix epoch, returning None on overflow.
    /// Valid over roughly +/- 30,000 years from 1970-01-01 UTC.
    pub fn checked_system_time_to_micros_from_epoch(time: SystemTime) -> Option<i64> {
        match time.duration_since(SystemTime::UNIX_EPOCH) {
            Ok(duration_since_epoch) => {
                // Safely convert to i64 microseconds or return None.
                let micros: u128 = duration_since_epoch.as_micros();
                i64::try_from(micros).ok()
            }
            Err(e) => {
                // Safely convert to i64 microseconds (negative), or return None.
                let micros: u128 = e.duration().as_micros();
                i64::try_from(micros).ok().and_then(i64::checked_neg)
            }
        }
    }

    /// Convert micro seconds from the unix epoch to SystemTime.
    pub fn micros_from_epoch_to_system_time(micros: i64) -> SystemTime {
        // Duration is always unsigned, so negative values need to be handled separately from
        // positive values
        if micros > 0 {
            let duration = Duration::from_micros(micros as u64);
            SystemTime::UNIX_EPOCH + duration
        } else {
            let duration = Duration::from_micros((micros as u64).wrapping_neg());
            SystemTime::UNIX_EPOCH - duration
        }
    }

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

        #[test]
        fn test_system_time_to_micros() {
            let system_time = SystemTime::UNIX_EPOCH + Duration::from_micros(123456789);
            assert_eq!(
                checked_system_time_to_micros_from_epoch(system_time).unwrap(),
                123456789
            )
        }

        #[test]
        fn test_system_time_to_micros_negative() {
            let system_time = SystemTime::UNIX_EPOCH - Duration::from_micros(123456789);
            assert_eq!(
                checked_system_time_to_micros_from_epoch(system_time).unwrap(),
                -123456789
            )
        }

        #[test]
        fn test_system_time_to_micros_overflow_is_none() {
            let system_time = SystemTime::UNIX_EPOCH + 2 * Duration::from_micros(u64::MAX);
            assert_eq!(checked_system_time_to_micros_from_epoch(system_time), None);
        }

        #[test]
        fn test_system_time_to_micros_negative_overflow_is_none() {
            let system_time = SystemTime::UNIX_EPOCH - 2 * Duration::from_micros(u64::MAX);
            assert_eq!(checked_system_time_to_micros_from_epoch(system_time), None);
        }

        #[test]
        fn test_system_time_from_micros() {
            let system_time = SystemTime::UNIX_EPOCH + Duration::from_micros(123456789);
            assert_eq!(micros_from_epoch_to_system_time(123456789), system_time);
        }

        #[test]
        fn test_system_time_from_micros_negative() {
            let system_time = SystemTime::UNIX_EPOCH - Duration::from_micros(123456789);
            assert_eq!(micros_from_epoch_to_system_time(-123456789), system_time);
        }

        #[test]
        fn test_system_time_from_micros_positive_max() {
            let system_time = SystemTime::UNIX_EPOCH + Duration::from_micros(i64::MAX as u64);
            assert_eq!(micros_from_epoch_to_system_time(i64::MAX), system_time);
        }

        #[test]
        fn test_system_time_from_micros_negative_min() {
            let system_time = SystemTime::UNIX_EPOCH - Duration::from_micros((i64::MAX as u64) + 1);
            assert_eq!(micros_from_epoch_to_system_time(i64::MIN), system_time);
        }
    }
}