Debian Codegraph @

third_party/rust/time-0.1.45/src/lib.rs

raw
1 // Copyright 2012-2013 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 //! Simple time handling.
12 //!
13 //! # Usage
14 //!
15 //! This crate is [on crates.io](https://crates.io/crates/time) and can be
16 //! used by adding `time` to the dependencies in your project's `Cargo.toml`.
17 //!
18 //! ```toml
19 //! [dependencies]
20 //! time = "0.1"
21 //! ```
22 //!
23 //! And this in your crate root:
24 //!
25 //! ```rust
26 //! extern crate time;
27 //! ```
28 //!
29 //! This crate uses the same syntax for format strings as the
30 //! [`strftime()`](http://man7.org/linux/man-pages/man3/strftime.3.html)
31 //! function from the C standard library.
32
33 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
34 html_favicon_url = "https://www.rust-lang.org/favicon.ico",
35 html_root_url = "https://doc.rust-lang.org/time/")]
36 #![allow(unknown_lints)]
37 #![allow(ellipsis_inclusive_range_patterns)] // `..=` requires Rust 1.26
38 #![allow(trivial_numeric_casts)]
39
40 #[cfg(unix)] extern crate libc;
41 #[cfg(windows)] extern crate winapi;
42 #[cfg(feature = "rustc-serialize")] extern crate rustc_serialize;
43
44 #[cfg(target_os = "wasi")] extern crate wasi;
45
46 #[cfg(test)] #[macro_use] extern crate log;
47
48 use std::cmp::Ordering;
49 use std::error::Error;
50 use std::fmt;
51 use std::ops::{Add, Sub};
52
53 pub use duration::{Duration, OutOfRangeError};
54
55 use self::ParseError::{InvalidDay, InvalidDayOfMonth, InvalidDayOfWeek,
56 InvalidDayOfYear, InvalidFormatSpecifier, InvalidHour,
57 InvalidMinute, InvalidMonth, InvalidSecond, InvalidTime,
58 InvalidYear, InvalidZoneOffset, InvalidSecondsSinceEpoch,
59 MissingFormatConverter, UnexpectedCharacter};
60
61 pub use parse::strptime;
62
63 mod display;
64 mod duration;
65 mod parse;
66 mod sys;
67
68 static NSEC_PER_SEC: i32 = 1_000_000_000;
69
70 /// A record specifying a time value in seconds and nanoseconds, where
71 /// nanoseconds represent the offset from the given second.
72 ///
73 /// For example a timespec of 1.2 seconds after the beginning of the epoch would
74 /// be represented as {sec: 1, nsec: 200000000}.
75 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
76 #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
77 pub struct Timespec { pub sec: i64, pub nsec: i32 }
78 /*
79 * Timespec assumes that pre-epoch Timespecs have negative sec and positive
80 * nsec fields. Darwin's and Linux's struct timespec functions handle pre-
81 * epoch timestamps using a "two steps back, one step forward" representation,
82 * though the man pages do not actually document this. For example, the time
83 * -1.2 seconds before the epoch is represented by `Timespec { sec: -2_i64,
84 * nsec: 800_000_000 }`.
85 */
86 impl Timespec {
87 pub fn new(sec: i64, nsec: i32) -> Timespec {
88 assert!(nsec >= 0 && nsec < NSEC_PER_SEC);
89 Timespec { sec: sec, nsec: nsec }
90 }
91 }
92
93 impl Add<Duration> for Timespec {
94 type Output = Timespec;
95
96 fn add(self, other: Duration) -> Timespec {
97 let d_sec = other.num_seconds();
98 // It is safe to unwrap the nanoseconds, because there cannot be
99 // more than one second left, which fits in i64 and in i32.
100 let d_nsec = (other - Duration::seconds(d_sec))
101 .num_nanoseconds().unwrap() as i32;
102 let mut sec = self.sec + d_sec;
103 let mut nsec = self.nsec + d_nsec;
104 if nsec >= NSEC_PER_SEC {
105 nsec -= NSEC_PER_SEC;
106 sec += 1;
107 } else if nsec < 0 {
108 nsec += NSEC_PER_SEC;
109 sec -= 1;
110 }
111 Timespec::new(sec, nsec)
112 }
113 }
114
115 impl Sub<Duration> for Timespec {
116 type Output = Timespec;
117
118 fn sub(self, other: Duration) -> Timespec {
119 let d_sec = other.num_seconds();
120 // It is safe to unwrap the nanoseconds, because there cannot be
121 // more than one second left, which fits in i64 and in i32.
122 let d_nsec = (other - Duration::seconds(d_sec))
123 .num_nanoseconds().unwrap() as i32;
124 let mut sec = self.sec - d_sec;
125 let mut nsec = self.nsec - d_nsec;
126 if nsec >= NSEC_PER_SEC {
127 nsec -= NSEC_PER_SEC;
128 sec += 1;
129 } else if nsec < 0 {
130 nsec += NSEC_PER_SEC;
131 sec -= 1;
132 }
133 Timespec::new(sec, nsec)
134 }
135 }
136
137 impl Sub<Timespec> for Timespec {
138 type Output = Duration;
139
140 fn sub(self, other: Timespec) -> Duration {
141 let sec = self.sec - other.sec;
142 let nsec = self.nsec - other.nsec;
143 Duration::seconds(sec) + Duration::nanoseconds(nsec as i64)
144 }
145 }
146
147 /**
148 * Returns the current time as a `timespec` containing the seconds and
149 * nanoseconds since 1970-01-01T00:00:00Z.
150 */
151 pub fn get_time() -> Timespec {
152 let (sec, nsec) = sys::get_time();
153 Timespec::new(sec, nsec)
154 }
155
156
157 /**
158 * Returns the current value of a high-resolution performance counter
159 * in nanoseconds since an unspecified epoch.
160 */
161 #[inline]
162 pub fn precise_time_ns() -> u64 {
163 sys::get_precise_ns()
164 }
165
166
167 /**
168 * Returns the current value of a high-resolution performance counter
169 * in seconds since an unspecified epoch.
170 */
171 pub fn precise_time_s() -> f64 {
172 return (precise_time_ns() as f64) / 1000000000.;
173 }
174
175 /// An opaque structure representing a moment in time.
176 ///
177 /// The only operation that can be performed on a `PreciseTime` is the
178 /// calculation of the `Duration` of time that lies between them.
179 ///
180 /// # Examples
181 ///
182 /// Repeatedly call a function for 1 second:
183 ///
184 /// ```rust
185 /// use time::{Duration, PreciseTime};
186 /// # fn do_some_work() {}
187 ///
188 /// let start = PreciseTime::now();
189 ///
190 /// while start.to(PreciseTime::now()) < Duration::seconds(1) {
191 /// do_some_work();
192 /// }
193 /// ```
194 #[derive(Copy, Clone)]
195 pub struct PreciseTime(u64);
196
197 impl PreciseTime {
198 /// Returns a `PreciseTime` representing the current moment in time.
199 pub fn now() -> PreciseTime {
200 PreciseTime(precise_time_ns())
201 }
202
203 /// Returns a `Duration` representing the span of time from the value of
204 /// `self` to the value of `later`.
205 ///
206 /// # Notes
207 ///
208 /// If `later` represents a time before `self`, the result of this method
209 /// is unspecified.
210 ///
211 /// If `later` represents a time more than 293 years after `self`, the
212 /// result of this method is unspecified.
213 #[inline]
214 pub fn to(&self, later: PreciseTime) -> Duration {
215 // NB: even if later is less than self due to overflow, this will work
216 // since the subtraction will underflow properly as well.
217 //
218 // We could deal with the overflow when casting to an i64, but all that
219 // gets us is the ability to handle intervals of up to 584 years, which
220 // seems not very useful :)
221 Duration::nanoseconds((later.0 - self.0) as i64)
222 }
223 }
224
225 /// A structure representing a moment in time.
226 ///
227 /// `SteadyTime`s are generated by a "steady" clock, that is, a clock which
228 /// never experiences discontinuous jumps and for which time always flows at
229 /// the same rate.
230 ///
231 /// # Examples
232 ///
233 /// Repeatedly call a function for 1 second:
234 ///
235 /// ```rust
236 /// # use time::{Duration, SteadyTime};
237 /// # fn do_some_work() {}
238 /// let start = SteadyTime::now();
239 ///
240 /// while SteadyTime::now() - start < Duration::seconds(1) {
241 /// do_some_work();
242 /// }
243 /// ```
244 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Debug)]
245 pub struct SteadyTime(sys::SteadyTime);
246
247 impl SteadyTime {
248 /// Returns a `SteadyTime` representing the current moment in time.
249 pub fn now() -> SteadyTime {
250 SteadyTime(sys::SteadyTime::now())
251 }
252 }
253
254 impl fmt::Display for SteadyTime {
255 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
256 // TODO: needs a display customization
257 fmt::Debug::fmt(self, fmt)
258 }
259 }
260
261 impl Sub for SteadyTime {
262 type Output = Duration;
263
264 fn sub(self, other: SteadyTime) -> Duration {
265 self.0 - other.0
266 }
267 }
268
269 impl Sub<Duration> for SteadyTime {
270 type Output = SteadyTime;
271
272 fn sub(self, other: Duration) -> SteadyTime {
273 SteadyTime(self.0 - other)
274 }
275 }
276
277 impl Add<Duration> for SteadyTime {
278 type Output = SteadyTime;
279
280 fn add(self, other: Duration) -> SteadyTime {
281 SteadyTime(self.0 + other)
282 }
283 }
284
285 #[cfg(not(any(windows, target_env = "sgx")))]
286 pub fn tzset() {
287 extern { fn tzset(); }
288 unsafe { tzset() }
289 }
290
291
292 #[cfg(any(windows, target_env = "sgx"))]
293 pub fn tzset() {}
294
295 /// Holds a calendar date and time broken down into its components (year, month,
296 /// day, and so on), also called a broken-down time value.
297 // FIXME: use c_int instead of i32?
298 #[repr(C)]
299 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
300 #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
301 pub struct Tm {
302 /// Seconds after the minute - [0, 60]
303 pub tm_sec: i32,
304
305 /// Minutes after the hour - [0, 59]
306 pub tm_min: i32,
307
308 /// Hours after midnight - [0, 23]
309 pub tm_hour: i32,
310
311 /// Day of the month - [1, 31]
312 pub tm_mday: i32,
313
314 /// Months since January - [0, 11]
315 pub tm_mon: i32,
316
317 /// Years since 1900
318 pub tm_year: i32,
319
320 /// Days since Sunday - [0, 6]. 0 = Sunday, 1 = Monday, ..., 6 = Saturday.
321 pub tm_wday: i32,
322
323 /// Days since January 1 - [0, 365]
324 pub tm_yday: i32,
325
326 /// Daylight Saving Time flag.
327 ///
328 /// This value is positive if Daylight Saving Time is in effect, zero if
329 /// Daylight Saving Time is not in effect, and negative if this information
330 /// is not available.
331 pub tm_isdst: i32,
332
333 /// Identifies the time zone that was used to compute this broken-down time
334 /// value, including any adjustment for Daylight Saving Time. This is the
335 /// number of seconds east of UTC. For example, for U.S. Pacific Daylight
336 /// Time, the value is `-7*60*60 = -25200`.
337 pub tm_utcoff: i32,
338
339 /// Nanoseconds after the second - [0, 10<sup>9</sup> - 1]
340 pub tm_nsec: i32,
341 }
342
343 impl Add<Duration> for Tm {
344 type Output = Tm;
345
346 /// The resulting Tm is in UTC.
347 // FIXME: The resulting Tm should have the same timezone as `self`;
348 // however, we need a function such as `at_tm(clock: Timespec, offset: i32)`
349 // for this.
350 fn add(self, other: Duration) -> Tm {
351 at_utc(self.to_timespec() + other)
352 }
353 }
354
355 impl Sub<Duration> for Tm {
356 type Output = Tm;
357
358 /// The resulting Tm is in UTC.
359 // FIXME: The resulting Tm should have the same timezone as `self`;
360 // however, we need a function such as `at_tm(clock: Timespec, offset: i32)`
361 // for this.
362 fn sub(self, other: Duration) -> Tm {
363 at_utc(self.to_timespec() - other)
364 }
365 }
366
367 impl Sub<Tm> for Tm {
368 type Output = Duration;
369
370 fn sub(self, other: Tm) -> Duration {
371 self.to_timespec() - other.to_timespec()
372 }
373 }
374
375 impl PartialOrd for Tm {
376 fn partial_cmp(&self, other: &Tm) -> Option<Ordering> {
377 self.to_timespec().partial_cmp(&other.to_timespec())
378 }
379 }
380
381 impl Ord for Tm {
382 fn cmp(&self, other: &Tm) -> Ordering {
383 self.to_timespec().cmp(&other.to_timespec())
384 }
385 }
386
387 pub fn empty_tm() -> Tm {
388 Tm {
389 tm_sec: 0,
390 tm_min: 0,
391 tm_hour: 0,
392 tm_mday: 0,
393 tm_mon: 0,
394 tm_year: 0,
395 tm_wday: 0,
396 tm_yday: 0,
397 tm_isdst: 0,
398 tm_utcoff: 0,
399 tm_nsec: 0,
400 }
401 }
402
403 /// Returns the specified time in UTC
404 pub fn at_utc(clock: Timespec) -> Tm {
405 let Timespec { sec, nsec } = clock;
406 let mut tm = empty_tm();
407 sys::time_to_utc_tm(sec, &mut tm);
408 tm.tm_nsec = nsec;
409 tm
410 }
411
412 /// Returns the current time in UTC
413 pub fn now_utc() -> Tm {
414 at_utc(get_time())
415 }
416
417 /// Returns the specified time in the local timezone
418 pub fn at(clock: Timespec) -> Tm {
419 let Timespec { sec, nsec } = clock;
420 let mut tm = empty_tm();
421 sys::time_to_local_tm(sec, &mut tm);
422 tm.tm_nsec = nsec;
423 tm
424 }
425
426 /// Returns the current time in the local timezone
427 pub fn now() -> Tm {
428 at(get_time())
429 }
430
431 impl Tm {
432 /// Convert time to the seconds from January 1, 1970
433 pub fn to_timespec(&self) -> Timespec {
434 let sec = match self.tm_utcoff {
435 0 => sys::utc_tm_to_time(self),
436 _ => sys::local_tm_to_time(self)
437 };
438
439 Timespec::new(sec, self.tm_nsec)
440 }
441
442 /// Convert time to the local timezone
443 pub fn to_local(&self) -> Tm {
444 at(self.to_timespec())
445 }
446
447 /// Convert time to the UTC
448 pub fn to_utc(&self) -> Tm {
449 match self.tm_utcoff {
450 0 => *self,
451 _ => at_utc(self.to_timespec())
452 }
453 }
454
455 /**
456 * Returns a TmFmt that outputs according to the `asctime` format in ISO
457 * C, in the local timezone.
458 *
459 * Example: "Thu Jan 1 00:00:00 1970"
460 */
461 pub fn ctime(&self) -> TmFmt {
462 TmFmt {
463 tm: self,
464 format: Fmt::Ctime,
465 }
466 }
467
468 /**
469 * Returns a TmFmt that outputs according to the `asctime` format in ISO
470 * C.
471 *
472 * Example: "Thu Jan 1 00:00:00 1970"
473 */
474 pub fn asctime(&self) -> TmFmt {
475 TmFmt {
476 tm: self,
477 format: Fmt::Str("%c"),
478 }
479 }
480
481 /// Formats the time according to the format string.
482 pub fn strftime<'a>(&'a self, format: &'a str) -> Result<TmFmt<'a>, ParseError> {
483 validate_format(TmFmt {
484 tm: self,
485 format: Fmt::Str(format),
486 })
487 }
488
489 /**
490 * Returns a TmFmt that outputs according to RFC 822.
491 *
492 * local: "Thu, 22 Mar 2012 07:53:18 PST"
493 * utc: "Thu, 22 Mar 2012 14:53:18 GMT"
494 */
495 pub fn rfc822(&self) -> TmFmt {
496 let fmt = if self.tm_utcoff == 0 {
497 "%a, %d %b %Y %T GMT"
498 } else {
499 "%a, %d %b %Y %T %Z"
500 };
501 TmFmt {
502 tm: self,
503 format: Fmt::Str(fmt),
504 }
505 }
506
507 /**
508 * Returns a TmFmt that outputs according to RFC 822 with Zulu time.
509 *
510 * local: "Thu, 22 Mar 2012 07:53:18 -0700"
511 * utc: "Thu, 22 Mar 2012 14:53:18 -0000"
512 */
513 pub fn rfc822z(&self) -> TmFmt {
514 TmFmt {
515 tm: self,
516 format: Fmt::Str("%a, %d %b %Y %T %z"),
517 }
518 }
519
520 /**
521 * Returns a TmFmt that outputs according to RFC 3339. RFC 3339 is
522 * compatible with ISO 8601.
523 *
524 * local: "2012-02-22T07:53:18-07:00"
525 * utc: "2012-02-22T14:53:18Z"
526 */
527 pub fn rfc3339<'a>(&'a self) -> TmFmt {
528 TmFmt {
529 tm: self,
530 format: Fmt::Rfc3339,
531 }
532 }
533 }
534
535 #[derive(Copy, PartialEq, Debug, Clone)]
536 pub enum ParseError {
537 InvalidSecond,
538 InvalidMinute,
539 InvalidHour,
540 InvalidDay,
541 InvalidMonth,
542 InvalidYear,
543 InvalidDayOfWeek,
544 InvalidDayOfMonth,
545 InvalidDayOfYear,
546 InvalidZoneOffset,
547 InvalidTime,
548 InvalidSecondsSinceEpoch,
549 MissingFormatConverter,
550 InvalidFormatSpecifier(char),
551 UnexpectedCharacter(char, char),
552 }
553
554 impl fmt::Display for ParseError {
555 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
556 #[allow(deprecated)]
557 match *self {
558 InvalidFormatSpecifier(ch) => {
559 write!(f, "{}: %{}", self.description(), ch)
560 }
561 UnexpectedCharacter(a, b) => {
562 write!(f, "expected: `{}`, found: `{}`", a, b)
563 }
564 _ => write!(f, "{}", self.description())
565 }
566 }
567 }
568
569 impl Error for ParseError {
570 fn description(&self) -> &str {
571 match *self {
572 InvalidSecond => "Invalid second.",
573 InvalidMinute => "Invalid minute.",
574 InvalidHour => "Invalid hour.",
575 InvalidDay => "Invalid day.",
576 InvalidMonth => "Invalid month.",
577 InvalidYear => "Invalid year.",
578 InvalidDayOfWeek => "Invalid day of the week.",
579 InvalidDayOfMonth => "Invalid day of the month.",
580 InvalidDayOfYear => "Invalid day of the year.",
581 InvalidZoneOffset => "Invalid zone offset.",
582 InvalidTime => "Invalid time.",
583 InvalidSecondsSinceEpoch => "Invalid seconds since epoch.",
584 MissingFormatConverter => "missing format converter after `%`",
585 InvalidFormatSpecifier(..) => "invalid format specifier",
586 UnexpectedCharacter(..) => "Unexpected character.",
587 }
588 }
589 }
590
591 /// A wrapper around a `Tm` and format string that implements Display.
592 #[derive(Debug)]
593 pub struct TmFmt<'a> {
594 tm: &'a Tm,
595 format: Fmt<'a>
596 }
597
598 #[derive(Debug)]
599 enum Fmt<'a> {
600 Str(&'a str),
601 Rfc3339,
602 Ctime,
603 }
604
605 fn validate_format<'a>(fmt: TmFmt<'a>) -> Result<TmFmt<'a>, ParseError> {
606
607 match (fmt.tm.tm_wday, fmt.tm.tm_mon) {
608 (0...6, 0...11) => (),
609 (_wday, 0...11) => return Err(InvalidDayOfWeek),
610 (0...6, _mon) => return Err(InvalidMonth),
611 _ => return Err(InvalidDay)
612 }
613 match fmt.format {
614 Fmt::Str(ref s) => {
615 let mut chars = s.chars();
616 loop {
617 match chars.next() {
618 Some('%') => {
619 match chars.next() {
620 Some('A') | Some('a') | Some('B') | Some('b') |
621 Some('C') | Some('c') | Some('D') | Some('d') |
622 Some('e') | Some('F') | Some('f') | Some('G') |
623 Some('g') | Some('H') | Some('h') | Some('I') |
624 Some('j') | Some('k') | Some('l') | Some('M') |
625 Some('m') | Some('n') | Some('P') | Some('p') |
626 Some('R') | Some('r') | Some('S') | Some('s') |
627 Some('T') | Some('t') | Some('U') | Some('u') |
628 Some('V') | Some('v') | Some('W') | Some('w') |
629 Some('X') | Some('x') | Some('Y') | Some('y') |
630 Some('Z') | Some('z') | Some('+') | Some('%') => (),
631
632 Some(c) => return Err(InvalidFormatSpecifier(c)),
633 None => return Err(MissingFormatConverter),
634 }
635 },
636 None => break,
637 _ => ()
638 }
639 }
640 },
641 _ => ()
642 }
643 Ok(fmt)
644 }
645
646 /// Formats the time according to the format string.
647 pub fn strftime(format: &str, tm: &Tm) -> Result<String, ParseError> {
648 tm.strftime(format).map(|fmt| fmt.to_string())
649 }
650
651 #[cfg(test)]
652 mod tests {
653 use super::{Timespec, get_time, precise_time_ns, precise_time_s,
654 at_utc, at, strptime, PreciseTime, SteadyTime, ParseError, Duration};
655 use super::ParseError::{InvalidTime, InvalidYear, MissingFormatConverter,
656 InvalidFormatSpecifier};
657
658 #[allow(deprecated)] // `Once::new` is const starting in Rust 1.32
659 use std::sync::ONCE_INIT;
660 use std::sync::{Once, Mutex, MutexGuard, LockResult};
661 use std::i32;
662 use std::mem;
663
664 struct TzReset {
665 _tzreset: ::sys::TzReset,
666 _lock: LockResult<MutexGuard<'static, ()>>,
667 }
668
669 fn set_time_zone_la_or_london(london: bool) -> TzReset {
670 // Lock manages current timezone because some tests require LA some
671 // London
672 static mut LOCK: *mut Mutex<()> = 0 as *mut _;
673 #[allow(deprecated)] // `Once::new` is const starting in Rust 1.32
674 static INIT: Once = ONCE_INIT;
675
676 unsafe {
677 INIT.call_once(|| {
678 LOCK = mem::transmute(Box::new(Mutex::new(())));
679 });
680
681 let timezone_lock = (*LOCK).lock();
682 let reset_func = if london {
683 ::sys::set_london_with_dst_time_zone()
684 } else {
685 ::sys::set_los_angeles_time_zone()
686 };
687 TzReset {
688 _lock: timezone_lock,
689 _tzreset: reset_func,
690 }
691 }
692 }
693
694 fn set_time_zone() -> TzReset {
695 set_time_zone_la_or_london(false)
696 }
697
698 fn set_time_zone_london_dst() -> TzReset {
699 set_time_zone_la_or_london(true)
700 }
701
702 #[test]
703 fn test_get_time() {
704 static SOME_RECENT_DATE: i64 = 1577836800i64; // 2020-01-01T00:00:00Z
705 static SOME_FUTURE_DATE: i64 = i32::MAX as i64; // Y2038
706
707 let tv1 = get_time();
708 debug!("tv1={} sec + {} nsec", tv1.sec, tv1.nsec);
709
710 assert!(tv1.sec > SOME_RECENT_DATE);
711 assert!(tv1.nsec < 1000000000i32);
712
713 let tv2 = get_time();
714 debug!("tv2={} sec + {} nsec", tv2.sec, tv2.nsec);
715
716 assert!(tv2.sec >= tv1.sec);
717 assert!(tv2.sec < SOME_FUTURE_DATE);
718 assert!(tv2.nsec < 1000000000i32);
719 if tv2.sec == tv1.sec {
720 assert!(tv2.nsec >= tv1.nsec);
721 }
722 }
723
724 #[test]
725 fn test_precise_time() {
726 let s0 = precise_time_s();
727 debug!("s0={} sec", s0);
728 assert!(s0 > 0.);
729
730 let ns0 = precise_time_ns();
731 let ns1 = precise_time_ns();
732 debug!("ns0={} ns", ns0);
733 debug!("ns1={} ns", ns1);
734 assert!(ns1 >= ns0);
735
736 let ns2 = precise_time_ns();
737 debug!("ns2={} ns", ns2);
738 assert!(ns2 >= ns1);
739 }
740
741 #[test]
742 fn test_precise_time_to() {
743 let t0 = PreciseTime(1000);
744 let t1 = PreciseTime(1023);
745 assert_eq!(Duration::nanoseconds(23), t0.to(t1));
746 }
747
748 #[test]
749 fn test_at_utc() {
750 let _reset = set_time_zone();
751
752 let time = Timespec::new(1234567890, 54321);
753 let utc = at_utc(time);
754
755 assert_eq!(utc.tm_sec, 30);
756 assert_eq!(utc.tm_min, 31);
757 assert_eq!(utc.tm_hour, 23);
758 assert_eq!(utc.tm_mday, 13);
759 assert_eq!(utc.tm_mon, 1);
760 assert_eq!(utc.tm_year, 109);
761 assert_eq!(utc.tm_wday, 5);
762 assert_eq!(utc.tm_yday, 43);
763 assert_eq!(utc.tm_isdst, 0);
764 assert_eq!(utc.tm_utcoff, 0);
765 assert_eq!(utc.tm_nsec, 54321);
766 }
767
768 #[test]
769 fn test_at() {
770 let _reset = set_time_zone();
771
772 let time = Timespec::new(1234567890, 54321);
773 let local = at(time);
774
775 debug!("time_at: {:?}", local);
776
777 assert_eq!(local.tm_sec, 30);
778 assert_eq!(local.tm_min, 31);
779 assert_eq!(local.tm_hour, 15);
780 assert_eq!(local.tm_mday, 13);
781 assert_eq!(local.tm_mon, 1);
782 assert_eq!(local.tm_year, 109);
783 assert_eq!(local.tm_wday, 5);
784 assert_eq!(local.tm_yday, 43);
785 assert_eq!(local.tm_isdst, 0);
786 assert_eq!(local.tm_utcoff, -28800);
787 assert_eq!(local.tm_nsec, 54321);
788 }
789
790 #[test]
791 fn test_to_timespec() {
792 let _reset = set_time_zone();
793
794 let time = Timespec::new(1234567890, 54321);
795 let utc = at_utc(time);
796
797 assert_eq!(utc.to_timespec(), time);
798 assert_eq!(utc.to_local().to_timespec(), time);
799 }
800
801 #[test]
802 fn test_conversions() {
803 let _reset = set_time_zone();
804
805 let time = Timespec::new(1234567890, 54321);
806 let utc = at_utc(time);
807 let local = at(time);
808
809 assert!(local.to_local() == local);
810 assert!(local.to_utc() == utc);
811 assert!(local.to_utc().to_local() == local);
812 assert!(utc.to_utc() == utc);
813 assert!(utc.to_local() == local);
814 assert!(utc.to_local().to_utc() == utc);
815 }
816
817 #[test]
818 fn test_strptime() {
819 let _reset = set_time_zone();
820
821 match strptime("", "") {
822 Ok(ref tm) => {
823 assert!(tm.tm_sec == 0);
824 assert!(tm.tm_min == 0);
825 assert!(tm.tm_hour == 0);
826 assert!(tm.tm_mday == 0);
827 assert!(tm.tm_mon == 0);
828 assert!(tm.tm_year == 0);
829 assert!(tm.tm_wday == 0);
830 assert!(tm.tm_isdst == 0);
831 assert!(tm.tm_utcoff == 0);
832 assert!(tm.tm_nsec == 0);
833 }
834 Err(_) => ()
835 }
836
837 let format = "%a %b %e %T.%f %Y";
838 assert_eq!(strptime("", format), Err(ParseError::InvalidDay));
839 assert_eq!(strptime("Fri Feb 13 15:31:30", format),
840 Err(InvalidTime));
841
842 match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
843 Err(e) => panic!("{}", e),
844 Ok(ref tm) => {
845 assert_eq!(tm.tm_sec, 30);
846 assert_eq!(tm.tm_min, 31);
847 assert_eq!(tm.tm_hour, 15);
848 assert_eq!(tm.tm_mday, 13);
849 assert_eq!(tm.tm_mon, 1);
850 assert_eq!(tm.tm_year, 109);
851 assert_eq!(tm.tm_wday, 5);
852 assert_eq!(tm.tm_yday, 0);
853 assert_eq!(tm.tm_isdst, 0);
854 assert_eq!(tm.tm_utcoff, 0);
855 assert_eq!(tm.tm_nsec, 12340000);
856 }
857 }
858
859 fn test(s: &str, format: &str) -> bool {
860 match strptime(s, format) {
861 Ok(tm) => {
862 tm.strftime(format).unwrap().to_string() == s.to_string()
863 },
864 Err(e) => panic!("{:?}, s={:?}, format={:?}", e, s, format)
865 }
866 }
867
868 fn test_oneway(s : &str, format : &str) -> bool {
869 match strptime(s, format) {
870 Ok(_) => {
871 // oneway tests are used when reformatting the parsed Tm
872 // back into a string can generate a different string
873 // from the original (i.e. leading zeroes)
874 true
875 },
876 Err(e) => panic!("{:?}, s={:?}, format={:?}", e, s, format)
877 }
878 }
879
880 let days = [
881 "Sunday".to_string(),
882 "Monday".to_string(),
883 "Tuesday".to_string(),
884 "Wednesday".to_string(),
885 "Thursday".to_string(),
886 "Friday".to_string(),
887 "Saturday".to_string()
888 ];
889 for day in days.iter() {
890 assert!(test(&day, "%A"));
891 }
892
893 let days = [
894 "Sun".to_string(),
895 "Mon".to_string(),
896 "Tue".to_string(),
897 "Wed".to_string(),
898 "Thu".to_string(),
899 "Fri".to_string(),
900 "Sat".to_string()
901 ];
902 for day in days.iter() {
903 assert!(test(&day, "%a"));
904 }
905
906 let months = [
907 "January".to_string(),
908 "February".to_string(),
909 "March".to_string(),
910 "April".to_string(),
911 "May".to_string(),
912 "June".to_string(),
913 "July".to_string(),
914 "August".to_string(),
915 "September".to_string(),
916 "October".to_string(),
917 "November".to_string(),
918 "December".to_string()
919 ];
920 for day in months.iter() {
921 assert!(test(&day, "%B"));
922 }
923
924 let months = [
925 "Jan".to_string(),
926 "Feb".to_string(),
927 "Mar".to_string(),
928 "Apr".to_string(),
929 "May".to_string(),
930 "Jun".to_string(),
931 "Jul".to_string(),
932 "Aug".to_string(),
933 "Sep".to_string(),
934 "Oct".to_string(),
935 "Nov".to_string(),
936 "Dec".to_string()
937 ];
938 for day in months.iter() {
939 assert!(test(&day, "%b"));
940 }
941
942 assert!(test("19", "%C"));
943 assert!(test("Fri Feb 3 23:31:30 2009", "%c"));
944 assert!(test("Fri Feb 13 23:31:30 2009", "%c"));
945 assert!(test("02/13/09", "%D"));
946 assert!(test("03", "%d"));
947 assert!(test("13", "%d"));
948 assert!(test(" 3", "%e"));
949 assert!(test("13", "%e"));
950 assert!(test("2009-02-13", "%F"));
951 assert!(test("03", "%H"));
952 assert!(test("13", "%H"));
953 assert!(test("03", "%I")); // FIXME (#2350): flesh out
954 assert!(test("11", "%I")); // FIXME (#2350): flesh out
955 assert!(test("044", "%j"));
956 assert!(test(" 3", "%k"));
957 assert!(test("13", "%k"));
958 assert!(test(" 1", "%l"));
959 assert!(test("11", "%l"));
960 assert!(test("03", "%M"));
961 assert!(test("13", "%M"));
962 assert!(test("\n", "%n"));
963 assert!(test("am", "%P"));
964 assert!(test("pm", "%P"));
965 assert!(test("AM", "%p"));
966 assert!(test("PM", "%p"));
967 assert!(test("23:31", "%R"));
968 assert!(test("11:31:30 AM", "%r"));
969 assert!(test("11:31:30 PM", "%r"));
970 assert!(test("03", "%S"));
971 assert!(test("13", "%S"));
972 assert!(test("15:31:30", "%T"));
973 assert!(test("\t", "%t"));
974 assert!(test("1", "%u"));
975 assert!(test("7", "%u"));
976 assert!(test("13-Feb-2009", "%v"));
977 assert!(test("0", "%w"));
978 assert!(test("6", "%w"));
979 assert!(test("2009", "%Y"));
980 assert!(test("09", "%y"));
981
982 assert!(test_oneway("3", "%d"));
983 assert!(test_oneway("3", "%H"));
984 assert!(test_oneway("3", "%e"));
985 assert!(test_oneway("3", "%M"));
986 assert!(test_oneway("3", "%S"));
987
988 assert!(strptime("-0000", "%z").unwrap().tm_utcoff == 0);
989 assert!(strptime("-00:00", "%z").unwrap().tm_utcoff == 0);
990 assert!(strptime("Z", "%z").unwrap().tm_utcoff == 0);
991 assert_eq!(-28800, strptime("-0800", "%z").unwrap().tm_utcoff);
992 assert_eq!(-28800, strptime("-08:00", "%z").unwrap().tm_utcoff);
993 assert_eq!(28800, strptime("+0800", "%z").unwrap().tm_utcoff);
994 assert_eq!(28800, strptime("+08:00", "%z").unwrap().tm_utcoff);
995 assert_eq!(5400, strptime("+0130", "%z").unwrap().tm_utcoff);
996 assert_eq!(5400, strptime("+01:30", "%z").unwrap().tm_utcoff);
997 assert!(test("%", "%%"));
998
999 // Test for #7256
1000 assert_eq!(strptime("360", "%Y-%m-%d"), Err(InvalidYear));
1001
1002 // Test for epoch seconds parsing
1003 {
1004 assert!(test("1428035610", "%s"));
1005 let tm = strptime("1428035610", "%s").unwrap();
1006 assert_eq!(tm.tm_utcoff, 0);
1007 assert_eq!(tm.tm_isdst, 0);
1008 assert_eq!(tm.tm_yday, 92);
1009 assert_eq!(tm.tm_wday, 5);
1010 assert_eq!(tm.tm_year, 115);
1011 assert_eq!(tm.tm_mon, 3);
1012 assert_eq!(tm.tm_mday, 3);
1013 assert_eq!(tm.tm_hour, 4);
1014 }
1015 }
1016
1017 #[test]
1018 fn test_asctime() {
1019 let _reset = set_time_zone();
1020
1021 let time = Timespec::new(1234567890, 54321);
1022 let utc = at_utc(time);
1023 let local = at(time);
1024
1025 debug!("test_ctime: {} {}", utc.asctime(), local.asctime());
1026
1027 assert_eq!(utc.asctime().to_string(), "Fri Feb 13 23:31:30 2009".to_string());
1028 assert_eq!(local.asctime().to_string(), "Fri Feb 13 15:31:30 2009".to_string());
1029 }
1030
1031 #[test]
1032 fn test_ctime() {
1033 let _reset = set_time_zone();
1034
1035 let time = Timespec::new(1234567890, 54321);
1036 let utc = at_utc(time);
1037 let local = at(time);
1038
1039 debug!("test_ctime: {} {}", utc.ctime(), local.ctime());
1040
1041 assert_eq!(utc.ctime().to_string(), "Fri Feb 13 15:31:30 2009".to_string());
1042 assert_eq!(local.ctime().to_string(), "Fri Feb 13 15:31:30 2009".to_string());
1043 }
1044
1045 #[test]
1046 fn test_strftime() {
1047 let _reset = set_time_zone();
1048
1049 let time = Timespec::new(1234567890, 54321);
1050 let utc = at_utc(time);
1051 let local = at(time);
1052
1053 assert_eq!(local.strftime("").unwrap().to_string(), "".to_string());
1054 assert_eq!(local.strftime("%A").unwrap().to_string(), "Friday".to_string());
1055 assert_eq!(local.strftime("%a").unwrap().to_string(), "Fri".to_string());
1056 assert_eq!(local.strftime("%B").unwrap().to_string(), "February".to_string());
1057 assert_eq!(local.strftime("%b").unwrap().to_string(), "Feb".to_string());
1058 assert_eq!(local.strftime("%C").unwrap().to_string(), "20".to_string());
1059 assert_eq!(local.strftime("%c").unwrap().to_string(),
1060 "Fri Feb 13 15:31:30 2009".to_string());
1061 assert_eq!(local.strftime("%D").unwrap().to_string(), "02/13/09".to_string());
1062 assert_eq!(local.strftime("%d").unwrap().to_string(), "13".to_string());
1063 assert_eq!(local.strftime("%e").unwrap().to_string(), "13".to_string());
1064 assert_eq!(local.strftime("%F").unwrap().to_string(), "2009-02-13".to_string());
1065 assert_eq!(local.strftime("%f").unwrap().to_string(), "000054321".to_string());
1066 assert_eq!(local.strftime("%G").unwrap().to_string(), "2009".to_string());
1067 assert_eq!(local.strftime("%g").unwrap().to_string(), "09".to_string());
1068 assert_eq!(local.strftime("%H").unwrap().to_string(), "15".to_string());
1069 assert_eq!(local.strftime("%h").unwrap().to_string(), "Feb".to_string());
1070 assert_eq!(local.strftime("%I").unwrap().to_string(), "03".to_string());
1071 assert_eq!(local.strftime("%j").unwrap().to_string(), "044".to_string());
1072 assert_eq!(local.strftime("%k").unwrap().to_string(), "15".to_string());
1073 assert_eq!(local.strftime("%l").unwrap().to_string(), " 3".to_string());
1074 assert_eq!(local.strftime("%M").unwrap().to_string(), "31".to_string());
1075 assert_eq!(local.strftime("%m").unwrap().to_string(), "02".to_string());
1076 assert_eq!(local.strftime("%n").unwrap().to_string(), "\n".to_string());
1077 assert_eq!(local.strftime("%P").unwrap().to_string(), "pm".to_string());
1078 assert_eq!(local.strftime("%p").unwrap().to_string(), "PM".to_string());
1079 assert_eq!(local.strftime("%R").unwrap().to_string(), "15:31".to_string());
1080 assert_eq!(local.strftime("%r").unwrap().to_string(), "03:31:30 PM".to_string());
1081 assert_eq!(local.strftime("%S").unwrap().to_string(), "30".to_string());
1082 assert_eq!(local.strftime("%s").unwrap().to_string(), "1234567890".to_string());
1083 assert_eq!(local.strftime("%T").unwrap().to_string(), "15:31:30".to_string());
1084 assert_eq!(local.strftime("%t").unwrap().to_string(), "\t".to_string());
1085 assert_eq!(local.strftime("%U").unwrap().to_string(), "06".to_string());
1086 assert_eq!(local.strftime("%u").unwrap().to_string(), "5".to_string());
1087 assert_eq!(local.strftime("%V").unwrap().to_string(), "07".to_string());
1088 assert_eq!(local.strftime("%v").unwrap().to_string(), "13-Feb-2009".to_string());
1089 assert_eq!(local.strftime("%W").unwrap().to_string(), "06".to_string());
1090 assert_eq!(local.strftime("%w").unwrap().to_string(), "5".to_string());
1091 // FIXME (#2350): support locale
1092 assert_eq!(local.strftime("%X").unwrap().to_string(), "15:31:30".to_string());
1093 // FIXME (#2350): support locale
1094 assert_eq!(local.strftime("%x").unwrap().to_string(), "02/13/09".to_string());
1095 assert_eq!(local.strftime("%Y").unwrap().to_string(), "2009".to_string());
1096 assert_eq!(local.strftime("%y").unwrap().to_string(), "09".to_string());
1097 // FIXME (#2350): support locale
1098 assert_eq!(local.strftime("%Z").unwrap().to_string(), "".to_string());
1099 assert_eq!(local.strftime("%z").unwrap().to_string(), "-0800".to_string());
1100 assert_eq!(local.strftime("%+").unwrap().to_string(),
1101 "2009-02-13T15:31:30-08:00".to_string());
1102 assert_eq!(local.strftime("%%").unwrap().to_string(), "%".to_string());
1103
1104 let invalid_specifiers = ["%E", "%J", "%K", "%L", "%N", "%O", "%o", "%Q", "%q"];
1105 for &sp in invalid_specifiers.iter() {
1106 assert_eq!(local.strftime(sp).unwrap_err(),
1107 InvalidFormatSpecifier(sp[1..].chars().next().unwrap()));
1108 }
1109 assert_eq!(local.strftime("%").unwrap_err(), MissingFormatConverter);
1110 assert_eq!(local.strftime("%A %").unwrap_err(), MissingFormatConverter);
1111
1112 assert_eq!(local.asctime().to_string(), "Fri Feb 13 15:31:30 2009".to_string());
1113 assert_eq!(local.ctime().to_string(), "Fri Feb 13 15:31:30 2009".to_string());
1114 assert_eq!(local.rfc822z().to_string(), "Fri, 13 Feb 2009 15:31:30 -0800".to_string());
1115 assert_eq!(local.rfc3339().to_string(), "2009-02-13T15:31:30-08:00".to_string());
1116
1117 assert_eq!(utc.asctime().to_string(), "Fri Feb 13 23:31:30 2009".to_string());
1118 assert_eq!(utc.ctime().to_string(), "Fri Feb 13 15:31:30 2009".to_string());
1119 assert_eq!(utc.rfc822().to_string(), "Fri, 13 Feb 2009 23:31:30 GMT".to_string());
1120 assert_eq!(utc.rfc822z().to_string(), "Fri, 13 Feb 2009 23:31:30 -0000".to_string());
1121 assert_eq!(utc.rfc3339().to_string(), "2009-02-13T23:31:30Z".to_string());
1122 }
1123
1124 #[test]
1125 fn test_timespec_eq_ord() {
1126 let a = &Timespec::new(-2, 1);
1127 let b = &Timespec::new(-1, 2);
1128 let c = &Timespec::new(1, 2);
1129 let d = &Timespec::new(2, 1);
1130 let e = &Timespec::new(2, 1);
1131
1132 assert!(d.eq(e));
1133 assert!(c.ne(e));
1134
1135 assert!(a.lt(b));
1136 assert!(b.lt(c));
1137 assert!(c.lt(d));
1138
1139 assert!(a.le(b));
1140 assert!(b.le(c));
1141 assert!(c.le(d));
1142 assert!(d.le(e));
1143 assert!(e.le(d));
1144
1145 assert!(b.ge(a));
1146 assert!(c.ge(b));
1147 assert!(d.ge(c));
1148 assert!(e.ge(d));
1149 assert!(d.ge(e));
1150
1151 assert!(b.gt(a));
1152 assert!(c.gt(b));
1153 assert!(d.gt(c));
1154 }
1155
1156 #[test]
1157 #[allow(deprecated)]
1158 fn test_timespec_hash() {
1159 use std::hash::{Hash, Hasher};
1160
1161 let c = &Timespec::new(3, 2);
1162 let d = &Timespec::new(2, 1);
1163 let e = &Timespec::new(2, 1);
1164
1165 let mut hasher = ::std::hash::SipHasher::new();
1166
1167 let d_hash:u64 = {
1168 d.hash(&mut hasher);
1169 hasher.finish()
1170 };
1171
1172 hasher = ::std::hash::SipHasher::new();
1173
1174 let e_hash:u64 = {
1175 e.hash(&mut hasher);
1176 hasher.finish()
1177 };
1178
1179 hasher = ::std::hash::SipHasher::new();
1180
1181 let c_hash:u64 = {
1182 c.hash(&mut hasher);
1183 hasher.finish()
1184 };
1185
1186 assert_eq!(d_hash, e_hash);
1187 assert!(c_hash != e_hash);
1188 }
1189
1190 #[test]
1191 fn test_timespec_add() {
1192 let a = Timespec::new(1, 2);
1193 let b = Duration::seconds(2) + Duration::nanoseconds(3);
1194 let c = a + b;
1195 assert_eq!(c.sec, 3);
1196 assert_eq!(c.nsec, 5);
1197
1198 let p = Timespec::new(1, super::NSEC_PER_SEC - 2);
1199 let q = Duration::seconds(2) + Duration::nanoseconds(2);
1200 let r = p + q;
1201 assert_eq!(r.sec, 4);
1202 assert_eq!(r.nsec, 0);
1203
1204 let u = Timespec::new(1, super::NSEC_PER_SEC - 2);
1205 let v = Duration::seconds(2) + Duration::nanoseconds(3);
1206 let w = u + v;
1207 assert_eq!(w.sec, 4);
1208 assert_eq!(w.nsec, 1);
1209
1210 let k = Timespec::new(1, 0);
1211 let l = Duration::nanoseconds(-1);
1212 let m = k + l;
1213 assert_eq!(m.sec, 0);
1214 assert_eq!(m.nsec, 999_999_999);
1215 }
1216
1217 #[test]
1218 fn test_timespec_sub() {
1219 let a = Timespec::new(2, 3);
1220 let b = Timespec::new(1, 2);
1221 let c = a - b;
1222 assert_eq!(c.num_nanoseconds(), Some(super::NSEC_PER_SEC as i64 + 1));
1223
1224 let p = Timespec::new(2, 0);
1225 let q = Timespec::new(1, 2);
1226 let r = p - q;
1227 assert_eq!(r.num_nanoseconds(), Some(super::NSEC_PER_SEC as i64 - 2));
1228
1229 let u = Timespec::new(1, 2);
1230 let v = Timespec::new(2, 3);
1231 let w = u - v;
1232 assert_eq!(w.num_nanoseconds(), Some(-super::NSEC_PER_SEC as i64 - 1));
1233 }
1234
1235 #[test]
1236 fn test_time_sub() {
1237 let a = ::now();
1238 let b = at(a.to_timespec() + Duration::seconds(5));
1239 let c = b - a;
1240 assert_eq!(c.num_nanoseconds(), Some(super::NSEC_PER_SEC as i64 * 5));
1241 }
1242
1243 #[test]
1244 fn test_steadytime_sub() {
1245 let a = SteadyTime::now();
1246 let b = a + Duration::seconds(1);
1247 assert_eq!(b - a, Duration::seconds(1));
1248 assert_eq!(a - b, Duration::seconds(-1));
1249 }
1250
1251 #[test]
1252 fn test_date_before_1970() {
1253 let early = strptime("1901-01-06", "%F").unwrap();
1254 let late = strptime("2000-01-01", "%F").unwrap();
1255 assert!(early < late);
1256 }
1257
1258 #[test]
1259 fn test_dst() {
1260 let _reset = set_time_zone_london_dst();
1261 let utc_in_feb = strptime("2015-02-01Z", "%F%z").unwrap();
1262 let utc_in_jun = strptime("2015-06-01Z", "%F%z").unwrap();
1263 let utc_in_nov = strptime("2015-11-01Z", "%F%z").unwrap();
1264 let local_in_feb = utc_in_feb.to_local();
1265 let local_in_jun = utc_in_jun.to_local();
1266 let local_in_nov = utc_in_nov.to_local();
1267
1268 assert_eq!(local_in_feb.tm_mon, 1);
1269 assert_eq!(local_in_feb.tm_hour, 0);
1270 assert_eq!(local_in_feb.tm_utcoff, 0);
1271 assert_eq!(local_in_feb.tm_isdst, 0);
1272
1273 assert_eq!(local_in_jun.tm_mon, 5);
1274 assert_eq!(local_in_jun.tm_hour, 1);
1275 assert_eq!(local_in_jun.tm_utcoff, 3600);
1276 assert_eq!(local_in_jun.tm_isdst, 1);
1277
1278 assert_eq!(local_in_nov.tm_mon, 10);
1279 assert_eq!(local_in_nov.tm_hour, 0);
1280 assert_eq!(local_in_nov.tm_utcoff, 0);
1281 assert_eq!(local_in_nov.tm_isdst, 0)
1282 }
1283 }