]> git.lizzy.rs Git - rust.git/blob - src/libstd/time.rs
Rollup merge of #55838 - dralley:fix-cfg-step, r=Kimundi
[rust.git] / src / libstd / time.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Temporal quantification.
12 //!
13 //! Example:
14 //!
15 //! ```
16 //! use std::time::Duration;
17 //!
18 //! let five_seconds = Duration::new(5, 0);
19 //! // both declarations are equivalent
20 //! assert_eq!(Duration::new(5, 0), Duration::from_secs(5));
21 //! ```
22
23 #![stable(feature = "time", since = "1.3.0")]
24
25 use error::Error;
26 use fmt;
27 use ops::{Add, Sub, AddAssign, SubAssign};
28 use sys::time;
29 use sys_common::FromInner;
30
31 #[stable(feature = "time", since = "1.3.0")]
32 pub use core::time::Duration;
33
34 /// A measurement of a monotonically nondecreasing clock.
35 /// Opaque and useful only with `Duration`.
36 ///
37 /// Instants are always guaranteed to be no less than any previously measured
38 /// instant when created, and are often useful for tasks such as measuring
39 /// benchmarks or timing how long an operation takes.
40 ///
41 /// Note, however, that instants are not guaranteed to be **steady**.  In other
42 /// words, each tick of the underlying clock may not be the same length (e.g.
43 /// some seconds may be longer than others). An instant may jump forwards or
44 /// experience time dilation (slow down or speed up), but it will never go
45 /// backwards.
46 ///
47 /// Instants are opaque types that can only be compared to one another. There is
48 /// no method to get "the number of seconds" from an instant. Instead, it only
49 /// allows measuring the duration between two instants (or comparing two
50 /// instants).
51 ///
52 /// The size of an `Instant` struct may vary depending on the target operating
53 /// system.
54 ///
55 /// Example:
56 ///
57 /// ```no_run
58 /// use std::time::{Duration, Instant};
59 /// use std::thread::sleep;
60 ///
61 /// fn main() {
62 ///    let now = Instant::now();
63 ///
64 ///    // we sleep for 2 seconds
65 ///    sleep(Duration::new(2, 0));
66 ///    // it prints '2'
67 ///    println!("{}", now.elapsed().as_secs());
68 /// }
69 /// ```
70 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
71 #[stable(feature = "time2", since = "1.8.0")]
72 pub struct Instant(time::Instant);
73
74 /// A measurement of the system clock, useful for talking to
75 /// external entities like the file system or other processes.
76 ///
77 /// Distinct from the [`Instant`] type, this time measurement **is not
78 /// monotonic**. This means that you can save a file to the file system, then
79 /// save another file to the file system, **and the second file has a
80 /// `SystemTime` measurement earlier than the first**. In other words, an
81 /// operation that happens after another operation in real time may have an
82 /// earlier `SystemTime`!
83 ///
84 /// Consequently, comparing two `SystemTime` instances to learn about the
85 /// duration between them returns a [`Result`] instead of an infallible [`Duration`]
86 /// to indicate that this sort of time drift may happen and needs to be handled.
87 ///
88 /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
89 /// constant is provided in this module as an anchor in time to learn
90 /// information about a `SystemTime`. By calculating the duration from this
91 /// fixed point in time, a `SystemTime` can be converted to a human-readable time,
92 /// or perhaps some other string representation.
93 ///
94 /// The size of a `SystemTime` struct may vary depending on the target operating
95 /// system.
96 ///
97 /// [`Instant`]: ../../std/time/struct.Instant.html
98 /// [`Result`]: ../../std/result/enum.Result.html
99 /// [`Duration`]: ../../std/time/struct.Duration.html
100 /// [`UNIX_EPOCH`]: ../../std/time/constant.UNIX_EPOCH.html
101 ///
102 /// Example:
103 ///
104 /// ```no_run
105 /// use std::time::{Duration, SystemTime};
106 /// use std::thread::sleep;
107 ///
108 /// fn main() {
109 ///    let now = SystemTime::now();
110 ///
111 ///    // we sleep for 2 seconds
112 ///    sleep(Duration::new(2, 0));
113 ///    match now.elapsed() {
114 ///        Ok(elapsed) => {
115 ///            // it prints '2'
116 ///            println!("{}", elapsed.as_secs());
117 ///        }
118 ///        Err(e) => {
119 ///            // an error occurred!
120 ///            println!("Error: {:?}", e);
121 ///        }
122 ///    }
123 /// }
124 /// ```
125 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
126 #[stable(feature = "time2", since = "1.8.0")]
127 pub struct SystemTime(time::SystemTime);
128
129 /// An error returned from the `duration_since` and `elapsed` methods on
130 /// `SystemTime`, used to learn how far in the opposite direction a system time
131 /// lies.
132 ///
133 /// # Examples
134 ///
135 /// ```no_run
136 /// use std::thread::sleep;
137 /// use std::time::{Duration, SystemTime};
138 ///
139 /// let sys_time = SystemTime::now();
140 /// sleep(Duration::from_secs(1));
141 /// let new_sys_time = SystemTime::now();
142 /// match sys_time.duration_since(new_sys_time) {
143 ///     Ok(_) => {}
144 ///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
145 /// }
146 /// ```
147 #[derive(Clone, Debug)]
148 #[stable(feature = "time2", since = "1.8.0")]
149 pub struct SystemTimeError(Duration);
150
151 impl Instant {
152     /// Returns an instant corresponding to "now".
153     ///
154     /// # Examples
155     ///
156     /// ```
157     /// use std::time::Instant;
158     ///
159     /// let now = Instant::now();
160     /// ```
161     #[stable(feature = "time2", since = "1.8.0")]
162     pub fn now() -> Instant {
163         Instant(time::Instant::now())
164     }
165
166     /// Returns the amount of time elapsed from another instant to this one.
167     ///
168     /// # Panics
169     ///
170     /// This function will panic if `earlier` is later than `self`.
171     ///
172     /// # Examples
173     ///
174     /// ```no_run
175     /// use std::time::{Duration, Instant};
176     /// use std::thread::sleep;
177     ///
178     /// let now = Instant::now();
179     /// sleep(Duration::new(1, 0));
180     /// let new_now = Instant::now();
181     /// println!("{:?}", new_now.duration_since(now));
182     /// ```
183     #[stable(feature = "time2", since = "1.8.0")]
184     pub fn duration_since(&self, earlier: Instant) -> Duration {
185         self.0.sub_instant(&earlier.0)
186     }
187
188     /// Returns the amount of time elapsed since this instant was created.
189     ///
190     /// # Panics
191     ///
192     /// This function may panic if the current time is earlier than this
193     /// instant, which is something that can happen if an `Instant` is
194     /// produced synthetically.
195     ///
196     /// # Examples
197     ///
198     /// ```no_run
199     /// use std::thread::sleep;
200     /// use std::time::{Duration, Instant};
201     ///
202     /// let instant = Instant::now();
203     /// let three_secs = Duration::from_secs(3);
204     /// sleep(three_secs);
205     /// assert!(instant.elapsed() >= three_secs);
206     /// ```
207     #[stable(feature = "time2", since = "1.8.0")]
208     pub fn elapsed(&self) -> Duration {
209         Instant::now() - *self
210     }
211 }
212
213 #[stable(feature = "time2", since = "1.8.0")]
214 impl Add<Duration> for Instant {
215     type Output = Instant;
216
217     fn add(self, other: Duration) -> Instant {
218         Instant(self.0.add_duration(&other))
219     }
220 }
221
222 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
223 impl AddAssign<Duration> for Instant {
224     fn add_assign(&mut self, other: Duration) {
225         *self = *self + other;
226     }
227 }
228
229 #[stable(feature = "time2", since = "1.8.0")]
230 impl Sub<Duration> for Instant {
231     type Output = Instant;
232
233     fn sub(self, other: Duration) -> Instant {
234         Instant(self.0.sub_duration(&other))
235     }
236 }
237
238 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
239 impl SubAssign<Duration> for Instant {
240     fn sub_assign(&mut self, other: Duration) {
241         *self = *self - other;
242     }
243 }
244
245 #[stable(feature = "time2", since = "1.8.0")]
246 impl Sub<Instant> for Instant {
247     type Output = Duration;
248
249     fn sub(self, other: Instant) -> Duration {
250         self.duration_since(other)
251     }
252 }
253
254 #[stable(feature = "time2", since = "1.8.0")]
255 impl fmt::Debug for Instant {
256     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
257         self.0.fmt(f)
258     }
259 }
260
261 impl SystemTime {
262     /// An anchor in time which can be used to create new `SystemTime` instances or
263     /// learn about where in time a `SystemTime` lies.
264     ///
265     /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
266     /// respect to the system clock. Using `duration_since` on an existing
267     /// `SystemTime` instance can tell how far away from this point in time a
268     /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
269     /// `SystemTime` instance to represent another fixed point in time.
270     ///
271     /// # Examples
272     ///
273     /// ```no_run
274     /// use std::time::SystemTime;
275     ///
276     /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
277     ///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
278     ///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
279     /// }
280     /// ```
281     #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
282     pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
283
284     /// Returns the system time corresponding to "now".
285     ///
286     /// # Examples
287     ///
288     /// ```
289     /// use std::time::SystemTime;
290     ///
291     /// let sys_time = SystemTime::now();
292     /// ```
293     #[stable(feature = "time2", since = "1.8.0")]
294     pub fn now() -> SystemTime {
295         SystemTime(time::SystemTime::now())
296     }
297
298     /// Returns the amount of time elapsed from an earlier point in time.
299     ///
300     /// This function may fail because measurements taken earlier are not
301     /// guaranteed to always be before later measurements (due to anomalies such
302     /// as the system clock being adjusted either forwards or backwards).
303     ///
304     /// If successful, [`Ok`]`(`[`Duration`]`)` is returned where the duration represents
305     /// the amount of time elapsed from the specified measurement to this one.
306     ///
307     /// Returns an [`Err`] if `earlier` is later than `self`, and the error
308     /// contains how far from `self` the time is.
309     ///
310     /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
311     /// [`Duration`]: ../../std/time/struct.Duration.html
312     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
313     ///
314     /// # Examples
315     ///
316     /// ```
317     /// use std::time::SystemTime;
318     ///
319     /// let sys_time = SystemTime::now();
320     /// let difference = sys_time.duration_since(sys_time)
321     ///                          .expect("SystemTime::duration_since failed");
322     /// println!("{:?}", difference);
323     /// ```
324     #[stable(feature = "time2", since = "1.8.0")]
325     pub fn duration_since(&self, earlier: SystemTime)
326                           -> Result<Duration, SystemTimeError> {
327         self.0.sub_time(&earlier.0).map_err(SystemTimeError)
328     }
329
330     /// Returns the amount of time elapsed since this system time was created.
331     ///
332     /// This function may fail as the underlying system clock is susceptible to
333     /// drift and updates (e.g. the system clock could go backwards), so this
334     /// function may not always succeed. If successful, [`Ok`]`(`[`Duration`]`)` is
335     /// returned where the duration represents the amount of time elapsed from
336     /// this time measurement to the current time.
337     ///
338     /// Returns an [`Err`] if `self` is later than the current system time, and
339     /// the error contains how far from the current system time `self` is.
340     ///
341     /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
342     /// [`Duration`]: ../../std/time/struct.Duration.html
343     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
344     ///
345     /// # Examples
346     ///
347     /// ```no_run
348     /// use std::thread::sleep;
349     /// use std::time::{Duration, SystemTime};
350     ///
351     /// let sys_time = SystemTime::now();
352     /// let one_sec = Duration::from_secs(1);
353     /// sleep(one_sec);
354     /// assert!(sys_time.elapsed().unwrap() >= one_sec);
355     /// ```
356     #[stable(feature = "time2", since = "1.8.0")]
357     pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
358         SystemTime::now().duration_since(*self)
359     }
360 }
361
362 #[stable(feature = "time2", since = "1.8.0")]
363 impl Add<Duration> for SystemTime {
364     type Output = SystemTime;
365
366     fn add(self, dur: Duration) -> SystemTime {
367         SystemTime(self.0.add_duration(&dur))
368     }
369 }
370
371 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
372 impl AddAssign<Duration> for SystemTime {
373     fn add_assign(&mut self, other: Duration) {
374         *self = *self + other;
375     }
376 }
377
378 #[stable(feature = "time2", since = "1.8.0")]
379 impl Sub<Duration> for SystemTime {
380     type Output = SystemTime;
381
382     fn sub(self, dur: Duration) -> SystemTime {
383         SystemTime(self.0.sub_duration(&dur))
384     }
385 }
386
387 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
388 impl SubAssign<Duration> for SystemTime {
389     fn sub_assign(&mut self, other: Duration) {
390         *self = *self - other;
391     }
392 }
393
394 #[stable(feature = "time2", since = "1.8.0")]
395 impl fmt::Debug for SystemTime {
396     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
397         self.0.fmt(f)
398     }
399 }
400
401 /// An anchor in time which can be used to create new `SystemTime` instances or
402 /// learn about where in time a `SystemTime` lies.
403 ///
404 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
405 /// respect to the system clock. Using `duration_since` on an existing
406 /// [`SystemTime`] instance can tell how far away from this point in time a
407 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
408 /// [`SystemTime`] instance to represent another fixed point in time.
409 ///
410 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
411 ///
412 /// # Examples
413 ///
414 /// ```no_run
415 /// use std::time::{SystemTime, UNIX_EPOCH};
416 ///
417 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
418 ///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
419 ///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
420 /// }
421 /// ```
422 #[stable(feature = "time2", since = "1.8.0")]
423 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
424
425 impl SystemTimeError {
426     /// Returns the positive duration which represents how far forward the
427     /// second system time was from the first.
428     ///
429     /// A `SystemTimeError` is returned from the [`duration_since`] and [`elapsed`]
430     /// methods of [`SystemTime`] whenever the second system time represents a point later
431     /// in time than the `self` of the method call.
432     ///
433     /// [`duration_since`]: ../../std/time/struct.SystemTime.html#method.duration_since
434     /// [`elapsed`]: ../../std/time/struct.SystemTime.html#method.elapsed
435     /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
436     ///
437     /// # Examples
438     ///
439     /// ```no_run
440     /// use std::thread::sleep;
441     /// use std::time::{Duration, SystemTime};
442     ///
443     /// let sys_time = SystemTime::now();
444     /// sleep(Duration::from_secs(1));
445     /// let new_sys_time = SystemTime::now();
446     /// match sys_time.duration_since(new_sys_time) {
447     ///     Ok(_) => {}
448     ///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
449     /// }
450     /// ```
451     #[stable(feature = "time2", since = "1.8.0")]
452     pub fn duration(&self) -> Duration {
453         self.0
454     }
455 }
456
457 #[stable(feature = "time2", since = "1.8.0")]
458 impl Error for SystemTimeError {
459     fn description(&self) -> &str { "other time was not earlier than self" }
460 }
461
462 #[stable(feature = "time2", since = "1.8.0")]
463 impl fmt::Display for SystemTimeError {
464     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
465         write!(f, "second time provided was later than self")
466     }
467 }
468
469 impl FromInner<time::SystemTime> for SystemTime {
470     fn from_inner(time: time::SystemTime) -> SystemTime {
471         SystemTime(time)
472     }
473 }
474
475 #[cfg(test)]
476 mod tests {
477     use super::{Instant, SystemTime, Duration, UNIX_EPOCH};
478
479     macro_rules! assert_almost_eq {
480         ($a:expr, $b:expr) => ({
481             let (a, b) = ($a, $b);
482             if a != b {
483                 let (a, b) = if a > b {(a, b)} else {(b, a)};
484                 assert!(a - Duration::new(0, 1000) <= b,
485                         "{:?} is not almost equal to {:?}", a, b);
486             }
487         })
488     }
489
490     #[test]
491     fn instant_monotonic() {
492         let a = Instant::now();
493         let b = Instant::now();
494         assert!(b >= a);
495     }
496
497     #[test]
498     fn instant_elapsed() {
499         let a = Instant::now();
500         a.elapsed();
501     }
502
503     #[test]
504     fn instant_math() {
505         let a = Instant::now();
506         let b = Instant::now();
507         println!("a: {:?}", a);
508         println!("b: {:?}", b);
509         let dur = b.duration_since(a);
510         println!("dur: {:?}", dur);
511         assert_almost_eq!(b - dur, a);
512         assert_almost_eq!(a + dur, b);
513
514         let second = Duration::new(1, 0);
515         assert_almost_eq!(a - second + second, a);
516     }
517
518     #[test]
519     #[should_panic]
520     fn instant_duration_panic() {
521         let a = Instant::now();
522         (a - Duration::new(1, 0)).duration_since(a);
523     }
524
525     #[test]
526     fn system_time_math() {
527         let a = SystemTime::now();
528         let b = SystemTime::now();
529         match b.duration_since(a) {
530             Ok(dur) if dur == Duration::new(0, 0) => {
531                 assert_almost_eq!(a, b);
532             }
533             Ok(dur) => {
534                 assert!(b > a);
535                 assert_almost_eq!(b - dur, a);
536                 assert_almost_eq!(a + dur, b);
537             }
538             Err(dur) => {
539                 let dur = dur.duration();
540                 assert!(a > b);
541                 assert_almost_eq!(b + dur, a);
542                 assert_almost_eq!(a - dur, b);
543             }
544         }
545
546         let second = Duration::new(1, 0);
547         assert_almost_eq!(a.duration_since(a - second).unwrap(), second);
548         assert_almost_eq!(a.duration_since(a + second).unwrap_err()
549                            .duration(), second);
550
551         assert_almost_eq!(a - second + second, a);
552
553         // A difference of 80 and 800 years cannot fit inside a 32-bit time_t
554         if !(cfg!(unix) && ::mem::size_of::<::libc::time_t>() <= 4) {
555             let eighty_years = second * 60 * 60 * 24 * 365 * 80;
556             assert_almost_eq!(a - eighty_years + eighty_years, a);
557             assert_almost_eq!(a - (eighty_years * 10) + (eighty_years * 10), a);
558         }
559
560         let one_second_from_epoch = UNIX_EPOCH + Duration::new(1, 0);
561         let one_second_from_epoch2 = UNIX_EPOCH + Duration::new(0, 500_000_000)
562             + Duration::new(0, 500_000_000);
563         assert_eq!(one_second_from_epoch, one_second_from_epoch2);
564     }
565
566     #[test]
567     fn system_time_elapsed() {
568         let a = SystemTime::now();
569         drop(a.elapsed());
570     }
571
572     #[test]
573     fn since_epoch() {
574         let ts = SystemTime::now();
575         let a = ts.duration_since(UNIX_EPOCH).unwrap();
576         let b = ts.duration_since(UNIX_EPOCH - Duration::new(1, 0)).unwrap();
577         assert!(b > a);
578         assert_eq!(b - a, Duration::new(1, 0));
579
580         let thirty_years = Duration::new(1, 0) * 60 * 60 * 24 * 365 * 30;
581
582         // Right now for CI this test is run in an emulator, and apparently the
583         // aarch64 emulator's sense of time is that we're still living in the
584         // 70s.
585         //
586         // Otherwise let's assume that we're all running computers later than
587         // 2000.
588         if !cfg!(target_arch = "aarch64") {
589             assert!(a > thirty_years);
590         }
591
592         // let's assume that we're all running computers earlier than 2090.
593         // Should give us ~70 years to fix this!
594         let hundred_twenty_years = thirty_years * 4;
595         assert!(a < hundred_twenty_years);
596     }
597 }