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