]> git.lizzy.rs Git - rust.git/blob - library/std/src/time.rs
Auto merge of #99943 - compiler-errors:tuple-trait, r=jackh726
[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 #[cfg(test)]
35 mod tests;
36
37 use crate::error::Error;
38 use crate::fmt;
39 use crate::ops::{Add, AddAssign, Sub, SubAssign};
40 use crate::sys::time;
41 use crate::sys_common::{FromInner, IntoInner};
42
43 #[stable(feature = "time", since = "1.3.0")]
44 pub use core::time::Duration;
45
46 #[stable(feature = "duration_checked_float", since = "CURRENT_RUSTC_VERSION")]
47 pub use core::time::TryFromFloatSecsError;
48
49 /// A measurement of a monotonically nondecreasing clock.
50 /// Opaque and useful only with [`Duration`].
51 ///
52 /// Instants are always guaranteed, barring [platform bugs], to be no less than any previously
53 /// measured instant when created, and are often useful for tasks such as measuring
54 /// benchmarks or timing how long an operation takes.
55 ///
56 /// Note, however, that instants are **not** guaranteed to be **steady**. In other
57 /// words, each tick of the underlying clock might not be the same length (e.g.
58 /// some seconds may be longer than others). An instant may jump forwards or
59 /// experience time dilation (slow down or speed up), but it will never go
60 /// backwards.
61 ///
62 /// Instants are opaque types that can only be compared to one another. There is
63 /// no method to get "the number of seconds" from an instant. Instead, it only
64 /// allows measuring the duration between two instants (or comparing two
65 /// instants).
66 ///
67 /// The size of an `Instant` struct may vary depending on the target operating
68 /// system.
69 ///
70 /// Example:
71 ///
72 /// ```no_run
73 /// use std::time::{Duration, Instant};
74 /// use std::thread::sleep;
75 ///
76 /// fn main() {
77 ///    let now = Instant::now();
78 ///
79 ///    // we sleep for 2 seconds
80 ///    sleep(Duration::new(2, 0));
81 ///    // it prints '2'
82 ///    println!("{}", now.elapsed().as_secs());
83 /// }
84 /// ```
85 ///
86 /// [platform bugs]: Instant#monotonicity
87 ///
88 /// # OS-specific behaviors
89 ///
90 /// An `Instant` is a wrapper around system-specific types and it may behave
91 /// differently depending on the underlying operating system. For example,
92 /// the following snippet is fine on Linux but panics on macOS:
93 ///
94 /// ```no_run
95 /// use std::time::{Instant, Duration};
96 ///
97 /// let now = Instant::now();
98 /// let max_seconds = u64::MAX / 1_000_000_000;
99 /// let duration = Duration::new(max_seconds, 0);
100 /// println!("{:?}", now + duration);
101 /// ```
102 ///
103 /// # Underlying System calls
104 ///
105 /// The following system calls are [currently] being used by `now()` to find out
106 /// the current time:
107 ///
108 /// |  Platform |               System call                                            |
109 /// |-----------|----------------------------------------------------------------------|
110 /// | SGX       | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
111 /// | UNIX      | [clock_gettime (Monotonic Clock)]                                    |
112 /// | Darwin    | [mach_absolute_time]                                                 |
113 /// | VXWorks   | [clock_gettime (Monotonic Clock)]                                    |
114 /// | SOLID     | `get_tim`                                                            |
115 /// | WASI      | [__wasi_clock_time_get (Monotonic Clock)]                            |
116 /// | Windows   | [QueryPerformanceCounter]                                            |
117 ///
118 /// [currently]: crate::io#platform-specific-behavior
119 /// [QueryPerformanceCounter]: https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter
120 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
121 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
122 /// [__wasi_clock_time_get (Monotonic Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
123 /// [clock_gettime (Monotonic Clock)]: https://linux.die.net/man/3/clock_gettime
124 /// [mach_absolute_time]: https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/KernelProgramming/services/services.html
125 ///
126 /// **Disclaimer:** These system calls might change over time.
127 ///
128 /// > Note: mathematical operations like [`add`] may panic if the underlying
129 /// > structure cannot represent the new point in time.
130 ///
131 /// [`add`]: Instant::add
132 ///
133 /// ## Monotonicity
134 ///
135 /// On all platforms `Instant` will try to use an OS API that guarantees monotonic behavior
136 /// if available, which is the case for all [tier 1] platforms.
137 /// In practice such guarantees are – under rare circumstances – broken by hardware, virtualization
138 /// or operating system bugs. To work around these bugs and platforms not offering monotonic clocks
139 /// [`duration_since`], [`elapsed`] and [`sub`] saturate to zero. In older Rust versions this
140 /// lead to a panic instead. [`checked_duration_since`] can be used to detect and handle situations
141 /// where monotonicity is violated, or `Instant`s are subtracted in the wrong order.
142 ///
143 /// This workaround obscures programming errors where earlier and later instants are accidentally
144 /// swapped. For this reason future rust versions may reintroduce panics.
145 ///
146 /// [tier 1]: https://doc.rust-lang.org/rustc/platform-support.html
147 /// [`duration_since`]: Instant::duration_since
148 /// [`elapsed`]: Instant::elapsed
149 /// [`sub`]: Instant::sub
150 /// [`checked_duration_since`]: Instant::checked_duration_since
151 ///
152 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
153 #[stable(feature = "time2", since = "1.8.0")]
154 pub struct Instant(time::Instant);
155
156 /// A measurement of the system clock, useful for talking to
157 /// external entities like the file system or other processes.
158 ///
159 /// Distinct from the [`Instant`] type, this time measurement **is not
160 /// monotonic**. This means that you can save a file to the file system, then
161 /// save another file to the file system, **and the second file has a
162 /// `SystemTime` measurement earlier than the first**. In other words, an
163 /// operation that happens after another operation in real time may have an
164 /// earlier `SystemTime`!
165 ///
166 /// Consequently, comparing two `SystemTime` instances to learn about the
167 /// duration between them returns a [`Result`] instead of an infallible [`Duration`]
168 /// to indicate that this sort of time drift may happen and needs to be handled.
169 ///
170 /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
171 /// constant is provided in this module as an anchor in time to learn
172 /// information about a `SystemTime`. By calculating the duration from this
173 /// fixed point in time, a `SystemTime` can be converted to a human-readable time,
174 /// or perhaps some other string representation.
175 ///
176 /// The size of a `SystemTime` struct may vary depending on the target operating
177 /// system.
178 ///
179 /// Example:
180 ///
181 /// ```no_run
182 /// use std::time::{Duration, SystemTime};
183 /// use std::thread::sleep;
184 ///
185 /// fn main() {
186 ///    let now = SystemTime::now();
187 ///
188 ///    // we sleep for 2 seconds
189 ///    sleep(Duration::new(2, 0));
190 ///    match now.elapsed() {
191 ///        Ok(elapsed) => {
192 ///            // it prints '2'
193 ///            println!("{}", elapsed.as_secs());
194 ///        }
195 ///        Err(e) => {
196 ///            // an error occurred!
197 ///            println!("Error: {e:?}");
198 ///        }
199 ///    }
200 /// }
201 /// ```
202 ///
203 /// # Platform-specific behavior
204 ///
205 /// The precision of `SystemTime` can depend on the underlying OS-specific time format.
206 /// For example, on Windows the time is represented in 100 nanosecond intervals whereas Linux
207 /// can represent nanosecond intervals.
208 ///
209 /// The following system calls are [currently] being used by `now()` to find out
210 /// the current time:
211 ///
212 /// |  Platform |               System call                                            |
213 /// |-----------|----------------------------------------------------------------------|
214 /// | SGX       | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
215 /// | UNIX      | [clock_gettime (Realtime Clock)]                                     |
216 /// | Darwin    | [gettimeofday]                                                       |
217 /// | VXWorks   | [clock_gettime (Realtime Clock)]                                     |
218 /// | SOLID     | `SOLID_RTC_ReadTime`                                                 |
219 /// | WASI      | [__wasi_clock_time_get (Realtime Clock)]                             |
220 /// | Windows   | [GetSystemTimePreciseAsFileTime] / [GetSystemTimeAsFileTime]         |
221 ///
222 /// [currently]: crate::io#platform-specific-behavior
223 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
224 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
225 /// [gettimeofday]: https://man7.org/linux/man-pages/man2/gettimeofday.2.html
226 /// [clock_gettime (Realtime Clock)]: https://linux.die.net/man/3/clock_gettime
227 /// [__wasi_clock_time_get (Realtime Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
228 /// [GetSystemTimePreciseAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
229 /// [GetSystemTimeAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime
230 ///
231 /// **Disclaimer:** These system calls might change over time.
232 ///
233 /// > Note: mathematical operations like [`add`] may panic if the underlying
234 /// > structure cannot represent the new point in time.
235 ///
236 /// [`add`]: SystemTime::add
237 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
238 #[stable(feature = "time2", since = "1.8.0")]
239 pub struct SystemTime(time::SystemTime);
240
241 /// An error returned from the `duration_since` and `elapsed` methods on
242 /// `SystemTime`, used to learn how far in the opposite direction a system time
243 /// lies.
244 ///
245 /// # Examples
246 ///
247 /// ```no_run
248 /// use std::thread::sleep;
249 /// use std::time::{Duration, SystemTime};
250 ///
251 /// let sys_time = SystemTime::now();
252 /// sleep(Duration::from_secs(1));
253 /// let new_sys_time = SystemTime::now();
254 /// match sys_time.duration_since(new_sys_time) {
255 ///     Ok(_) => {}
256 ///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
257 /// }
258 /// ```
259 #[derive(Clone, Debug)]
260 #[stable(feature = "time2", since = "1.8.0")]
261 pub struct SystemTimeError(Duration);
262
263 impl Instant {
264     /// Returns an instant corresponding to "now".
265     ///
266     /// # Examples
267     ///
268     /// ```
269     /// use std::time::Instant;
270     ///
271     /// let now = Instant::now();
272     /// ```
273     #[must_use]
274     #[stable(feature = "time2", since = "1.8.0")]
275     pub fn now() -> Instant {
276         Instant(time::Instant::now())
277     }
278
279     /// Returns the amount of time elapsed from another instant to this one,
280     /// or zero duration if that instant is later than this one.
281     ///
282     /// # Panics
283     ///
284     /// Previous rust versions panicked when `earlier` was later than `self`. Currently this
285     /// method saturates. Future versions may reintroduce the panic in some circumstances.
286     /// See [Monotonicity].
287     ///
288     /// [Monotonicity]: Instant#monotonicity
289     ///
290     /// # Examples
291     ///
292     /// ```no_run
293     /// use std::time::{Duration, Instant};
294     /// use std::thread::sleep;
295     ///
296     /// let now = Instant::now();
297     /// sleep(Duration::new(1, 0));
298     /// let new_now = Instant::now();
299     /// println!("{:?}", new_now.duration_since(now));
300     /// println!("{:?}", now.duration_since(new_now)); // 0ns
301     /// ```
302     #[must_use]
303     #[stable(feature = "time2", since = "1.8.0")]
304     pub fn duration_since(&self, earlier: Instant) -> Duration {
305         self.checked_duration_since(earlier).unwrap_or_default()
306     }
307
308     /// Returns the amount of time elapsed from another instant to this one,
309     /// or None if that instant is later than this one.
310     ///
311     /// Due to [monotonicity bugs], even under correct logical ordering of the passed `Instant`s,
312     /// this method can return `None`.
313     ///
314     /// [monotonicity bugs]: Instant#monotonicity
315     ///
316     /// # Examples
317     ///
318     /// ```no_run
319     /// use std::time::{Duration, Instant};
320     /// use std::thread::sleep;
321     ///
322     /// let now = Instant::now();
323     /// sleep(Duration::new(1, 0));
324     /// let new_now = Instant::now();
325     /// println!("{:?}", new_now.checked_duration_since(now));
326     /// println!("{:?}", now.checked_duration_since(new_now)); // None
327     /// ```
328     #[must_use]
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     #[must_use]
350     #[stable(feature = "checked_duration_since", since = "1.39.0")]
351     pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
352         self.checked_duration_since(earlier).unwrap_or_default()
353     }
354
355     /// Returns the amount of time elapsed since this instant was created.
356     ///
357     /// # Panics
358     ///
359     /// Previous rust versions panicked when the current time was earlier than self. Currently this
360     /// method returns a Duration of zero in that case. Future versions may reintroduce the panic.
361     /// See [Monotonicity].
362     ///
363     /// [Monotonicity]: Instant#monotonicity
364     ///
365     /// # Examples
366     ///
367     /// ```no_run
368     /// use std::thread::sleep;
369     /// use std::time::{Duration, Instant};
370     ///
371     /// let instant = Instant::now();
372     /// let three_secs = Duration::from_secs(3);
373     /// sleep(three_secs);
374     /// assert!(instant.elapsed() >= three_secs);
375     /// ```
376     #[must_use]
377     #[stable(feature = "time2", since = "1.8.0")]
378     pub fn elapsed(&self) -> Duration {
379         Instant::now() - *self
380     }
381
382     /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
383     /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
384     /// otherwise.
385     #[stable(feature = "time_checked_add", since = "1.34.0")]
386     pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
387         self.0.checked_add_duration(&duration).map(Instant)
388     }
389
390     /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
391     /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
392     /// otherwise.
393     #[stable(feature = "time_checked_add", since = "1.34.0")]
394     pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
395         self.0.checked_sub_duration(&duration).map(Instant)
396     }
397 }
398
399 #[stable(feature = "time2", since = "1.8.0")]
400 impl Add<Duration> for Instant {
401     type Output = Instant;
402
403     /// # Panics
404     ///
405     /// This function may panic if the resulting point in time cannot be represented by the
406     /// underlying data structure. See [`Instant::checked_add`] for a version without panic.
407     fn add(self, other: Duration) -> Instant {
408         self.checked_add(other).expect("overflow when adding duration to instant")
409     }
410 }
411
412 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
413 impl AddAssign<Duration> for Instant {
414     fn add_assign(&mut self, other: Duration) {
415         *self = *self + other;
416     }
417 }
418
419 #[stable(feature = "time2", since = "1.8.0")]
420 impl Sub<Duration> for Instant {
421     type Output = Instant;
422
423     fn sub(self, other: Duration) -> Instant {
424         self.checked_sub(other).expect("overflow when subtracting duration from instant")
425     }
426 }
427
428 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
429 impl SubAssign<Duration> for Instant {
430     fn sub_assign(&mut self, other: Duration) {
431         *self = *self - other;
432     }
433 }
434
435 #[stable(feature = "time2", since = "1.8.0")]
436 impl Sub<Instant> for Instant {
437     type Output = Duration;
438
439     /// Returns the amount of time elapsed from another instant to this one,
440     /// or zero duration if that instant is later than this one.
441     ///
442     /// # Panics
443     ///
444     /// Previous rust versions panicked when `other` was later than `self`. Currently this
445     /// method saturates. Future versions may reintroduce the panic in some circumstances.
446     /// See [Monotonicity].
447     ///
448     /// [Monotonicity]: Instant#monotonicity
449     fn sub(self, other: Instant) -> Duration {
450         self.duration_since(other)
451     }
452 }
453
454 #[stable(feature = "time2", since = "1.8.0")]
455 impl fmt::Debug for Instant {
456     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457         self.0.fmt(f)
458     }
459 }
460
461 impl SystemTime {
462     /// An anchor in time which can be used to create new `SystemTime` instances or
463     /// learn about where in time a `SystemTime` lies.
464     ///
465     /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
466     /// respect to the system clock. Using `duration_since` on an existing
467     /// `SystemTime` instance can tell how far away from this point in time a
468     /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
469     /// `SystemTime` instance to represent another fixed point in time.
470     ///
471     /// # Examples
472     ///
473     /// ```no_run
474     /// use std::time::SystemTime;
475     ///
476     /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
477     ///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
478     ///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
479     /// }
480     /// ```
481     #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
482     pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
483
484     /// Returns the system time corresponding to "now".
485     ///
486     /// # Examples
487     ///
488     /// ```
489     /// use std::time::SystemTime;
490     ///
491     /// let sys_time = SystemTime::now();
492     /// ```
493     #[must_use]
494     #[stable(feature = "time2", since = "1.8.0")]
495     pub fn now() -> SystemTime {
496         SystemTime(time::SystemTime::now())
497     }
498
499     /// Returns the amount of time elapsed from an earlier point in time.
500     ///
501     /// This function may fail because measurements taken earlier are not
502     /// guaranteed to always be before later measurements (due to anomalies such
503     /// as the system clock being adjusted either forwards or backwards).
504     /// [`Instant`] can be used to measure elapsed time without this risk of failure.
505     ///
506     /// If successful, <code>[Ok]\([Duration])</code> is returned where the duration represents
507     /// the amount of time elapsed from the specified measurement to this one.
508     ///
509     /// Returns an [`Err`] if `earlier` is later than `self`, and the error
510     /// contains how far from `self` the time is.
511     ///
512     /// # Examples
513     ///
514     /// ```no_run
515     /// use std::time::SystemTime;
516     ///
517     /// let sys_time = SystemTime::now();
518     /// let new_sys_time = SystemTime::now();
519     /// let difference = new_sys_time.duration_since(sys_time)
520     ///     .expect("Clock may have gone backwards");
521     /// println!("{difference:?}");
522     /// ```
523     #[stable(feature = "time2", since = "1.8.0")]
524     pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> {
525         self.0.sub_time(&earlier.0).map_err(SystemTimeError)
526     }
527
528     /// Returns the difference between the clock time when this
529     /// system time was created, and the current clock time.
530     ///
531     /// This function may fail as the underlying system clock is susceptible to
532     /// drift and updates (e.g., the system clock could go backwards), so this
533     /// function might not always succeed. If successful, <code>[Ok]\([Duration])</code> is
534     /// returned where the duration represents the amount of time elapsed from
535     /// this time measurement to the current time.
536     ///
537     /// To measure elapsed time reliably, use [`Instant`] instead.
538     ///
539     /// Returns an [`Err`] if `self` is later than the current system time, and
540     /// the error contains how far from the current system time `self` is.
541     ///
542     /// # Examples
543     ///
544     /// ```no_run
545     /// use std::thread::sleep;
546     /// use std::time::{Duration, SystemTime};
547     ///
548     /// let sys_time = SystemTime::now();
549     /// let one_sec = Duration::from_secs(1);
550     /// sleep(one_sec);
551     /// assert!(sys_time.elapsed().unwrap() >= one_sec);
552     /// ```
553     #[stable(feature = "time2", since = "1.8.0")]
554     pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
555         SystemTime::now().duration_since(*self)
556     }
557
558     /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
559     /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
560     /// otherwise.
561     #[stable(feature = "time_checked_add", since = "1.34.0")]
562     pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
563         self.0.checked_add_duration(&duration).map(SystemTime)
564     }
565
566     /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
567     /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
568     /// otherwise.
569     #[stable(feature = "time_checked_add", since = "1.34.0")]
570     pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
571         self.0.checked_sub_duration(&duration).map(SystemTime)
572     }
573 }
574
575 #[stable(feature = "time2", since = "1.8.0")]
576 impl Add<Duration> for SystemTime {
577     type Output = SystemTime;
578
579     /// # Panics
580     ///
581     /// This function may panic if the resulting point in time cannot be represented by the
582     /// underlying data structure. See [`SystemTime::checked_add`] for a version without panic.
583     fn add(self, dur: Duration) -> SystemTime {
584         self.checked_add(dur).expect("overflow when adding duration to instant")
585     }
586 }
587
588 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
589 impl AddAssign<Duration> for SystemTime {
590     fn add_assign(&mut self, other: Duration) {
591         *self = *self + other;
592     }
593 }
594
595 #[stable(feature = "time2", since = "1.8.0")]
596 impl Sub<Duration> for SystemTime {
597     type Output = SystemTime;
598
599     fn sub(self, dur: Duration) -> SystemTime {
600         self.checked_sub(dur).expect("overflow when subtracting duration from instant")
601     }
602 }
603
604 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
605 impl SubAssign<Duration> for SystemTime {
606     fn sub_assign(&mut self, other: Duration) {
607         *self = *self - other;
608     }
609 }
610
611 #[stable(feature = "time2", since = "1.8.0")]
612 impl fmt::Debug for SystemTime {
613     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
614         self.0.fmt(f)
615     }
616 }
617
618 /// An anchor in time which can be used to create new `SystemTime` instances or
619 /// learn about where in time a `SystemTime` lies.
620 ///
621 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
622 /// respect to the system clock. Using `duration_since` on an existing
623 /// [`SystemTime`] instance can tell how far away from this point in time a
624 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
625 /// [`SystemTime`] instance to represent another fixed point in time.
626 ///
627 /// # Examples
628 ///
629 /// ```no_run
630 /// use std::time::{SystemTime, UNIX_EPOCH};
631 ///
632 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
633 ///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
634 ///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
635 /// }
636 /// ```
637 #[stable(feature = "time2", since = "1.8.0")]
638 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
639
640 impl SystemTimeError {
641     /// Returns the positive duration which represents how far forward the
642     /// second system time was from the first.
643     ///
644     /// A `SystemTimeError` is returned from the [`SystemTime::duration_since`]
645     /// and [`SystemTime::elapsed`] methods whenever the second system time
646     /// represents a point later in time than the `self` of the method call.
647     ///
648     /// # Examples
649     ///
650     /// ```no_run
651     /// use std::thread::sleep;
652     /// use std::time::{Duration, SystemTime};
653     ///
654     /// let sys_time = SystemTime::now();
655     /// sleep(Duration::from_secs(1));
656     /// let new_sys_time = SystemTime::now();
657     /// match sys_time.duration_since(new_sys_time) {
658     ///     Ok(_) => {}
659     ///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
660     /// }
661     /// ```
662     #[must_use]
663     #[stable(feature = "time2", since = "1.8.0")]
664     pub fn duration(&self) -> Duration {
665         self.0
666     }
667 }
668
669 #[stable(feature = "time2", since = "1.8.0")]
670 impl Error for SystemTimeError {
671     #[allow(deprecated)]
672     fn description(&self) -> &str {
673         "other time was not earlier than self"
674     }
675 }
676
677 #[stable(feature = "time2", since = "1.8.0")]
678 impl fmt::Display for SystemTimeError {
679     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
680         write!(f, "second time provided was later than self")
681     }
682 }
683
684 impl FromInner<time::SystemTime> for SystemTime {
685     fn from_inner(time: time::SystemTime) -> SystemTime {
686         SystemTime(time)
687     }
688 }
689
690 impl IntoInner<time::SystemTime> for SystemTime {
691     fn into_inner(self) -> time::SystemTime {
692         self.0
693     }
694 }