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