time.rs - source
Description: Source of the Rust file `library/std/src/time.rs`.

#
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::{FromInner, IntoInner, time};
    43
    44/// A measurement of a monotonically nondecreasing clock.
    45/// Opaque and useful only with [`Duration`].
    46///
    47/// Instants are always guaranteed, barring [platform bugs], to be no less than any previously
    48/// measured instant when created, and are often useful for tasks such as measuring
    49/// benchmarks or timing how long an operation takes.
    50///
    51/// Note, however, that instants are **not** guaranteed to be **steady**. In other
    52/// words, each tick of the underlying clock might not be the same length (e.g.
    53/// some seconds may be longer than others). An instant may jump forwards or
    54/// experience time dilation (slow down or speed up), but it will never go
    55/// backwards.
    56/// As part of this non-guarantee it is also not specified whether system suspends count as
    57/// elapsed time or not. The behavior varies across platforms and Rust versions.
    58///
    59/// Instants are opaque types that can only be compared to one another. There is
    60/// no method to get "the number of seconds" from an instant. Instead, it only
    61/// allows measuring the duration between two instants (or comparing two
    62/// instants).
    63///
    64/// The size of an `Instant` struct may vary depending on the target operating
    65/// system.
    66///
    67/// Example:
    68///
    69/// ```no_run
    70/// use std::time::{Duration, Instant};
    71/// use std::thread::sleep;
    72///
    73/// fn main() {
    74///    let now = Instant::now();
    75///
    76///    // we sleep for 2 seconds
    77///    sleep(Duration::new(2, 0));
    78///    // it prints '2'
    79///    println!("{}", now.elapsed().as_secs());
    80/// }
    81/// ```
    82///
    83/// [platform bugs]: Instant#monotonicity
    84///
    85/// # OS-specific behaviors
    86///
    87/// An `Instant` is a wrapper around system-specific types and it may behave
    88/// differently depending on the underlying operating system. For example,
    89/// the following snippet is fine on Linux but panics on macOS:
    90///
    91/// ```no_run
    92/// use std::time::{Instant, Duration};
    93///
    94/// let now = Instant::now();
    95/// let days_per_10_millennia = 365_2425;
    96/// let solar_seconds_per_day = 60 * 60 * 24;
    97/// let millennium_in_solar_seconds = 31_556_952_000;
    98/// assert_eq!(millennium_in_solar_seconds, days_per_10_millennia * solar_seconds_per_day / 10);
    99///
    100/// let duration = Duration::new(millennium_in_solar_seconds, 0);
    101/// println!("{:?}", now + duration);
    102/// ```
    103///
    104/// For cross-platform code, you can comfortably use durations of up to around one hundred years.
    105///
    106/// # Underlying System calls
    107///
    108/// The following system calls are [currently] being used by `now()` to find out
    109/// the current time:
    110///
    111/// |  Platform |               System call                                            |
    112/// |-----------|----------------------------------------------------------------------|
    113/// | SGX       | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
    114/// | UNIX      | [clock_gettime] with `CLOCK_MONOTONIC`                               |
    115/// | Darwin    | [clock_gettime] with `CLOCK_UPTIME_RAW`                              |
    116/// | VXWorks   | [clock_gettime] with `CLOCK_MONOTONIC`                               |
    117/// | SOLID     | `get_tim`                                                            |
    118/// | WASI      | [__wasi_clock_time_get] with `monotonic`                             |
    119/// | Windows   | [QueryPerformanceCounter]                                            |
    120///
    121/// [currently]: crate::io#platform-specific-behavior
    122/// [QueryPerformanceCounter]: https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter
    123/// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
    124/// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
    125/// [__wasi_clock_time_get]: https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#clock_time_get
    126/// [clock_gettime]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/clock_getres.html
    127///
    128/// **Disclaimer:** These system calls might change over time.
    129///
    130/// > Note: mathematical operations like [`add`] may panic if the underlying
    131/// > structure cannot represent the new point in time.
    132///
    133/// [`add`]: Instant::add
    134///
    135/// ## Monotonicity
    136///
    137/// On all platforms `Instant` will try to use an OS API that guarantees monotonic behavior
    138/// if available, which is the case for all [tier 1] platforms.
    139/// In practice such guarantees are – under rare circumstances – broken by hardware, virtualization
    140/// or operating system bugs. To work around these bugs and platforms not offering monotonic clocks
    141/// [`duration_since`], [`elapsed`] and [`sub`] saturate to zero. In older Rust versions this
    142/// lead to a panic instead. [`checked_duration_since`] can be used to detect and handle situations
    143/// where monotonicity is violated, or `Instant`s are subtracted in the wrong order.
    144///
    145/// This workaround obscures programming errors where earlier and later instants are accidentally
    146/// swapped. For this reason future Rust versions may reintroduce panics.
    147///
    148/// [tier 1]: https://doc.rust-lang.org/rustc/platform-support.html
    149/// [`duration_since`]: Instant::duration_since
    150/// [`elapsed`]: Instant::elapsed
    151/// [`sub`]: Instant::sub
    152/// [`checked_duration_since`]: Instant::checked_duration_since
    153///
    154#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
    155#[stable(feature = "time2", since = "1.8.0")]
    156#[cfg_attr(not(test), rustc_diagnostic_item = "Instant")]
    157pub struct Instant(time::Instant);
    158
    159/// A measurement of the system clock, useful for talking to
    160/// external entities like the file system or other processes.
    161///
    162/// Distinct from the [`Instant`] type, this time measurement **is not
    163/// monotonic**. This means that you can save a file to the file system, then
    164/// save another file to the file system, **and the second file has a
    165/// `SystemTime` measurement earlier than the first**. In other words, an
    166/// operation that happens after another operation in real time may have an
    167/// earlier `SystemTime`!
    168///
    169/// Consequently, comparing two `SystemTime` instances to learn about the
    170/// duration between them returns a [`Result`] instead of an infallible [`Duration`]
    171/// to indicate that this sort of time drift may happen and needs to be handled.
    172///
    173/// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
    174/// constant is provided in this module as an anchor in time to learn
    175/// information about a `SystemTime`. By calculating the duration from this
    176/// fixed point in time, a `SystemTime` can be converted to a human-readable time,
    177/// or perhaps some other string representation.
    178///
    179/// The size of a `SystemTime` struct may vary depending on the target operating
    180/// system.
    181///
    182/// A `SystemTime` does not count leap seconds.
    183/// `SystemTime::now()`'s behavior around a leap second
    184/// is the same as the operating system's wall clock.
    185/// The precise behavior near a leap second
    186/// (e.g. whether the clock appears to run slow or fast, or stop, or jump)
    187/// depends on platform and configuration,
    188/// so should not be relied on.
    189///
    190/// Example:
    191///
    192/// ```no_run
    193/// use std::time::{Duration, SystemTime};
    194/// use std::thread::sleep;
    195///
    196/// fn main() {
    197///    let now = SystemTime::now();
    198///
    199///    // we sleep for 2 seconds
    200///    sleep(Duration::new(2, 0));
    201///    match now.elapsed() {
    202///        Ok(elapsed) => {
    203///            // it prints '2'
    204///            println!("{}", elapsed.as_secs());
    205///        }
    206///        Err(e) => {
    207///            // the system clock went backwards!
    208///            println!("Great Scott! {e:?}");
    209///        }
    210///    }
    211/// }
    212/// ```
    213///
    214/// # Platform-specific behavior
    215///
    216/// The precision of `SystemTime` can depend on the underlying OS-specific time format.
    217/// For example, on Windows the time is represented in 100 nanosecond intervals whereas Linux
    218/// can represent nanosecond intervals.
    219///
    220/// The following system calls are [currently] being used by `now()` to find out
    221/// the current time:
    222///
    223/// |  Platform |               System call                                            |
    224/// |-----------|----------------------------------------------------------------------|
    225/// | SGX       | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
    226/// | UNIX      | [clock_gettime (Realtime Clock)]                                     |
    227/// | Darwin    | [clock_gettime (Realtime Clock)]                                     |
    228/// | VXWorks   | [clock_gettime (Realtime Clock)]                                     |
    229/// | SOLID     | `SOLID_RTC_ReadTime`                                                 |
    230/// | WASI      | [__wasi_clock_time_get (Realtime Clock)]                             |
    231/// | Windows   | [GetSystemTimePreciseAsFileTime] / [GetSystemTimeAsFileTime]         |
    232///
    233/// [currently]: crate::io#platform-specific-behavior
    234/// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
    235/// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
    236/// [clock_gettime (Realtime Clock)]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/clock_getres.html
    237/// [__wasi_clock_time_get (Realtime Clock)]: https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#clock_time_get
    238/// [GetSystemTimePreciseAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
    239/// [GetSystemTimeAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime
    240///
    241/// **Disclaimer:** These system calls might change over time.
    242///
    243/// > Note: mathematical operations like [`add`] may panic if the underlying
    244/// > structure cannot represent the new point in time.
    245///
    246/// [`add`]: SystemTime::add
    247/// [`UNIX_EPOCH`]: SystemTime::UNIX_EPOCH
    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    // Used by platform specific `sleep_until` implementations such as the one used on Linux.
    411    #[cfg_attr(
    412        not(target_os = "linux"),
    413        allow(unused, reason = "not every platform has a specific `sleep_until`")
    414    )]
    415    pub(crate) fn into_inner(self) -> time::Instant {
    416        self.0
    417    }
    418}
    419
    420#[stable(feature = "time2", since = "1.8.0")]
    421impl Add<Duration> for Instant {
    422    type Output = Instant;
    423
    424    /// # Panics
    425    ///
    426    /// This function may panic if the resulting point in time cannot be represented by the
    427    /// underlying data structure. See [`Instant::checked_add`] for a version without panic.
    428    fn add(self, other: Duration) -> Instant {
    429        self.checked_add(other).expect("overflow when adding duration to instant")
    430    }
    431}
    432
    433#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
    434impl AddAssign<Duration> for Instant {
    435    fn add_assign(&mut self, other: Duration) {
    436        *self = *self + other;
    437    }
    438}
    439
    440#[stable(feature = "time2", since = "1.8.0")]
    441impl Sub<Duration> for Instant {
    442    type Output = Instant;
    443
    444    fn sub(self, other: Duration) -> Instant {
    445        self.checked_sub(other).expect("overflow when subtracting duration from instant")
    446    }
    447}
    448
    449#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
    450impl SubAssign<Duration> for Instant {
    451    fn sub_assign(&mut self, other: Duration) {
    452        *self = *self - other;
    453    }
    454}
    455
    456#[stable(feature = "time2", since = "1.8.0")]
    457impl Sub<Instant> for Instant {
    458    type Output = Duration;
    459
    460    /// Returns the amount of time elapsed from another instant to this one,
    461    /// or zero duration if that instant is later than this one.
    462    ///
    463    /// # Panics
    464    ///
    465    /// Previous Rust versions panicked when `other` was later than `self`. Currently this
    466    /// method saturates. Future versions may reintroduce the panic in some circumstances.
    467    /// See [Monotonicity].
    468    ///
    469    /// [Monotonicity]: Instant#monotonicity
    470    fn sub(self, other: Instant) -> Duration {
    471        self.duration_since(other)
    472    }
    473}
    474
    475#[stable(feature = "time2", since = "1.8.0")]
    476impl fmt::Debug for Instant {
    477    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    478        self.0.fmt(f)
    479    }
    480}
    481
    482impl SystemTime {
    483    /// An anchor in time which can be used to create new `SystemTime` instances or
    484    /// learn about where in time a `SystemTime` lies.
    485    //
    486    // NOTE! this documentation is duplicated, here and in std::time::UNIX_EPOCH.
    487    // The two copies are not quite identical, because of the difference in naming.
    488    ///
    489    /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
    490    /// respect to the system clock. Using `duration_since` on an existing
    491    /// `SystemTime` instance can tell how far away from this point in time a
    492    /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
    493    /// `SystemTime` instance to represent another fixed point in time.
    494    ///
    495    /// `duration_since(UNIX_EPOCH).unwrap().as_secs()` returns
    496    /// the number of non-leap seconds since the start of 1970 UTC.
    497    /// This is a POSIX `time_t` (as a `u64`),
    498    /// and is the same time representation as used in many Internet protocols.
    499    ///
    500    /// # Examples
    501    ///
    502    /// ```no_run
    503    /// use std::time::SystemTime;
    504    ///
    505    /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
    506    ///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
    507    ///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
    508    /// }
    509    /// ```
    510    #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
    511    pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
    512
    513    /// Represents the maximum value representable by [`SystemTime`] on this platform.
    514    ///
    515    /// This value differs a lot between platforms, but it is always the case
    516    /// that any positive addition of a [`Duration`], whose value is greater
    517    /// than or equal to the time precision of the operating system, to
    518    /// [`SystemTime::MAX`] will fail.
    519    ///
    520    /// # Examples
    521    ///
    522    /// ```no_run
    523    /// #![feature(time_systemtime_limits)]
    524    /// use std::time::{Duration, SystemTime};
    525    ///
    526    /// // Adding zero will change nothing.
    527    /// assert_eq!(SystemTime::MAX.checked_add(Duration::ZERO), Some(SystemTime::MAX));
    528    ///
    529    /// // But adding just one second will already fail ...
    530    /// //
    531    /// // Keep in mind that this in fact may succeed, if the Duration is
    532    /// // smaller than the time precision of the operating system, which
    533    /// // happens to be 1ns on most operating systems, with Windows being the
    534    /// // notable exception by using 100ns, hence why this example uses 1s.
    535    /// assert_eq!(SystemTime::MAX.checked_add(Duration::new(1, 0)), None);
    536    ///
    537    /// // Utilize this for saturating arithmetic to improve error handling.
    538    /// // In this case, we will use a certificate with a timestamp in the
    539    /// // future as a practical example.
    540    /// let configured_offset = Duration::from_secs(60 * 60 * 24);
    541    /// let valid_after =
    542    ///     SystemTime::now()
    543    ///         .checked_add(configured_offset)
    544    ///         .unwrap_or(SystemTime::MAX);
    545    /// ```
    546    #[unstable(feature = "time_systemtime_limits", issue = "149067")]
    547    pub const MAX: SystemTime = SystemTime(time::SystemTime::MAX);
    548
    549    /// Represents the minimum value representable by [`SystemTime`] on this platform.
    550    ///
    551    /// This value differs a lot between platforms, but it is always the case
    552    /// that any positive subtraction of a [`Duration`] from, whose value is
    553    /// greater than or equal to the time precision of the operating system, to
    554    /// [`SystemTime::MIN`] will fail.
    555    ///
    556    /// Depending on the platform, this may be either less than or equal to
    557    /// [`SystemTime::UNIX_EPOCH`], depending on whether the operating system
    558    /// supports the representation of timestamps before the Unix epoch or not.
    559    /// However, it is always guaranteed that a [`SystemTime::UNIX_EPOCH`] fits
    560    /// between a [`SystemTime::MIN`] and [`SystemTime::MAX`].
    561    ///
    562    /// # Examples
    563    ///
    564    /// ```
    565    /// #![feature(time_systemtime_limits)]
    566    /// use std::time::{Duration, SystemTime};
    567    ///
    568    /// // Subtracting zero will change nothing.
    569    /// assert_eq!(SystemTime::MIN.checked_sub(Duration::ZERO), Some(SystemTime::MIN));
    570    ///
    571    /// // But subtracting just one second will already fail.
    572    /// //
    573    /// // Keep in mind that this in fact may succeed, if the Duration is
    574    /// // smaller than the time precision of the operating system, which
    575    /// // happens to be 1ns on most operating systems, with Windows being the
    576    /// // notable exception by using 100ns, hence why this example uses 1s.
    577    /// assert_eq!(SystemTime::MIN.checked_sub(Duration::new(1, 0)), None);
    578    ///
    579    /// // Utilize this for saturating arithmetic to improve error handling.
    580    /// // In this case, we will use a cache expiry as a practical example.
    581    /// let configured_expiry = Duration::from_secs(60 * 3);
    582    /// let expiry_threshold =
    583    ///     SystemTime::now()
    584    ///         .checked_sub(configured_expiry)
    585    ///         .unwrap_or(SystemTime::MIN);
    586    /// ```
    587    #[unstable(feature = "time_systemtime_limits", issue = "149067")]
    588    pub const MIN: SystemTime = SystemTime(time::SystemTime::MIN);
    589
    590    /// Returns the system time corresponding to "now".
    591    ///
    592    /// # Examples
    593    ///
    594    /// ```
    595    /// use std::time::SystemTime;
    596    ///
    597    /// let sys_time = SystemTime::now();
    598    /// ```
    599    #[must_use]
    600    #[stable(feature = "time2", since = "1.8.0")]
    601    pub fn now() -> SystemTime {
    602        SystemTime(time::SystemTime::now())
    603    }
    604
    605    /// Returns the amount of time elapsed from an earlier point in time.
    606    ///
    607    /// This function may fail because measurements taken earlier are not
    608    /// guaranteed to always be before later measurements (due to anomalies such
    609    /// as the system clock being adjusted either forwards or backwards).
    610    /// [`Instant`] can be used to measure elapsed time without this risk of failure.
    611    ///
    612    /// If successful, <code>[Ok]\([Duration])</code> is returned where the duration represents
    613    /// the amount of time elapsed from the specified measurement to this one.
    614    ///
    615    /// Returns an [`Err`] if `earlier` is later than `self`, and the error
    616    /// contains how far from `self` the time is.
    617    ///
    618    /// # Examples
    619    ///
    620    /// ```no_run
    621    /// use std::time::SystemTime;
    622    ///
    623    /// let sys_time = SystemTime::now();
    624    /// let new_sys_time = SystemTime::now();
    625    /// let difference = new_sys_time.duration_since(sys_time)
    626    ///     .expect("Clock may have gone backwards");
    627    /// println!("{difference:?}");
    628    /// ```
    629    #[stable(feature = "time2", since = "1.8.0")]
    630    pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> {
    631        self.0.sub_time(&earlier.0).map_err(SystemTimeError)
    632    }
    633
    634    /// Returns the difference from this system time to the
    635    /// current clock time.
    636    ///
    637    /// This function may fail as the underlying system clock is susceptible to
    638    /// drift and updates (e.g., the system clock could go backwards), so this
    639    /// function might not always succeed. If successful, <code>[Ok]\([Duration])</code> is
    640    /// returned where the duration represents the amount of time elapsed from
    641    /// this time measurement to the current time.
    642    ///
    643    /// To measure elapsed time reliably, use [`Instant`] instead.
    644    ///
    645    /// Returns an [`Err`] if `self` is later than the current system time, and
    646    /// the error contains how far from the current system time `self` is.
    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    /// let one_sec = Duration::from_secs(1);
    656    /// sleep(one_sec);
    657    /// assert!(sys_time.elapsed().unwrap() >= one_sec);
    658    /// ```
    659    #[stable(feature = "time2", since = "1.8.0")]
    660    pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
    661        SystemTime::now().duration_since(*self)
    662    }
    663
    664    /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
    665    /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
    666    /// otherwise.
    667    ///
    668    /// In the case that the `duration` is smaller than the time precision of the operating
    669    /// system, `Some(self)` will be returned.
    670    #[stable(feature = "time_checked_add", since = "1.34.0")]
    671    pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
    672        self.0.checked_add_duration(&duration).map(SystemTime)
    673    }
    674
    675    /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
    676    /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
    677    /// otherwise.
    678    ///
    679    /// In the case that the `duration` is smaller than the time precision of the operating
    680    /// system, `Some(self)` will be returned.
    681    #[stable(feature = "time_checked_add", since = "1.34.0")]
    682    pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
    683        self.0.checked_sub_duration(&duration).map(SystemTime)
    684    }
    685}
    686
    687#[stable(feature = "time2", since = "1.8.0")]
    688impl Add<Duration> for SystemTime {
    689    type Output = SystemTime;
    690
    691    /// # Panics
    692    ///
    693    /// This function may panic if the resulting point in time cannot be represented by the
    694    /// underlying data structure. See [`SystemTime::checked_add`] for a version without panic.
    695    fn add(self, dur: Duration) -> SystemTime {
    696        self.checked_add(dur).expect("overflow when adding duration to instant")
    697    }
    698}
    699
    700#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
    701impl AddAssign<Duration> for SystemTime {
    702    fn add_assign(&mut self, other: Duration) {
    703        *self = *self + other;
    704    }
    705}
    706
    707#[stable(feature = "time2", since = "1.8.0")]
    708impl Sub<Duration> for SystemTime {
    709    type Output = SystemTime;
    710
    711    fn sub(self, dur: Duration) -> SystemTime {
    712        self.checked_sub(dur).expect("overflow when subtracting duration from instant")
    713    }
    714}
    715
    716#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
    717impl SubAssign<Duration> for SystemTime {
    718    fn sub_assign(&mut self, other: Duration) {
    719        *self = *self - other;
    720    }
    721}
    722
    723#[stable(feature = "time2", since = "1.8.0")]
    724impl fmt::Debug for SystemTime {
    725    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    726        self.0.fmt(f)
    727    }
    728}
    729
    730/// An anchor in time which can be used to create new `SystemTime` instances or
    731/// learn about where in time a `SystemTime` lies.
    732//
    733// NOTE! this documentation is duplicated, here and in SystemTime::UNIX_EPOCH.
    734// The two copies are not quite identical, because of the difference in naming.
    735///
    736/// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
    737/// respect to the system clock. Using `duration_since` on an existing
    738/// [`SystemTime`] instance can tell how far away from this point in time a
    739/// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
    740/// [`SystemTime`] instance to represent another fixed point in time.
    741///
    742/// `duration_since(UNIX_EPOCH).unwrap().as_secs()` returns
    743/// the number of non-leap seconds since the start of 1970 UTC.
    744/// This is a POSIX `time_t` (as a `u64`),
    745/// and is the same time representation as used in many Internet protocols.
    746///
    747/// # Examples
    748///
    749/// ```no_run
    750/// use std::time::{SystemTime, UNIX_EPOCH};
    751///
    752/// match SystemTime::now().duration_since(UNIX_EPOCH) {
    753///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
    754///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
    755/// }
    756/// ```
    757#[stable(feature = "time2", since = "1.8.0")]
    758pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
    759
    760impl SystemTimeError {
    761    /// Returns the positive duration which represents how far forward the
    762    /// second system time was from the first.
    763    ///
    764    /// A `SystemTimeError` is returned from the [`SystemTime::duration_since`]
    765    /// and [`SystemTime::elapsed`] methods whenever the second system time
    766    /// represents a point later in time than the `self` of the method call.
    767    ///
    768    /// # Examples
    769    ///
    770    /// ```no_run
    771    /// use std::thread::sleep;
    772    /// use std::time::{Duration, SystemTime};
    773    ///
    774    /// let sys_time = SystemTime::now();
    775    /// sleep(Duration::from_secs(1));
    776    /// let new_sys_time = SystemTime::now();
    777    /// match sys_time.duration_since(new_sys_time) {
    778    ///     Ok(_) => {}
    779    ///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
    780    /// }
    781    /// ```
    782    #[must_use]
    783    #[stable(feature = "time2", since = "1.8.0")]
    784    pub fn duration(&self) -> Duration {
    785        self.0
    786    }
    787}
    788
    789#[stable(feature = "time2", since = "1.8.0")]
    790impl Error for SystemTimeError {}
    791
    792#[stable(feature = "time2", since = "1.8.0")]
    793impl fmt::Display for SystemTimeError {
    794    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    795        write!(f, "second time provided was later than self")
    796    }
    797}
    798
    799impl FromInner<time::SystemTime> for SystemTime {
    800    fn from_inner(time: time::SystemTime) -> SystemTime {
    801        SystemTime(time)
    802    }
    803}
    804
    805impl IntoInner<time::SystemTime> for SystemTime {
    806    fn into_inner(self) -> time::SystemTime {
    807        self.0
    808    }
    809}