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