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