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 millennium_in_solar_seconds = 31_556_952_000;
99/// assert_eq!(millennium_in_solar_seconds, days_per_10_millennia * solar_seconds_per_day / 10);
100///
101/// let duration = Duration::new(millennium_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///            // the system clock went backwards!
209///            println!("Great Scott! {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/// [`UNIX_EPOCH`]: SystemTime::UNIX_EPOCH
249#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
250#[stable(feature = "time2", since = "1.8.0")]
251pub struct SystemTime(time::SystemTime);
252
253/// An error returned from the `duration_since` and `elapsed` methods on
254/// `SystemTime`, used to learn how far in the opposite direction a system time
255/// lies.
256///
257/// # Examples
258///
259/// ```no_run
260/// use std::thread::sleep;
261/// use std::time::{Duration, SystemTime};
262///
263/// let sys_time = SystemTime::now();
264/// sleep(Duration::from_secs(1));
265/// let new_sys_time = SystemTime::now();
266/// match sys_time.duration_since(new_sys_time) {
267///     Ok(_) => {}
268///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
269/// }
270/// ```
271#[derive(Clone, Debug)]
272#[stable(feature = "time2", since = "1.8.0")]
273pub struct SystemTimeError(Duration);
274
275impl Instant {
276    /// Returns an instant corresponding to "now".
277    ///
278    /// # Examples
279    ///
280    /// ```
281    /// use std::time::Instant;
282    ///
283    /// let now = Instant::now();
284    /// ```
285    #[must_use]
286    #[stable(feature = "time2", since = "1.8.0")]
287    #[cfg_attr(not(test), rustc_diagnostic_item = "instant_now")]
288    pub fn now() -> Instant {
289        Instant(time::Instant::now())
290    }
291
292    /// Returns the amount of time elapsed from another instant to this one,
293    /// or zero duration if that instant is later than this one.
294    ///
295    /// # Panics
296    ///
297    /// Previous Rust versions panicked when `earlier` was later than `self`. Currently this
298    /// method saturates. Future versions may reintroduce the panic in some circumstances.
299    /// See [Monotonicity].
300    ///
301    /// [Monotonicity]: Instant#monotonicity
302    ///
303    /// # Examples
304    ///
305    /// ```no_run
306    /// use std::time::{Duration, Instant};
307    /// use std::thread::sleep;
308    ///
309    /// let now = Instant::now();
310    /// sleep(Duration::new(1, 0));
311    /// let new_now = Instant::now();
312    /// println!("{:?}", new_now.duration_since(now));
313    /// println!("{:?}", now.duration_since(new_now)); // 0ns
314    /// ```
315    #[must_use]
316    #[stable(feature = "time2", since = "1.8.0")]
317    pub fn duration_since(&self, earlier: Instant) -> Duration {
318        self.checked_duration_since(earlier).unwrap_or_default()
319    }
320
321    /// Returns the amount of time elapsed from another instant to this one,
322    /// or None if that instant is later than this one.
323    ///
324    /// Due to [monotonicity bugs], even under correct logical ordering of the passed `Instant`s,
325    /// this method can return `None`.
326    ///
327    /// [monotonicity bugs]: Instant#monotonicity
328    ///
329    /// # Examples
330    ///
331    /// ```no_run
332    /// use std::time::{Duration, Instant};
333    /// use std::thread::sleep;
334    ///
335    /// let now = Instant::now();
336    /// sleep(Duration::new(1, 0));
337    /// let new_now = Instant::now();
338    /// println!("{:?}", new_now.checked_duration_since(now));
339    /// println!("{:?}", now.checked_duration_since(new_now)); // None
340    /// ```
341    #[must_use]
342    #[stable(feature = "checked_duration_since", since = "1.39.0")]
343    pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
344        self.0.checked_sub_instant(&earlier.0)
345    }
346
347    /// Returns the amount of time elapsed from another instant to this one,
348    /// or zero duration if that instant is later than this one.
349    ///
350    /// # Examples
351    ///
352    /// ```no_run
353    /// use std::time::{Duration, Instant};
354    /// use std::thread::sleep;
355    ///
356    /// let now = Instant::now();
357    /// sleep(Duration::new(1, 0));
358    /// let new_now = Instant::now();
359    /// println!("{:?}", new_now.saturating_duration_since(now));
360    /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
361    /// ```
362    #[must_use]
363    #[stable(feature = "checked_duration_since", since = "1.39.0")]
364    pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
365        self.checked_duration_since(earlier).unwrap_or_default()
366    }
367
368    /// Returns the amount of time elapsed since this instant.
369    ///
370    /// # Panics
371    ///
372    /// Previous Rust versions panicked when the current time was earlier than self. Currently this
373    /// method returns a Duration of zero in that case. Future versions may reintroduce the panic.
374    /// See [Monotonicity].
375    ///
376    /// [Monotonicity]: Instant#monotonicity
377    ///
378    /// # Examples
379    ///
380    /// ```no_run
381    /// use std::thread::sleep;
382    /// use std::time::{Duration, Instant};
383    ///
384    /// let instant = Instant::now();
385    /// let three_secs = Duration::from_secs(3);
386    /// sleep(three_secs);
387    /// assert!(instant.elapsed() >= three_secs);
388    /// ```
389    #[must_use]
390    #[stable(feature = "time2", since = "1.8.0")]
391    pub fn elapsed(&self) -> Duration {
392        Instant::now() - *self
393    }
394
395    /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
396    /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
397    /// otherwise.
398    #[stable(feature = "time_checked_add", since = "1.34.0")]
399    pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
400        self.0.checked_add_duration(&duration).map(Instant)
401    }
402
403    /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
404    /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
405    /// otherwise.
406    #[stable(feature = "time_checked_add", since = "1.34.0")]
407    pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
408        self.0.checked_sub_duration(&duration).map(Instant)
409    }
410
411    // Used by platform specific `sleep_until` implementations such as the one used on Linux.
412    #[cfg_attr(
413        not(target_os = "linux"),
414        allow(unused, reason = "not every platform has a specific `sleep_until`")
415    )]
416    pub(crate) fn into_inner(self) -> time::Instant {
417        self.0
418    }
419}
420
421#[stable(feature = "time2", since = "1.8.0")]
422impl Add<Duration> for Instant {
423    type Output = Instant;
424
425    /// # Panics
426    ///
427    /// This function may panic if the resulting point in time cannot be represented by the
428    /// underlying data structure. See [`Instant::checked_add`] for a version without panic.
429    fn add(self, other: Duration) -> Instant {
430        self.checked_add(other).expect("overflow when adding duration to instant")
431    }
432}
433
434#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
435impl AddAssign<Duration> for Instant {
436    fn add_assign(&mut self, other: Duration) {
437        *self = *self + other;
438    }
439}
440
441#[stable(feature = "time2", since = "1.8.0")]
442impl Sub<Duration> for Instant {
443    type Output = Instant;
444
445    fn sub(self, other: Duration) -> Instant {
446        self.checked_sub(other).expect("overflow when subtracting duration from instant")
447    }
448}
449
450#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
451impl SubAssign<Duration> for Instant {
452    fn sub_assign(&mut self, other: Duration) {
453        *self = *self - other;
454    }
455}
456
457#[stable(feature = "time2", since = "1.8.0")]
458impl Sub<Instant> for Instant {
459    type Output = Duration;
460
461    /// Returns the amount of time elapsed from another instant to this one,
462    /// or zero duration if that instant is later than this one.
463    ///
464    /// # Panics
465    ///
466    /// Previous Rust versions panicked when `other` was later than `self`. Currently this
467    /// method saturates. Future versions may reintroduce the panic in some circumstances.
468    /// See [Monotonicity].
469    ///
470    /// [Monotonicity]: Instant#monotonicity
471    fn sub(self, other: Instant) -> Duration {
472        self.duration_since(other)
473    }
474}
475
476#[stable(feature = "time2", since = "1.8.0")]
477impl fmt::Debug for Instant {
478    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
479        self.0.fmt(f)
480    }
481}
482
483impl SystemTime {
484    /// An anchor in time which can be used to create new `SystemTime` instances or
485    /// learn about where in time a `SystemTime` lies.
486    //
487    // NOTE! this documentation is duplicated, here and in std::time::UNIX_EPOCH.
488    // The two copies are not quite identical, because of the difference in naming.
489    ///
490    /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
491    /// respect to the system clock. Using `duration_since` on an existing
492    /// `SystemTime` instance can tell how far away from this point in time a
493    /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
494    /// `SystemTime` instance to represent another fixed point in time.
495    ///
496    /// `duration_since(UNIX_EPOCH).unwrap().as_secs()` returns
497    /// the number of non-leap seconds since the start of 1970 UTC.
498    /// This is a POSIX `time_t` (as a `u64`),
499    /// and is the same time representation as used in many Internet protocols.
500    ///
501    /// # Examples
502    ///
503    /// ```no_run
504    /// use std::time::SystemTime;
505    ///
506    /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
507    ///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
508    ///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
509    /// }
510    /// ```
511    #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
512    pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
513
514    /// Returns the system time corresponding to "now".
515    ///
516    /// # Examples
517    ///
518    /// ```
519    /// use std::time::SystemTime;
520    ///
521    /// let sys_time = SystemTime::now();
522    /// ```
523    #[must_use]
524    #[stable(feature = "time2", since = "1.8.0")]
525    pub fn now() -> SystemTime {
526        SystemTime(time::SystemTime::now())
527    }
528
529    /// Returns the amount of time elapsed from an earlier point in time.
530    ///
531    /// This function may fail because measurements taken earlier are not
532    /// guaranteed to always be before later measurements (due to anomalies such
533    /// as the system clock being adjusted either forwards or backwards).
534    /// [`Instant`] can be used to measure elapsed time without this risk of failure.
535    ///
536    /// If successful, <code>[Ok]\([Duration])</code> is returned where the duration represents
537    /// the amount of time elapsed from the specified measurement to this one.
538    ///
539    /// Returns an [`Err`] if `earlier` is later than `self`, and the error
540    /// contains how far from `self` the time is.
541    ///
542    /// # Examples
543    ///
544    /// ```no_run
545    /// use std::time::SystemTime;
546    ///
547    /// let sys_time = SystemTime::now();
548    /// let new_sys_time = SystemTime::now();
549    /// let difference = new_sys_time.duration_since(sys_time)
550    ///     .expect("Clock may have gone backwards");
551    /// println!("{difference:?}");
552    /// ```
553    #[stable(feature = "time2", since = "1.8.0")]
554    pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> {
555        self.0.sub_time(&earlier.0).map_err(SystemTimeError)
556    }
557
558    /// Returns the difference from this system time to the
559    /// current clock time.
560    ///
561    /// This function may fail as the underlying system clock is susceptible to
562    /// drift and updates (e.g., the system clock could go backwards), so this
563    /// function might not always succeed. If successful, <code>[Ok]\([Duration])</code> is
564    /// returned where the duration represents the amount of time elapsed from
565    /// this time measurement to the current time.
566    ///
567    /// To measure elapsed time reliably, use [`Instant`] instead.
568    ///
569    /// Returns an [`Err`] if `self` is later than the current system time, and
570    /// the error contains how far from the current system time `self` is.
571    ///
572    /// # Examples
573    ///
574    /// ```no_run
575    /// use std::thread::sleep;
576    /// use std::time::{Duration, SystemTime};
577    ///
578    /// let sys_time = SystemTime::now();
579    /// let one_sec = Duration::from_secs(1);
580    /// sleep(one_sec);
581    /// assert!(sys_time.elapsed().unwrap() >= one_sec);
582    /// ```
583    #[stable(feature = "time2", since = "1.8.0")]
584    pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
585        SystemTime::now().duration_since(*self)
586    }
587
588    /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
589    /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
590    /// otherwise.
591    #[stable(feature = "time_checked_add", since = "1.34.0")]
592    pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
593        self.0.checked_add_duration(&duration).map(SystemTime)
594    }
595
596    /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
597    /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
598    /// otherwise.
599    #[stable(feature = "time_checked_add", since = "1.34.0")]
600    pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
601        self.0.checked_sub_duration(&duration).map(SystemTime)
602    }
603}
604
605#[stable(feature = "time2", since = "1.8.0")]
606impl Add<Duration> for SystemTime {
607    type Output = SystemTime;
608
609    /// # Panics
610    ///
611    /// This function may panic if the resulting point in time cannot be represented by the
612    /// underlying data structure. See [`SystemTime::checked_add`] for a version without panic.
613    fn add(self, dur: Duration) -> SystemTime {
614        self.checked_add(dur).expect("overflow when adding duration to instant")
615    }
616}
617
618#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
619impl AddAssign<Duration> for SystemTime {
620    fn add_assign(&mut self, other: Duration) {
621        *self = *self + other;
622    }
623}
624
625#[stable(feature = "time2", since = "1.8.0")]
626impl Sub<Duration> for SystemTime {
627    type Output = SystemTime;
628
629    fn sub(self, dur: Duration) -> SystemTime {
630        self.checked_sub(dur).expect("overflow when subtracting duration from instant")
631    }
632}
633
634#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
635impl SubAssign<Duration> for SystemTime {
636    fn sub_assign(&mut self, other: Duration) {
637        *self = *self - other;
638    }
639}
640
641#[stable(feature = "time2", since = "1.8.0")]
642impl fmt::Debug for SystemTime {
643    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
644        self.0.fmt(f)
645    }
646}
647
648/// An anchor in time which can be used to create new `SystemTime` instances or
649/// learn about where in time a `SystemTime` lies.
650//
651// NOTE! this documentation is duplicated, here and in SystemTime::UNIX_EPOCH.
652// The two copies are not quite identical, because of the difference in naming.
653///
654/// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
655/// respect to the system clock. Using `duration_since` on an existing
656/// [`SystemTime`] instance can tell how far away from this point in time a
657/// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
658/// [`SystemTime`] instance to represent another fixed point in time.
659///
660/// `duration_since(UNIX_EPOCH).unwrap().as_secs()` returns
661/// the number of non-leap seconds since the start of 1970 UTC.
662/// This is a POSIX `time_t` (as a `u64`),
663/// and is the same time representation as used in many Internet protocols.
664///
665/// # Examples
666///
667/// ```no_run
668/// use std::time::{SystemTime, UNIX_EPOCH};
669///
670/// match SystemTime::now().duration_since(UNIX_EPOCH) {
671///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
672///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
673/// }
674/// ```
675#[stable(feature = "time2", since = "1.8.0")]
676pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
677
678impl SystemTimeError {
679    /// Returns the positive duration which represents how far forward the
680    /// second system time was from the first.
681    ///
682    /// A `SystemTimeError` is returned from the [`SystemTime::duration_since`]
683    /// and [`SystemTime::elapsed`] methods whenever the second system time
684    /// represents a point later in time than the `self` of the method call.
685    ///
686    /// # Examples
687    ///
688    /// ```no_run
689    /// use std::thread::sleep;
690    /// use std::time::{Duration, SystemTime};
691    ///
692    /// let sys_time = SystemTime::now();
693    /// sleep(Duration::from_secs(1));
694    /// let new_sys_time = SystemTime::now();
695    /// match sys_time.duration_since(new_sys_time) {
696    ///     Ok(_) => {}
697    ///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
698    /// }
699    /// ```
700    #[must_use]
701    #[stable(feature = "time2", since = "1.8.0")]
702    pub fn duration(&self) -> Duration {
703        self.0
704    }
705}
706
707#[stable(feature = "time2", since = "1.8.0")]
708impl Error for SystemTimeError {
709    #[allow(deprecated)]
710    fn description(&self) -> &str {
711        "other time was not earlier than self"
712    }
713}
714
715#[stable(feature = "time2", since = "1.8.0")]
716impl fmt::Display for SystemTimeError {
717    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
718        write!(f, "second time provided was later than self")
719    }
720}
721
722impl FromInner<time::SystemTime> for SystemTime {
723    fn from_inner(time: time::SystemTime) -> SystemTime {
724        SystemTime(time)
725    }
726}
727
728impl IntoInner<time::SystemTime> for SystemTime {
729    fn into_inner(self) -> time::SystemTime {
730        self.0
731    }
732}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy