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