]> git.lizzy.rs Git - rust.git/blob - src/libstd/time.rs
Various minor/cosmetic improvements to code
[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     /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
362     /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
363     /// otherwise.
364     #[unstable(feature = "time_checked_add", issue = "55940")]
365     pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
366         self.0.checked_add_duration(&duration).map(|t| SystemTime(t))
367     }
368 }
369
370 #[stable(feature = "time2", since = "1.8.0")]
371 impl Add<Duration> for SystemTime {
372     type Output = SystemTime;
373
374     fn add(self, dur: Duration) -> SystemTime {
375         SystemTime(self.0.add_duration(&dur))
376     }
377 }
378
379 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
380 impl AddAssign<Duration> for SystemTime {
381     fn add_assign(&mut self, other: Duration) {
382         *self = *self + other;
383     }
384 }
385
386 #[stable(feature = "time2", since = "1.8.0")]
387 impl Sub<Duration> for SystemTime {
388     type Output = SystemTime;
389
390     fn sub(self, dur: Duration) -> SystemTime {
391         SystemTime(self.0.sub_duration(&dur))
392     }
393 }
394
395 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
396 impl SubAssign<Duration> for SystemTime {
397     fn sub_assign(&mut self, other: Duration) {
398         *self = *self - other;
399     }
400 }
401
402 #[stable(feature = "time2", since = "1.8.0")]
403 impl fmt::Debug for SystemTime {
404     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
405         self.0.fmt(f)
406     }
407 }
408
409 /// An anchor in time which can be used to create new `SystemTime` instances or
410 /// learn about where in time a `SystemTime` lies.
411 ///
412 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
413 /// respect to the system clock. Using `duration_since` on an existing
414 /// [`SystemTime`] instance can tell how far away from this point in time a
415 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
416 /// [`SystemTime`] instance to represent another fixed point in time.
417 ///
418 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
419 ///
420 /// # Examples
421 ///
422 /// ```no_run
423 /// use std::time::{SystemTime, UNIX_EPOCH};
424 ///
425 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
426 ///     Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
427 ///     Err(_) => panic!("SystemTime before UNIX EPOCH!"),
428 /// }
429 /// ```
430 #[stable(feature = "time2", since = "1.8.0")]
431 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
432
433 impl SystemTimeError {
434     /// Returns the positive duration which represents how far forward the
435     /// second system time was from the first.
436     ///
437     /// A `SystemTimeError` is returned from the [`duration_since`] and [`elapsed`]
438     /// methods of [`SystemTime`] whenever the second system time represents a point later
439     /// in time than the `self` of the method call.
440     ///
441     /// [`duration_since`]: ../../std/time/struct.SystemTime.html#method.duration_since
442     /// [`elapsed`]: ../../std/time/struct.SystemTime.html#method.elapsed
443     /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
444     ///
445     /// # Examples
446     ///
447     /// ```no_run
448     /// use std::thread::sleep;
449     /// use std::time::{Duration, SystemTime};
450     ///
451     /// let sys_time = SystemTime::now();
452     /// sleep(Duration::from_secs(1));
453     /// let new_sys_time = SystemTime::now();
454     /// match sys_time.duration_since(new_sys_time) {
455     ///     Ok(_) => {}
456     ///     Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
457     /// }
458     /// ```
459     #[stable(feature = "time2", since = "1.8.0")]
460     pub fn duration(&self) -> Duration {
461         self.0
462     }
463 }
464
465 #[stable(feature = "time2", since = "1.8.0")]
466 impl Error for SystemTimeError {
467     fn description(&self) -> &str { "other time was not earlier than self" }
468 }
469
470 #[stable(feature = "time2", since = "1.8.0")]
471 impl fmt::Display for SystemTimeError {
472     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
473         write!(f, "second time provided was later than self")
474     }
475 }
476
477 impl FromInner<time::SystemTime> for SystemTime {
478     fn from_inner(time: time::SystemTime) -> SystemTime {
479         SystemTime(time)
480     }
481 }
482
483 #[cfg(test)]
484 mod tests {
485     use super::{Instant, SystemTime, Duration, UNIX_EPOCH};
486
487     macro_rules! assert_almost_eq {
488         ($a:expr, $b:expr) => ({
489             let (a, b) = ($a, $b);
490             if a != b {
491                 let (a, b) = if a > b {(a, b)} else {(b, a)};
492                 assert!(a - Duration::new(0, 1000) <= b,
493                         "{:?} is not almost equal to {:?}", a, b);
494             }
495         })
496     }
497
498     #[test]
499     fn instant_monotonic() {
500         let a = Instant::now();
501         let b = Instant::now();
502         assert!(b >= a);
503     }
504
505     #[test]
506     fn instant_elapsed() {
507         let a = Instant::now();
508         a.elapsed();
509     }
510
511     #[test]
512     fn instant_math() {
513         let a = Instant::now();
514         let b = Instant::now();
515         println!("a: {:?}", a);
516         println!("b: {:?}", b);
517         let dur = b.duration_since(a);
518         println!("dur: {:?}", dur);
519         assert_almost_eq!(b - dur, a);
520         assert_almost_eq!(a + dur, b);
521
522         let second = Duration::new(1, 0);
523         assert_almost_eq!(a - second + second, a);
524     }
525
526     #[test]
527     #[should_panic]
528     fn instant_duration_panic() {
529         let a = Instant::now();
530         (a - Duration::new(1, 0)).duration_since(a);
531     }
532
533     #[test]
534     fn system_time_math() {
535         let a = SystemTime::now();
536         let b = SystemTime::now();
537         match b.duration_since(a) {
538             Ok(dur) if dur == Duration::new(0, 0) => {
539                 assert_almost_eq!(a, b);
540             }
541             Ok(dur) => {
542                 assert!(b > a);
543                 assert_almost_eq!(b - dur, a);
544                 assert_almost_eq!(a + dur, b);
545             }
546             Err(dur) => {
547                 let dur = dur.duration();
548                 assert!(a > b);
549                 assert_almost_eq!(b + dur, a);
550                 assert_almost_eq!(a - dur, b);
551             }
552         }
553
554         let second = Duration::new(1, 0);
555         assert_almost_eq!(a.duration_since(a - second).unwrap(), second);
556         assert_almost_eq!(a.duration_since(a + second).unwrap_err()
557                            .duration(), second);
558
559         assert_almost_eq!(a - second + second, a);
560
561         // A difference of 80 and 800 years cannot fit inside a 32-bit time_t
562         if !(cfg!(unix) && ::mem::size_of::<::libc::time_t>() <= 4) {
563             let eighty_years = second * 60 * 60 * 24 * 365 * 80;
564             assert_almost_eq!(a - eighty_years + eighty_years, a);
565             assert_almost_eq!(a - (eighty_years * 10) + (eighty_years * 10), a);
566         }
567
568         let one_second_from_epoch = UNIX_EPOCH + Duration::new(1, 0);
569         let one_second_from_epoch2 = UNIX_EPOCH + Duration::new(0, 500_000_000)
570             + Duration::new(0, 500_000_000);
571         assert_eq!(one_second_from_epoch, one_second_from_epoch2);
572
573         // checked_add_duration will not panic on overflow
574         let mut maybe_t = Some(SystemTime::UNIX_EPOCH);
575         let max_duration = Duration::from_secs(u64::max_value());
576         // in case `SystemTime` can store `>= UNIX_EPOCH + max_duration`.
577         for _ in 0..2 {
578             maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration));
579         }
580         assert_eq!(maybe_t, None);
581
582         // checked_add_duration calculates the right time and will work for another year
583         let year = Duration::from_secs(60 * 60 * 24 * 365);
584         assert_eq!(a + year, a.checked_add(year).unwrap());
585     }
586
587     #[test]
588     fn system_time_elapsed() {
589         let a = SystemTime::now();
590         drop(a.elapsed());
591     }
592
593     #[test]
594     fn since_epoch() {
595         let ts = SystemTime::now();
596         let a = ts.duration_since(UNIX_EPOCH).unwrap();
597         let b = ts.duration_since(UNIX_EPOCH - Duration::new(1, 0)).unwrap();
598         assert!(b > a);
599         assert_eq!(b - a, Duration::new(1, 0));
600
601         let thirty_years = Duration::new(1, 0) * 60 * 60 * 24 * 365 * 30;
602
603         // Right now for CI this test is run in an emulator, and apparently the
604         // aarch64 emulator's sense of time is that we're still living in the
605         // 70s.
606         //
607         // Otherwise let's assume that we're all running computers later than
608         // 2000.
609         if !cfg!(target_arch = "aarch64") {
610             assert!(a > thirty_years);
611         }
612
613         // let's assume that we're all running computers earlier than 2090.
614         // Should give us ~70 years to fix this!
615         let hundred_twenty_years = thirty_years * 4;
616         assert!(a < hundred_twenty_years);
617     }
618 }