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
#[cfg_attr(target_env = "musl", allow(deprecated))]
// https://github.com/rust-lang/libc/issues/1848
pub use libc::{suseconds_t, time_t};
use libc::{timespec, timeval};
use std::convert::From;
use std::time::Duration;
use std::{cmp, fmt, ops};

const fn zero_init_timespec() -> timespec {
    // `std::mem::MaybeUninit::zeroed()` is not yet a const fn
    // (https://github.com/rust-lang/rust/issues/91850) so we will instead initialize an array of
    // the appropriate size to zero and then transmute it to a timespec value.
    unsafe { std::mem::transmute([0u8; std::mem::size_of::<timespec>()]) }
}

#[cfg(any(
    all(feature = "time", any(target_os = "android", target_os = "linux")),
    all(
        any(
            target_os = "freebsd",
            target_os = "illumos",
            target_os = "linux",
            target_os = "netbsd"
        ),
        feature = "time",
        feature = "signal"
    )
))]
pub(crate) mod timer {
    use crate::sys::time::{zero_init_timespec, TimeSpec};
    use bitflags::bitflags;

    #[derive(Debug, Clone, Copy)]
    pub(crate) struct TimerSpec(libc::itimerspec);

    impl TimerSpec {
        pub const fn none() -> Self {
            Self(libc::itimerspec {
                it_interval: zero_init_timespec(),
                it_value: zero_init_timespec(),
            })
        }
    }

    impl AsMut<libc::itimerspec> for TimerSpec {
        fn as_mut(&mut self) -> &mut libc::itimerspec {
            &mut self.0
        }
    }

    impl AsRef<libc::itimerspec> for TimerSpec {
        fn as_ref(&self) -> &libc::itimerspec {
            &self.0
        }
    }

    impl From<Expiration> for TimerSpec {
        fn from(expiration: Expiration) -> TimerSpec {
            match expiration {
                Expiration::OneShot(t) => TimerSpec(libc::itimerspec {
                    it_interval: zero_init_timespec(),
                    it_value: *t.as_ref(),
                }),
                Expiration::IntervalDelayed(start, interval) => {
                    TimerSpec(libc::itimerspec {
                        it_interval: *interval.as_ref(),
                        it_value: *start.as_ref(),
                    })
                }
                Expiration::Interval(t) => TimerSpec(libc::itimerspec {
                    it_interval: *t.as_ref(),
                    it_value: *t.as_ref(),
                }),
            }
        }
    }

    /// An enumeration allowing the definition of the expiration time of an alarm,
    /// recurring or not.
    #[derive(Debug, Clone, Copy, Eq, PartialEq)]
    pub enum Expiration {
        /// Alarm will trigger once after the time given in `TimeSpec`
        OneShot(TimeSpec),
        /// Alarm will trigger after a specified delay and then every interval of
        /// time.
        IntervalDelayed(TimeSpec, TimeSpec),
        /// Alarm will trigger every specified interval of time.
        Interval(TimeSpec),
    }

    #[cfg(any(target_os = "android", target_os = "linux"))]
    bitflags! {
        /// Flags that are used for arming the timer.
        #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
        pub struct TimerSetTimeFlags: libc::c_int {
            const TFD_TIMER_ABSTIME = libc::TFD_TIMER_ABSTIME;
            const TFD_TIMER_CANCEL_ON_SET = libc::TFD_TIMER_CANCEL_ON_SET;
        }
    }
    #[cfg(any(
        target_os = "freebsd",
        target_os = "netbsd",
        target_os = "dragonfly",
        target_os = "illumos"
    ))]
    bitflags! {
        /// Flags that are used for arming the timer.
        #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
        pub struct TimerSetTimeFlags: libc::c_int {
            const TFD_TIMER_ABSTIME = libc::TIMER_ABSTIME;
        }
    }

    impl From<TimerSpec> for Expiration {
        fn from(timerspec: TimerSpec) -> Expiration {
            match timerspec {
                TimerSpec(libc::itimerspec {
                    it_interval:
                        libc::timespec {
                            tv_sec: 0,
                            tv_nsec: 0,
                            ..
                        },
                    it_value: ts,
                }) => Expiration::OneShot(ts.into()),
                TimerSpec(libc::itimerspec {
                    it_interval: int_ts,
                    it_value: val_ts,
                }) => {
                    if (int_ts.tv_sec == val_ts.tv_sec)
                        && (int_ts.tv_nsec == val_ts.tv_nsec)
                    {
                        Expiration::Interval(int_ts.into())
                    } else {
                        Expiration::IntervalDelayed(
                            val_ts.into(),
                            int_ts.into(),
                        )
                    }
                }
            }
        }
    }
}

pub trait TimeValLike: Sized {
    #[inline]
    fn zero() -> Self {
        Self::seconds(0)
    }

    #[inline]
    fn hours(hours: i64) -> Self {
        let secs = hours
            .checked_mul(SECS_PER_HOUR)
            .expect("TimeValLike::hours ouf of bounds");
        Self::seconds(secs)
    }

    #[inline]
    fn minutes(minutes: i64) -> Self {
        let secs = minutes
            .checked_mul(SECS_PER_MINUTE)
            .expect("TimeValLike::minutes out of bounds");
        Self::seconds(secs)
    }

    fn seconds(seconds: i64) -> Self;
    fn milliseconds(milliseconds: i64) -> Self;
    fn microseconds(microseconds: i64) -> Self;
    fn nanoseconds(nanoseconds: i64) -> Self;

    #[inline]
    fn num_hours(&self) -> i64 {
        self.num_seconds() / 3600
    }

    #[inline]
    fn num_minutes(&self) -> i64 {
        self.num_seconds() / 60
    }

    fn num_seconds(&self) -> i64;
    fn num_milliseconds(&self) -> i64;
    fn num_microseconds(&self) -> i64;
    fn num_nanoseconds(&self) -> i64;
}

#[repr(C)]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct TimeSpec(timespec);

const NANOS_PER_SEC: i64 = 1_000_000_000;
const SECS_PER_MINUTE: i64 = 60;
const SECS_PER_HOUR: i64 = 3600;

#[cfg(target_pointer_width = "64")]
const TS_MAX_SECONDS: i64 = (i64::MAX / NANOS_PER_SEC) - 1;

#[cfg(target_pointer_width = "32")]
const TS_MAX_SECONDS: i64 = isize::MAX as i64;

const TS_MIN_SECONDS: i64 = -TS_MAX_SECONDS;

// x32 compatibility
// See https://sourceware.org/bugzilla/show_bug.cgi?id=16437
#[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))]
type timespec_tv_nsec_t = i64;
#[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))]
type timespec_tv_nsec_t = libc::c_long;

impl From<timespec> for TimeSpec {
    fn from(ts: timespec) -> Self {
        Self(ts)
    }
}

impl From<Duration> for TimeSpec {
    fn from(duration: Duration) -> Self {
        Self::from_duration(duration)
    }
}

impl From<TimeSpec> for Duration {
    fn from(timespec: TimeSpec) -> Self {
        Duration::new(timespec.0.tv_sec as u64, timespec.0.tv_nsec as u32)
    }
}

impl AsRef<timespec> for TimeSpec {
    fn as_ref(&self) -> &timespec {
        &self.0
    }
}

impl AsMut<timespec> for TimeSpec {
    fn as_mut(&mut self) -> &mut timespec {
        &mut self.0
    }
}

impl Ord for TimeSpec {
    // The implementation of cmp is simplified by assuming that the struct is
    // normalized.  That is, tv_nsec must always be within [0, 1_000_000_000)
    fn cmp(&self, other: &TimeSpec) -> cmp::Ordering {
        if self.tv_sec() == other.tv_sec() {
            self.tv_nsec().cmp(&other.tv_nsec())
        } else {
            self.tv_sec().cmp(&other.tv_sec())
        }
    }
}

impl PartialOrd for TimeSpec {
    fn partial_cmp(&self, other: &TimeSpec) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl TimeValLike for TimeSpec {
    #[inline]
    #[cfg_attr(target_env = "musl", allow(deprecated))]
    // https://github.com/rust-lang/libc/issues/1848
    fn seconds(seconds: i64) -> TimeSpec {
        assert!(
            (TS_MIN_SECONDS..=TS_MAX_SECONDS).contains(&seconds),
            "TimeSpec out of bounds; seconds={seconds}",
        );
        let mut ts = zero_init_timespec();
        ts.tv_sec = seconds as time_t;
        TimeSpec(ts)
    }

    #[inline]
    fn milliseconds(milliseconds: i64) -> TimeSpec {
        let nanoseconds = milliseconds
            .checked_mul(1_000_000)
            .expect("TimeSpec::milliseconds out of bounds");

        TimeSpec::nanoseconds(nanoseconds)
    }

    /// Makes a new `TimeSpec` with given number of microseconds.
    #[inline]
    fn microseconds(microseconds: i64) -> TimeSpec {
        let nanoseconds = microseconds
            .checked_mul(1_000)
            .expect("TimeSpec::milliseconds out of bounds");

        TimeSpec::nanoseconds(nanoseconds)
    }

    /// Makes a new `TimeSpec` with given number of nanoseconds.
    #[inline]
    #[cfg_attr(target_env = "musl", allow(deprecated))]
    // https://github.com/rust-lang/libc/issues/1848
    fn nanoseconds(nanoseconds: i64) -> TimeSpec {
        let (secs, nanos) = div_mod_floor_64(nanoseconds, NANOS_PER_SEC);
        assert!(
            (TS_MIN_SECONDS..=TS_MAX_SECONDS).contains(&secs),
            "TimeSpec out of bounds"
        );
        let mut ts = zero_init_timespec();
        ts.tv_sec = secs as time_t;
        ts.tv_nsec = nanos as timespec_tv_nsec_t;
        TimeSpec(ts)
    }

    // The cast is not unnecessary on all platforms.
    #[allow(clippy::unnecessary_cast)]
    fn num_seconds(&self) -> i64 {
        if self.tv_sec() < 0 && self.tv_nsec() > 0 {
            (self.tv_sec() + 1) as i64
        } else {
            self.tv_sec() as i64
        }
    }

    fn num_milliseconds(&self) -> i64 {
        self.num_nanoseconds() / 1_000_000
    }

    fn num_microseconds(&self) -> i64 {
        self.num_nanoseconds() / 1_000
    }

    // The cast is not unnecessary on all platforms.
    #[allow(clippy::unnecessary_cast)]
    fn num_nanoseconds(&self) -> i64 {
        let secs = self.num_seconds() * 1_000_000_000;
        let nsec = self.nanos_mod_sec();
        secs + nsec as i64
    }
}

impl TimeSpec {
    /// Construct a new `TimeSpec` from its components
    #[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848
    pub const fn new(seconds: time_t, nanoseconds: timespec_tv_nsec_t) -> Self {
        let mut ts = zero_init_timespec();
        ts.tv_sec = seconds;
        ts.tv_nsec = nanoseconds;
        Self(ts)
    }

    fn nanos_mod_sec(&self) -> timespec_tv_nsec_t {
        if self.tv_sec() < 0 && self.tv_nsec() > 0 {
            self.tv_nsec() - NANOS_PER_SEC as timespec_tv_nsec_t
        } else {
            self.tv_nsec()
        }
    }

    #[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848
    pub const fn tv_sec(&self) -> time_t {
        self.0.tv_sec
    }

    pub const fn tv_nsec(&self) -> timespec_tv_nsec_t {
        self.0.tv_nsec
    }

    #[cfg_attr(target_env = "musl", allow(deprecated))]
    // https://github.com/rust-lang/libc/issues/1848
    pub const fn from_duration(duration: Duration) -> Self {
        let mut ts = zero_init_timespec();
        ts.tv_sec = duration.as_secs() as time_t;
        ts.tv_nsec = duration.subsec_nanos() as timespec_tv_nsec_t;
        TimeSpec(ts)
    }

    pub const fn from_timespec(timespec: timespec) -> Self {
        Self(timespec)
    }
}

impl ops::Neg for TimeSpec {
    type Output = TimeSpec;

    fn neg(self) -> TimeSpec {
        TimeSpec::nanoseconds(-self.num_nanoseconds())
    }
}

impl ops::Add for TimeSpec {
    type Output = TimeSpec;

    fn add(self, rhs: TimeSpec) -> TimeSpec {
        TimeSpec::nanoseconds(self.num_nanoseconds() + rhs.num_nanoseconds())
    }
}

impl ops::Sub for TimeSpec {
    type Output = TimeSpec;

    fn sub(self, rhs: TimeSpec) -> TimeSpec {
        TimeSpec::nanoseconds(self.num_nanoseconds() - rhs.num_nanoseconds())
    }
}

impl ops::Mul<i32> for TimeSpec {
    type Output = TimeSpec;

    fn mul(self, rhs: i32) -> TimeSpec {
        let usec = self
            .num_nanoseconds()
            .checked_mul(i64::from(rhs))
            .expect("TimeSpec multiply out of bounds");

        TimeSpec::nanoseconds(usec)
    }
}

impl ops::Div<i32> for TimeSpec {
    type Output = TimeSpec;

    fn div(self, rhs: i32) -> TimeSpec {
        let usec = self.num_nanoseconds() / i64::from(rhs);
        TimeSpec::nanoseconds(usec)
    }
}

impl fmt::Display for TimeSpec {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let (abs, sign) = if self.tv_sec() < 0 {
            (-*self, "-")
        } else {
            (*self, "")
        };

        let sec = abs.tv_sec();

        write!(f, "{sign}")?;

        if abs.tv_nsec() == 0 {
            if sec == 1 {
                write!(f, "1 second")?;
            } else {
                write!(f, "{sec} seconds")?;
            }
        } else if abs.tv_nsec() % 1_000_000 == 0 {
            write!(f, "{sec}.{:03} seconds", abs.tv_nsec() / 1_000_000)?;
        } else if abs.tv_nsec() % 1_000 == 0 {
            write!(f, "{sec}.{:06} seconds", abs.tv_nsec() / 1_000)?;
        } else {
            write!(f, "{sec}.{:09} seconds", abs.tv_nsec())?;
        }

        Ok(())
    }
}

#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct TimeVal(timeval);

const MICROS_PER_SEC: i64 = 1_000_000;

#[cfg(target_pointer_width = "64")]
const TV_MAX_SECONDS: i64 = (i64::MAX / MICROS_PER_SEC) - 1;

#[cfg(target_pointer_width = "32")]
const TV_MAX_SECONDS: i64 = isize::MAX as i64;

const TV_MIN_SECONDS: i64 = -TV_MAX_SECONDS;

impl AsRef<timeval> for TimeVal {
    fn as_ref(&self) -> &timeval {
        &self.0
    }
}

impl AsMut<timeval> for TimeVal {
    fn as_mut(&mut self) -> &mut timeval {
        &mut self.0
    }
}

impl Ord for TimeVal {
    // The implementation of cmp is simplified by assuming that the struct is
    // normalized.  That is, tv_usec must always be within [0, 1_000_000)
    fn cmp(&self, other: &TimeVal) -> cmp::Ordering {
        if self.tv_sec() == other.tv_sec() {
            self.tv_usec().cmp(&other.tv_usec())
        } else {
            self.tv_sec().cmp(&other.tv_sec())
        }
    }
}

impl PartialOrd for TimeVal {
    fn partial_cmp(&self, other: &TimeVal) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl TimeValLike for TimeVal {
    #[inline]
    fn seconds(seconds: i64) -> TimeVal {
        assert!(
            (TV_MIN_SECONDS..=TV_MAX_SECONDS).contains(&seconds),
            "TimeVal out of bounds; seconds={seconds}"
        );
        #[cfg_attr(target_env = "musl", allow(deprecated))]
        // https://github.com/rust-lang/libc/issues/1848
        TimeVal(timeval {
            tv_sec: seconds as time_t,
            tv_usec: 0,
        })
    }

    #[inline]
    fn milliseconds(milliseconds: i64) -> TimeVal {
        let microseconds = milliseconds
            .checked_mul(1_000)
            .expect("TimeVal::milliseconds out of bounds");

        TimeVal::microseconds(microseconds)
    }

    /// Makes a new `TimeVal` with given number of microseconds.
    #[inline]
    fn microseconds(microseconds: i64) -> TimeVal {
        let (secs, micros) = div_mod_floor_64(microseconds, MICROS_PER_SEC);
        assert!(
            (TV_MIN_SECONDS..=TV_MAX_SECONDS).contains(&secs),
            "TimeVal out of bounds"
        );
        #[cfg_attr(target_env = "musl", allow(deprecated))]
        // https://github.com/rust-lang/libc/issues/1848
        TimeVal(timeval {
            tv_sec: secs as time_t,
            tv_usec: micros as suseconds_t,
        })
    }

    /// Makes a new `TimeVal` with given number of nanoseconds.  Some precision
    /// will be lost
    #[inline]
    fn nanoseconds(nanoseconds: i64) -> TimeVal {
        let microseconds = nanoseconds / 1000;
        let (secs, micros) = div_mod_floor_64(microseconds, MICROS_PER_SEC);
        assert!(
            (TV_MIN_SECONDS..=TV_MAX_SECONDS).contains(&secs),
            "TimeVal out of bounds"
        );
        #[cfg_attr(target_env = "musl", allow(deprecated))]
        // https://github.com/rust-lang/libc/issues/1848
        TimeVal(timeval {
            tv_sec: secs as time_t,
            tv_usec: micros as suseconds_t,
        })
    }

    // The cast is not unnecessary on all platforms.
    #[allow(clippy::unnecessary_cast)]
    fn num_seconds(&self) -> i64 {
        if self.tv_sec() < 0 && self.tv_usec() > 0 {
            (self.tv_sec() + 1) as i64
        } else {
            self.tv_sec() as i64
        }
    }

    fn num_milliseconds(&self) -> i64 {
        self.num_microseconds() / 1_000
    }

    // The cast is not unnecessary on all platforms.
    #[allow(clippy::unnecessary_cast)]
    fn num_microseconds(&self) -> i64 {
        let secs = self.num_seconds() * 1_000_000;
        let usec = self.micros_mod_sec();
        secs + usec as i64
    }

    fn num_nanoseconds(&self) -> i64 {
        self.num_microseconds() * 1_000
    }
}

impl TimeVal {
    /// Construct a new `TimeVal` from its components
    #[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848
    pub const fn new(seconds: time_t, microseconds: suseconds_t) -> Self {
        Self(timeval {
            tv_sec: seconds,
            tv_usec: microseconds,
        })
    }

    fn micros_mod_sec(&self) -> suseconds_t {
        if self.tv_sec() < 0 && self.tv_usec() > 0 {
            self.tv_usec() - MICROS_PER_SEC as suseconds_t
        } else {
            self.tv_usec()
        }
    }

    #[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848
    pub const fn tv_sec(&self) -> time_t {
        self.0.tv_sec
    }

    pub const fn tv_usec(&self) -> suseconds_t {
        self.0.tv_usec
    }
}

impl ops::Neg for TimeVal {
    type Output = TimeVal;

    fn neg(self) -> TimeVal {
        TimeVal::microseconds(-self.num_microseconds())
    }
}

impl ops::Add for TimeVal {
    type Output = TimeVal;

    fn add(self, rhs: TimeVal) -> TimeVal {
        TimeVal::microseconds(self.num_microseconds() + rhs.num_microseconds())
    }
}

impl ops::Sub for TimeVal {
    type Output = TimeVal;

    fn sub(self, rhs: TimeVal) -> TimeVal {
        TimeVal::microseconds(self.num_microseconds() - rhs.num_microseconds())
    }
}

impl ops::Mul<i32> for TimeVal {
    type Output = TimeVal;

    fn mul(self, rhs: i32) -> TimeVal {
        let usec = self
            .num_microseconds()
            .checked_mul(i64::from(rhs))
            .expect("TimeVal multiply out of bounds");

        TimeVal::microseconds(usec)
    }
}

impl ops::Div<i32> for TimeVal {
    type Output = TimeVal;

    fn div(self, rhs: i32) -> TimeVal {
        let usec = self.num_microseconds() / i64::from(rhs);
        TimeVal::microseconds(usec)
    }
}

impl fmt::Display for TimeVal {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let (abs, sign) = if self.tv_sec() < 0 {
            (-*self, "-")
        } else {
            (*self, "")
        };

        let sec = abs.tv_sec();

        write!(f, "{sign}")?;

        if abs.tv_usec() == 0 {
            if sec == 1 {
                write!(f, "1 second")?;
            } else {
                write!(f, "{sec} seconds")?;
            }
        } else if abs.tv_usec() % 1000 == 0 {
            write!(f, "{sec}.{:03} seconds", abs.tv_usec() / 1000)?;
        } else {
            write!(f, "{sec}.{:06} seconds", abs.tv_usec())?;
        }

        Ok(())
    }
}

impl From<timeval> for TimeVal {
    fn from(tv: timeval) -> Self {
        TimeVal(tv)
    }
}

#[inline]
fn div_mod_floor_64(this: i64, other: i64) -> (i64, i64) {
    (div_floor_64(this, other), mod_floor_64(this, other))
}

#[inline]
fn div_floor_64(this: i64, other: i64) -> i64 {
    match div_rem_64(this, other) {
        (d, r) if (r > 0 && other < 0) || (r < 0 && other > 0) => d - 1,
        (d, _) => d,
    }
}

#[inline]
fn mod_floor_64(this: i64, other: i64) -> i64 {
    match this % other {
        r if (r > 0 && other < 0) || (r < 0 && other > 0) => r + other,
        r => r,
    }
}

#[inline]
fn div_rem_64(this: i64, other: i64) -> (i64, i64) {
    (this / other, this % other)
}

#[cfg(test)]
mod test {
    use super::{TimeSpec, TimeVal, TimeValLike};
    use std::time::Duration;

    #[test]
    pub fn test_timespec() {
        assert_ne!(TimeSpec::seconds(1), TimeSpec::zero());
        assert_eq!(
            TimeSpec::seconds(1) + TimeSpec::seconds(2),
            TimeSpec::seconds(3)
        );
        assert_eq!(
            TimeSpec::minutes(3) + TimeSpec::seconds(2),
            TimeSpec::seconds(182)
        );
    }

    #[test]
    pub fn test_timespec_from() {
        let duration = Duration::new(123, 123_456_789);
        let timespec = TimeSpec::nanoseconds(123_123_456_789);

        assert_eq!(TimeSpec::from(duration), timespec);
        assert_eq!(Duration::from(timespec), duration);
    }

    #[test]
    pub fn test_timespec_neg() {
        let a = TimeSpec::seconds(1) + TimeSpec::nanoseconds(123);
        let b = TimeSpec::seconds(-1) + TimeSpec::nanoseconds(-123);

        assert_eq!(a, -b);
    }

    #[test]
    pub fn test_timespec_ord() {
        assert_eq!(TimeSpec::seconds(1), TimeSpec::nanoseconds(1_000_000_000));
        assert!(TimeSpec::seconds(1) < TimeSpec::nanoseconds(1_000_000_001));
        assert!(TimeSpec::seconds(1) > TimeSpec::nanoseconds(999_999_999));
        assert!(TimeSpec::seconds(-1) < TimeSpec::nanoseconds(-999_999_999));
        assert!(TimeSpec::seconds(-1) > TimeSpec::nanoseconds(-1_000_000_001));
    }

    #[test]
    pub fn test_timespec_fmt() {
        assert_eq!(TimeSpec::zero().to_string(), "0 seconds");
        assert_eq!(TimeSpec::seconds(42).to_string(), "42 seconds");
        assert_eq!(TimeSpec::milliseconds(42).to_string(), "0.042 seconds");
        assert_eq!(TimeSpec::microseconds(42).to_string(), "0.000042 seconds");
        assert_eq!(
            TimeSpec::nanoseconds(42).to_string(),
            "0.000000042 seconds"
        );
        assert_eq!(TimeSpec::seconds(-86401).to_string(), "-86401 seconds");
    }

    #[test]
    pub fn test_timeval() {
        assert_ne!(TimeVal::seconds(1), TimeVal::zero());
        assert_eq!(
            TimeVal::seconds(1) + TimeVal::seconds(2),
            TimeVal::seconds(3)
        );
        assert_eq!(
            TimeVal::minutes(3) + TimeVal::seconds(2),
            TimeVal::seconds(182)
        );
    }

    #[test]
    pub fn test_timeval_ord() {
        assert_eq!(TimeVal::seconds(1), TimeVal::microseconds(1_000_000));
        assert!(TimeVal::seconds(1) < TimeVal::microseconds(1_000_001));
        assert!(TimeVal::seconds(1) > TimeVal::microseconds(999_999));
        assert!(TimeVal::seconds(-1) < TimeVal::microseconds(-999_999));
        assert!(TimeVal::seconds(-1) > TimeVal::microseconds(-1_000_001));
    }

    #[test]
    pub fn test_timeval_neg() {
        let a = TimeVal::seconds(1) + TimeVal::microseconds(123);
        let b = TimeVal::seconds(-1) + TimeVal::microseconds(-123);

        assert_eq!(a, -b);
    }

    #[test]
    pub fn test_timeval_fmt() {
        assert_eq!(TimeVal::zero().to_string(), "0 seconds");
        assert_eq!(TimeVal::seconds(42).to_string(), "42 seconds");
        assert_eq!(TimeVal::milliseconds(42).to_string(), "0.042 seconds");
        assert_eq!(TimeVal::microseconds(42).to_string(), "0.000042 seconds");
        assert_eq!(TimeVal::nanoseconds(1402).to_string(), "0.000001 seconds");
        assert_eq!(TimeVal::seconds(-86401).to_string(), "-86401 seconds");
    }
}