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