]> git.lizzy.rs Git - rust.git/blob - src/libstd/time.rs
Rollup merge of #63055 - Mark-Simulacrum:save-analysis-clean-2, r=Xanewok
[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.checked_sub_instant(&earlier.0).expect("supplied instant is later than self")
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         self.0.checked_sub_instant(&earlier.0)
237     }
238
239     /// Returns the amount of time elapsed from another instant to this one,
240     /// or zero duration if that instant is earlier than this one.
241     ///
242     /// # Examples
243     ///
244     /// ```no_run
245     /// #![feature(checked_duration_since)]
246     /// use std::time::{Duration, Instant};
247     /// use std::thread::sleep;
248     ///
249     /// let now = Instant::now();
250     /// sleep(Duration::new(1, 0));
251     /// let new_now = Instant::now();
252     /// println!("{:?}", new_now.saturating_duration_since(now));
253     /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
254     /// ```
255     #[unstable(feature = "checked_duration_since", issue = "58402")]
256     pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
257         self.checked_duration_since(earlier).unwrap_or(Duration::new(0, 0))
258     }
259
260     /// Returns the amount of time elapsed since this instant was created.
261     ///
262     /// # Panics
263     ///
264     /// This function may panic if the current time is earlier than this
265     /// instant, which is something that can happen if an `Instant` is
266     /// produced synthetically.
267     ///
268     /// # Examples
269     ///
270     /// ```no_run
271     /// use std::thread::sleep;
272     /// use std::time::{Duration, Instant};
273     ///
274     /// let instant = Instant::now();
275     /// let three_secs = Duration::from_secs(3);
276     /// sleep(three_secs);
277     /// assert!(instant.elapsed() >= three_secs);
278     /// ```
279     #[stable(feature = "time2", since = "1.8.0")]
280     pub fn elapsed(&self) -> Duration {
281         Instant::now() - *self
282     }
283
284     /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
285     /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
286     /// otherwise.
287     #[stable(feature = "time_checked_add", since = "1.34.0")]
288     pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
289         self.0.checked_add_duration(&duration).map(Instant)
290     }
291
292     /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
293     /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
294     /// otherwise.
295     #[stable(feature = "time_checked_add", since = "1.34.0")]
296     pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
297         self.0.checked_sub_duration(&duration).map(Instant)
298     }
299 }
300
301 #[stable(feature = "time2", since = "1.8.0")]
302 impl Add<Duration> for Instant {
303     type Output = Instant;
304
305     /// # Panics
306     ///
307     /// This function may panic if the resulting point in time cannot be represented by the
308     /// underlying data structure. See [`checked_add`] for a version without panic.
309     ///
310     /// [`checked_add`]: ../../std/time/struct.Instant.html#method.checked_add
311     fn add(self, other: Duration) -> Instant {
312         self.checked_add(other)
313             .expect("overflow when adding duration to instant")
314     }
315 }
316
317 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
318 impl AddAssign<Duration> for Instant {
319     fn add_assign(&mut self, other: Duration) {
320         *self = *self + other;
321     }
322 }
323
324 #[stable(feature = "time2", since = "1.8.0")]
325 impl Sub<Duration> for Instant {
326     type Output = Instant;
327
328     fn sub(self, other: Duration) -> Instant {
329         self.checked_sub(other)
330             .expect("overflow when subtracting duration from instant")
331     }
332 }
333
334 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
335 impl SubAssign<Duration> for Instant {
336     fn sub_assign(&mut self, other: Duration) {
337         *self = *self - other;
338     }
339 }
340
341 #[stable(feature = "time2", since = "1.8.0")]
342 impl Sub<Instant> for Instant {
343     type Output = Duration;
344
345     fn sub(self, other: Instant) -> Duration {
346         self.duration_since(other)
347     }
348 }
349
350 #[stable(feature = "time2", since = "1.8.0")]
351 impl fmt::Debug for Instant {
352     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
353         self.0.fmt(f)
354     }
355 }
356
357 impl SystemTime {
358     /// An anchor in time which can be used to create new `SystemTime` instances or
359     /// learn about where in time a `SystemTime` lies.
360     ///
361     /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
362     /// respect to the system clock. Using `duration_since` on an existing
363     /// `SystemTime` instance can tell how far away from this point in time a
364     /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
365     /// `SystemTime` instance to represent another fixed point in time.
366     ///
367     /// # Examples
368     ///
369     /// ```no_run
370     /// use std::time::SystemTime;
371     ///
372     /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
373     ///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
374     ///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
375     /// }
376     /// ```
377     #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
378     pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
379
380     /// Returns the system time corresponding to "now".
381     ///
382     /// # Examples
383     ///
384     /// ```
385     /// use std::time::SystemTime;
386     ///
387     /// let sys_time = SystemTime::now();
388     /// ```
389     #[stable(feature = "time2", since = "1.8.0")]
390     pub fn now() -> SystemTime {
391         SystemTime(time::SystemTime::now())
392     }
393
394     /// Returns the amount of time elapsed from an earlier point in time.
395     ///
396     /// This function may fail because measurements taken earlier are not
397     /// guaranteed to always be before later measurements (due to anomalies such
398     /// as the system clock being adjusted either forwards or backwards).
399     /// [`Instant`] can be used to measure elapsed time without this risk of failure.
400     ///
401     /// If successful, [`Ok`]`(`[`Duration`]`)` is returned where the duration represents
402     /// the amount of time elapsed from the specified measurement to this one.
403     ///
404     /// Returns an [`Err`] if `earlier` is later than `self`, and the error
405     /// contains how far from `self` the time is.
406     ///
407     /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
408     /// [`Duration`]: ../../std/time/struct.Duration.html
409     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
410     /// [`Instant`]: ../../std/time/struct.Instant.html
411     ///
412     /// # Examples
413     ///
414     /// ```
415     /// use std::time::SystemTime;
416     ///
417     /// let sys_time = SystemTime::now();
418     /// let difference = sys_time.duration_since(sys_time)
419     ///                          .expect("Clock may have gone backwards");
420     /// println!("{:?}", difference);
421     /// ```
422     #[stable(feature = "time2", since = "1.8.0")]
423     pub fn duration_since(&self, earlier: SystemTime)
424                           -> Result<Duration, SystemTimeError> {
425         self.0.sub_time(&earlier.0).map_err(SystemTimeError)
426     }
427
428     /// Returns the difference between the clock time when this
429     /// system time was created, and the current clock time.
430     ///
431     /// This function may fail as the underlying system clock is susceptible to
432     /// drift and updates (e.g., the system clock could go backwards), so this
433     /// function may not always succeed. If successful, [`Ok`]`(`[`Duration`]`)` is
434     /// returned where the duration represents the amount of time elapsed from
435     /// this time measurement to the current time.
436     ///
437     /// To measure elapsed time reliably, use [`Instant`] instead.
438     ///
439     /// Returns an [`Err`] if `self` is later than the current system time, and
440     /// the error contains how far from the current system time `self` is.
441     ///
442     /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
443     /// [`Duration`]: ../../std/time/struct.Duration.html
444     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
445     /// [`Instant`]: ../../std/time/struct.Instant.html
446     ///
447     /// # Examples
448     ///
449     /// ```no_run
450     /// use std::thread::sleep;
451     /// use std::time::{Duration, SystemTime};
452     ///
453     /// let sys_time = SystemTime::now();
454     /// let one_sec = Duration::from_secs(1);
455     /// sleep(one_sec);
456     /// assert!(sys_time.elapsed().unwrap() >= one_sec);
457     /// ```
458     #[stable(feature = "time2", since = "1.8.0")]
459     pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
460         SystemTime::now().duration_since(*self)
461     }
462
463     /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
464     /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
465     /// otherwise.
466     #[stable(feature = "time_checked_add", since = "1.34.0")]
467     pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
468         self.0.checked_add_duration(&duration).map(SystemTime)
469     }
470
471     /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
472     /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
473     /// otherwise.
474     #[stable(feature = "time_checked_add", since = "1.34.0")]
475     pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
476         self.0.checked_sub_duration(&duration).map(SystemTime)
477     }
478 }
479
480 #[stable(feature = "time2", since = "1.8.0")]
481 impl Add<Duration> for SystemTime {
482     type Output = SystemTime;
483
484     /// # Panics
485     ///
486     /// This function may panic if the resulting point in time cannot be represented by the
487     /// underlying data structure. See [`checked_add`] for a version without panic.
488     ///
489     /// [`checked_add`]: ../../std/time/struct.SystemTime.html#method.checked_add
490     fn add(self, dur: Duration) -> SystemTime {
491         self.checked_add(dur)
492             .expect("overflow when adding duration to instant")
493     }
494 }
495
496 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
497 impl AddAssign<Duration> for SystemTime {
498     fn add_assign(&mut self, other: Duration) {
499         *self = *self + other;
500     }
501 }
502
503 #[stable(feature = "time2", since = "1.8.0")]
504 impl Sub<Duration> for SystemTime {
505     type Output = SystemTime;
506
507     fn sub(self, dur: Duration) -> SystemTime {
508         self.checked_sub(dur)
509             .expect("overflow when subtracting duration from instant")
510     }
511 }
512
513 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
514 impl SubAssign<Duration> for SystemTime {
515     fn sub_assign(&mut self, other: Duration) {
516         *self = *self - other;
517     }
518 }
519
520 #[stable(feature = "time2", since = "1.8.0")]
521 impl fmt::Debug for SystemTime {
522     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523         self.0.fmt(f)
524     }
525 }
526
527 /// An anchor in time which can be used to create new `SystemTime` instances or
528 /// learn about where in time a `SystemTime` lies.
529 ///
530 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
531 /// respect to the system clock. Using `duration_since` on an existing
532 /// [`SystemTime`] instance can tell how far away from this point in time a
533 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
534 /// [`SystemTime`] instance to represent another fixed point in time.
535 ///
536 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
537 ///
538 /// # Examples
539 ///
540 /// ```no_run
541 /// use std::time::{SystemTime, UNIX_EPOCH};
542 ///
543 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
544 ///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
545 ///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
546 /// }
547 /// ```
548 #[stable(feature = "time2", since = "1.8.0")]
549 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
550
551 impl SystemTimeError {
552     /// Returns the positive duration which represents how far forward the
553     /// second system time was from the first.
554     ///
555     /// A `SystemTimeError` is returned from the [`duration_since`] and [`elapsed`]
556     /// methods of [`SystemTime`] whenever the second system time represents a point later
557     /// in time than the `self` of the method call.
558     ///
559     /// [`duration_since`]: ../../std/time/struct.SystemTime.html#method.duration_since
560     /// [`elapsed`]: ../../std/time/struct.SystemTime.html#method.elapsed
561     /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
562     ///
563     /// # Examples
564     ///
565     /// ```no_run
566     /// use std::thread::sleep;
567     /// use std::time::{Duration, SystemTime};
568     ///
569     /// let sys_time = SystemTime::now();
570     /// sleep(Duration::from_secs(1));
571     /// let new_sys_time = SystemTime::now();
572     /// match sys_time.duration_since(new_sys_time) {
573     ///     Ok(_) => {}
574     ///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
575     /// }
576     /// ```
577     #[stable(feature = "time2", since = "1.8.0")]
578     pub fn duration(&self) -> Duration {
579         self.0
580     }
581 }
582
583 #[stable(feature = "time2", since = "1.8.0")]
584 impl Error for SystemTimeError {
585     fn description(&self) -> &str { "other time was not earlier than self" }
586 }
587
588 #[stable(feature = "time2", since = "1.8.0")]
589 impl fmt::Display for SystemTimeError {
590     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
591         write!(f, "second time provided was later than self")
592     }
593 }
594
595 impl FromInner<time::SystemTime> for SystemTime {
596     fn from_inner(time: time::SystemTime) -> SystemTime {
597         SystemTime(time)
598     }
599 }
600
601 #[cfg(test)]
602 mod tests {
603     use super::{Instant, SystemTime, Duration, UNIX_EPOCH};
604
605     macro_rules! assert_almost_eq {
606         ($a:expr, $b:expr) => ({
607             let (a, b) = ($a, $b);
608             if a != b {
609                 let (a, b) = if a > b {(a, b)} else {(b, a)};
610                 assert!(a - Duration::new(0, 1000) <= b,
611                         "{:?} is not almost equal to {:?}", a, b);
612             }
613         })
614     }
615
616     #[test]
617     fn instant_monotonic() {
618         let a = Instant::now();
619         let b = Instant::now();
620         assert!(b >= a);
621     }
622
623     #[test]
624     fn instant_elapsed() {
625         let a = Instant::now();
626         a.elapsed();
627     }
628
629     #[test]
630     fn instant_math() {
631         let a = Instant::now();
632         let b = Instant::now();
633         println!("a: {:?}", a);
634         println!("b: {:?}", b);
635         let dur = b.duration_since(a);
636         println!("dur: {:?}", dur);
637         assert_almost_eq!(b - dur, a);
638         assert_almost_eq!(a + dur, b);
639
640         let second = Duration::new(1, 0);
641         assert_almost_eq!(a - second + second, a);
642         assert_almost_eq!(a.checked_sub(second).unwrap().checked_add(second).unwrap(), a);
643
644         // checked_add_duration will not panic on overflow
645         let mut maybe_t = Some(Instant::now());
646         let max_duration = Duration::from_secs(u64::max_value());
647         // in case `Instant` can store `>= now + max_duration`.
648         for _ in 0..2 {
649             maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration));
650         }
651         assert_eq!(maybe_t, None);
652
653         // checked_add_duration calculates the right time and will work for another year
654         let year = Duration::from_secs(60 * 60 * 24 * 365);
655         assert_eq!(a + year, a.checked_add(year).unwrap());
656     }
657
658     #[test]
659     fn instant_math_is_associative() {
660         let now = Instant::now();
661         let offset = Duration::from_millis(5);
662         // Changing the order of instant math shouldn't change the results,
663         // especially when the expression reduces to X + identity.
664         assert_eq!((now + offset) - now, (now - now) + offset);
665     }
666
667     #[test]
668     #[should_panic]
669     fn instant_duration_since_panic() {
670         let a = Instant::now();
671         (a - Duration::new(1, 0)).duration_since(a);
672     }
673
674     #[test]
675     fn instant_checked_duration_since_nopanic() {
676         let now = Instant::now();
677         let earlier = now - Duration::new(1, 0);
678         let later = now + Duration::new(1, 0);
679         assert_eq!(earlier.checked_duration_since(now), None);
680         assert_eq!(later.checked_duration_since(now), Some(Duration::new(1, 0)));
681         assert_eq!(now.checked_duration_since(now), Some(Duration::new(0, 0)));
682     }
683
684     #[test]
685     fn instant_saturating_duration_since_nopanic() {
686         let a = Instant::now();
687         let ret = (a - Duration::new(1, 0)).saturating_duration_since(a);
688         assert_eq!(ret, Duration::new(0,0));
689     }
690
691     #[test]
692     fn system_time_math() {
693         let a = SystemTime::now();
694         let b = SystemTime::now();
695         match b.duration_since(a) {
696             Ok(dur) if dur == Duration::new(0, 0) => {
697                 assert_almost_eq!(a, b);
698             }
699             Ok(dur) => {
700                 assert!(b > a);
701                 assert_almost_eq!(b - dur, a);
702                 assert_almost_eq!(a + dur, b);
703             }
704             Err(dur) => {
705                 let dur = dur.duration();
706                 assert!(a > b);
707                 assert_almost_eq!(b + dur, a);
708                 assert_almost_eq!(a - dur, b);
709             }
710         }
711
712         let second = Duration::new(1, 0);
713         assert_almost_eq!(a.duration_since(a - second).unwrap(), second);
714         assert_almost_eq!(a.duration_since(a + second).unwrap_err()
715                            .duration(), second);
716
717         assert_almost_eq!(a - second + second, a);
718         assert_almost_eq!(a.checked_sub(second).unwrap().checked_add(second).unwrap(), a);
719
720         let one_second_from_epoch = UNIX_EPOCH + Duration::new(1, 0);
721         let one_second_from_epoch2 = UNIX_EPOCH + Duration::new(0, 500_000_000)
722             + Duration::new(0, 500_000_000);
723         assert_eq!(one_second_from_epoch, one_second_from_epoch2);
724
725         // checked_add_duration will not panic on overflow
726         let mut maybe_t = Some(SystemTime::UNIX_EPOCH);
727         let max_duration = Duration::from_secs(u64::max_value());
728         // in case `SystemTime` can store `>= UNIX_EPOCH + max_duration`.
729         for _ in 0..2 {
730             maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration));
731         }
732         assert_eq!(maybe_t, None);
733
734         // checked_add_duration calculates the right time and will work for another year
735         let year = Duration::from_secs(60 * 60 * 24 * 365);
736         assert_eq!(a + year, a.checked_add(year).unwrap());
737     }
738
739     #[test]
740     fn system_time_elapsed() {
741         let a = SystemTime::now();
742         drop(a.elapsed());
743     }
744
745     #[test]
746     fn since_epoch() {
747         let ts = SystemTime::now();
748         let a = ts.duration_since(UNIX_EPOCH + Duration::new(1, 0)).unwrap();
749         let b = ts.duration_since(UNIX_EPOCH).unwrap();
750         assert!(b > a);
751         assert_eq!(b - a, Duration::new(1, 0));
752
753         let thirty_years = Duration::new(1, 0) * 60 * 60 * 24 * 365 * 30;
754
755         // Right now for CI this test is run in an emulator, and apparently the
756         // aarch64 emulator's sense of time is that we're still living in the
757         // 70s.
758         //
759         // Otherwise let's assume that we're all running computers later than
760         // 2000.
761         if !cfg!(target_arch = "aarch64") {
762             assert!(a > thirty_years);
763         }
764
765         // let's assume that we're all running computers earlier than 2090.
766         // Should give us ~70 years to fix this!
767         let hundred_twenty_years = thirty_years * 4;
768         assert!(a < hundred_twenty_years);
769     }
770 }