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