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.
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.
11 //! Simple time handling.
13 #![crate_name = "time"]
14 #![deprecated = "use the http://github.com/rust-lang/time crate instead"]
17 #![crate_type = "rlib"]
18 #![crate_type = "dylib"]
19 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
20 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
21 html_root_url = "http://doc.rust-lang.org/nightly/",
22 html_playground_url = "http://play.rust-lang.org/")]
23 #![feature(phase, globs)]
25 #[cfg(test)] #[phase(plugin, link)] extern crate log;
27 extern crate serialize;
30 pub use self::ParseError::*;
35 use std::num::SignedInt;
36 use std::string::String;
37 use std::time::Duration;
39 static NSEC_PER_SEC: i32 = 1_000_000_000_i32;
46 pub fn rust_gmtime(sec: i64, nsec: i32, result: &mut Tm);
47 pub fn rust_localtime(sec: i64, nsec: i32, result: &mut Tm);
48 pub fn rust_timegm(tm: &Tm) -> i64;
49 pub fn rust_mktime(tm: &Tm) -> i64;
53 #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios")))]
55 use libc::{c_int, timespec};
57 // Apparently android provides this in some other library?
58 #[cfg(not(target_os = "android"))]
63 pub fn clock_gettime(clk_id: c_int, tp: *mut timespec) -> c_int;
67 #[cfg(any(target_os = "macos", target_os = "ios"))]
69 use libc::{timeval, timezone, c_int, mach_timebase_info};
72 pub fn gettimeofday(tp: *mut timeval, tzp: *mut timezone) -> c_int;
73 pub fn mach_absolute_time() -> u64;
74 pub fn mach_timebase_info(info: *mut mach_timebase_info) -> c_int;
78 /// A record specifying a time value in seconds and nanoseconds.
79 #[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Show)]
80 pub struct Timespec { pub sec: i64, pub nsec: i32 }
82 * Timespec assumes that pre-epoch Timespecs have negative sec and positive
83 * nsec fields. Darwin's and Linux's struct timespec functions handle pre-
84 * epoch timestamps using a "two steps back, one step forward" representation,
85 * though the man pages do not actually document this. For example, the time
86 * -1.2 seconds before the epoch is represented by `Timespec { sec: -2_i64,
87 * nsec: 800_000_000_i32 }`.
90 pub fn new(sec: i64, nsec: i32) -> Timespec {
91 assert!(nsec >= 0 && nsec < NSEC_PER_SEC);
92 Timespec { sec: sec, nsec: nsec }
96 impl Add<Duration, Timespec> for Timespec {
97 fn add(&self, other: &Duration) -> Timespec {
98 let d_sec = other.num_seconds();
99 // It is safe to unwrap the nanoseconds, because there cannot be
100 // more than one second left, which fits in i64 and in i32.
101 let d_nsec = (*other - Duration::seconds(d_sec))
102 .num_nanoseconds().unwrap() as i32;
103 let mut sec = self.sec + d_sec;
104 let mut nsec = self.nsec + d_nsec;
105 if nsec >= NSEC_PER_SEC {
106 nsec -= NSEC_PER_SEC;
109 nsec += NSEC_PER_SEC;
112 Timespec::new(sec, nsec)
116 impl Sub<Timespec, Duration> for Timespec {
117 fn sub(&self, other: &Timespec) -> Duration {
118 let sec = self.sec - other.sec;
119 let nsec = self.nsec - other.nsec;
120 Duration::seconds(sec) + Duration::nanoseconds(nsec as i64)
124 /// Returns the current time as a `timespec` containing the seconds and
125 /// nanoseconds since 1970-01-01T00:00:00Z.
126 pub fn get_time() -> Timespec {
128 let (sec, nsec) = os_get_time();
129 return Timespec::new(sec, nsec);
133 unsafe fn os_get_time() -> (i64, i32) {
134 static NANOSECONDS_FROM_1601_TO_1970: u64 = 11644473600000000;
136 let mut time = libc::FILETIME {
140 libc::GetSystemTimeAsFileTime(&mut time);
142 // A FILETIME contains a 64-bit value representing the number of
143 // hectonanosecond (100-nanosecond) intervals since 1601-01-01T00:00:00Z.
144 // http://support.microsoft.com/kb/167296/en-us
145 let ns_since_1601 = ((time.dwHighDateTime as u64 << 32) |
146 (time.dwLowDateTime as u64 << 0)) / 10;
147 let ns_since_1970 = ns_since_1601 - NANOSECONDS_FROM_1601_TO_1970;
149 ((ns_since_1970 / 1000000) as i64,
150 ((ns_since_1970 % 1000000) * 1000) as i32)
153 #[cfg(any(target_os = "macos", target_os = "ios"))]
154 unsafe fn os_get_time() -> (i64, i32) {
156 let mut tv = libc::timeval { tv_sec: 0, tv_usec: 0 };
157 imp::gettimeofday(&mut tv, ptr::null_mut());
158 (tv.tv_sec as i64, tv.tv_usec * 1000)
161 #[cfg(not(any(target_os = "macos", target_os = "ios", windows)))]
162 unsafe fn os_get_time() -> (i64, i32) {
163 let mut tv = libc::timespec { tv_sec: 0, tv_nsec: 0 };
164 imp::clock_gettime(libc::CLOCK_REALTIME, &mut tv);
165 (tv.tv_sec as i64, tv.tv_nsec as i32)
170 /// Returns the current value of a high-resolution performance counter
171 /// in nanoseconds since an unspecified epoch.
172 pub fn precise_time_ns() -> u64 {
173 return os_precise_time_ns();
176 fn os_precise_time_ns() -> u64 {
177 let mut ticks_per_s = 0;
179 libc::QueryPerformanceFrequency(&mut ticks_per_s)
181 let ticks_per_s = if ticks_per_s == 0 {1} else {ticks_per_s};
184 libc::QueryPerformanceCounter(&mut ticks)
187 return (ticks as u64 * 1000000000) / (ticks_per_s as u64);
190 #[cfg(any(target_os = "macos", target_os = "ios"))]
191 fn os_precise_time_ns() -> u64 {
192 static mut TIMEBASE: libc::mach_timebase_info = libc::mach_timebase_info { numer: 0,
194 static ONCE: std::sync::Once = std::sync::ONCE_INIT;
197 imp::mach_timebase_info(&mut TIMEBASE);
199 let time = imp::mach_absolute_time();
200 time * TIMEBASE.numer as u64 / TIMEBASE.denom as u64
204 #[cfg(not(any(windows, target_os = "macos", target_os = "ios")))]
205 fn os_precise_time_ns() -> u64 {
206 let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
208 imp::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
210 return (ts.tv_sec as u64) * 1000000000 + (ts.tv_nsec as u64)
215 /// Returns the current value of a high-resolution performance counter
216 /// in seconds since an unspecified epoch.
217 pub fn precise_time_s() -> f64 {
218 return (precise_time_ns() as f64) / 1000000000.;
223 rustrt::rust_tzset();
227 /// Holds a calendar date and time broken down into its components (year, month, day, and so on),
228 /// also called a broken-down time value.
229 // FIXME: use c_int instead of i32?
231 #[deriving(Clone, PartialEq, Eq, Show)]
233 /// Seconds after the minute - [0, 60]
236 /// Minutes after the hour - [0, 59]
239 /// Hours after midnight - [0, 23]
242 /// Day of the month - [1, 31]
245 /// Months since January - [0, 11]
251 /// Days since Sunday - [0, 6]. 0 = Sunday, 1 = Monday, ..., 6 = Saturday.
254 /// Days since January 1 - [0, 365]
257 /// Daylight Saving Time flag.
259 /// This value is positive if Daylight Saving Time is in effect, zero if Daylight Saving Time
260 /// is not in effect, and negative if this information is not available.
263 /// Identifies the time zone that was used to compute this broken-down time value, including any
264 /// adjustment for Daylight Saving Time. This is the number of seconds east of UTC. For example,
265 /// for U.S. Pacific Daylight Time, the value is -7*60*60 = -25200.
268 /// Nanoseconds after the second - [0, 10<sup>9</sup> - 1]
272 pub fn empty_tm() -> Tm {
288 /// Returns the specified time in UTC
289 pub fn at_utc(clock: Timespec) -> Tm {
291 let Timespec { sec, nsec } = clock;
292 let mut tm = empty_tm();
293 rustrt::rust_gmtime(sec, nsec, &mut tm);
298 /// Returns the current time in UTC
299 pub fn now_utc() -> Tm {
303 /// Returns the specified time in the local timezone
304 pub fn at(clock: Timespec) -> Tm {
306 let Timespec { sec, nsec } = clock;
307 let mut tm = empty_tm();
308 rustrt::rust_localtime(sec, nsec, &mut tm);
313 /// Returns the current time in the local timezone
319 /// Convert time to the seconds from January 1, 1970
320 pub fn to_timespec(&self) -> Timespec {
322 let sec = match self.tm_gmtoff {
323 0_i32 => rustrt::rust_timegm(self),
324 _ => rustrt::rust_mktime(self)
327 Timespec::new(sec, self.tm_nsec)
331 /// Convert time to the local timezone
332 pub fn to_local(&self) -> Tm {
333 at(self.to_timespec())
336 /// Convert time to the UTC
337 pub fn to_utc(&self) -> Tm {
338 at_utc(self.to_timespec())
341 /// Returns a TmFmt that outputs according to the `asctime` format in ISO
342 /// C, in the local timezone.
344 /// Example: "Thu Jan 1 00:00:00 1970"
345 pub fn ctime(&self) -> TmFmt {
352 /// Returns a TmFmt that outputs according to the `asctime` format in ISO
355 /// Example: "Thu Jan 1 00:00:00 1970"
356 pub fn asctime(&self) -> TmFmt {
359 format: FmtStr("%c"),
363 /// Formats the time according to the format string.
364 pub fn strftime<'a>(&'a self, format: &'a str) -> Result<TmFmt<'a>, ParseError> {
365 validate_format(TmFmt {
367 format: FmtStr(format),
371 /// Returns a TmFmt that outputs according to RFC 822.
373 /// local: "Thu, 22 Mar 2012 07:53:18 PST"
374 /// utc: "Thu, 22 Mar 2012 14:53:18 GMT"
375 pub fn rfc822(&self) -> TmFmt {
376 if self.tm_gmtoff == 0_i32 {
379 format: FmtStr("%a, %d %b %Y %T GMT"),
384 format: FmtStr("%a, %d %b %Y %T %Z"),
389 /// Returns a TmFmt that outputs according to RFC 822 with Zulu time.
391 /// local: "Thu, 22 Mar 2012 07:53:18 -0700"
392 /// utc: "Thu, 22 Mar 2012 14:53:18 -0000"
393 pub fn rfc822z(&self) -> TmFmt {
396 format: FmtStr("%a, %d %b %Y %T %z"),
400 /// Returns a TmFmt that outputs according to RFC 3339. RFC 3339 is
401 /// compatible with ISO 8601.
403 /// local: "2012-02-22T07:53:18-07:00"
404 /// utc: "2012-02-22T14:53:18Z"
405 pub fn rfc3339<'a>(&'a self) -> TmFmt {
413 #[deriving(PartialEq)]
414 pub enum ParseError {
426 MissingFormatConverter,
427 InvalidFormatSpecifier(char),
428 UnexpectedCharacter(char, char),
431 impl Show for ParseError {
432 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
434 InvalidSecond => write!(f, "Invalid second."),
435 InvalidMinute => write!(f, "Invalid minute."),
436 InvalidHour => write!(f, "Invalid hour."),
437 InvalidDay => write!(f, "Invalid day."),
438 InvalidMonth => write!(f, "Invalid month."),
439 InvalidYear => write!(f, "Invalid year."),
440 InvalidDayOfWeek => write!(f, "Invalid day of the week."),
441 InvalidDayOfMonth => write!(f, "Invalid day of the month."),
442 InvalidDayOfYear => write!(f, "Invalid day of the year."),
443 InvalidZoneOffset => write!(f, "Invalid zone offset."),
444 InvalidTime => write!(f, "Invalid time."),
445 MissingFormatConverter => write!(f, "Missing format converter after `%`"),
446 InvalidFormatSpecifier(ch) => write!(f, "Invalid format specifier: %{}", ch),
447 UnexpectedCharacter(a, b) => write!(f, "Expected: {}, found: {}.", a, b),
452 /// A wrapper around a `Tm` and format string that implements Show.
453 pub struct TmFmt<'a> {
464 fn validate_format<'a>(fmt: TmFmt<'a>) -> Result<TmFmt<'a>, ParseError> {
466 match (fmt.tm.tm_wday, fmt.tm.tm_mon) {
467 (0...6, 0...11) => (),
468 (_wday, 0...11) => return Err(InvalidDayOfWeek),
469 (0...6, _mon) => return Err(InvalidMonth),
470 _ => return Err(InvalidDay)
474 let mut chars = s.chars();
524 Some(c) => return Err(InvalidFormatSpecifier(c)),
525 None => return Err(MissingFormatConverter),
538 impl<'a> fmt::Show for TmFmt<'a> {
539 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
540 fn days_in_year(year: int) -> i32 {
541 if (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) {
542 366 /* Days in a leap year */
544 365 /* Days in a non-leap year */
548 fn iso_week_days(yday: i32, wday: i32) -> int {
549 /* The number of days from the first day of the first ISO week of this
550 * year to the year day YDAY with week day WDAY.
551 * ISO weeks start on Monday. The first ISO week has the year's first
553 * YDAY may be as small as yday_minimum.
555 let yday: int = yday as int;
556 let wday: int = wday as int;
557 let iso_week_start_wday: int = 1; /* Monday */
558 let iso_week1_wday: int = 4; /* Thursday */
559 let yday_minimum: int = 366;
560 /* Add enough to the first operand of % to make it nonnegative. */
561 let big_enough_multiple_of_7: int = (yday_minimum / 7 + 2) * 7;
563 yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
564 + iso_week1_wday - iso_week_start_wday
567 fn iso_week(fmt: &mut fmt::Formatter, ch:char, tm: &Tm) -> fmt::Result {
568 let mut year: int = tm.tm_year as int + 1900;
569 let mut days: int = iso_week_days (tm.tm_yday, tm.tm_wday);
572 /* This ISO week belongs to the previous year. */
574 days = iso_week_days (tm.tm_yday + (days_in_year(year)), tm.tm_wday);
576 let d: int = iso_week_days (tm.tm_yday - (days_in_year(year)),
579 /* This ISO week belongs to the next year. */
586 'G' => write!(fmt, "{}", year),
587 'g' => write!(fmt, "{:02}", (year % 100 + 100) % 100),
588 'V' => write!(fmt, "{:02}", days / 7 + 1),
593 fn parse_type(fmt: &mut fmt::Formatter, ch: char, tm: &Tm) -> fmt::Result {
598 'A' => match tm.tm_wday as int {
608 'a' => match tm.tm_wday as int {
618 'B' => match tm.tm_mon as int {
633 'b' | 'h' => match tm.tm_mon as int {
648 'C' => return write!(fmt, "{:02}", (tm.tm_year as int + 1900) / 100),
650 try!(parse_type(fmt, 'a', tm));
652 try!(parse_type(fmt, 'b', tm));
654 try!(parse_type(fmt, 'e', tm));
656 try!(parse_type(fmt, 'T', tm));
658 return parse_type(fmt, 'Y', tm);
661 try!(parse_type(fmt, 'm', tm));
663 try!(parse_type(fmt, 'd', tm));
665 return parse_type(fmt, 'y', tm);
667 'd' => return write!(fmt, "{:02}", tm.tm_mday),
668 'e' => return write!(fmt, "{:2}", tm.tm_mday),
669 'f' => return write!(fmt, "{:09}", tm.tm_nsec),
671 try!(parse_type(fmt, 'Y', tm));
673 try!(parse_type(fmt, 'm', tm));
675 return parse_type(fmt, 'd', tm);
677 'G' => return iso_week(fmt, 'G', tm),
678 'g' => return iso_week(fmt, 'g', tm),
679 'H' => return write!(fmt, "{:02}", tm.tm_hour),
681 let mut h = tm.tm_hour;
683 if h > 12 { h -= 12 }
684 return write!(fmt, "{:02}", h)
686 'j' => return write!(fmt, "{:03}", tm.tm_yday + 1),
687 'k' => return write!(fmt, "{:2}", tm.tm_hour),
689 let mut h = tm.tm_hour;
691 if h > 12 { h -= 12 }
692 return write!(fmt, "{:2}", h)
694 'M' => return write!(fmt, "{:02}", tm.tm_min),
695 'm' => return write!(fmt, "{:02}", tm.tm_mon + 1),
697 'P' => if (tm.tm_hour as int) < 12 { "am" } else { "pm" },
698 'p' => if (tm.tm_hour as int) < 12 { "AM" } else { "PM" },
700 try!(parse_type(fmt, 'H', tm));
702 return parse_type(fmt, 'M', tm);
705 try!(parse_type(fmt, 'I', tm));
707 try!(parse_type(fmt, 'M', tm));
709 try!(parse_type(fmt, 'S', tm));
711 return parse_type(fmt, 'p', tm);
713 'S' => return write!(fmt, "{:02}", tm.tm_sec),
714 's' => return write!(fmt, "{}", tm.to_timespec().sec),
716 try!(parse_type(fmt, 'H', tm));
718 try!(parse_type(fmt, 'M', tm));
720 return parse_type(fmt, 'S', tm);
723 'U' => return write!(fmt, "{:02}", (tm.tm_yday - tm.tm_wday + 7) / 7),
725 let i = tm.tm_wday as int;
726 return (if i == 0 { 7 } else { i }).fmt(fmt);
728 'V' => return iso_week(fmt, 'V', tm),
730 try!(parse_type(fmt, 'e', tm));
732 try!(parse_type(fmt, 'b', tm));
734 return parse_type(fmt, 'Y', tm);
737 return write!(fmt, "{:02}",
738 (tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7) / 7)
740 'w' => return (tm.tm_wday as int).fmt(fmt),
741 'Y' => return (tm.tm_year as int + 1900).fmt(fmt),
742 'y' => return write!(fmt, "{:02}", (tm.tm_year as int + 1900) % 100),
743 'Z' => if tm.tm_gmtoff == 0_i32 { "GMT"} else { "" }, // FIXME (#2350): support locale
745 let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
746 let mut m = tm.tm_gmtoff.abs() / 60_i32;
749 return write!(fmt, "{}{:02}{:02}", sign, h, m);
751 '+' => return tm.rfc3339().fmt(fmt),
759 let mut chars = s.chars();
763 // we've already validated that % always precedes another char
764 try!(parse_type(fmt, chars.next().unwrap(), self.tm));
766 Some(ch) => try!(ch.fmt(fmt)),
774 self.tm.to_local().asctime().fmt(fmt)
777 if self.tm.tm_gmtoff == 0_i32 {
780 format: FmtStr("%Y-%m-%dT%H:%M:%SZ"),
785 format: FmtStr("%Y-%m-%dT%H:%M:%S"),
787 let sign = if self.tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
788 let mut m = self.tm.tm_gmtoff.abs() / 60_i32;
791 write!(fmt, "{}{}{:02}:{:02}", s, sign, h as int, m as int)
798 /// Parses the time from the string according to the format string.
799 pub fn strptime(s: &str, format: &str) -> Result<Tm, ParseError> {
800 fn match_str(s: &str, pos: uint, needle: &str) -> bool {
801 s.slice_from(pos).starts_with(needle)
804 fn match_strs(ss: &str, pos: uint, strs: &[(&str, i32)])
805 -> Option<(i32, uint)> {
806 for &(needle, value) in strs.iter() {
807 if match_str(ss, pos, needle) {
808 return Some((value, pos + needle.len()));
815 fn match_digits(ss: &str, pos: uint, digits: uint, ws: bool)
816 -> Option<(i32, uint)> {
819 let mut value = 0_i32;
826 let range = ss.char_range_at(pos);
831 value = value * 10_i32 + (range.ch as i32 - '0' as i32);
842 fn match_fractional_seconds(ss: &str, pos: uint) -> (i32, uint) {
844 let mut value = 0_i32;
845 let mut multiplier = NSEC_PER_SEC / 10;
852 let range = ss.char_range_at(pos);
857 // This will drop digits after the nanoseconds place
858 let digit = range.ch as i32 - '0' as i32;
859 value += digit * multiplier;
869 fn match_digits_in_range(ss: &str, pos: uint, digits: uint, ws: bool,
870 min: i32, max: i32) -> Option<(i32, uint)> {
871 match match_digits(ss, pos, digits, ws) {
872 Some((val, pos)) if val >= min && val <= max => {
879 fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, ParseError> {
880 let range = s.char_range_at(pos);
885 Err(UnexpectedCharacter(c, range.ch))
889 fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
890 -> Result<uint, ParseError> {
892 'A' => match match_strs(s, pos, &[
896 ("Wednesday", 3_i32),
901 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
902 None => Err(InvalidDay)
904 'a' => match match_strs(s, pos, &[
913 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
914 None => Err(InvalidDay)
916 'B' => match match_strs(s, pos, &[
925 ("September", 8_i32),
927 ("November", 10_i32),
930 Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
931 None => Err(InvalidMonth)
933 'b' | 'h' => match match_strs(s, pos, &[
947 Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
948 None => Err(InvalidMonth)
950 'C' => match match_digits_in_range(s, pos, 2u, false, 0_i32,
954 tm.tm_year += (v * 100_i32) - 1900_i32;
957 None => Err(InvalidYear)
960 parse_type(s, pos, 'a', &mut *tm)
961 .and_then(|pos| parse_char(s, pos, ' '))
962 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
963 .and_then(|pos| parse_char(s, pos, ' '))
964 .and_then(|pos| parse_type(s, pos, 'e', &mut *tm))
965 .and_then(|pos| parse_char(s, pos, ' '))
966 .and_then(|pos| parse_type(s, pos, 'T', &mut *tm))
967 .and_then(|pos| parse_char(s, pos, ' '))
968 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
971 parse_type(s, pos, 'm', &mut *tm)
972 .and_then(|pos| parse_char(s, pos, '/'))
973 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
974 .and_then(|pos| parse_char(s, pos, '/'))
975 .and_then(|pos| parse_type(s, pos, 'y', &mut *tm))
977 'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
979 Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
980 None => Err(InvalidDayOfMonth)
982 'e' => match match_digits_in_range(s, pos, 2u, true, 1_i32,
984 Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
985 None => Err(InvalidDayOfMonth)
988 let (val, pos) = match_fractional_seconds(s, pos);
993 parse_type(s, pos, 'Y', &mut *tm)
994 .and_then(|pos| parse_char(s, pos, '-'))
995 .and_then(|pos| parse_type(s, pos, 'm', &mut *tm))
996 .and_then(|pos| parse_char(s, pos, '-'))
997 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
1000 match match_digits_in_range(s, pos, 2u, false, 0_i32, 23_i32) {
1001 Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
1002 None => Err(InvalidHour)
1006 match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
1008 let (v, pos) = item;
1009 tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
1012 None => Err(InvalidHour)
1016 match match_digits_in_range(s, pos, 3u, false, 1_i32, 366_i32) {
1018 let (v, pos) = item;
1019 tm.tm_yday = v - 1_i32;
1022 None => Err(InvalidDayOfYear)
1026 match match_digits_in_range(s, pos, 2u, true, 0_i32, 23_i32) {
1027 Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
1028 None => Err(InvalidHour)
1032 match match_digits_in_range(s, pos, 2u, true, 1_i32, 12_i32) {
1034 let (v, pos) = item;
1035 tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
1038 None => Err(InvalidHour)
1042 match match_digits_in_range(s, pos, 2u, false, 0_i32, 59_i32) {
1043 Some(item) => { let (v, pos) = item; tm.tm_min = v; Ok(pos) }
1044 None => Err(InvalidMinute)
1048 match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
1050 let (v, pos) = item;
1051 tm.tm_mon = v - 1_i32;
1054 None => Err(InvalidMonth)
1057 'n' => parse_char(s, pos, '\n'),
1058 'P' => match match_strs(s, pos,
1059 &[("am", 0_i32), ("pm", 12_i32)]) {
1061 Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
1062 None => Err(InvalidHour)
1064 'p' => match match_strs(s, pos,
1065 &[("AM", 0_i32), ("PM", 12_i32)]) {
1067 Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
1068 None => Err(InvalidHour)
1071 parse_type(s, pos, 'H', &mut *tm)
1072 .and_then(|pos| parse_char(s, pos, ':'))
1073 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
1076 parse_type(s, pos, 'I', &mut *tm)
1077 .and_then(|pos| parse_char(s, pos, ':'))
1078 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
1079 .and_then(|pos| parse_char(s, pos, ':'))
1080 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
1081 .and_then(|pos| parse_char(s, pos, ' '))
1082 .and_then(|pos| parse_type(s, pos, 'p', &mut *tm))
1085 match match_digits_in_range(s, pos, 2u, false, 0_i32, 60_i32) {
1087 let (v, pos) = item;
1091 None => Err(InvalidSecond)
1096 parse_type(s, pos, 'H', &mut *tm)
1097 .and_then(|pos| parse_char(s, pos, ':'))
1098 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
1099 .and_then(|pos| parse_char(s, pos, ':'))
1100 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
1102 't' => parse_char(s, pos, '\t'),
1104 match match_digits_in_range(s, pos, 1u, false, 1_i32, 7_i32) {
1106 let (v, pos) = item;
1107 tm.tm_wday = if v == 7 { 0 } else { v };
1110 None => Err(InvalidDayOfWeek)
1114 parse_type(s, pos, 'e', &mut *tm)
1115 .and_then(|pos| parse_char(s, pos, '-'))
1116 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
1117 .and_then(|pos| parse_char(s, pos, '-'))
1118 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
1122 match match_digits_in_range(s, pos, 1u, false, 0_i32, 6_i32) {
1123 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
1124 None => Err(InvalidDayOfWeek)
1128 match match_digits(s, pos, 4u, false) {
1130 let (v, pos) = item;
1131 tm.tm_year = v - 1900_i32;
1134 None => Err(InvalidYear)
1138 match match_digits_in_range(s, pos, 2u, false, 0_i32, 99_i32) {
1140 let (v, pos) = item;
1144 None => Err(InvalidYear)
1148 if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") {
1149 tm.tm_gmtoff = 0_i32;
1152 // It's odd, but to maintain compatibility with c's
1153 // strptime we ignore the timezone.
1157 let range = s.char_range_at(pos);
1159 if range.ch == ' ' { break; }
1166 let range = s.char_range_at(pos);
1168 if range.ch == '+' || range.ch == '-' {
1169 match match_digits(s, range.next, 4u, false) {
1171 let (v, pos) = item;
1173 tm.tm_gmtoff = 0_i32;
1178 None => Err(InvalidZoneOffset)
1181 Err(InvalidZoneOffset)
1184 '%' => parse_char(s, pos, '%'),
1185 ch => Err(InvalidFormatSpecifier(ch))
1189 let mut rdr: &[u8] = format.as_bytes();
1205 let mut result = Err(InvalidTime);
1208 let range = s.char_range_at(pos);
1210 let next = range.next;
1213 let c = match (&mut rdr).read(&mut buf) {
1214 Ok(..) => buf[0] as char,
1219 let ch = match (&mut rdr).read(&mut buf) {
1220 Ok(..) => buf[0] as char,
1223 match parse_type(s, pos, ch, &mut tm) {
1224 Ok(next) => pos = next,
1225 Err(e) => { result = Err(e); break; }
1229 if c != ch { break }
1235 if pos == len && (&mut rdr).is_empty() {
1239 tm_hour: tm.tm_hour,
1240 tm_mday: tm.tm_mday,
1242 tm_year: tm.tm_year,
1243 tm_wday: tm.tm_wday,
1244 tm_yday: tm.tm_yday,
1245 tm_isdst: tm.tm_isdst,
1246 tm_gmtoff: tm.tm_gmtoff,
1247 tm_nsec: tm.tm_nsec,
1252 /// Formats the time according to the format string.
1253 pub fn strftime(format: &str, tm: &Tm) -> Result<String, ParseError> {
1254 tm.strftime(format).map(|fmt| fmt.to_string())
1260 use super::{Timespec, InvalidTime, InvalidYear, get_time, precise_time_ns,
1261 precise_time_s, tzset, at_utc, at, strptime, MissingFormatConverter,
1262 InvalidFormatSpecifier};
1265 use std::result::{Err, Ok};
1266 use std::time::Duration;
1267 use self::test::Bencher;
1270 fn set_time_zone() {
1272 // Windows crt doesn't see any environment variable set by
1273 // `SetEnvironmentVariable`, which `os::setenv` internally uses.
1274 // It is why we use `putenv` here.
1276 fn _putenv(envstring: *const libc::c_char) -> libc::c_int;
1280 // Windows does not understand "America/Los_Angeles".
1281 // PST+08 may look wrong, but not! "PST" indicates
1282 // the name of timezone. "+08" means UTC = local + 08.
1283 "TZ=PST+08".with_c_str(|env| {
1289 #[cfg(not(windows))]
1290 fn set_time_zone() {
1292 os::setenv("TZ", "America/Los_Angeles");
1296 fn test_get_time() {
1297 static SOME_RECENT_DATE: i64 = 1325376000i64; // 2012-01-01T00:00:00Z
1298 static SOME_FUTURE_DATE: i64 = 1577836800i64; // 2020-01-01T00:00:00Z
1300 let tv1 = get_time();
1301 debug!("tv1={} sec + {} nsec", tv1.sec as uint, tv1.nsec as uint);
1303 assert!(tv1.sec > SOME_RECENT_DATE);
1304 assert!(tv1.nsec < 1000000000i32);
1306 let tv2 = get_time();
1307 debug!("tv2={} sec + {} nsec", tv2.sec as uint, tv2.nsec as uint);
1309 assert!(tv2.sec >= tv1.sec);
1310 assert!(tv2.sec < SOME_FUTURE_DATE);
1311 assert!(tv2.nsec < 1000000000i32);
1312 if tv2.sec == tv1.sec {
1313 assert!(tv2.nsec >= tv1.nsec);
1317 fn test_precise_time() {
1318 let s0 = precise_time_s();
1319 debug!("s0={} sec", f64::to_str_digits(s0, 9u));
1322 let ns0 = precise_time_ns();
1323 let ns1 = precise_time_ns();
1324 debug!("ns0={} ns", ns0);
1325 debug!("ns1={} ns", ns1);
1326 assert!(ns1 >= ns0);
1328 let ns2 = precise_time_ns();
1329 debug!("ns2={} ns", ns2);
1330 assert!(ns2 >= ns1);
1336 let time = Timespec::new(1234567890, 54321);
1337 let utc = at_utc(time);
1339 assert_eq!(utc.tm_sec, 30_i32);
1340 assert_eq!(utc.tm_min, 31_i32);
1341 assert_eq!(utc.tm_hour, 23_i32);
1342 assert_eq!(utc.tm_mday, 13_i32);
1343 assert_eq!(utc.tm_mon, 1_i32);
1344 assert_eq!(utc.tm_year, 109_i32);
1345 assert_eq!(utc.tm_wday, 5_i32);
1346 assert_eq!(utc.tm_yday, 43_i32);
1347 assert_eq!(utc.tm_isdst, 0_i32);
1348 assert_eq!(utc.tm_gmtoff, 0_i32);
1349 assert_eq!(utc.tm_nsec, 54321_i32);
1355 let time = Timespec::new(1234567890, 54321);
1356 let local = at(time);
1358 debug!("time_at: {}", local);
1360 assert_eq!(local.tm_sec, 30_i32);
1361 assert_eq!(local.tm_min, 31_i32);
1362 assert_eq!(local.tm_hour, 15_i32);
1363 assert_eq!(local.tm_mday, 13_i32);
1364 assert_eq!(local.tm_mon, 1_i32);
1365 assert_eq!(local.tm_year, 109_i32);
1366 assert_eq!(local.tm_wday, 5_i32);
1367 assert_eq!(local.tm_yday, 43_i32);
1368 assert_eq!(local.tm_isdst, 0_i32);
1369 assert_eq!(local.tm_gmtoff, -28800_i32);
1370 assert_eq!(local.tm_nsec, 54321_i32);
1373 fn test_to_timespec() {
1376 let time = Timespec::new(1234567890, 54321);
1377 let utc = at_utc(time);
1379 assert_eq!(utc.to_timespec(), time);
1380 assert_eq!(utc.to_local().to_timespec(), time);
1383 fn test_conversions() {
1386 let time = Timespec::new(1234567890, 54321);
1387 let utc = at_utc(time);
1388 let local = at(time);
1390 assert!(local.to_local() == local);
1391 assert!(local.to_utc() == utc);
1392 assert!(local.to_utc().to_local() == local);
1393 assert!(utc.to_utc() == utc);
1394 assert!(utc.to_local() == local);
1395 assert!(utc.to_local().to_utc() == utc);
1398 fn test_strptime() {
1401 match strptime("", "") {
1403 assert!(tm.tm_sec == 0_i32);
1404 assert!(tm.tm_min == 0_i32);
1405 assert!(tm.tm_hour == 0_i32);
1406 assert!(tm.tm_mday == 0_i32);
1407 assert!(tm.tm_mon == 0_i32);
1408 assert!(tm.tm_year == 0_i32);
1409 assert!(tm.tm_wday == 0_i32);
1410 assert!(tm.tm_isdst == 0_i32);
1411 assert!(tm.tm_gmtoff == 0_i32);
1412 assert!(tm.tm_nsec == 0_i32);
1417 let format = "%a %b %e %T.%f %Y";
1418 assert_eq!(strptime("", format), Err(InvalidTime));
1419 assert!(strptime("Fri Feb 13 15:31:30", format)
1420 == Err(InvalidTime));
1422 match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
1423 Err(e) => panic!(e),
1425 assert!(tm.tm_sec == 30_i32);
1426 assert!(tm.tm_min == 31_i32);
1427 assert!(tm.tm_hour == 15_i32);
1428 assert!(tm.tm_mday == 13_i32);
1429 assert!(tm.tm_mon == 1_i32);
1430 assert!(tm.tm_year == 109_i32);
1431 assert!(tm.tm_wday == 5_i32);
1432 assert!(tm.tm_yday == 0_i32);
1433 assert!(tm.tm_isdst == 0_i32);
1434 assert!(tm.tm_gmtoff == 0_i32);
1435 assert!(tm.tm_nsec == 12340000_i32);
1439 fn test(s: &str, format: &str) -> bool {
1440 match strptime(s, format) {
1442 tm.strftime(format).unwrap().to_string() == s.to_string()
1449 "Sunday".to_string(),
1450 "Monday".to_string(),
1451 "Tuesday".to_string(),
1452 "Wednesday".to_string(),
1453 "Thursday".to_string(),
1454 "Friday".to_string(),
1455 "Saturday".to_string()
1457 for day in days.iter() {
1458 assert!(test(day.as_slice(), "%A"));
1470 for day in days.iter() {
1471 assert!(test(day.as_slice(), "%a"));
1475 "January".to_string(),
1476 "February".to_string(),
1477 "March".to_string(),
1478 "April".to_string(),
1482 "August".to_string(),
1483 "September".to_string(),
1484 "October".to_string(),
1485 "November".to_string(),
1486 "December".to_string()
1488 for day in months.iter() {
1489 assert!(test(day.as_slice(), "%B"));
1506 for day in months.iter() {
1507 assert!(test(day.as_slice(), "%b"));
1510 assert!(test("19", "%C"));
1511 assert!(test("Fri Feb 13 23:31:30 2009", "%c"));
1512 assert!(test("02/13/09", "%D"));
1513 assert!(test("03", "%d"));
1514 assert!(test("13", "%d"));
1515 assert!(test(" 3", "%e"));
1516 assert!(test("13", "%e"));
1517 assert!(test("2009-02-13", "%F"));
1518 assert!(test("03", "%H"));
1519 assert!(test("13", "%H"));
1520 assert!(test("03", "%I")); // FIXME (#2350): flesh out
1521 assert!(test("11", "%I")); // FIXME (#2350): flesh out
1522 assert!(test("044", "%j"));
1523 assert!(test(" 3", "%k"));
1524 assert!(test("13", "%k"));
1525 assert!(test(" 1", "%l"));
1526 assert!(test("11", "%l"));
1527 assert!(test("03", "%M"));
1528 assert!(test("13", "%M"));
1529 assert!(test("\n", "%n"));
1530 assert!(test("am", "%P"));
1531 assert!(test("pm", "%P"));
1532 assert!(test("AM", "%p"));
1533 assert!(test("PM", "%p"));
1534 assert!(test("23:31", "%R"));
1535 assert!(test("11:31:30 AM", "%r"));
1536 assert!(test("11:31:30 PM", "%r"));
1537 assert!(test("03", "%S"));
1538 assert!(test("13", "%S"));
1539 assert!(test("15:31:30", "%T"));
1540 assert!(test("\t", "%t"));
1541 assert!(test("1", "%u"));
1542 assert!(test("7", "%u"));
1543 assert!(test("13-Feb-2009", "%v"));
1544 assert!(test("0", "%w"));
1545 assert!(test("6", "%w"));
1546 assert!(test("2009", "%Y"));
1547 assert!(test("09", "%y"));
1548 assert!(strptime("-0000", "%z").unwrap().tm_gmtoff ==
1550 assert!(strptime("-0800", "%z").unwrap().tm_gmtoff ==
1552 assert!(test("%", "%%"));
1555 assert_eq!(strptime("360", "%Y-%m-%d"), Err(InvalidYear));
1561 let time = Timespec::new(1234567890, 54321);
1562 let utc = at_utc(time);
1563 let local = at(time);
1565 debug!("test_ctime: {} {}", utc.asctime(), local.asctime());
1567 assert_eq!(utc.asctime().to_string(), "Fri Feb 13 23:31:30 2009".to_string());
1568 assert_eq!(local.asctime().to_string(), "Fri Feb 13 15:31:30 2009".to_string());
1574 let time = Timespec::new(1234567890, 54321);
1575 let utc = at_utc(time);
1576 let local = at(time);
1578 debug!("test_ctime: {} {}", utc.ctime(), local.ctime());
1580 assert_eq!(utc.ctime().to_string(), "Fri Feb 13 15:31:30 2009".to_string());
1581 assert_eq!(local.ctime().to_string(), "Fri Feb 13 15:31:30 2009".to_string());
1584 fn test_strftime() {
1587 let time = Timespec::new(1234567890, 54321);
1588 let utc = at_utc(time);
1589 let local = at(time);
1591 assert_eq!(local.strftime("").unwrap().to_string(), "".to_string());
1592 assert_eq!(local.strftime("%A").unwrap().to_string(), "Friday".to_string());
1593 assert_eq!(local.strftime("%a").unwrap().to_string(), "Fri".to_string());
1594 assert_eq!(local.strftime("%B").unwrap().to_string(), "February".to_string());
1595 assert_eq!(local.strftime("%b").unwrap().to_string(), "Feb".to_string());
1596 assert_eq!(local.strftime("%C").unwrap().to_string(), "20".to_string());
1597 assert_eq!(local.strftime("%c").unwrap().to_string(),
1598 "Fri Feb 13 15:31:30 2009".to_string());
1599 assert_eq!(local.strftime("%D").unwrap().to_string(), "02/13/09".to_string());
1600 assert_eq!(local.strftime("%d").unwrap().to_string(), "13".to_string());
1601 assert_eq!(local.strftime("%e").unwrap().to_string(), "13".to_string());
1602 assert_eq!(local.strftime("%F").unwrap().to_string(), "2009-02-13".to_string());
1603 assert_eq!(local.strftime("%f").unwrap().to_string(), "000054321".to_string());
1604 assert_eq!(local.strftime("%G").unwrap().to_string(), "2009".to_string());
1605 assert_eq!(local.strftime("%g").unwrap().to_string(), "09".to_string());
1606 assert_eq!(local.strftime("%H").unwrap().to_string(), "15".to_string());
1607 assert_eq!(local.strftime("%h").unwrap().to_string(), "Feb".to_string());
1608 assert_eq!(local.strftime("%I").unwrap().to_string(), "03".to_string());
1609 assert_eq!(local.strftime("%j").unwrap().to_string(), "044".to_string());
1610 assert_eq!(local.strftime("%k").unwrap().to_string(), "15".to_string());
1611 assert_eq!(local.strftime("%l").unwrap().to_string(), " 3".to_string());
1612 assert_eq!(local.strftime("%M").unwrap().to_string(), "31".to_string());
1613 assert_eq!(local.strftime("%m").unwrap().to_string(), "02".to_string());
1614 assert_eq!(local.strftime("%n").unwrap().to_string(), "\n".to_string());
1615 assert_eq!(local.strftime("%P").unwrap().to_string(), "pm".to_string());
1616 assert_eq!(local.strftime("%p").unwrap().to_string(), "PM".to_string());
1617 assert_eq!(local.strftime("%R").unwrap().to_string(), "15:31".to_string());
1618 assert_eq!(local.strftime("%r").unwrap().to_string(), "03:31:30 PM".to_string());
1619 assert_eq!(local.strftime("%S").unwrap().to_string(), "30".to_string());
1620 assert_eq!(local.strftime("%s").unwrap().to_string(), "1234567890".to_string());
1621 assert_eq!(local.strftime("%T").unwrap().to_string(), "15:31:30".to_string());
1622 assert_eq!(local.strftime("%t").unwrap().to_string(), "\t".to_string());
1623 assert_eq!(local.strftime("%U").unwrap().to_string(), "06".to_string());
1624 assert_eq!(local.strftime("%u").unwrap().to_string(), "5".to_string());
1625 assert_eq!(local.strftime("%V").unwrap().to_string(), "07".to_string());
1626 assert_eq!(local.strftime("%v").unwrap().to_string(), "13-Feb-2009".to_string());
1627 assert_eq!(local.strftime("%W").unwrap().to_string(), "06".to_string());
1628 assert_eq!(local.strftime("%w").unwrap().to_string(), "5".to_string());
1629 // FIXME (#2350): support locale
1630 assert_eq!(local.strftime("%X").unwrap().to_string(), "15:31:30".to_string());
1631 // FIXME (#2350): support locale
1632 assert_eq!(local.strftime("%x").unwrap().to_string(), "02/13/09".to_string());
1633 assert_eq!(local.strftime("%Y").unwrap().to_string(), "2009".to_string());
1634 assert_eq!(local.strftime("%y").unwrap().to_string(), "09".to_string());
1635 // FIXME (#2350): support locale
1636 assert_eq!(local.strftime("%Z").unwrap().to_string(), "".to_string());
1637 assert_eq!(local.strftime("%z").unwrap().to_string(), "-0800".to_string());
1638 assert_eq!(local.strftime("%+").unwrap().to_string(),
1639 "2009-02-13T15:31:30-08:00".to_string());
1640 assert_eq!(local.strftime("%%").unwrap().to_string(), "%".to_string());
1642 let invalid_specifiers = ["%E", "%J", "%K", "%L", "%N", "%O", "%o", "%Q", "%q"];
1643 for &sp in invalid_specifiers.iter() {
1644 assert_eq!(local.strftime(sp).unwrap_err(), InvalidFormatSpecifier(sp.char_at(1)));
1646 assert_eq!(local.strftime("%").unwrap_err(), MissingFormatConverter);
1647 assert_eq!(local.strftime("%A %").unwrap_err(), MissingFormatConverter);
1649 assert_eq!(local.asctime().to_string(), "Fri Feb 13 15:31:30 2009".to_string());
1650 assert_eq!(local.ctime().to_string(), "Fri Feb 13 15:31:30 2009".to_string());
1651 assert_eq!(local.rfc822z().to_string(), "Fri, 13 Feb 2009 15:31:30 -0800".to_string());
1652 assert_eq!(local.rfc3339().to_string(), "2009-02-13T15:31:30-08:00".to_string());
1654 assert_eq!(utc.asctime().to_string(), "Fri Feb 13 23:31:30 2009".to_string());
1655 assert_eq!(utc.ctime().to_string(), "Fri Feb 13 15:31:30 2009".to_string());
1656 assert_eq!(utc.rfc822().to_string(), "Fri, 13 Feb 2009 23:31:30 GMT".to_string());
1657 assert_eq!(utc.rfc822z().to_string(), "Fri, 13 Feb 2009 23:31:30 -0000".to_string());
1658 assert_eq!(utc.rfc3339().to_string(), "2009-02-13T23:31:30Z".to_string());
1661 fn test_timespec_eq_ord() {
1662 let a = &Timespec::new(-2, 1);
1663 let b = &Timespec::new(-1, 2);
1664 let c = &Timespec::new(1, 2);
1665 let d = &Timespec::new(2, 1);
1666 let e = &Timespec::new(2, 1);
1692 fn test_timespec_add() {
1693 let a = Timespec::new(1, 2);
1694 let b = Duration::seconds(2) + Duration::nanoseconds(3);
1696 assert_eq!(c.sec, 3);
1697 assert_eq!(c.nsec, 5);
1699 let p = Timespec::new(1, super::NSEC_PER_SEC - 2);
1700 let q = Duration::seconds(2) + Duration::nanoseconds(2);
1702 assert_eq!(r.sec, 4);
1703 assert_eq!(r.nsec, 0);
1705 let u = Timespec::new(1, super::NSEC_PER_SEC - 2);
1706 let v = Duration::seconds(2) + Duration::nanoseconds(3);
1708 assert_eq!(w.sec, 4);
1709 assert_eq!(w.nsec, 1);
1711 let k = Timespec::new(1, 0);
1712 let l = Duration::nanoseconds(-1);
1714 assert_eq!(m.sec, 0);
1715 assert_eq!(m.nsec, 999_999_999);
1718 fn test_timespec_sub() {
1719 let a = Timespec::new(2, 3);
1720 let b = Timespec::new(1, 2);
1722 assert_eq!(c.num_nanoseconds(), Some(super::NSEC_PER_SEC as i64 + 1));
1724 let p = Timespec::new(2, 0);
1725 let q = Timespec::new(1, 2);
1727 assert_eq!(r.num_nanoseconds(), Some(super::NSEC_PER_SEC as i64 - 2));
1729 let u = Timespec::new(1, 2);
1730 let v = Timespec::new(2, 3);
1732 assert_eq!(w.num_nanoseconds(), Some(-super::NSEC_PER_SEC as i64 - 1));
1736 #[cfg_attr(target_os = "android", ignore)] // FIXME #10958
1738 // The tests race on tzset. So instead of having many independent
1739 // tests, we will just call the functions now.
1741 test_precise_time();
1750 test_timespec_eq_ord();
1751 test_timespec_add();
1752 test_timespec_sub();
1756 fn bench_precise_time_ns(b: &mut Bencher) {
1757 b.iter(|| precise_time_ns())