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