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