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