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