]> git.lizzy.rs Git - rust.git/blob - src/libstd/time.rs
Complete the std::time documentation to warn about the inconsistencies between OS
[rust.git] / src / libstd / time.rs
1 //! Temporal quantification.
2 //!
3 //! Example:
4 //!
5 //! ```
6 //! use std::time::Duration;
7 //!
8 //! let five_seconds = Duration::new(5, 0);
9 //! // both declarations are equivalent
10 //! assert_eq!(Duration::new(5, 0), Duration::from_secs(5));
11 //! ```
12
13 #![stable(feature = "time", since = "1.3.0")]
14
15 use crate::cmp;
16 use crate::error::Error;
17 use crate::fmt;
18 use crate::ops::{Add, AddAssign, Sub, SubAssign};
19 use crate::sys::time;
20 use crate::sys_common::mutex::Mutex;
21 use crate::sys_common::FromInner;
22
23 #[stable(feature = "time", since = "1.3.0")]
24 pub use core::time::Duration;
25
26 /// A measurement of a monotonically nondecreasing clock.
27 /// Opaque and useful only with `Duration`.
28 ///
29 /// Instants are always guaranteed to be no less than any previously measured
30 /// instant when created, and are often useful for tasks such as measuring
31 /// benchmarks or timing how long an operation takes.
32 ///
33 /// Note, however, that instants are not guaranteed to be **steady**. In other
34 /// words, each tick of the underlying clock may not be the same length (e.g.
35 /// some seconds may be longer than others). An instant may jump forwards or
36 /// experience time dilation (slow down or speed up), but it will never go
37 /// backwards.
38 ///
39 /// Instants are opaque types that can only be compared to one another. There is
40 /// no method to get "the number of seconds" from an instant. Instead, it only
41 /// allows measuring the duration between two instants (or comparing two
42 /// instants).
43 ///
44 /// The size of an `Instant` struct may vary depending on the target operating
45 /// system.
46 ///
47 /// Example:
48 ///
49 /// ```no_run
50 /// use std::time::{Duration, Instant};
51 /// use std::thread::sleep;
52 ///
53 /// fn main() {
54 ///    let now = Instant::now();
55 ///
56 ///    // we sleep for 2 seconds
57 ///    sleep(Duration::new(2, 0));
58 ///    // it prints '2'
59 ///    println!("{}", now.elapsed().as_secs());
60 /// }
61 /// ```
62 ///
63 /// # OS-specific behaviors
64 ///
65 /// An `Instant` is a wrapper around system-specific types and it may behave
66 /// differently depending on the underlying operating system. For example,
67 /// the following snippet is fine on Linux but panics on macOS:
68 ///
69 /// ```no_run
70 /// use std::time::{Instant, Duration};
71 ///
72 /// let now = Instant::now();
73 /// let max_nanoseconds = u64::MAX / 1_000_000_000;
74 /// let duration = Duration::new(max_nanoseconds, 0);
75 /// println!("{:?}", now + duration);
76 /// ```
77 ///
78 /// # Underlying System calls
79 /// Currently, the following system calls are being used to get the current time using `now()`:
80 ///
81 /// |  Platform |               System call                                            |
82 /// |:---------:|:--------------------------------------------------------------------:|
83 /// | CloudABI  | [clock_time_get (Monotonic Clock)]                                   |
84 /// | SGX       | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
85 /// | UNIX      | [clock_gettime (Monotonic Clock)]                                    |
86 /// | Darwin    | [mach_absolute_time]                                                 |
87 /// | VXWorks   | [clock_gettime (Monotonic Clock)]                                    |
88 /// | WASI      | [__wasi_clock_time_get (Monotonic Clock)]                            |
89 /// | Windows   | [QueryPerformanceCounter]                                            |
90 ///
91 /// [QueryPerformanceCounter]: https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter
92 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
93 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
94 /// [__wasi_clock_time_get (Monotonic Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
95 /// [clock_gettime (Monotonic Clock)]: https://linux.die.net/man/3/clock_gettime
96 /// [mach_absolute_time]: https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/KernelProgramming/services/services.html
97 /// [clock_time_get (Monotonic Clock)]: https://nuxi.nl/cloudabi/#clock_time_get
98 ///
99 /// **Disclaimer:** These system calls might change over time.
100 ///
101 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
102 #[stable(feature = "time2", since = "1.8.0")]
103 pub struct Instant(time::Instant);
104
105 /// A measurement of the system clock, useful for talking to
106 /// external entities like the file system or other processes.
107 ///
108 /// Distinct from the [`Instant`] type, this time measurement **is not
109 /// monotonic**. This means that you can save a file to the file system, then
110 /// save another file to the file system, **and the second file has a
111 /// `SystemTime` measurement earlier than the first**. In other words, an
112 /// operation that happens after another operation in real time may have an
113 /// earlier `SystemTime`!
114 ///
115 /// Consequently, comparing two `SystemTime` instances to learn about the
116 /// duration between them returns a [`Result`] instead of an infallible [`Duration`]
117 /// to indicate that this sort of time drift may happen and needs to be handled.
118 ///
119 /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
120 /// constant is provided in this module as an anchor in time to learn
121 /// information about a `SystemTime`. By calculating the duration from this
122 /// fixed point in time, a `SystemTime` can be converted to a human-readable time,
123 /// or perhaps some other string representation.
124 ///
125 /// The size of a `SystemTime` struct may vary depending on the target operating
126 /// system.
127 ///
128 /// [`Instant`]: ../../std/time/struct.Instant.html
129 /// [`Result`]: ../../std/result/enum.Result.html
130 /// [`Duration`]: ../../std/time/struct.Duration.html
131 /// [`UNIX_EPOCH`]: ../../std/time/constant.UNIX_EPOCH.html
132 ///
133 /// Example:
134 ///
135 /// ```no_run
136 /// use std::time::{Duration, SystemTime};
137 /// use std::thread::sleep;
138 ///
139 /// fn main() {
140 ///    let now = SystemTime::now();
141 ///
142 ///    // we sleep for 2 seconds
143 ///    sleep(Duration::new(2, 0));
144 ///    match now.elapsed() {
145 ///        Ok(elapsed) => {
146 ///            // it prints '2'
147 ///            println!("{}", elapsed.as_secs());
148 ///        }
149 ///        Err(e) => {
150 ///            // an error occurred!
151 ///            println!("Error: {:?}", e);
152 ///        }
153 ///    }
154 /// }
155 /// ```
156 ///
157 /// # Underlying System calls
158 /// Currently, the following system calls are being used to get the current time using `now()`:
159 ///
160 /// |  Platform |               System call                                            |
161 /// |:---------:|:--------------------------------------------------------------------:|
162 /// | CloudABI  | [clock_time_get (Realtime Clock)]                                    |
163 /// | SGX       | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
164 /// | UNIX      | [clock_gettime (Realtime Clock)]                                     |
165 /// | DARWIN    | [gettimeofday]                                                       |
166 /// | VXWorks   | [clock_gettime (Realtime Clock)]                                     |
167 /// | WASI      | [__wasi_clock_time_get (Realtime Clock)]                             |
168 /// | Windows   | [GetSystemTimeAsFileTime]                                            |
169 ///
170 /// [clock_time_get (Realtime Clock)]: https://nuxi.nl/cloudabi/#clock_time_get
171 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
172 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
173 /// [gettimeofday]: http://man7.org/linux/man-pages/man2/gettimeofday.2.html
174 /// [clock_gettime (Realtime Clock)]: https://linux.die.net/man/3/clock_gettime
175 /// [__wasi_clock_time_get (Realtime Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
176 /// [GetSystemTimeAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime
177 ///
178 /// **Disclaimer:** These system calls might change over time.
179 ///
180 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
181 #[stable(feature = "time2", since = "1.8.0")]
182 pub struct SystemTime(time::SystemTime);
183
184 /// An error returned from the `duration_since` and `elapsed` methods on
185 /// `SystemTime`, used to learn how far in the opposite direction a system time
186 /// lies.
187 ///
188 /// # Examples
189 ///
190 /// ```no_run
191 /// use std::thread::sleep;
192 /// use std::time::{Duration, SystemTime};
193 ///
194 /// let sys_time = SystemTime::now();
195 /// sleep(Duration::from_secs(1));
196 /// let new_sys_time = SystemTime::now();
197 /// match sys_time.duration_since(new_sys_time) {
198 ///     Ok(_) => {}
199 ///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
200 /// }
201 /// ```
202 #[derive(Clone, Debug)]
203 #[stable(feature = "time2", since = "1.8.0")]
204 pub struct SystemTimeError(Duration);
205
206 impl Instant {
207     /// Returns an instant corresponding to "now".
208     ///
209     /// # Examples
210     ///
211     /// ```
212     /// use std::time::Instant;
213     ///
214     /// let now = Instant::now();
215     /// ```
216     #[stable(feature = "time2", since = "1.8.0")]
217     pub fn now() -> Instant {
218         let os_now = time::Instant::now();
219
220         // And here we come upon a sad state of affairs. The whole point of
221         // `Instant` is that it's monotonically increasing. We've found in the
222         // wild, however, that it's not actually monotonically increasing for
223         // one reason or another. These appear to be OS and hardware level bugs,
224         // and there's not really a whole lot we can do about them. Here's a
225         // taste of what we've found:
226         //
227         // * #48514 - OpenBSD, x86_64
228         // * #49281 - linux arm64 and s390x
229         // * #51648 - windows, x86
230         // * #56560 - windows, x86_64, AWS
231         // * #56612 - windows, x86, vm (?)
232         // * #56940 - linux, arm64
233         // * https://bugzilla.mozilla.org/show_bug.cgi?id=1487778 - a similar
234         //   Firefox bug
235         //
236         // It seems that this just happens a lot in the wild.
237         // We're seeing panics across various platforms where consecutive calls
238         // to `Instant::now`, such as via the `elapsed` function, are panicking
239         // as they're going backwards. Placed here is a last-ditch effort to try
240         // to fix things up. We keep a global "latest now" instance which is
241         // returned instead of what the OS says if the OS goes backwards.
242         //
243         // To hopefully mitigate the impact of this, a few platforms are
244         // whitelisted as "these at least haven't gone backwards yet".
245         if time::Instant::actually_monotonic() {
246             return Instant(os_now);
247         }
248
249         static LOCK: Mutex = Mutex::new();
250         static mut LAST_NOW: time::Instant = time::Instant::zero();
251         unsafe {
252             let _lock = LOCK.lock();
253             let now = cmp::max(LAST_NOW, os_now);
254             LAST_NOW = now;
255             Instant(now)
256         }
257     }
258
259     /// Returns the amount of time elapsed from another instant to this one.
260     ///
261     /// # Panics
262     ///
263     /// This function will panic if `earlier` is later than `self`.
264     ///
265     /// # Examples
266     ///
267     /// ```no_run
268     /// use std::time::{Duration, Instant};
269     /// use std::thread::sleep;
270     ///
271     /// let now = Instant::now();
272     /// sleep(Duration::new(1, 0));
273     /// let new_now = Instant::now();
274     /// println!("{:?}", new_now.duration_since(now));
275     /// ```
276     #[stable(feature = "time2", since = "1.8.0")]
277     pub fn duration_since(&self, earlier: Instant) -> Duration {
278         self.0.checked_sub_instant(&earlier.0).expect("supplied instant is later than self")
279     }
280
281     /// Returns the amount of time elapsed from another instant to this one,
282     /// or None if that instant is later than this one.
283     ///
284     /// # Examples
285     ///
286     /// ```no_run
287     /// use std::time::{Duration, Instant};
288     /// use std::thread::sleep;
289     ///
290     /// let now = Instant::now();
291     /// sleep(Duration::new(1, 0));
292     /// let new_now = Instant::now();
293     /// println!("{:?}", new_now.checked_duration_since(now));
294     /// println!("{:?}", now.checked_duration_since(new_now)); // None
295     /// ```
296     #[stable(feature = "checked_duration_since", since = "1.39.0")]
297     pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
298         self.0.checked_sub_instant(&earlier.0)
299     }
300
301     /// Returns the amount of time elapsed from another instant to this one,
302     /// or zero duration if that instant is later than this one.
303     ///
304     /// # Examples
305     ///
306     /// ```no_run
307     /// use std::time::{Duration, Instant};
308     /// use std::thread::sleep;
309     ///
310     /// let now = Instant::now();
311     /// sleep(Duration::new(1, 0));
312     /// let new_now = Instant::now();
313     /// println!("{:?}", new_now.saturating_duration_since(now));
314     /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
315     /// ```
316     #[stable(feature = "checked_duration_since", since = "1.39.0")]
317     pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
318         self.checked_duration_since(earlier).unwrap_or(Duration::new(0, 0))
319     }
320
321     /// Returns the amount of time elapsed since this instant was created.
322     ///
323     /// # Panics
324     ///
325     /// This function may panic if the current time is earlier than this
326     /// instant, which is something that can happen if an `Instant` is
327     /// produced synthetically.
328     ///
329     /// # Examples
330     ///
331     /// ```no_run
332     /// use std::thread::sleep;
333     /// use std::time::{Duration, Instant};
334     ///
335     /// let instant = Instant::now();
336     /// let three_secs = Duration::from_secs(3);
337     /// sleep(three_secs);
338     /// assert!(instant.elapsed() >= three_secs);
339     /// ```
340     #[stable(feature = "time2", since = "1.8.0")]
341     pub fn elapsed(&self) -> Duration {
342         Instant::now() - *self
343     }
344
345     /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
346     /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
347     /// otherwise.
348     #[stable(feature = "time_checked_add", since = "1.34.0")]
349     pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
350         self.0.checked_add_duration(&duration).map(Instant)
351     }
352
353     /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
354     /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
355     /// otherwise.
356     #[stable(feature = "time_checked_add", since = "1.34.0")]
357     pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
358         self.0.checked_sub_duration(&duration).map(Instant)
359     }
360 }
361
362 #[stable(feature = "time2", since = "1.8.0")]
363 impl Add<Duration> for Instant {
364     type Output = Instant;
365
366     /// # Panics
367     ///
368     /// This function may panic if the resulting point in time cannot be represented by the
369     /// underlying data structure. See [`checked_add`] for a version without panic.
370     ///
371     /// [`checked_add`]: ../../std/time/struct.Instant.html#method.checked_add
372     fn add(self, other: Duration) -> Instant {
373         self.checked_add(other).expect("overflow when adding duration to instant")
374     }
375 }
376
377 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
378 impl AddAssign<Duration> for Instant {
379     fn add_assign(&mut self, other: Duration) {
380         *self = *self + other;
381     }
382 }
383
384 #[stable(feature = "time2", since = "1.8.0")]
385 impl Sub<Duration> for Instant {
386     type Output = Instant;
387
388     fn sub(self, other: Duration) -> Instant {
389         self.checked_sub(other).expect("overflow when subtracting duration from instant")
390     }
391 }
392
393 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
394 impl SubAssign<Duration> for Instant {
395     fn sub_assign(&mut self, other: Duration) {
396         *self = *self - other;
397     }
398 }
399
400 #[stable(feature = "time2", since = "1.8.0")]
401 impl Sub<Instant> for Instant {
402     type Output = Duration;
403
404     fn sub(self, other: Instant) -> Duration {
405         self.duration_since(other)
406     }
407 }
408
409 #[stable(feature = "time2", since = "1.8.0")]
410 impl fmt::Debug for Instant {
411     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
412         self.0.fmt(f)
413     }
414 }
415
416 impl SystemTime {
417     /// An anchor in time which can be used to create new `SystemTime` instances or
418     /// learn about where in time a `SystemTime` lies.
419     ///
420     /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
421     /// respect to the system clock. Using `duration_since` on an existing
422     /// `SystemTime` instance can tell how far away from this point in time a
423     /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
424     /// `SystemTime` instance to represent another fixed point in time.
425     ///
426     /// # Examples
427     ///
428     /// ```no_run
429     /// use std::time::SystemTime;
430     ///
431     /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
432     ///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
433     ///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
434     /// }
435     /// ```
436     #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
437     pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
438
439     /// Returns the system time corresponding to "now".
440     ///
441     /// # Examples
442     ///
443     /// ```
444     /// use std::time::SystemTime;
445     ///
446     /// let sys_time = SystemTime::now();
447     /// ```
448     #[stable(feature = "time2", since = "1.8.0")]
449     pub fn now() -> SystemTime {
450         SystemTime(time::SystemTime::now())
451     }
452
453     /// Returns the amount of time elapsed from an earlier point in time.
454     ///
455     /// This function may fail because measurements taken earlier are not
456     /// guaranteed to always be before later measurements (due to anomalies such
457     /// as the system clock being adjusted either forwards or backwards).
458     /// [`Instant`] can be used to measure elapsed time without this risk of failure.
459     ///
460     /// If successful, [`Ok`]`(`[`Duration`]`)` is returned where the duration represents
461     /// the amount of time elapsed from the specified measurement to this one.
462     ///
463     /// Returns an [`Err`] if `earlier` is later than `self`, and the error
464     /// contains how far from `self` the time is.
465     ///
466     /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
467     /// [`Duration`]: ../../std/time/struct.Duration.html
468     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
469     /// [`Instant`]: ../../std/time/struct.Instant.html
470     ///
471     /// # Examples
472     ///
473     /// ```
474     /// use std::time::SystemTime;
475     ///
476     /// let sys_time = SystemTime::now();
477     /// let difference = sys_time.duration_since(sys_time)
478     ///                          .expect("Clock may have gone backwards");
479     /// println!("{:?}", difference);
480     /// ```
481     #[stable(feature = "time2", since = "1.8.0")]
482     pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> {
483         self.0.sub_time(&earlier.0).map_err(SystemTimeError)
484     }
485
486     /// Returns the difference between the clock time when this
487     /// system time was created, and the current clock time.
488     ///
489     /// This function may fail as the underlying system clock is susceptible to
490     /// drift and updates (e.g., the system clock could go backwards), so this
491     /// function may not always succeed. If successful, [`Ok`]`(`[`Duration`]`)` is
492     /// returned where the duration represents the amount of time elapsed from
493     /// this time measurement to the current time.
494     ///
495     /// To measure elapsed time reliably, use [`Instant`] instead.
496     ///
497     /// Returns an [`Err`] if `self` is later than the current system time, and
498     /// the error contains how far from the current system time `self` is.
499     ///
500     /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
501     /// [`Duration`]: ../../std/time/struct.Duration.html
502     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
503     /// [`Instant`]: ../../std/time/struct.Instant.html
504     ///
505     /// # Examples
506     ///
507     /// ```no_run
508     /// use std::thread::sleep;
509     /// use std::time::{Duration, SystemTime};
510     ///
511     /// let sys_time = SystemTime::now();
512     /// let one_sec = Duration::from_secs(1);
513     /// sleep(one_sec);
514     /// assert!(sys_time.elapsed().unwrap() >= one_sec);
515     /// ```
516     #[stable(feature = "time2", since = "1.8.0")]
517     pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
518         SystemTime::now().duration_since(*self)
519     }
520
521     /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
522     /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
523     /// otherwise.
524     #[stable(feature = "time_checked_add", since = "1.34.0")]
525     pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
526         self.0.checked_add_duration(&duration).map(SystemTime)
527     }
528
529     /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
530     /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
531     /// otherwise.
532     #[stable(feature = "time_checked_add", since = "1.34.0")]
533     pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
534         self.0.checked_sub_duration(&duration).map(SystemTime)
535     }
536 }
537
538 #[stable(feature = "time2", since = "1.8.0")]
539 impl Add<Duration> for SystemTime {
540     type Output = SystemTime;
541
542     /// # Panics
543     ///
544     /// This function may panic if the resulting point in time cannot be represented by the
545     /// underlying data structure. See [`checked_add`] for a version without panic.
546     ///
547     /// [`checked_add`]: ../../std/time/struct.SystemTime.html#method.checked_add
548     fn add(self, dur: Duration) -> SystemTime {
549         self.checked_add(dur).expect("overflow when adding duration to instant")
550     }
551 }
552
553 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
554 impl AddAssign<Duration> for SystemTime {
555     fn add_assign(&mut self, other: Duration) {
556         *self = *self + other;
557     }
558 }
559
560 #[stable(feature = "time2", since = "1.8.0")]
561 impl Sub<Duration> for SystemTime {
562     type Output = SystemTime;
563
564     fn sub(self, dur: Duration) -> SystemTime {
565         self.checked_sub(dur).expect("overflow when subtracting duration from instant")
566     }
567 }
568
569 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
570 impl SubAssign<Duration> for SystemTime {
571     fn sub_assign(&mut self, other: Duration) {
572         *self = *self - other;
573     }
574 }
575
576 #[stable(feature = "time2", since = "1.8.0")]
577 impl fmt::Debug for SystemTime {
578     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
579         self.0.fmt(f)
580     }
581 }
582
583 /// An anchor in time which can be used to create new `SystemTime` instances or
584 /// learn about where in time a `SystemTime` lies.
585 ///
586 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
587 /// respect to the system clock. Using `duration_since` on an existing
588 /// [`SystemTime`] instance can tell how far away from this point in time a
589 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
590 /// [`SystemTime`] instance to represent another fixed point in time.
591 ///
592 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
593 ///
594 /// # Examples
595 ///
596 /// ```no_run
597 /// use std::time::{SystemTime, UNIX_EPOCH};
598 ///
599 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
600 ///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
601 ///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
602 /// }
603 /// ```
604 #[stable(feature = "time2", since = "1.8.0")]
605 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
606
607 impl SystemTimeError {
608     /// Returns the positive duration which represents how far forward the
609     /// second system time was from the first.
610     ///
611     /// A `SystemTimeError` is returned from the [`duration_since`] and [`elapsed`]
612     /// methods of [`SystemTime`] whenever the second system time represents a point later
613     /// in time than the `self` of the method call.
614     ///
615     /// [`duration_since`]: ../../std/time/struct.SystemTime.html#method.duration_since
616     /// [`elapsed`]: ../../std/time/struct.SystemTime.html#method.elapsed
617     /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
618     ///
619     /// # Examples
620     ///
621     /// ```no_run
622     /// use std::thread::sleep;
623     /// use std::time::{Duration, SystemTime};
624     ///
625     /// let sys_time = SystemTime::now();
626     /// sleep(Duration::from_secs(1));
627     /// let new_sys_time = SystemTime::now();
628     /// match sys_time.duration_since(new_sys_time) {
629     ///     Ok(_) => {}
630     ///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
631     /// }
632     /// ```
633     #[stable(feature = "time2", since = "1.8.0")]
634     pub fn duration(&self) -> Duration {
635         self.0
636     }
637 }
638
639 #[stable(feature = "time2", since = "1.8.0")]
640 impl Error for SystemTimeError {
641     #[allow(deprecated)]
642     fn description(&self) -> &str {
643         "other time was not earlier than self"
644     }
645 }
646
647 #[stable(feature = "time2", since = "1.8.0")]
648 impl fmt::Display for SystemTimeError {
649     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
650         write!(f, "second time provided was later than self")
651     }
652 }
653
654 impl FromInner<time::SystemTime> for SystemTime {
655     fn from_inner(time: time::SystemTime) -> SystemTime {
656         SystemTime(time)
657     }
658 }
659
660 #[cfg(test)]
661 mod tests {
662     use super::{Duration, Instant, SystemTime, UNIX_EPOCH};
663
664     macro_rules! assert_almost_eq {
665         ($a:expr, $b:expr) => {{
666             let (a, b) = ($a, $b);
667             if a != b {
668                 let (a, b) = if a > b { (a, b) } else { (b, a) };
669                 assert!(a - Duration::new(0, 1000) <= b, "{:?} is not almost equal to {:?}", a, b);
670             }
671         }};
672     }
673
674     #[test]
675     fn instant_monotonic() {
676         let a = Instant::now();
677         let b = Instant::now();
678         assert!(b >= a);
679     }
680
681     #[test]
682     fn instant_elapsed() {
683         let a = Instant::now();
684         a.elapsed();
685     }
686
687     #[test]
688     fn instant_math() {
689         let a = Instant::now();
690         let b = Instant::now();
691         println!("a: {:?}", a);
692         println!("b: {:?}", b);
693         let dur = b.duration_since(a);
694         println!("dur: {:?}", dur);
695         assert_almost_eq!(b - dur, a);
696         assert_almost_eq!(a + dur, b);
697
698         let second = Duration::new(1, 0);
699         assert_almost_eq!(a - second + second, a);
700         assert_almost_eq!(a.checked_sub(second).unwrap().checked_add(second).unwrap(), a);
701
702         // checked_add_duration will not panic on overflow
703         let mut maybe_t = Some(Instant::now());
704         let max_duration = Duration::from_secs(u64::max_value());
705         // in case `Instant` can store `>= now + max_duration`.
706         for _ in 0..2 {
707             maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration));
708         }
709         assert_eq!(maybe_t, None);
710
711         // checked_add_duration calculates the right time and will work for another year
712         let year = Duration::from_secs(60 * 60 * 24 * 365);
713         assert_eq!(a + year, a.checked_add(year).unwrap());
714     }
715
716     #[test]
717     fn instant_math_is_associative() {
718         let now = Instant::now();
719         let offset = Duration::from_millis(5);
720         // Changing the order of instant math shouldn't change the results,
721         // especially when the expression reduces to X + identity.
722         assert_eq!((now + offset) - now, (now - now) + offset);
723     }
724
725     #[test]
726     #[should_panic]
727     fn instant_duration_since_panic() {
728         let a = Instant::now();
729         (a - Duration::new(1, 0)).duration_since(a);
730     }
731
732     #[test]
733     fn instant_checked_duration_since_nopanic() {
734         let now = Instant::now();
735         let earlier = now - Duration::new(1, 0);
736         let later = now + Duration::new(1, 0);
737         assert_eq!(earlier.checked_duration_since(now), None);
738         assert_eq!(later.checked_duration_since(now), Some(Duration::new(1, 0)));
739         assert_eq!(now.checked_duration_since(now), Some(Duration::new(0, 0)));
740     }
741
742     #[test]
743     fn instant_saturating_duration_since_nopanic() {
744         let a = Instant::now();
745         let ret = (a - Duration::new(1, 0)).saturating_duration_since(a);
746         assert_eq!(ret, Duration::new(0, 0));
747     }
748
749     #[test]
750     fn system_time_math() {
751         let a = SystemTime::now();
752         let b = SystemTime::now();
753         match b.duration_since(a) {
754             Ok(dur) if dur == Duration::new(0, 0) => {
755                 assert_almost_eq!(a, b);
756             }
757             Ok(dur) => {
758                 assert!(b > a);
759                 assert_almost_eq!(b - dur, a);
760                 assert_almost_eq!(a + dur, b);
761             }
762             Err(dur) => {
763                 let dur = dur.duration();
764                 assert!(a > b);
765                 assert_almost_eq!(b + dur, a);
766                 assert_almost_eq!(a - dur, b);
767             }
768         }
769
770         let second = Duration::new(1, 0);
771         assert_almost_eq!(a.duration_since(a - second).unwrap(), second);
772         assert_almost_eq!(a.duration_since(a + second).unwrap_err().duration(), second);
773
774         assert_almost_eq!(a - second + second, a);
775         assert_almost_eq!(a.checked_sub(second).unwrap().checked_add(second).unwrap(), a);
776
777         let one_second_from_epoch = UNIX_EPOCH + Duration::new(1, 0);
778         let one_second_from_epoch2 =
779             UNIX_EPOCH + Duration::new(0, 500_000_000) + Duration::new(0, 500_000_000);
780         assert_eq!(one_second_from_epoch, one_second_from_epoch2);
781
782         // checked_add_duration will not panic on overflow
783         let mut maybe_t = Some(SystemTime::UNIX_EPOCH);
784         let max_duration = Duration::from_secs(u64::max_value());
785         // in case `SystemTime` can store `>= UNIX_EPOCH + max_duration`.
786         for _ in 0..2 {
787             maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration));
788         }
789         assert_eq!(maybe_t, None);
790
791         // checked_add_duration calculates the right time and will work for another year
792         let year = Duration::from_secs(60 * 60 * 24 * 365);
793         assert_eq!(a + year, a.checked_add(year).unwrap());
794     }
795
796     #[test]
797     fn system_time_elapsed() {
798         let a = SystemTime::now();
799         drop(a.elapsed());
800     }
801
802     #[test]
803     fn since_epoch() {
804         let ts = SystemTime::now();
805         let a = ts.duration_since(UNIX_EPOCH + Duration::new(1, 0)).unwrap();
806         let b = ts.duration_since(UNIX_EPOCH).unwrap();
807         assert!(b > a);
808         assert_eq!(b - a, Duration::new(1, 0));
809
810         let thirty_years = Duration::new(1, 0) * 60 * 60 * 24 * 365 * 30;
811
812         // Right now for CI this test is run in an emulator, and apparently the
813         // aarch64 emulator's sense of time is that we're still living in the
814         // 70s.
815         //
816         // Otherwise let's assume that we're all running computers later than
817         // 2000.
818         if !cfg!(target_arch = "aarch64") {
819             assert!(a > thirty_years);
820         }
821
822         // let's assume that we're all running computers earlier than 2090.
823         // Should give us ~70 years to fix this!
824         let hundred_twenty_years = thirty_years * 4;
825         assert!(a < hundred_twenty_years);
826     }
827 }