-
Notifications
You must be signed in to change notification settings - Fork 13.1k
/
Copy pathtime.rs
1688 lines (1585 loc) · 60.9 KB
/
time.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
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
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![stable(feature = "duration_core", since = "1.25.0")]
//! Temporal quantification.
//!
//! # Examples:
//!
//! There are multiple ways to create a new [`Duration`]:
//!
//! ```
//! # use std::time::Duration;
//! let five_seconds = Duration::from_secs(5);
//! assert_eq!(five_seconds, Duration::from_millis(5_000));
//! assert_eq!(five_seconds, Duration::from_micros(5_000_000));
//! assert_eq!(five_seconds, Duration::from_nanos(5_000_000_000));
//!
//! let ten_seconds = Duration::from_secs(10);
//! let seven_nanos = Duration::from_nanos(7);
//! let total = ten_seconds + seven_nanos;
//! assert_eq!(total, Duration::new(10, 7));
//! ```
use crate::fmt;
use crate::iter::Sum;
use crate::num::niche_types::Nanoseconds;
use crate::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
const NANOS_PER_SEC: u32 = 1_000_000_000;
const NANOS_PER_MILLI: u32 = 1_000_000;
const NANOS_PER_MICRO: u32 = 1_000;
const MILLIS_PER_SEC: u64 = 1_000;
const MICROS_PER_SEC: u64 = 1_000_000;
#[unstable(feature = "duration_units", issue = "120301")]
const SECS_PER_MINUTE: u64 = 60;
#[unstable(feature = "duration_units", issue = "120301")]
const MINS_PER_HOUR: u64 = 60;
#[unstable(feature = "duration_units", issue = "120301")]
const HOURS_PER_DAY: u64 = 24;
#[unstable(feature = "duration_units", issue = "120301")]
const DAYS_PER_WEEK: u64 = 7;
/// A `Duration` type to represent a span of time, typically used for system
/// timeouts.
///
/// Each `Duration` is composed of a whole number of seconds and a fractional part
/// represented in nanoseconds. If the underlying system does not support
/// nanosecond-level precision, APIs binding a system timeout will typically round up
/// the number of nanoseconds.
///
/// [`Duration`]s implement many common traits, including [`Add`], [`Sub`], and other
/// [`ops`] traits. It implements [`Default`] by returning a zero-length `Duration`.
///
/// [`ops`]: crate::ops
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let five_seconds = Duration::new(5, 0);
/// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
///
/// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
/// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
///
/// let ten_millis = Duration::from_millis(10);
/// ```
///
/// # Formatting `Duration` values
///
/// `Duration` intentionally does not have a `Display` impl, as there are a
/// variety of ways to format spans of time for human readability. `Duration`
/// provides a `Debug` impl that shows the full precision of the value.
///
/// The `Debug` output uses the non-ASCII "µs" suffix for microseconds. If your
/// program output may appear in contexts that cannot rely on full Unicode
/// compatibility, you may wish to format `Duration` objects yourself or use a
/// crate to do so.
#[stable(feature = "duration", since = "1.3.0")]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[cfg_attr(not(test), rustc_diagnostic_item = "Duration")]
pub struct Duration {
secs: u64,
nanos: Nanoseconds, // Always 0 <= nanos < NANOS_PER_SEC
}
impl Duration {
/// The duration of one second.
///
/// # Examples
///
/// ```
/// #![feature(duration_constants)]
/// use std::time::Duration;
///
/// assert_eq!(Duration::SECOND, Duration::from_secs(1));
/// ```
#[unstable(feature = "duration_constants", issue = "57391")]
pub const SECOND: Duration = Duration::from_secs(1);
/// The duration of one millisecond.
///
/// # Examples
///
/// ```
/// #![feature(duration_constants)]
/// use std::time::Duration;
///
/// assert_eq!(Duration::MILLISECOND, Duration::from_millis(1));
/// ```
#[unstable(feature = "duration_constants", issue = "57391")]
pub const MILLISECOND: Duration = Duration::from_millis(1);
/// The duration of one microsecond.
///
/// # Examples
///
/// ```
/// #![feature(duration_constants)]
/// use std::time::Duration;
///
/// assert_eq!(Duration::MICROSECOND, Duration::from_micros(1));
/// ```
#[unstable(feature = "duration_constants", issue = "57391")]
pub const MICROSECOND: Duration = Duration::from_micros(1);
/// The duration of one nanosecond.
///
/// # Examples
///
/// ```
/// #![feature(duration_constants)]
/// use std::time::Duration;
///
/// assert_eq!(Duration::NANOSECOND, Duration::from_nanos(1));
/// ```
#[unstable(feature = "duration_constants", issue = "57391")]
pub const NANOSECOND: Duration = Duration::from_nanos(1);
/// A duration of zero time.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let duration = Duration::ZERO;
/// assert!(duration.is_zero());
/// assert_eq!(duration.as_nanos(), 0);
/// ```
#[stable(feature = "duration_zero", since = "1.53.0")]
pub const ZERO: Duration = Duration::from_nanos(0);
/// The maximum duration.
///
/// May vary by platform as necessary. Must be able to contain the difference between
/// two instances of [`Instant`] or two instances of [`SystemTime`].
/// This constraint gives it a value of about 584,942,417,355 years in practice,
/// which is currently used on all platforms.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// assert_eq!(Duration::MAX, Duration::new(u64::MAX, 1_000_000_000 - 1));
/// ```
/// [`Instant`]: ../../std/time/struct.Instant.html
/// [`SystemTime`]: ../../std/time/struct.SystemTime.html
#[stable(feature = "duration_saturating_ops", since = "1.53.0")]
pub const MAX: Duration = Duration::new(u64::MAX, NANOS_PER_SEC - 1);
/// Creates a new `Duration` from the specified number of whole seconds and
/// additional nanoseconds.
///
/// If the number of nanoseconds is greater than 1 billion (the number of
/// nanoseconds in a second), then it will carry over into the seconds provided.
///
/// # Panics
///
/// This constructor will panic if the carry from the nanoseconds overflows
/// the seconds counter.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let five_seconds = Duration::new(5, 0);
/// ```
#[stable(feature = "duration", since = "1.3.0")]
#[inline]
#[must_use]
#[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
pub const fn new(secs: u64, nanos: u32) -> Duration {
if nanos < NANOS_PER_SEC {
// SAFETY: nanos < NANOS_PER_SEC, therefore nanos is within the valid range
Duration { secs, nanos: unsafe { Nanoseconds::new_unchecked(nanos) } }
} else {
let secs = secs
.checked_add((nanos / NANOS_PER_SEC) as u64)
.expect("overflow in Duration::new");
let nanos = nanos % NANOS_PER_SEC;
// SAFETY: nanos % NANOS_PER_SEC < NANOS_PER_SEC, therefore nanos is within the valid range
Duration { secs, nanos: unsafe { Nanoseconds::new_unchecked(nanos) } }
}
}
/// Creates a new `Duration` from the specified number of whole seconds.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let duration = Duration::from_secs(5);
///
/// assert_eq!(5, duration.as_secs());
/// assert_eq!(0, duration.subsec_nanos());
/// ```
#[stable(feature = "duration", since = "1.3.0")]
#[must_use]
#[inline]
#[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
pub const fn from_secs(secs: u64) -> Duration {
Duration { secs, nanos: Nanoseconds::ZERO }
}
/// Creates a new `Duration` from the specified number of milliseconds.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let duration = Duration::from_millis(2_569);
///
/// assert_eq!(2, duration.as_secs());
/// assert_eq!(569_000_000, duration.subsec_nanos());
/// ```
#[stable(feature = "duration", since = "1.3.0")]
#[must_use]
#[inline]
#[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
pub const fn from_millis(millis: u64) -> Duration {
let secs = millis / MILLIS_PER_SEC;
let subsec_millis = (millis % MILLIS_PER_SEC) as u32;
// SAFETY: (x % 1_000) * 1_000_000 < 1_000_000_000
// => x % 1_000 < 1_000
let subsec_nanos = unsafe { Nanoseconds::new_unchecked(subsec_millis * NANOS_PER_MILLI) };
Duration { secs, nanos: subsec_nanos }
}
/// Creates a new `Duration` from the specified number of microseconds.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let duration = Duration::from_micros(1_000_002);
///
/// assert_eq!(1, duration.as_secs());
/// assert_eq!(2_000, duration.subsec_nanos());
/// ```
#[stable(feature = "duration_from_micros", since = "1.27.0")]
#[must_use]
#[inline]
#[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
pub const fn from_micros(micros: u64) -> Duration {
let secs = micros / MICROS_PER_SEC;
let subsec_micros = (micros % MICROS_PER_SEC) as u32;
// SAFETY: (x % 1_000_000) * 1_000 < 1_000_000_000
// => x % 1_000_000 < 1_000_000
let subsec_nanos = unsafe { Nanoseconds::new_unchecked(subsec_micros * NANOS_PER_MICRO) };
Duration { secs, nanos: subsec_nanos }
}
/// Creates a new `Duration` from the specified number of nanoseconds.
///
/// Note: Using this on the return value of `as_nanos()` might cause unexpected behavior:
/// `as_nanos()` returns a u128, and can return values that do not fit in u64, e.g. 585 years.
/// Instead, consider using the pattern `Duration::new(d.as_secs(), d.subsec_nanos())`
/// if you cannot copy/clone the Duration directly.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let duration = Duration::from_nanos(1_000_000_123);
///
/// assert_eq!(1, duration.as_secs());
/// assert_eq!(123, duration.subsec_nanos());
/// ```
#[stable(feature = "duration_extras", since = "1.27.0")]
#[must_use]
#[inline]
#[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
pub const fn from_nanos(nanos: u64) -> Duration {
const NANOS_PER_SEC: u64 = self::NANOS_PER_SEC as u64;
let secs = nanos / NANOS_PER_SEC;
let subsec_nanos = (nanos % NANOS_PER_SEC) as u32;
// SAFETY: x % 1_000_000_000 < 1_000_000_000
let subsec_nanos = unsafe { Nanoseconds::new_unchecked(subsec_nanos) };
Duration { secs, nanos: subsec_nanos }
}
/// Creates a new `Duration` from the specified number of weeks.
///
/// # Panics
///
/// Panics if the given number of weeks overflows the `Duration` size.
///
/// # Examples
///
/// ```
/// #![feature(duration_constructors)]
/// use std::time::Duration;
///
/// let duration = Duration::from_weeks(4);
///
/// assert_eq!(4 * 7 * 24 * 60 * 60, duration.as_secs());
/// assert_eq!(0, duration.subsec_nanos());
/// ```
#[unstable(feature = "duration_constructors", issue = "120301")]
#[must_use]
#[inline]
pub const fn from_weeks(weeks: u64) -> Duration {
if weeks > u64::MAX / (SECS_PER_MINUTE * MINS_PER_HOUR * HOURS_PER_DAY * DAYS_PER_WEEK) {
panic!("overflow in Duration::from_weeks");
}
Duration::from_secs(weeks * MINS_PER_HOUR * SECS_PER_MINUTE * HOURS_PER_DAY * DAYS_PER_WEEK)
}
/// Creates a new `Duration` from the specified number of days.
///
/// # Panics
///
/// Panics if the given number of days overflows the `Duration` size.
///
/// # Examples
///
/// ```
/// #![feature(duration_constructors)]
/// use std::time::Duration;
///
/// let duration = Duration::from_days(7);
///
/// assert_eq!(7 * 24 * 60 * 60, duration.as_secs());
/// assert_eq!(0, duration.subsec_nanos());
/// ```
#[unstable(feature = "duration_constructors", issue = "120301")]
#[must_use]
#[inline]
pub const fn from_days(days: u64) -> Duration {
if days > u64::MAX / (SECS_PER_MINUTE * MINS_PER_HOUR * HOURS_PER_DAY) {
panic!("overflow in Duration::from_days");
}
Duration::from_secs(days * MINS_PER_HOUR * SECS_PER_MINUTE * HOURS_PER_DAY)
}
/// Creates a new `Duration` from the specified number of hours.
///
/// # Panics
///
/// Panics if the given number of hours overflows the `Duration` size.
///
/// # Examples
///
/// ```
/// #![feature(duration_constructors)]
/// use std::time::Duration;
///
/// let duration = Duration::from_hours(6);
///
/// assert_eq!(6 * 60 * 60, duration.as_secs());
/// assert_eq!(0, duration.subsec_nanos());
/// ```
#[unstable(feature = "duration_constructors", issue = "120301")]
#[must_use]
#[inline]
pub const fn from_hours(hours: u64) -> Duration {
if hours > u64::MAX / (SECS_PER_MINUTE * MINS_PER_HOUR) {
panic!("overflow in Duration::from_hours");
}
Duration::from_secs(hours * MINS_PER_HOUR * SECS_PER_MINUTE)
}
/// Creates a new `Duration` from the specified number of minutes.
///
/// # Panics
///
/// Panics if the given number of minutes overflows the `Duration` size.
///
/// # Examples
///
/// ```
/// #![feature(duration_constructors)]
/// use std::time::Duration;
///
/// let duration = Duration::from_mins(10);
///
/// assert_eq!(10 * 60, duration.as_secs());
/// assert_eq!(0, duration.subsec_nanos());
/// ```
#[unstable(feature = "duration_constructors", issue = "120301")]
#[must_use]
#[inline]
pub const fn from_mins(mins: u64) -> Duration {
if mins > u64::MAX / SECS_PER_MINUTE {
panic!("overflow in Duration::from_mins");
}
Duration::from_secs(mins * SECS_PER_MINUTE)
}
/// Returns true if this `Duration` spans no time.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// assert!(Duration::ZERO.is_zero());
/// assert!(Duration::new(0, 0).is_zero());
/// assert!(Duration::from_nanos(0).is_zero());
/// assert!(Duration::from_secs(0).is_zero());
///
/// assert!(!Duration::new(1, 1).is_zero());
/// assert!(!Duration::from_nanos(1).is_zero());
/// assert!(!Duration::from_secs(1).is_zero());
/// ```
#[must_use]
#[stable(feature = "duration_zero", since = "1.53.0")]
#[rustc_const_stable(feature = "duration_zero", since = "1.53.0")]
#[inline]
pub const fn is_zero(&self) -> bool {
self.secs == 0 && self.nanos.as_inner() == 0
}
/// Returns the number of _whole_ seconds contained by this `Duration`.
///
/// The returned value does not include the fractional (nanosecond) part of the
/// duration, which can be obtained using [`subsec_nanos`].
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let duration = Duration::new(5, 730_023_852);
/// assert_eq!(duration.as_secs(), 5);
/// ```
///
/// To determine the total number of seconds represented by the `Duration`
/// including the fractional part, use [`as_secs_f64`] or [`as_secs_f32`]
///
/// [`as_secs_f64`]: Duration::as_secs_f64
/// [`as_secs_f32`]: Duration::as_secs_f32
/// [`subsec_nanos`]: Duration::subsec_nanos
#[stable(feature = "duration", since = "1.3.0")]
#[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn as_secs(&self) -> u64 {
self.secs
}
/// Returns the fractional part of this `Duration`, in whole milliseconds.
///
/// This method does **not** return the length of the duration when
/// represented by milliseconds. The returned number always represents a
/// fractional portion of a second (i.e., it is less than one thousand).
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let duration = Duration::from_millis(5_432);
/// assert_eq!(duration.as_secs(), 5);
/// assert_eq!(duration.subsec_millis(), 432);
/// ```
#[stable(feature = "duration_extras", since = "1.27.0")]
#[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn subsec_millis(&self) -> u32 {
self.nanos.as_inner() / NANOS_PER_MILLI
}
/// Returns the fractional part of this `Duration`, in whole microseconds.
///
/// This method does **not** return the length of the duration when
/// represented by microseconds. The returned number always represents a
/// fractional portion of a second (i.e., it is less than one million).
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let duration = Duration::from_micros(1_234_567);
/// assert_eq!(duration.as_secs(), 1);
/// assert_eq!(duration.subsec_micros(), 234_567);
/// ```
#[stable(feature = "duration_extras", since = "1.27.0")]
#[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn subsec_micros(&self) -> u32 {
self.nanos.as_inner() / NANOS_PER_MICRO
}
/// Returns the fractional part of this `Duration`, in nanoseconds.
///
/// This method does **not** return the length of the duration when
/// represented by nanoseconds. The returned number always represents a
/// fractional portion of a second (i.e., it is less than one billion).
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let duration = Duration::from_millis(5_010);
/// assert_eq!(duration.as_secs(), 5);
/// assert_eq!(duration.subsec_nanos(), 10_000_000);
/// ```
#[stable(feature = "duration", since = "1.3.0")]
#[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn subsec_nanos(&self) -> u32 {
self.nanos.as_inner()
}
/// Returns the total number of whole milliseconds contained by this `Duration`.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let duration = Duration::new(5, 730_023_852);
/// assert_eq!(duration.as_millis(), 5_730);
/// ```
#[stable(feature = "duration_as_u128", since = "1.33.0")]
#[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
#[must_use]
#[inline]
pub const fn as_millis(&self) -> u128 {
self.secs as u128 * MILLIS_PER_SEC as u128
+ (self.nanos.as_inner() / NANOS_PER_MILLI) as u128
}
/// Returns the total number of whole microseconds contained by this `Duration`.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let duration = Duration::new(5, 730_023_852);
/// assert_eq!(duration.as_micros(), 5_730_023);
/// ```
#[stable(feature = "duration_as_u128", since = "1.33.0")]
#[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
#[must_use]
#[inline]
pub const fn as_micros(&self) -> u128 {
self.secs as u128 * MICROS_PER_SEC as u128
+ (self.nanos.as_inner() / NANOS_PER_MICRO) as u128
}
/// Returns the total number of nanoseconds contained by this `Duration`.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let duration = Duration::new(5, 730_023_852);
/// assert_eq!(duration.as_nanos(), 5_730_023_852);
/// ```
#[stable(feature = "duration_as_u128", since = "1.33.0")]
#[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
#[must_use]
#[inline]
pub const fn as_nanos(&self) -> u128 {
self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos.as_inner() as u128
}
/// Computes the absolute difference between `self` and `other`.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// assert_eq!(Duration::new(100, 0).abs_diff(Duration::new(80, 0)), Duration::new(20, 0));
/// assert_eq!(Duration::new(100, 400_000_000).abs_diff(Duration::new(110, 0)), Duration::new(9, 600_000_000));
/// ```
#[stable(feature = "duration_abs_diff", since = "1.81.0")]
#[rustc_const_stable(feature = "duration_abs_diff", since = "1.81.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Duration) -> Duration {
if let Some(res) = self.checked_sub(other) { res } else { other.checked_sub(self).unwrap() }
}
/// Checked `Duration` addition. Computes `self + other`, returning [`None`]
/// if overflow occurred.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
/// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(u64::MAX, 0)), None);
/// ```
#[stable(feature = "duration_checked_ops", since = "1.16.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
pub const fn checked_add(self, rhs: Duration) -> Option<Duration> {
if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
let mut nanos = self.nanos.as_inner() + rhs.nanos.as_inner();
if nanos >= NANOS_PER_SEC {
nanos -= NANOS_PER_SEC;
if let Some(new_secs) = secs.checked_add(1) {
secs = new_secs;
} else {
return None;
}
}
debug_assert!(nanos < NANOS_PER_SEC);
Some(Duration::new(secs, nanos))
} else {
None
}
}
/// Saturating `Duration` addition. Computes `self + other`, returning [`Duration::MAX`]
/// if overflow occurred.
///
/// # Examples
///
/// ```
/// #![feature(duration_constants)]
/// use std::time::Duration;
///
/// assert_eq!(Duration::new(0, 0).saturating_add(Duration::new(0, 1)), Duration::new(0, 1));
/// assert_eq!(Duration::new(1, 0).saturating_add(Duration::new(u64::MAX, 0)), Duration::MAX);
/// ```
#[stable(feature = "duration_saturating_ops", since = "1.53.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
pub const fn saturating_add(self, rhs: Duration) -> Duration {
match self.checked_add(rhs) {
Some(res) => res,
None => Duration::MAX,
}
}
/// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
/// if the result would be negative or if overflow occurred.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
/// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
/// ```
#[stable(feature = "duration_checked_ops", since = "1.16.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
pub const fn checked_sub(self, rhs: Duration) -> Option<Duration> {
if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
let nanos = if self.nanos.as_inner() >= rhs.nanos.as_inner() {
self.nanos.as_inner() - rhs.nanos.as_inner()
} else if let Some(sub_secs) = secs.checked_sub(1) {
secs = sub_secs;
self.nanos.as_inner() + NANOS_PER_SEC - rhs.nanos.as_inner()
} else {
return None;
};
debug_assert!(nanos < NANOS_PER_SEC);
Some(Duration::new(secs, nanos))
} else {
None
}
}
/// Saturating `Duration` subtraction. Computes `self - other`, returning [`Duration::ZERO`]
/// if the result would be negative or if overflow occurred.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// assert_eq!(Duration::new(0, 1).saturating_sub(Duration::new(0, 0)), Duration::new(0, 1));
/// assert_eq!(Duration::new(0, 0).saturating_sub(Duration::new(0, 1)), Duration::ZERO);
/// ```
#[stable(feature = "duration_saturating_ops", since = "1.53.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
pub const fn saturating_sub(self, rhs: Duration) -> Duration {
match self.checked_sub(rhs) {
Some(res) => res,
None => Duration::ZERO,
}
}
/// Checked `Duration` multiplication. Computes `self * other`, returning
/// [`None`] if overflow occurred.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
/// assert_eq!(Duration::new(u64::MAX - 1, 0).checked_mul(2), None);
/// ```
#[stable(feature = "duration_checked_ops", since = "1.16.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
pub const fn checked_mul(self, rhs: u32) -> Option<Duration> {
// Multiply nanoseconds as u64, because it cannot overflow that way.
let total_nanos = self.nanos.as_inner() as u64 * rhs as u64;
let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
// FIXME(const-hack): use `and_then` once that is possible.
if let Some(s) = self.secs.checked_mul(rhs as u64) {
if let Some(secs) = s.checked_add(extra_secs) {
debug_assert!(nanos < NANOS_PER_SEC);
return Some(Duration::new(secs, nanos));
}
}
None
}
/// Saturating `Duration` multiplication. Computes `self * other`, returning
/// [`Duration::MAX`] if overflow occurred.
///
/// # Examples
///
/// ```
/// #![feature(duration_constants)]
/// use std::time::Duration;
///
/// assert_eq!(Duration::new(0, 500_000_001).saturating_mul(2), Duration::new(1, 2));
/// assert_eq!(Duration::new(u64::MAX - 1, 0).saturating_mul(2), Duration::MAX);
/// ```
#[stable(feature = "duration_saturating_ops", since = "1.53.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
pub const fn saturating_mul(self, rhs: u32) -> Duration {
match self.checked_mul(rhs) {
Some(res) => res,
None => Duration::MAX,
}
}
/// Checked `Duration` division. Computes `self / other`, returning [`None`]
/// if `other == 0`.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
/// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
/// assert_eq!(Duration::new(2, 0).checked_div(0), None);
/// ```
#[stable(feature = "duration_checked_ops", since = "1.16.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
pub const fn checked_div(self, rhs: u32) -> Option<Duration> {
if rhs != 0 {
let (secs, extra_secs) = (self.secs / (rhs as u64), self.secs % (rhs as u64));
let (mut nanos, extra_nanos) =
(self.nanos.as_inner() / rhs, self.nanos.as_inner() % rhs);
nanos +=
((extra_secs * (NANOS_PER_SEC as u64) + extra_nanos as u64) / (rhs as u64)) as u32;
debug_assert!(nanos < NANOS_PER_SEC);
Some(Duration::new(secs, nanos))
} else {
None
}
}
/// Returns the number of seconds contained by this `Duration` as `f64`.
///
/// The returned value includes the fractional (nanosecond) part of the duration.
///
/// # Examples
/// ```
/// use std::time::Duration;
///
/// let dur = Duration::new(2, 700_000_000);
/// assert_eq!(dur.as_secs_f64(), 2.7);
/// ```
#[stable(feature = "duration_float", since = "1.38.0")]
#[must_use]
#[inline]
#[rustc_const_stable(feature = "duration_consts_float", since = "1.83.0")]
pub const fn as_secs_f64(&self) -> f64 {
(self.secs as f64) + (self.nanos.as_inner() as f64) / (NANOS_PER_SEC as f64)
}
/// Returns the number of seconds contained by this `Duration` as `f32`.
///
/// The returned value includes the fractional (nanosecond) part of the duration.
///
/// # Examples
/// ```
/// use std::time::Duration;
///
/// let dur = Duration::new(2, 700_000_000);
/// assert_eq!(dur.as_secs_f32(), 2.7);
/// ```
#[stable(feature = "duration_float", since = "1.38.0")]
#[must_use]
#[inline]
#[rustc_const_stable(feature = "duration_consts_float", since = "1.83.0")]
pub const fn as_secs_f32(&self) -> f32 {
(self.secs as f32) + (self.nanos.as_inner() as f32) / (NANOS_PER_SEC as f32)
}
/// Returns the number of milliseconds contained by this `Duration` as `f64`.
///
/// The returned value includes the fractional (nanosecond) part of the duration.
///
/// # Examples
/// ```
/// #![feature(duration_millis_float)]
/// use std::time::Duration;
///
/// let dur = Duration::new(2, 345_678_000);
/// assert_eq!(dur.as_millis_f64(), 2_345.678);
/// ```
#[unstable(feature = "duration_millis_float", issue = "122451")]
#[must_use]
#[inline]
pub const fn as_millis_f64(&self) -> f64 {
(self.secs as f64) * (MILLIS_PER_SEC as f64)
+ (self.nanos.as_inner() as f64) / (NANOS_PER_MILLI as f64)
}
/// Returns the number of milliseconds contained by this `Duration` as `f32`.
///
/// The returned value includes the fractional (nanosecond) part of the duration.
///
/// # Examples
/// ```
/// #![feature(duration_millis_float)]
/// use std::time::Duration;
///
/// let dur = Duration::new(2, 345_678_000);
/// assert_eq!(dur.as_millis_f32(), 2_345.678);
/// ```
#[unstable(feature = "duration_millis_float", issue = "122451")]
#[must_use]
#[inline]
pub const fn as_millis_f32(&self) -> f32 {
(self.secs as f32) * (MILLIS_PER_SEC as f32)
+ (self.nanos.as_inner() as f32) / (NANOS_PER_MILLI as f32)
}
/// Creates a new `Duration` from the specified number of seconds represented
/// as `f64`.
///
/// # Panics
/// This constructor will panic if `secs` is negative, overflows `Duration` or not finite.
///
/// # Examples
/// ```
/// use std::time::Duration;
///
/// let res = Duration::from_secs_f64(0.0);
/// assert_eq!(res, Duration::new(0, 0));
/// let res = Duration::from_secs_f64(1e-20);
/// assert_eq!(res, Duration::new(0, 0));
/// let res = Duration::from_secs_f64(4.2e-7);
/// assert_eq!(res, Duration::new(0, 420));
/// let res = Duration::from_secs_f64(2.7);
/// assert_eq!(res, Duration::new(2, 700_000_000));
/// let res = Duration::from_secs_f64(3e10);
/// assert_eq!(res, Duration::new(30_000_000_000, 0));
/// // subnormal float
/// let res = Duration::from_secs_f64(f64::from_bits(1));
/// assert_eq!(res, Duration::new(0, 0));
/// // conversion uses rounding
/// let res = Duration::from_secs_f64(0.999e-9);
/// assert_eq!(res, Duration::new(0, 1));
/// ```
#[stable(feature = "duration_float", since = "1.38.0")]
#[must_use]
#[inline]
pub fn from_secs_f64(secs: f64) -> Duration {
match Duration::try_from_secs_f64(secs) {
Ok(v) => v,
Err(e) => panic!("{}", e.description()),
}
}
/// Creates a new `Duration` from the specified number of seconds represented
/// as `f32`.
///
/// # Panics
/// This constructor will panic if `secs` is negative, overflows `Duration` or not finite.
///
/// # Examples
/// ```
/// use std::time::Duration;
///
/// let res = Duration::from_secs_f32(0.0);
/// assert_eq!(res, Duration::new(0, 0));
/// let res = Duration::from_secs_f32(1e-20);
/// assert_eq!(res, Duration::new(0, 0));
/// let res = Duration::from_secs_f32(4.2e-7);
/// assert_eq!(res, Duration::new(0, 420));
/// let res = Duration::from_secs_f32(2.7);
/// assert_eq!(res, Duration::new(2, 700_000_048));
/// let res = Duration::from_secs_f32(3e10);
/// assert_eq!(res, Duration::new(30_000_001_024, 0));
/// // subnormal float
/// let res = Duration::from_secs_f32(f32::from_bits(1));
/// assert_eq!(res, Duration::new(0, 0));
/// // conversion uses rounding
/// let res = Duration::from_secs_f32(0.999e-9);
/// assert_eq!(res, Duration::new(0, 1));
/// ```
#[stable(feature = "duration_float", since = "1.38.0")]
#[must_use]
#[inline]
pub fn from_secs_f32(secs: f32) -> Duration {
match Duration::try_from_secs_f32(secs) {
Ok(v) => v,
Err(e) => panic!("{}", e.description()),
}
}
/// Multiplies `Duration` by `f64`.
///
/// # Panics
/// This method will panic if result is negative, overflows `Duration` or not finite.
///
/// # Examples
/// ```
/// use std::time::Duration;
///
/// let dur = Duration::new(2, 700_000_000);
/// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
/// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
/// ```
#[stable(feature = "duration_float", since = "1.38.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn mul_f64(self, rhs: f64) -> Duration {
Duration::from_secs_f64(rhs * self.as_secs_f64())
}
/// Multiplies `Duration` by `f32`.
///
/// # Panics
/// This method will panic if result is negative, overflows `Duration` or not finite.
///
/// # Examples
/// ```
/// use std::time::Duration;
///