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