]> git.lizzy.rs Git - rust.git/blob - src/libstd/time.rs
Auto merge of #59068 - ljedrz:kill_off_NodeId_stragglers, r=Zoxc
[rust.git] / src / libstd / time.rs
1 //! Temporal quantification.
2 //!
3 //! Example:
4 //!
5 //! ```
6 //! use std::time::Duration;
7 //!
8 //! let five_seconds = Duration::new(5, 0);
9 //! // both declarations are equivalent
10 //! assert_eq!(Duration::new(5, 0), Duration::from_secs(5));
11 //! ```
12
13 #![stable(feature = "time", since = "1.3.0")]
14
15 use crate::cmp;
16 use crate::error::Error;
17 use crate::fmt;
18 use crate::ops::{Add, Sub, AddAssign, SubAssign};
19 use crate::sys::time;
20 use crate::sys_common::FromInner;
21 use crate::sys_common::mutex::Mutex;
22
23 #[stable(feature = "time", since = "1.3.0")]
24 pub use core::time::Duration;
25
26 /// A measurement of a monotonically nondecreasing clock.
27 /// Opaque and useful only with `Duration`.
28 ///
29 /// Instants are always guaranteed to be no less than any previously measured
30 /// instant when created, and are often useful for tasks such as measuring
31 /// benchmarks or timing how long an operation takes.
32 ///
33 /// Note, however, that instants are not guaranteed to be **steady**. In other
34 /// words, each tick of the underlying clock may not be the same length (e.g.
35 /// some seconds may be longer than others). An instant may jump forwards or
36 /// experience time dilation (slow down or speed up), but it will never go
37 /// backwards.
38 ///
39 /// Instants are opaque types that can only be compared to one another. There is
40 /// no method to get "the number of seconds" from an instant. Instead, it only
41 /// allows measuring the duration between two instants (or comparing two
42 /// instants).
43 ///
44 /// The size of an `Instant` struct may vary depending on the target operating
45 /// system.
46 ///
47 /// Example:
48 ///
49 /// ```no_run
50 /// use std::time::{Duration, Instant};
51 /// use std::thread::sleep;
52 ///
53 /// fn main() {
54 ///    let now = Instant::now();
55 ///
56 ///    // we sleep for 2 seconds
57 ///    sleep(Duration::new(2, 0));
58 ///    // it prints '2'
59 ///    println!("{}", now.elapsed().as_secs());
60 /// }
61 /// ```
62 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
63 #[stable(feature = "time2", since = "1.8.0")]
64 pub struct Instant(time::Instant);
65
66 /// A measurement of the system clock, useful for talking to
67 /// external entities like the file system or other processes.
68 ///
69 /// Distinct from the [`Instant`] type, this time measurement **is not
70 /// monotonic**. This means that you can save a file to the file system, then
71 /// save another file to the file system, **and the second file has a
72 /// `SystemTime` measurement earlier than the first**. In other words, an
73 /// operation that happens after another operation in real time may have an
74 /// earlier `SystemTime`!
75 ///
76 /// Consequently, comparing two `SystemTime` instances to learn about the
77 /// duration between them returns a [`Result`] instead of an infallible [`Duration`]
78 /// to indicate that this sort of time drift may happen and needs to be handled.
79 ///
80 /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
81 /// constant is provided in this module as an anchor in time to learn
82 /// information about a `SystemTime`. By calculating the duration from this
83 /// fixed point in time, a `SystemTime` can be converted to a human-readable time,
84 /// or perhaps some other string representation.
85 ///
86 /// The size of a `SystemTime` struct may vary depending on the target operating
87 /// system.
88 ///
89 /// [`Instant`]: ../../std/time/struct.Instant.html
90 /// [`Result`]: ../../std/result/enum.Result.html
91 /// [`Duration`]: ../../std/time/struct.Duration.html
92 /// [`UNIX_EPOCH`]: ../../std/time/constant.UNIX_EPOCH.html
93 ///
94 /// Example:
95 ///
96 /// ```no_run
97 /// use std::time::{Duration, SystemTime};
98 /// use std::thread::sleep;
99 ///
100 /// fn main() {
101 ///    let now = SystemTime::now();
102 ///
103 ///    // we sleep for 2 seconds
104 ///    sleep(Duration::new(2, 0));
105 ///    match now.elapsed() {
106 ///        Ok(elapsed) => {
107 ///            // it prints '2'
108 ///            println!("{}", elapsed.as_secs());
109 ///        }
110 ///        Err(e) => {
111 ///            // an error occurred!
112 ///            println!("Error: {:?}", e);
113 ///        }
114 ///    }
115 /// }
116 /// ```
117 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
118 #[stable(feature = "time2", since = "1.8.0")]
119 pub struct SystemTime(time::SystemTime);
120
121 /// An error returned from the `duration_since` and `elapsed` methods on
122 /// `SystemTime`, used to learn how far in the opposite direction a system time
123 /// lies.
124 ///
125 /// # Examples
126 ///
127 /// ```no_run
128 /// use std::thread::sleep;
129 /// use std::time::{Duration, SystemTime};
130 ///
131 /// let sys_time = SystemTime::now();
132 /// sleep(Duration::from_secs(1));
133 /// let new_sys_time = SystemTime::now();
134 /// match sys_time.duration_since(new_sys_time) {
135 ///     Ok(_) => {}
136 ///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
137 /// }
138 /// ```
139 #[derive(Clone, Debug)]
140 #[stable(feature = "time2", since = "1.8.0")]
141 pub struct SystemTimeError(Duration);
142
143 impl Instant {
144     /// Returns an instant corresponding to "now".
145     ///
146     /// # Examples
147     ///
148     /// ```
149     /// use std::time::Instant;
150     ///
151     /// let now = Instant::now();
152     /// ```
153     #[stable(feature = "time2", since = "1.8.0")]
154     pub fn now() -> Instant {
155         let os_now = time::Instant::now();
156
157         // And here we come upon a sad state of affairs. The whole point of
158         // `Instant` is that it's monotonically increasing. We've found in the
159         // wild, however, that it's not actually monotonically increasing for
160         // one reason or another. These appear to be OS and hardware level bugs,
161         // and there's not really a whole lot we can do about them. Here's a
162         // taste of what we've found:
163         //
164         // * #48514 - OpenBSD, x86_64
165         // * #49281 - linux arm64 and s390x
166         // * #51648 - windows, x86
167         // * #56560 - windows, x86_64, AWS
168         // * #56612 - windows, x86, vm (?)
169         // * #56940 - linux, arm64
170         // * https://bugzilla.mozilla.org/show_bug.cgi?id=1487778 - a similar
171         //   Firefox bug
172         //
173         // It simply seems that this it just happens so that a lot in the wild
174         // we're seeing panics across various platforms where consecutive calls
175         // to `Instant::now`, such as via the `elapsed` function, are panicking
176         // as they're going backwards. Placed here is a last-ditch effort to try
177         // to fix things up. We keep a global "latest now" instance which is
178         // returned instead of what the OS says if the OS goes backwards.
179         //
180         // To hopefully mitigate the impact of this though a few platforms are
181         // whitelisted as "these at least haven't gone backwards yet".
182         if time::Instant::actually_monotonic() {
183             return Instant(os_now)
184         }
185
186         static LOCK: Mutex = Mutex::new();
187         static mut LAST_NOW: time::Instant = time::Instant::zero();
188         unsafe {
189             let _lock = LOCK.lock();
190             let now = cmp::max(LAST_NOW, os_now);
191             LAST_NOW = now;
192             Instant(now)
193         }
194     }
195
196     /// Returns the amount of time elapsed from another instant to this one.
197     ///
198     /// # Panics
199     ///
200     /// This function will panic if `earlier` is later than `self`.
201     ///
202     /// # Examples
203     ///
204     /// ```no_run
205     /// use std::time::{Duration, Instant};
206     /// use std::thread::sleep;
207     ///
208     /// let now = Instant::now();
209     /// sleep(Duration::new(1, 0));
210     /// let new_now = Instant::now();
211     /// println!("{:?}", new_now.duration_since(now));
212     /// ```
213     #[stable(feature = "time2", since = "1.8.0")]
214     pub fn duration_since(&self, earlier: Instant) -> Duration {
215         self.0.sub_instant(&earlier.0)
216     }
217
218     /// Returns the amount of time elapsed from another instant to this one,
219     /// or None if that instant is earlier than this one.
220     ///
221     /// # Examples
222     ///
223     /// ```no_run
224     /// #![feature(checked_duration_since)]
225     /// use std::time::{Duration, Instant};
226     /// use std::thread::sleep;
227     ///
228     /// let now = Instant::now();
229     /// sleep(Duration::new(1, 0));
230     /// let new_now = Instant::now();
231     /// println!("{:?}", new_now.checked_duration_since(now));
232     /// println!("{:?}", now.checked_duration_since(new_now)); // None
233     /// ```
234     #[unstable(feature = "checked_duration_since", issue = "58402")]
235     pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
236         if self >= &earlier {
237             Some(self.0.sub_instant(&earlier.0))
238         } else {
239             None
240         }
241     }
242
243     /// Returns the amount of time elapsed from another instant to this one,
244     /// or zero duration if that instant is earlier than this one.
245     ///
246     /// # Examples
247     ///
248     /// ```no_run
249     /// #![feature(checked_duration_since)]
250     /// use std::time::{Duration, Instant};
251     /// use std::thread::sleep;
252     ///
253     /// let now = Instant::now();
254     /// sleep(Duration::new(1, 0));
255     /// let new_now = Instant::now();
256     /// println!("{:?}", new_now.saturating_duration_since(now));
257     /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
258     /// ```
259     #[unstable(feature = "checked_duration_since", issue = "58402")]
260     pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
261         self.checked_duration_since(earlier).unwrap_or(Duration::new(0, 0))
262     }
263
264     /// Returns the amount of time elapsed since this instant was created.
265     ///
266     /// # Panics
267     ///
268     /// This function may panic if the current time is earlier than this
269     /// instant, which is something that can happen if an `Instant` is
270     /// produced synthetically.
271     ///
272     /// # Examples
273     ///
274     /// ```no_run
275     /// use std::thread::sleep;
276     /// use std::time::{Duration, Instant};
277     ///
278     /// let instant = Instant::now();
279     /// let three_secs = Duration::from_secs(3);
280     /// sleep(three_secs);
281     /// assert!(instant.elapsed() >= three_secs);
282     /// ```
283     #[stable(feature = "time2", since = "1.8.0")]
284     pub fn elapsed(&self) -> Duration {
285         Instant::now() - *self
286     }
287
288     /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
289     /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
290     /// otherwise.
291     #[stable(feature = "time_checked_add", since = "1.34.0")]
292     pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
293         self.0.checked_add_duration(&duration).map(Instant)
294     }
295
296     /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
297     /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
298     /// otherwise.
299     #[stable(feature = "time_checked_add", since = "1.34.0")]
300     pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
301         self.0.checked_sub_duration(&duration).map(Instant)
302     }
303 }
304
305 #[stable(feature = "time2", since = "1.8.0")]
306 impl Add<Duration> for Instant {
307     type Output = Instant;
308
309     /// # Panics
310     ///
311     /// This function may panic if the resulting point in time cannot be represented by the
312     /// underlying data structure. See [`checked_add`] for a version without panic.
313     ///
314     /// [`checked_add`]: ../../std/time/struct.Instant.html#method.checked_add
315     fn add(self, other: Duration) -> Instant {
316         self.checked_add(other)
317             .expect("overflow when adding duration to instant")
318     }
319 }
320
321 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
322 impl AddAssign<Duration> for Instant {
323     fn add_assign(&mut self, other: Duration) {
324         *self = *self + other;
325     }
326 }
327
328 #[stable(feature = "time2", since = "1.8.0")]
329 impl Sub<Duration> for Instant {
330     type Output = Instant;
331
332     fn sub(self, other: Duration) -> Instant {
333         self.checked_sub(other)
334             .expect("overflow when subtracting duration from instant")
335     }
336 }
337
338 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
339 impl SubAssign<Duration> for Instant {
340     fn sub_assign(&mut self, other: Duration) {
341         *self = *self - other;
342     }
343 }
344
345 #[stable(feature = "time2", since = "1.8.0")]
346 impl Sub<Instant> for Instant {
347     type Output = Duration;
348
349     fn sub(self, other: Instant) -> Duration {
350         self.duration_since(other)
351     }
352 }
353
354 #[stable(feature = "time2", since = "1.8.0")]
355 impl fmt::Debug for Instant {
356     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
357         self.0.fmt(f)
358     }
359 }
360
361 impl SystemTime {
362     /// An anchor in time which can be used to create new `SystemTime` instances or
363     /// learn about where in time a `SystemTime` lies.
364     ///
365     /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
366     /// respect to the system clock. Using `duration_since` on an existing
367     /// `SystemTime` instance can tell how far away from this point in time a
368     /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
369     /// `SystemTime` instance to represent another fixed point in time.
370     ///
371     /// # Examples
372     ///
373     /// ```no_run
374     /// use std::time::SystemTime;
375     ///
376     /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
377     ///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
378     ///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
379     /// }
380     /// ```
381     #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
382     pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
383
384     /// Returns the system time corresponding to "now".
385     ///
386     /// # Examples
387     ///
388     /// ```
389     /// use std::time::SystemTime;
390     ///
391     /// let sys_time = SystemTime::now();
392     /// ```
393     #[stable(feature = "time2", since = "1.8.0")]
394     pub fn now() -> SystemTime {
395         SystemTime(time::SystemTime::now())
396     }
397
398     /// Returns the amount of time elapsed from an earlier point in time.
399     ///
400     /// This function may fail because measurements taken earlier are not
401     /// guaranteed to always be before later measurements (due to anomalies such
402     /// as the system clock being adjusted either forwards or backwards).
403     ///
404     /// If successful, [`Ok`]`(`[`Duration`]`)` is returned where the duration represents
405     /// the amount of time elapsed from the specified measurement to this one.
406     ///
407     /// Returns an [`Err`] if `earlier` is later than `self`, and the error
408     /// contains how far from `self` the time is.
409     ///
410     /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
411     /// [`Duration`]: ../../std/time/struct.Duration.html
412     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
413     ///
414     /// # Examples
415     ///
416     /// ```
417     /// use std::time::SystemTime;
418     ///
419     /// let sys_time = SystemTime::now();
420     /// let difference = sys_time.duration_since(sys_time)
421     ///                          .expect("SystemTime::duration_since failed");
422     /// println!("{:?}", difference);
423     /// ```
424     #[stable(feature = "time2", since = "1.8.0")]
425     pub fn duration_since(&self, earlier: SystemTime)
426                           -> Result<Duration, SystemTimeError> {
427         self.0.sub_time(&earlier.0).map_err(SystemTimeError)
428     }
429
430     /// Returns the amount of time elapsed since this system time was created.
431     ///
432     /// This function may fail as the underlying system clock is susceptible to
433     /// drift and updates (e.g., the system clock could go backwards), so this
434     /// function may not always succeed. If successful, [`Ok`]`(`[`Duration`]`)` is
435     /// returned where the duration represents the amount of time elapsed from
436     /// this time measurement to the current time.
437     ///
438     /// Returns an [`Err`] if `self` is later than the current system time, and
439     /// the error contains how far from the current system time `self` is.
440     ///
441     /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
442     /// [`Duration`]: ../../std/time/struct.Duration.html
443     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
444     ///
445     /// # Examples
446     ///
447     /// ```no_run
448     /// use std::thread::sleep;
449     /// use std::time::{Duration, SystemTime};
450     ///
451     /// let sys_time = SystemTime::now();
452     /// let one_sec = Duration::from_secs(1);
453     /// sleep(one_sec);
454     /// assert!(sys_time.elapsed().unwrap() >= one_sec);
455     /// ```
456     #[stable(feature = "time2", since = "1.8.0")]
457     pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
458         SystemTime::now().duration_since(*self)
459     }
460
461     /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
462     /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
463     /// otherwise.
464     #[stable(feature = "time_checked_add", since = "1.34.0")]
465     pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
466         self.0.checked_add_duration(&duration).map(SystemTime)
467     }
468
469     /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
470     /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
471     /// otherwise.
472     #[stable(feature = "time_checked_add", since = "1.34.0")]
473     pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
474         self.0.checked_sub_duration(&duration).map(SystemTime)
475     }
476 }
477
478 #[stable(feature = "time2", since = "1.8.0")]
479 impl Add<Duration> for SystemTime {
480     type Output = SystemTime;
481
482     /// # Panics
483     ///
484     /// This function may panic if the resulting point in time cannot be represented by the
485     /// underlying data structure. See [`checked_add`] for a version without panic.
486     ///
487     /// [`checked_add`]: ../../std/time/struct.SystemTime.html#method.checked_add
488     fn add(self, dur: Duration) -> SystemTime {
489         self.checked_add(dur)
490             .expect("overflow when adding duration to instant")
491     }
492 }
493
494 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
495 impl AddAssign<Duration> for SystemTime {
496     fn add_assign(&mut self, other: Duration) {
497         *self = *self + other;
498     }
499 }
500
501 #[stable(feature = "time2", since = "1.8.0")]
502 impl Sub<Duration> for SystemTime {
503     type Output = SystemTime;
504
505     fn sub(self, dur: Duration) -> SystemTime {
506         self.checked_sub(dur)
507             .expect("overflow when subtracting duration from instant")
508     }
509 }
510
511 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
512 impl SubAssign<Duration> for SystemTime {
513     fn sub_assign(&mut self, other: Duration) {
514         *self = *self - other;
515     }
516 }
517
518 #[stable(feature = "time2", since = "1.8.0")]
519 impl fmt::Debug for SystemTime {
520     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
521         self.0.fmt(f)
522     }
523 }
524
525 /// An anchor in time which can be used to create new `SystemTime` instances or
526 /// learn about where in time a `SystemTime` lies.
527 ///
528 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
529 /// respect to the system clock. Using `duration_since` on an existing
530 /// [`SystemTime`] instance can tell how far away from this point in time a
531 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
532 /// [`SystemTime`] instance to represent another fixed point in time.
533 ///
534 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
535 ///
536 /// # Examples
537 ///
538 /// ```no_run
539 /// use std::time::{SystemTime, UNIX_EPOCH};
540 ///
541 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
542 ///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
543 ///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
544 /// }
545 /// ```
546 #[stable(feature = "time2", since = "1.8.0")]
547 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
548
549 impl SystemTimeError {
550     /// Returns the positive duration which represents how far forward the
551     /// second system time was from the first.
552     ///
553     /// A `SystemTimeError` is returned from the [`duration_since`] and [`elapsed`]
554     /// methods of [`SystemTime`] whenever the second system time represents a point later
555     /// in time than the `self` of the method call.
556     ///
557     /// [`duration_since`]: ../../std/time/struct.SystemTime.html#method.duration_since
558     /// [`elapsed`]: ../../std/time/struct.SystemTime.html#method.elapsed
559     /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
560     ///
561     /// # Examples
562     ///
563     /// ```no_run
564     /// use std::thread::sleep;
565     /// use std::time::{Duration, SystemTime};
566     ///
567     /// let sys_time = SystemTime::now();
568     /// sleep(Duration::from_secs(1));
569     /// let new_sys_time = SystemTime::now();
570     /// match sys_time.duration_since(new_sys_time) {
571     ///     Ok(_) => {}
572     ///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
573     /// }
574     /// ```
575     #[stable(feature = "time2", since = "1.8.0")]
576     pub fn duration(&self) -> Duration {
577         self.0
578     }
579 }
580
581 #[stable(feature = "time2", since = "1.8.0")]
582 impl Error for SystemTimeError {
583     fn description(&self) -> &str { "other time was not earlier than self" }
584 }
585
586 #[stable(feature = "time2", since = "1.8.0")]
587 impl fmt::Display for SystemTimeError {
588     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
589         write!(f, "second time provided was later than self")
590     }
591 }
592
593 impl FromInner<time::SystemTime> for SystemTime {
594     fn from_inner(time: time::SystemTime) -> SystemTime {
595         SystemTime(time)
596     }
597 }
598
599 #[cfg(test)]
600 mod tests {
601     use super::{Instant, SystemTime, Duration, UNIX_EPOCH};
602
603     macro_rules! assert_almost_eq {
604         ($a:expr, $b:expr) => ({
605             let (a, b) = ($a, $b);
606             if a != b {
607                 let (a, b) = if a > b {(a, b)} else {(b, a)};
608                 assert!(a - Duration::new(0, 1000) <= b,
609                         "{:?} is not almost equal to {:?}", a, b);
610             }
611         })
612     }
613
614     #[test]
615     fn instant_monotonic() {
616         let a = Instant::now();
617         let b = Instant::now();
618         assert!(b >= a);
619     }
620
621     #[test]
622     fn instant_elapsed() {
623         let a = Instant::now();
624         a.elapsed();
625     }
626
627     #[test]
628     fn instant_math() {
629         let a = Instant::now();
630         let b = Instant::now();
631         println!("a: {:?}", a);
632         println!("b: {:?}", b);
633         let dur = b.duration_since(a);
634         println!("dur: {:?}", dur);
635         assert_almost_eq!(b - dur, a);
636         assert_almost_eq!(a + dur, b);
637
638         let second = Duration::new(1, 0);
639         assert_almost_eq!(a - second + second, a);
640         assert_almost_eq!(a.checked_sub(second).unwrap().checked_add(second).unwrap(), a);
641
642         // checked_add_duration will not panic on overflow
643         let mut maybe_t = Some(Instant::now());
644         let max_duration = Duration::from_secs(u64::max_value());
645         // in case `Instant` can store `>= now + max_duration`.
646         for _ in 0..2 {
647             maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration));
648         }
649         assert_eq!(maybe_t, None);
650
651         // checked_add_duration calculates the right time and will work for another year
652         let year = Duration::from_secs(60 * 60 * 24 * 365);
653         assert_eq!(a + year, a.checked_add(year).unwrap());
654     }
655
656     #[test]
657     fn instant_math_is_associative() {
658         let now = Instant::now();
659         let offset = Duration::from_millis(5);
660         // Changing the order of instant math shouldn't change the results,
661         // especially when the expression reduces to X + identity.
662         assert_eq!((now + offset) - now, (now - now) + offset);
663     }
664
665     #[test]
666     #[should_panic]
667     fn instant_duration_panic() {
668         let a = Instant::now();
669         (a - Duration::new(1, 0)).duration_since(a);
670     }
671
672     #[test]
673     fn checked_instant_duration_nopanic() {
674         let a = Instant::now();
675         let ret = (a - Duration::new(1, 0)).checked_duration_since(a);
676         assert_eq!(ret, None);
677     }
678
679     #[test]
680     fn saturating_instant_duration_nopanic() {
681         let a = Instant::now();
682         let ret = (a - Duration::new(1, 0)).saturating_duration_since(a);
683         assert_eq!(ret, Duration::new(0,0));
684     }
685
686     #[test]
687     fn system_time_math() {
688         let a = SystemTime::now();
689         let b = SystemTime::now();
690         match b.duration_since(a) {
691             Ok(dur) if dur == Duration::new(0, 0) => {
692                 assert_almost_eq!(a, b);
693             }
694             Ok(dur) => {
695                 assert!(b > a);
696                 assert_almost_eq!(b - dur, a);
697                 assert_almost_eq!(a + dur, b);
698             }
699             Err(dur) => {
700                 let dur = dur.duration();
701                 assert!(a > b);
702                 assert_almost_eq!(b + dur, a);
703                 assert_almost_eq!(a - dur, b);
704             }
705         }
706
707         let second = Duration::new(1, 0);
708         assert_almost_eq!(a.duration_since(a - second).unwrap(), second);
709         assert_almost_eq!(a.duration_since(a + second).unwrap_err()
710                            .duration(), second);
711
712         assert_almost_eq!(a - second + second, a);
713         assert_almost_eq!(a.checked_sub(second).unwrap().checked_add(second).unwrap(), a);
714
715         let one_second_from_epoch = UNIX_EPOCH + Duration::new(1, 0);
716         let one_second_from_epoch2 = UNIX_EPOCH + Duration::new(0, 500_000_000)
717             + Duration::new(0, 500_000_000);
718         assert_eq!(one_second_from_epoch, one_second_from_epoch2);
719
720         // checked_add_duration will not panic on overflow
721         let mut maybe_t = Some(SystemTime::UNIX_EPOCH);
722         let max_duration = Duration::from_secs(u64::max_value());
723         // in case `SystemTime` can store `>= UNIX_EPOCH + max_duration`.
724         for _ in 0..2 {
725             maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration));
726         }
727         assert_eq!(maybe_t, None);
728
729         // checked_add_duration calculates the right time and will work for another year
730         let year = Duration::from_secs(60 * 60 * 24 * 365);
731         assert_eq!(a + year, a.checked_add(year).unwrap());
732     }
733
734     #[test]
735     fn system_time_elapsed() {
736         let a = SystemTime::now();
737         drop(a.elapsed());
738     }
739
740     #[test]
741     fn since_epoch() {
742         let ts = SystemTime::now();
743         let a = ts.duration_since(UNIX_EPOCH + Duration::new(1, 0)).unwrap();
744         let b = ts.duration_since(UNIX_EPOCH).unwrap();
745         assert!(b > a);
746         assert_eq!(b - a, Duration::new(1, 0));
747
748         let thirty_years = Duration::new(1, 0) * 60 * 60 * 24 * 365 * 30;
749
750         // Right now for CI this test is run in an emulator, and apparently the
751         // aarch64 emulator's sense of time is that we're still living in the
752         // 70s.
753         //
754         // Otherwise let's assume that we're all running computers later than
755         // 2000.
756         if !cfg!(target_arch = "aarch64") {
757             assert!(a > thirty_years);
758         }
759
760         // let's assume that we're all running computers earlier than 2090.
761         // Should give us ~70 years to fix this!
762         let hundred_twenty_years = thirty_years * 4;
763         assert!(a < hundred_twenty_years);
764     }
765 }