]> git.lizzy.rs Git - rust.git/blob - src/libtime/lib.rs
auto merge of #19628 : jbranchaud/rust/add-string-as-string-doctest, r=steveklabnik
[rust.git] / src / libtime / lib.rs
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 #![crate_name = "time"]
14 #![deprecated = "use the http://github.com/rust-lang/time crate instead"]
15 #![allow(deprecated)]
16
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)]
24
25 #[cfg(test)] #[phase(plugin, link)] extern crate log;
26
27 extern crate serialize;
28 extern crate libc;
29
30 pub use self::ParseError::*;
31 use self::Fmt::*;
32
33 use std::fmt::Show;
34 use std::fmt;
35 use std::num::SignedInt;
36 use std::string::String;
37 use std::time::Duration;
38
39 static NSEC_PER_SEC: i32 = 1_000_000_000_i32;
40
41 mod rustrt {
42     use super::Tm;
43
44     extern {
45         pub fn rust_tzset();
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;
50     }
51 }
52
53 #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios")))]
54 mod imp {
55     use libc::{c_int, timespec};
56
57     // Apparently android provides this in some other library?
58     #[cfg(not(target_os = "android"))]
59     #[link(name = "rt")]
60     extern {}
61
62     extern {
63         pub fn clock_gettime(clk_id: c_int, tp: *mut timespec) -> c_int;
64     }
65
66 }
67 #[cfg(any(target_os = "macos", target_os = "ios"))]
68 mod imp {
69     use libc::{timeval, timezone, c_int, mach_timebase_info};
70
71     extern {
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;
75     }
76 }
77
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 {
81     pub sec: i64,
82     pub nsec: i32,
83 }
84
85 impl Copy for Timespec {}
86
87 /*
88  * Timespec assumes that pre-epoch Timespecs have negative sec and positive
89  * nsec fields. Darwin's and Linux's struct timespec functions handle pre-
90  * epoch timestamps using a "two steps back, one step forward" representation,
91  * though the man pages do not actually document this. For example, the time
92  * -1.2 seconds before the epoch is represented by `Timespec { sec: -2_i64,
93  * nsec: 800_000_000_i32 }`.
94  */
95 impl Timespec {
96     pub fn new(sec: i64, nsec: i32) -> Timespec {
97         assert!(nsec >= 0 && nsec < NSEC_PER_SEC);
98         Timespec { sec: sec, nsec: nsec }
99     }
100 }
101
102 impl Add<Duration, Timespec> for Timespec {
103     fn add(&self, other: &Duration) -> Timespec {
104         let d_sec = other.num_seconds();
105         // It is safe to unwrap the nanoseconds, because there cannot be
106         // more than one second left, which fits in i64 and in i32.
107         let d_nsec = (*other - Duration::seconds(d_sec))
108                      .num_nanoseconds().unwrap() as i32;
109         let mut sec = self.sec + d_sec;
110         let mut nsec = self.nsec + d_nsec;
111         if nsec >= NSEC_PER_SEC {
112             nsec -= NSEC_PER_SEC;
113             sec += 1;
114         } else if nsec < 0 {
115             nsec += NSEC_PER_SEC;
116             sec -= 1;
117         }
118         Timespec::new(sec, nsec)
119     }
120 }
121
122 impl Sub<Timespec, Duration> for Timespec {
123     fn sub(&self, other: &Timespec) -> Duration {
124         let sec = self.sec - other.sec;
125         let nsec = self.nsec - other.nsec;
126         Duration::seconds(sec) + Duration::nanoseconds(nsec as i64)
127     }
128 }
129
130 /// Returns the current time as a `timespec` containing the seconds and
131 /// nanoseconds since 1970-01-01T00:00:00Z.
132 pub fn get_time() -> Timespec {
133     unsafe {
134         let (sec, nsec) = os_get_time();
135         return Timespec::new(sec, nsec);
136     }
137
138     #[cfg(windows)]
139     unsafe fn os_get_time() -> (i64, i32) {
140         static NANOSECONDS_FROM_1601_TO_1970: u64 = 11644473600000000;
141
142         let mut time = libc::FILETIME {
143             dwLowDateTime: 0,
144             dwHighDateTime: 0,
145         };
146         libc::GetSystemTimeAsFileTime(&mut time);
147
148         // A FILETIME contains a 64-bit value representing the number of
149         // hectonanosecond (100-nanosecond) intervals since 1601-01-01T00:00:00Z.
150         // http://support.microsoft.com/kb/167296/en-us
151         let ns_since_1601 = ((time.dwHighDateTime as u64 << 32) |
152                              (time.dwLowDateTime  as u64 <<  0)) / 10;
153         let ns_since_1970 = ns_since_1601 - NANOSECONDS_FROM_1601_TO_1970;
154
155         ((ns_since_1970 / 1000000) as i64,
156          ((ns_since_1970 % 1000000) * 1000) as i32)
157     }
158
159     #[cfg(any(target_os = "macos", target_os = "ios"))]
160     unsafe fn os_get_time() -> (i64, i32) {
161         use std::ptr;
162         let mut tv = libc::timeval { tv_sec: 0, tv_usec: 0 };
163         imp::gettimeofday(&mut tv, ptr::null_mut());
164         (tv.tv_sec as i64, tv.tv_usec * 1000)
165     }
166
167     #[cfg(not(any(target_os = "macos", target_os = "ios", windows)))]
168     unsafe fn os_get_time() -> (i64, i32) {
169         let mut tv = libc::timespec { tv_sec: 0, tv_nsec: 0 };
170         imp::clock_gettime(libc::CLOCK_REALTIME, &mut tv);
171         (tv.tv_sec as i64, tv.tv_nsec as i32)
172     }
173 }
174
175
176 /// Returns the current value of a high-resolution performance counter
177 /// in nanoseconds since an unspecified epoch.
178 pub fn precise_time_ns() -> u64 {
179     return os_precise_time_ns();
180
181     #[cfg(windows)]
182     fn os_precise_time_ns() -> u64 {
183         let mut ticks_per_s = 0;
184         assert_eq!(unsafe {
185             libc::QueryPerformanceFrequency(&mut ticks_per_s)
186         }, 1);
187         let ticks_per_s = if ticks_per_s == 0 {1} else {ticks_per_s};
188         let mut ticks = 0;
189         assert_eq!(unsafe {
190             libc::QueryPerformanceCounter(&mut ticks)
191         }, 1);
192
193         return (ticks as u64 * 1000000000) / (ticks_per_s as u64);
194     }
195
196     #[cfg(any(target_os = "macos", target_os = "ios"))]
197     fn os_precise_time_ns() -> u64 {
198         static mut TIMEBASE: libc::mach_timebase_info = libc::mach_timebase_info { numer: 0,
199                                                                                    denom: 0 };
200         static ONCE: std::sync::Once = std::sync::ONCE_INIT;
201         unsafe {
202             ONCE.doit(|| {
203                 imp::mach_timebase_info(&mut TIMEBASE);
204             });
205             let time = imp::mach_absolute_time();
206             time * TIMEBASE.numer as u64 / TIMEBASE.denom as u64
207         }
208     }
209
210     #[cfg(not(any(windows, target_os = "macos", target_os = "ios")))]
211     fn os_precise_time_ns() -> u64 {
212         let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
213         unsafe {
214             imp::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
215         }
216         return (ts.tv_sec as u64) * 1000000000 + (ts.tv_nsec as u64)
217     }
218 }
219
220
221 /// Returns the current value of a high-resolution performance counter
222 /// in seconds since an unspecified epoch.
223 pub fn precise_time_s() -> f64 {
224     return (precise_time_ns() as f64) / 1000000000.;
225 }
226
227 pub fn tzset() {
228     unsafe {
229         rustrt::rust_tzset();
230     }
231 }
232
233 /// Holds a calendar date and time broken down into its components (year, month, day, and so on),
234 /// also called a broken-down time value.
235 // FIXME: use c_int instead of i32?
236 #[repr(C)]
237 #[deriving(Clone, PartialEq, Eq, Show)]
238 pub struct Tm {
239     /// Seconds after the minute - [0, 60]
240     pub tm_sec: i32,
241
242     /// Minutes after the hour - [0, 59]
243     pub tm_min: i32,
244
245     /// Hours after midnight - [0, 23]
246     pub tm_hour: i32,
247
248     /// Day of the month - [1, 31]
249     pub tm_mday: i32,
250
251     /// Months since January - [0, 11]
252     pub tm_mon: i32,
253
254     /// Years since 1900
255     pub tm_year: i32,
256
257     /// Days since Sunday - [0, 6]. 0 = Sunday, 1 = Monday, ..., 6 = Saturday.
258     pub tm_wday: i32,
259
260     /// Days since January 1 - [0, 365]
261     pub tm_yday: i32,
262
263     /// Daylight Saving Time flag.
264     ///
265     /// This value is positive if Daylight Saving Time is in effect, zero if Daylight Saving Time
266     /// is not in effect, and negative if this information is not available.
267     pub tm_isdst: i32,
268
269     /// Identifies the time zone that was used to compute this broken-down time value, including any
270     /// adjustment for Daylight Saving Time. This is the number of seconds east of UTC. For example,
271     /// for U.S. Pacific Daylight Time, the value is -7*60*60 = -25200.
272     pub tm_gmtoff: i32,
273
274     /// Nanoseconds after the second - [0, 10<sup>9</sup> - 1]
275     pub tm_nsec: i32,
276 }
277
278 impl Copy for Tm {}
279
280 pub fn empty_tm() -> Tm {
281     Tm {
282         tm_sec: 0_i32,
283         tm_min: 0_i32,
284         tm_hour: 0_i32,
285         tm_mday: 0_i32,
286         tm_mon: 0_i32,
287         tm_year: 0_i32,
288         tm_wday: 0_i32,
289         tm_yday: 0_i32,
290         tm_isdst: 0_i32,
291         tm_gmtoff: 0_i32,
292         tm_nsec: 0_i32,
293     }
294 }
295
296 /// Returns the specified time in UTC
297 pub fn at_utc(clock: Timespec) -> Tm {
298     unsafe {
299         let Timespec { sec, nsec } = clock;
300         let mut tm = empty_tm();
301         rustrt::rust_gmtime(sec, nsec, &mut tm);
302         tm
303     }
304 }
305
306 /// Returns the current time in UTC
307 pub fn now_utc() -> Tm {
308     at_utc(get_time())
309 }
310
311 /// Returns the specified time in the local timezone
312 pub fn at(clock: Timespec) -> Tm {
313     unsafe {
314         let Timespec { sec, nsec } = clock;
315         let mut tm = empty_tm();
316         rustrt::rust_localtime(sec, nsec, &mut tm);
317         tm
318     }
319 }
320
321 /// Returns the current time in the local timezone
322 pub fn now() -> Tm {
323     at(get_time())
324 }
325
326 impl Tm {
327     /// Convert time to the seconds from January 1, 1970
328     pub fn to_timespec(&self) -> Timespec {
329         unsafe {
330             let sec = match self.tm_gmtoff {
331                 0_i32 => rustrt::rust_timegm(self),
332                 _     => rustrt::rust_mktime(self)
333             };
334
335             Timespec::new(sec, self.tm_nsec)
336         }
337     }
338
339     /// Convert time to the local timezone
340     pub fn to_local(&self) -> Tm {
341         at(self.to_timespec())
342     }
343
344     /// Convert time to the UTC
345     pub fn to_utc(&self) -> Tm {
346         at_utc(self.to_timespec())
347     }
348
349     /// Returns a TmFmt that outputs according to the `asctime` format in ISO
350     /// C, in the local timezone.
351     ///
352     /// Example: "Thu Jan  1 00:00:00 1970"
353     pub fn ctime(&self) -> TmFmt {
354         TmFmt {
355             tm: self,
356             format: FmtCtime,
357         }
358     }
359
360     /// Returns a TmFmt that outputs according to the `asctime` format in ISO
361     /// C.
362     ///
363     /// Example: "Thu Jan  1 00:00:00 1970"
364     pub fn asctime(&self) -> TmFmt {
365         TmFmt {
366             tm: self,
367             format: FmtStr("%c"),
368         }
369     }
370
371     /// Formats the time according to the format string.
372     pub fn strftime<'a>(&'a self, format: &'a str) -> Result<TmFmt<'a>, ParseError> {
373         validate_format(TmFmt {
374             tm: self,
375             format: FmtStr(format),
376         })
377     }
378
379     /// Returns a TmFmt that outputs according to RFC 822.
380     ///
381     /// local: "Thu, 22 Mar 2012 07:53:18 PST"
382     /// utc:   "Thu, 22 Mar 2012 14:53:18 GMT"
383     pub fn rfc822(&self) -> TmFmt {
384         if self.tm_gmtoff == 0_i32 {
385             TmFmt {
386                 tm: self,
387                 format: FmtStr("%a, %d %b %Y %T GMT"),
388             }
389         } else {
390             TmFmt {
391                 tm: self,
392                 format: FmtStr("%a, %d %b %Y %T %Z"),
393             }
394         }
395     }
396
397     /// Returns a TmFmt that outputs according to RFC 822 with Zulu time.
398     ///
399     /// local: "Thu, 22 Mar 2012 07:53:18 -0700"
400     /// utc:   "Thu, 22 Mar 2012 14:53:18 -0000"
401     pub fn rfc822z(&self) -> TmFmt {
402         TmFmt {
403             tm: self,
404             format: FmtStr("%a, %d %b %Y %T %z"),
405         }
406     }
407
408     /// Returns a TmFmt that outputs according to RFC 3339. RFC 3339 is
409     /// compatible with ISO 8601.
410     ///
411     /// local: "2012-02-22T07:53:18-07:00"
412     /// utc:   "2012-02-22T14:53:18Z"
413     pub fn rfc3339<'a>(&'a self) -> TmFmt {
414         TmFmt {
415             tm: self,
416             format: FmtRfc3339,
417         }
418     }
419 }
420
421 #[deriving(PartialEq)]
422 pub enum ParseError {
423     InvalidSecond,
424     InvalidMinute,
425     InvalidHour,
426     InvalidDay,
427     InvalidMonth,
428     InvalidYear,
429     InvalidDayOfWeek,
430     InvalidDayOfMonth,
431     InvalidDayOfYear,
432     InvalidZoneOffset,
433     InvalidTime,
434     MissingFormatConverter,
435     InvalidFormatSpecifier(char),
436     UnexpectedCharacter(char, char),
437 }
438
439 impl Copy for ParseError {}
440
441 impl Show for ParseError {
442     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
443         match *self {
444             InvalidSecond => write!(f, "Invalid second."),
445             InvalidMinute => write!(f, "Invalid minute."),
446             InvalidHour => write!(f, "Invalid hour."),
447             InvalidDay => write!(f, "Invalid day."),
448             InvalidMonth => write!(f, "Invalid month."),
449             InvalidYear => write!(f, "Invalid year."),
450             InvalidDayOfWeek => write!(f, "Invalid day of the week."),
451             InvalidDayOfMonth => write!(f, "Invalid day of the month."),
452             InvalidDayOfYear => write!(f, "Invalid day of the year."),
453             InvalidZoneOffset => write!(f, "Invalid zone offset."),
454             InvalidTime => write!(f, "Invalid time."),
455             MissingFormatConverter => write!(f, "Missing format converter after `%`"),
456             InvalidFormatSpecifier(ch) => write!(f, "Invalid format specifier: %{}", ch),
457             UnexpectedCharacter(a, b) => write!(f, "Expected: {}, found: {}.", a, b),
458         }
459     }
460 }
461
462 /// A wrapper around a `Tm` and format string that implements Show.
463 pub struct TmFmt<'a> {
464     tm: &'a Tm,
465     format: Fmt<'a>
466 }
467
468 enum Fmt<'a> {
469     FmtStr(&'a str),
470     FmtRfc3339,
471     FmtCtime,
472 }
473
474 fn validate_format<'a>(fmt: TmFmt<'a>) -> Result<TmFmt<'a>, ParseError> {
475
476     match (fmt.tm.tm_wday, fmt.tm.tm_mon) {
477         (0...6, 0...11) => (),
478         (_wday, 0...11) => return Err(InvalidDayOfWeek),
479         (0...6, _mon) => return Err(InvalidMonth),
480         _ => return Err(InvalidDay)
481     }
482     match fmt.format {
483         FmtStr(ref s) => {
484             let mut chars = s.chars();
485             loop {
486                 match chars.next() {
487                     Some('%') => {
488                         match chars.next() {
489                             Some('A') |
490                             Some('a') |
491                             Some('B') |
492                             Some('b') |
493                             Some('C') |
494                             Some('c') |
495                             Some('D') |
496                             Some('d') |
497                             Some('e') |
498                             Some('F') |
499                             Some('f') |
500                             Some('G') |
501                             Some('g') |
502                             Some('H') |
503                             Some('h') |
504                             Some('I') |
505                             Some('j') |
506                             Some('k') |
507                             Some('l') |
508                             Some('M') |
509                             Some('m') |
510                             Some('n') |
511                             Some('P') |
512                             Some('p') |
513                             Some('R') |
514                             Some('r') |
515                             Some('S') |
516                             Some('s') |
517                             Some('T') |
518                             Some('t') |
519                             Some('U') |
520                             Some('u') |
521                             Some('V') |
522                             Some('v') |
523                             Some('W') |
524                             Some('w') |
525                             Some('X') |
526                             Some('x') |
527                             Some('Y') |
528                             Some('y') |
529                             Some('Z') |
530                             Some('z') |
531                             Some('+') |
532                             Some('%')
533                                 => (),
534                             Some(c) => return Err(InvalidFormatSpecifier(c)),
535                             None => return Err(MissingFormatConverter),
536                         }
537                     },
538                     None => break,
539                     _ => ()
540                 }
541             }
542         },
543         _ => ()
544     }
545     Ok(fmt)
546 }
547
548 impl<'a> fmt::Show for TmFmt<'a> {
549     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
550         fn days_in_year(year: int) -> i32 {
551             if (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) {
552                 366    /* Days in a leap year */
553             } else {
554                 365    /* Days in a non-leap year */
555             }
556         }
557
558         fn iso_week_days(yday: i32, wday: i32) -> int {
559             /* The number of days from the first day of the first ISO week of this
560             * year to the year day YDAY with week day WDAY.
561             * ISO weeks start on Monday. The first ISO week has the year's first
562             * Thursday.
563             * YDAY may be as small as yday_minimum.
564             */
565             let yday: int = yday as int;
566             let wday: int = wday as int;
567             let iso_week_start_wday: int = 1;                     /* Monday */
568             let iso_week1_wday: int = 4;                          /* Thursday */
569             let yday_minimum: int = 366;
570             /* Add enough to the first operand of % to make it nonnegative. */
571             let big_enough_multiple_of_7: int = (yday_minimum / 7 + 2) * 7;
572
573             yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
574                 + iso_week1_wday - iso_week_start_wday
575         }
576
577         fn iso_week(fmt: &mut fmt::Formatter, ch:char, tm: &Tm) -> fmt::Result {
578             let mut year: int = tm.tm_year as int + 1900;
579             let mut days: int = iso_week_days (tm.tm_yday, tm.tm_wday);
580
581             if days < 0 {
582                 /* This ISO week belongs to the previous year. */
583                 year -= 1;
584                 days = iso_week_days (tm.tm_yday + (days_in_year(year)), tm.tm_wday);
585             } else {
586                 let d: int = iso_week_days (tm.tm_yday - (days_in_year(year)),
587                                             tm.tm_wday);
588                 if 0 <= d {
589                     /* This ISO week belongs to the next year. */
590                     year += 1;
591                     days = d;
592                 }
593             }
594
595             match ch {
596                 'G' => write!(fmt, "{}", year),
597                 'g' => write!(fmt, "{:02}", (year % 100 + 100) % 100),
598                 'V' => write!(fmt, "{:02}", days / 7 + 1),
599                 _ => Ok(())
600             }
601         }
602
603         fn parse_type(fmt: &mut fmt::Formatter, ch: char, tm: &Tm) -> fmt::Result {
604             let die = || {
605                 unreachable!()
606             };
607             match ch {
608               'A' => match tm.tm_wday as int {
609                 0 => "Sunday",
610                 1 => "Monday",
611                 2 => "Tuesday",
612                 3 => "Wednesday",
613                 4 => "Thursday",
614                 5 => "Friday",
615                 6 => "Saturday",
616                 _ => return die()
617               },
618              'a' => match tm.tm_wday as int {
619                 0 => "Sun",
620                 1 => "Mon",
621                 2 => "Tue",
622                 3 => "Wed",
623                 4 => "Thu",
624                 5 => "Fri",
625                 6 => "Sat",
626                 _ => return die()
627               },
628               'B' => match tm.tm_mon as int {
629                 0 => "January",
630                 1 => "February",
631                 2 => "March",
632                 3 => "April",
633                 4 => "May",
634                 5 => "June",
635                 6 => "July",
636                 7 => "August",
637                 8 => "September",
638                 9 => "October",
639                 10 => "November",
640                 11 => "December",
641                 _ => return die()
642               },
643               'b' | 'h' => match tm.tm_mon as int {
644                 0 => "Jan",
645                 1 => "Feb",
646                 2 => "Mar",
647                 3 => "Apr",
648                 4 => "May",
649                 5 => "Jun",
650                 6 => "Jul",
651                 7 => "Aug",
652                 8 => "Sep",
653                 9 => "Oct",
654                 10 => "Nov",
655                 11 => "Dec",
656                 _  => return die()
657               },
658               'C' => return write!(fmt, "{:02}", (tm.tm_year as int + 1900) / 100),
659               'c' => {
660                     try!(parse_type(fmt, 'a', tm));
661                     try!(' '.fmt(fmt));
662                     try!(parse_type(fmt, 'b', tm));
663                     try!(' '.fmt(fmt));
664                     try!(parse_type(fmt, 'e', tm));
665                     try!(' '.fmt(fmt));
666                     try!(parse_type(fmt, 'T', tm));
667                     try!(' '.fmt(fmt));
668                     return parse_type(fmt, 'Y', tm);
669               }
670               'D' | 'x' => {
671                     try!(parse_type(fmt, 'm', tm));
672                     try!('/'.fmt(fmt));
673                     try!(parse_type(fmt, 'd', tm));
674                     try!('/'.fmt(fmt));
675                     return parse_type(fmt, 'y', tm);
676               }
677               'd' => return write!(fmt, "{:02}", tm.tm_mday),
678               'e' => return write!(fmt, "{:2}", tm.tm_mday),
679               'f' => return write!(fmt, "{:09}", tm.tm_nsec),
680               'F' => {
681                     try!(parse_type(fmt, 'Y', tm));
682                     try!('-'.fmt(fmt));
683                     try!(parse_type(fmt, 'm', tm));
684                     try!('-'.fmt(fmt));
685                     return parse_type(fmt, 'd', tm);
686               }
687               'G' => return iso_week(fmt, 'G', tm),
688               'g' => return iso_week(fmt, 'g', tm),
689               'H' => return write!(fmt, "{:02}", tm.tm_hour),
690               'I' => {
691                 let mut h = tm.tm_hour;
692                 if h == 0 { h = 12 }
693                 if h > 12 { h -= 12 }
694                 return write!(fmt, "{:02}", h)
695               }
696               'j' => return write!(fmt, "{:03}", tm.tm_yday + 1),
697               'k' => return write!(fmt, "{:2}", tm.tm_hour),
698               'l' => {
699                 let mut h = tm.tm_hour;
700                 if h == 0 { h = 12 }
701                 if h > 12 { h -= 12 }
702                 return write!(fmt, "{:2}", h)
703               }
704               'M' => return write!(fmt, "{:02}", tm.tm_min),
705               'm' => return write!(fmt, "{:02}", tm.tm_mon + 1),
706               'n' => "\n",
707               'P' => if (tm.tm_hour as int) < 12 { "am" } else { "pm" },
708               'p' => if (tm.tm_hour as int) < 12 { "AM" } else { "PM" },
709               'R' => {
710                     try!(parse_type(fmt, 'H', tm));
711                     try!(':'.fmt(fmt));
712                     return parse_type(fmt, 'M', tm);
713               }
714               'r' => {
715                     try!(parse_type(fmt, 'I', tm));
716                     try!(':'.fmt(fmt));
717                     try!(parse_type(fmt, 'M', tm));
718                     try!(':'.fmt(fmt));
719                     try!(parse_type(fmt, 'S', tm));
720                     try!(' '.fmt(fmt));
721                     return parse_type(fmt, 'p', tm);
722               }
723               'S' => return write!(fmt, "{:02}", tm.tm_sec),
724               's' => return write!(fmt, "{}", tm.to_timespec().sec),
725               'T' | 'X' => {
726                     try!(parse_type(fmt, 'H', tm));
727                     try!(':'.fmt(fmt));
728                     try!(parse_type(fmt, 'M', tm));
729                     try!(':'.fmt(fmt));
730                     return parse_type(fmt, 'S', tm);
731               }
732               't' => "\t",
733               'U' => return write!(fmt, "{:02}", (tm.tm_yday - tm.tm_wday + 7) / 7),
734               'u' => {
735                 let i = tm.tm_wday as int;
736                 return (if i == 0 { 7 } else { i }).fmt(fmt);
737               }
738               'V' => return iso_week(fmt, 'V', tm),
739               'v' => {
740                   try!(parse_type(fmt, 'e', tm));
741                   try!('-'.fmt(fmt));
742                   try!(parse_type(fmt, 'b', tm));
743                   try!('-'.fmt(fmt));
744                   return parse_type(fmt, 'Y', tm);
745               }
746               'W' => {
747                   return write!(fmt, "{:02}",
748                                  (tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7) / 7)
749               }
750               'w' => return (tm.tm_wday as int).fmt(fmt),
751               'Y' => return (tm.tm_year as int + 1900).fmt(fmt),
752               'y' => return write!(fmt, "{:02}", (tm.tm_year as int + 1900) % 100),
753               'Z' => if tm.tm_gmtoff == 0_i32 { "GMT"} else { "" }, // FIXME (#2350): support locale
754               'z' => {
755                 let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
756                 let mut m = tm.tm_gmtoff.abs() / 60_i32;
757                 let h = m / 60_i32;
758                 m -= h * 60_i32;
759                 return write!(fmt, "{}{:02}{:02}", sign, h, m);
760               }
761               '+' => return tm.rfc3339().fmt(fmt),
762               '%' => "%",
763               _   => return die()
764             }.fmt(fmt)
765         }
766
767         match self.format {
768             FmtStr(ref s) => {
769                 let mut chars = s.chars();
770                 loop {
771                     match chars.next() {
772                         Some('%') => {
773                             // we've already validated that % always precedes another char
774                             try!(parse_type(fmt, chars.next().unwrap(), self.tm));
775                         }
776                         Some(ch) => try!(ch.fmt(fmt)),
777                         None => break,
778                     }
779                 }
780
781                 Ok(())
782             }
783             FmtCtime => {
784                 self.tm.to_local().asctime().fmt(fmt)
785             }
786             FmtRfc3339 => {
787                 if self.tm.tm_gmtoff == 0_i32 {
788                     TmFmt {
789                         tm: self.tm,
790                         format: FmtStr("%Y-%m-%dT%H:%M:%SZ"),
791                     }.fmt(fmt)
792                 } else {
793                     let s = TmFmt {
794                         tm: self.tm,
795                         format: FmtStr("%Y-%m-%dT%H:%M:%S"),
796                     };
797                     let sign = if self.tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
798                     let mut m = self.tm.tm_gmtoff.abs() / 60_i32;
799                     let h = m / 60_i32;
800                     m -= h * 60_i32;
801                     write!(fmt, "{}{}{:02}:{:02}", s, sign, h as int, m as int)
802                 }
803             }
804         }
805     }
806 }
807
808 /// Parses the time from the string according to the format string.
809 pub fn strptime(s: &str, format: &str) -> Result<Tm, ParseError> {
810     fn match_str(s: &str, pos: uint, needle: &str) -> bool {
811         s.slice_from(pos).starts_with(needle)
812     }
813
814     fn match_strs(ss: &str, pos: uint, strs: &[(&str, i32)])
815       -> Option<(i32, uint)> {
816         for &(needle, value) in strs.iter() {
817             if match_str(ss, pos, needle) {
818                 return Some((value, pos + needle.len()));
819             }
820         }
821
822         None
823     }
824
825     fn match_digits(ss: &str, pos: uint, digits: uint, ws: bool)
826       -> Option<(i32, uint)> {
827         let mut pos = pos;
828         let len = ss.len();
829         let mut value = 0_i32;
830
831         let mut i = 0u;
832         while i < digits {
833             if pos >= len {
834                 return None;
835             }
836             let range = ss.char_range_at(pos);
837             pos = range.next;
838
839             match range.ch {
840               '0' ... '9' => {
841                 value = value * 10_i32 + (range.ch as i32 - '0' as i32);
842               }
843               ' ' if ws => (),
844               _ => return None
845             }
846             i += 1u;
847         }
848
849         Some((value, pos))
850     }
851
852     fn match_fractional_seconds(ss: &str, pos: uint) -> (i32, uint) {
853         let len = ss.len();
854         let mut value = 0_i32;
855         let mut multiplier = NSEC_PER_SEC / 10;
856         let mut pos = pos;
857
858         loop {
859             if pos >= len {
860                 break;
861             }
862             let range = ss.char_range_at(pos);
863
864             match range.ch {
865                 '0' ... '9' => {
866                     pos = range.next;
867                     // This will drop digits after the nanoseconds place
868                     let digit = range.ch as i32 - '0' as i32;
869                     value += digit * multiplier;
870                     multiplier /= 10;
871                 }
872                 _ => break
873             }
874         }
875
876         (value, pos)
877     }
878
879     fn match_digits_in_range(ss: &str, pos: uint, digits: uint, ws: bool,
880                              min: i32, max: i32) -> Option<(i32, uint)> {
881         match match_digits(ss, pos, digits, ws) {
882           Some((val, pos)) if val >= min && val <= max => {
883             Some((val, pos))
884           }
885           _ => None
886         }
887     }
888
889     fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, ParseError> {
890         let range = s.char_range_at(pos);
891
892         if c == range.ch {
893             Ok(range.next)
894         } else {
895             Err(UnexpectedCharacter(c, range.ch))
896         }
897     }
898
899     fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
900       -> Result<uint, ParseError> {
901         match ch {
902           'A' => match match_strs(s, pos, &[
903               ("Sunday", 0_i32),
904               ("Monday", 1_i32),
905               ("Tuesday", 2_i32),
906               ("Wednesday", 3_i32),
907               ("Thursday", 4_i32),
908               ("Friday", 5_i32),
909               ("Saturday", 6_i32)
910           ]) {
911             Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
912             None => Err(InvalidDay)
913           },
914           'a' => match match_strs(s, pos, &[
915               ("Sun", 0_i32),
916               ("Mon", 1_i32),
917               ("Tue", 2_i32),
918               ("Wed", 3_i32),
919               ("Thu", 4_i32),
920               ("Fri", 5_i32),
921               ("Sat", 6_i32)
922           ]) {
923             Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
924             None => Err(InvalidDay)
925           },
926           'B' => match match_strs(s, pos, &[
927               ("January", 0_i32),
928               ("February", 1_i32),
929               ("March", 2_i32),
930               ("April", 3_i32),
931               ("May", 4_i32),
932               ("June", 5_i32),
933               ("July", 6_i32),
934               ("August", 7_i32),
935               ("September", 8_i32),
936               ("October", 9_i32),
937               ("November", 10_i32),
938               ("December", 11_i32)
939           ]) {
940             Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
941             None => Err(InvalidMonth)
942           },
943           'b' | 'h' => match match_strs(s, pos, &[
944               ("Jan", 0_i32),
945               ("Feb", 1_i32),
946               ("Mar", 2_i32),
947               ("Apr", 3_i32),
948               ("May", 4_i32),
949               ("Jun", 5_i32),
950               ("Jul", 6_i32),
951               ("Aug", 7_i32),
952               ("Sep", 8_i32),
953               ("Oct", 9_i32),
954               ("Nov", 10_i32),
955               ("Dec", 11_i32)
956           ]) {
957             Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
958             None => Err(InvalidMonth)
959           },
960           'C' => match match_digits_in_range(s, pos, 2u, false, 0_i32,
961                                              99_i32) {
962             Some(item) => {
963                 let (v, pos) = item;
964                   tm.tm_year += (v * 100_i32) - 1900_i32;
965                   Ok(pos)
966               }
967             None => Err(InvalidYear)
968           },
969           'c' => {
970             parse_type(s, pos, 'a', &mut *tm)
971                 .and_then(|pos| parse_char(s, pos, ' '))
972                 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
973                 .and_then(|pos| parse_char(s, pos, ' '))
974                 .and_then(|pos| parse_type(s, pos, 'e', &mut *tm))
975                 .and_then(|pos| parse_char(s, pos, ' '))
976                 .and_then(|pos| parse_type(s, pos, 'T', &mut *tm))
977                 .and_then(|pos| parse_char(s, pos, ' '))
978                 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
979           }
980           'D' | 'x' => {
981             parse_type(s, pos, 'm', &mut *tm)
982                 .and_then(|pos| parse_char(s, pos, '/'))
983                 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
984                 .and_then(|pos| parse_char(s, pos, '/'))
985                 .and_then(|pos| parse_type(s, pos, 'y', &mut *tm))
986           }
987           'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
988                                              31_i32) {
989             Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
990             None => Err(InvalidDayOfMonth)
991           },
992           'e' => match match_digits_in_range(s, pos, 2u, true, 1_i32,
993                                              31_i32) {
994             Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
995             None => Err(InvalidDayOfMonth)
996           },
997           'f' => {
998             let (val, pos) = match_fractional_seconds(s, pos);
999             tm.tm_nsec = val;
1000             Ok(pos)
1001           }
1002           'F' => {
1003             parse_type(s, pos, 'Y', &mut *tm)
1004                 .and_then(|pos| parse_char(s, pos, '-'))
1005                 .and_then(|pos| parse_type(s, pos, 'm', &mut *tm))
1006                 .and_then(|pos| parse_char(s, pos, '-'))
1007                 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
1008           }
1009           'H' => {
1010             match match_digits_in_range(s, pos, 2u, false, 0_i32, 23_i32) {
1011               Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
1012               None => Err(InvalidHour)
1013             }
1014           }
1015           'I' => {
1016             match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
1017               Some(item) => {
1018                   let (v, pos) = item;
1019                   tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
1020                   Ok(pos)
1021               }
1022               None => Err(InvalidHour)
1023             }
1024           }
1025           'j' => {
1026             match match_digits_in_range(s, pos, 3u, false, 1_i32, 366_i32) {
1027               Some(item) => {
1028                 let (v, pos) = item;
1029                 tm.tm_yday = v - 1_i32;
1030                 Ok(pos)
1031               }
1032               None => Err(InvalidDayOfYear)
1033             }
1034           }
1035           'k' => {
1036             match match_digits_in_range(s, pos, 2u, true, 0_i32, 23_i32) {
1037               Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
1038               None => Err(InvalidHour)
1039             }
1040           }
1041           'l' => {
1042             match match_digits_in_range(s, pos, 2u, true, 1_i32, 12_i32) {
1043               Some(item) => {
1044                   let (v, pos) = item;
1045                   tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
1046                   Ok(pos)
1047               }
1048               None => Err(InvalidHour)
1049             }
1050           }
1051           'M' => {
1052             match match_digits_in_range(s, pos, 2u, false, 0_i32, 59_i32) {
1053               Some(item) => { let (v, pos) = item; tm.tm_min = v; Ok(pos) }
1054               None => Err(InvalidMinute)
1055             }
1056           }
1057           'm' => {
1058             match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
1059               Some(item) => {
1060                 let (v, pos) = item;
1061                 tm.tm_mon = v - 1_i32;
1062                 Ok(pos)
1063               }
1064               None => Err(InvalidMonth)
1065             }
1066           }
1067           'n' => parse_char(s, pos, '\n'),
1068           'P' => match match_strs(s, pos,
1069                                   &[("am", 0_i32), ("pm", 12_i32)]) {
1070
1071             Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
1072             None => Err(InvalidHour)
1073           },
1074           'p' => match match_strs(s, pos,
1075                                   &[("AM", 0_i32), ("PM", 12_i32)]) {
1076
1077             Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
1078             None => Err(InvalidHour)
1079           },
1080           'R' => {
1081             parse_type(s, pos, 'H', &mut *tm)
1082                 .and_then(|pos| parse_char(s, pos, ':'))
1083                 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
1084           }
1085           'r' => {
1086             parse_type(s, pos, 'I', &mut *tm)
1087                 .and_then(|pos| parse_char(s, pos, ':'))
1088                 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
1089                 .and_then(|pos| parse_char(s, pos, ':'))
1090                 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
1091                 .and_then(|pos| parse_char(s, pos, ' '))
1092                 .and_then(|pos| parse_type(s, pos, 'p', &mut *tm))
1093           }
1094           'S' => {
1095             match match_digits_in_range(s, pos, 2u, false, 0_i32, 60_i32) {
1096               Some(item) => {
1097                 let (v, pos) = item;
1098                 tm.tm_sec = v;
1099                 Ok(pos)
1100               }
1101               None => Err(InvalidSecond)
1102             }
1103           }
1104           //'s' {}
1105           'T' | 'X' => {
1106             parse_type(s, pos, 'H', &mut *tm)
1107                 .and_then(|pos| parse_char(s, pos, ':'))
1108                 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
1109                 .and_then(|pos| parse_char(s, pos, ':'))
1110                 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
1111           }
1112           't' => parse_char(s, pos, '\t'),
1113           'u' => {
1114             match match_digits_in_range(s, pos, 1u, false, 1_i32, 7_i32) {
1115               Some(item) => {
1116                 let (v, pos) = item;
1117                 tm.tm_wday = if v == 7 { 0 } else { v };
1118                 Ok(pos)
1119               }
1120               None => Err(InvalidDayOfWeek)
1121             }
1122           }
1123           'v' => {
1124             parse_type(s, pos, 'e', &mut *tm)
1125                 .and_then(|pos|  parse_char(s, pos, '-'))
1126                 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
1127                 .and_then(|pos| parse_char(s, pos, '-'))
1128                 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
1129           }
1130           //'W' {}
1131           'w' => {
1132             match match_digits_in_range(s, pos, 1u, false, 0_i32, 6_i32) {
1133               Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
1134               None => Err(InvalidDayOfWeek)
1135             }
1136           }
1137           'Y' => {
1138             match match_digits(s, pos, 4u, false) {
1139               Some(item) => {
1140                 let (v, pos) = item;
1141                 tm.tm_year = v - 1900_i32;
1142                 Ok(pos)
1143               }
1144               None => Err(InvalidYear)
1145             }
1146           }
1147           'y' => {
1148             match match_digits_in_range(s, pos, 2u, false, 0_i32, 99_i32) {
1149               Some(item) => {
1150                 let (v, pos) = item;
1151                 tm.tm_year = v;
1152                 Ok(pos)
1153               }
1154               None => Err(InvalidYear)
1155             }
1156           }
1157           'Z' => {
1158             if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") {
1159                 tm.tm_gmtoff = 0_i32;
1160                 Ok(pos + 3u)
1161             } else {
1162                 // It's odd, but to maintain compatibility with c's
1163                 // strptime we ignore the timezone.
1164                 let mut pos = pos;
1165                 let len = s.len();
1166                 while pos < len {
1167                     let range = s.char_range_at(pos);
1168                     pos = range.next;
1169                     if range.ch == ' ' { break; }
1170                 }
1171
1172                 Ok(pos)
1173             }
1174           }
1175           'z' => {
1176             let range = s.char_range_at(pos);
1177
1178             if range.ch == '+' || range.ch == '-' {
1179                 match match_digits(s, range.next, 4u, false) {
1180                   Some(item) => {
1181                     let (v, pos) = item;
1182                     if v == 0_i32 {
1183                         tm.tm_gmtoff = 0_i32;
1184                     }
1185
1186                     Ok(pos)
1187                   }
1188                   None => Err(InvalidZoneOffset)
1189                 }
1190             } else {
1191                 Err(InvalidZoneOffset)
1192             }
1193           }
1194           '%' => parse_char(s, pos, '%'),
1195           ch => Err(InvalidFormatSpecifier(ch))
1196         }
1197     }
1198
1199     let mut rdr: &[u8] = format.as_bytes();
1200     let mut tm = Tm {
1201         tm_sec: 0_i32,
1202         tm_min: 0_i32,
1203         tm_hour: 0_i32,
1204         tm_mday: 0_i32,
1205         tm_mon: 0_i32,
1206         tm_year: 0_i32,
1207         tm_wday: 0_i32,
1208         tm_yday: 0_i32,
1209         tm_isdst: 0_i32,
1210         tm_gmtoff: 0_i32,
1211         tm_nsec: 0_i32,
1212     };
1213     let mut pos = 0u;
1214     let len = s.len();
1215     let mut result = Err(InvalidTime);
1216
1217     while pos < len {
1218         let range = s.char_range_at(pos);
1219         let ch = range.ch;
1220         let next = range.next;
1221
1222         let mut buf = [0];
1223         let c = match (&mut rdr).read(&mut buf) {
1224             Ok(..) => buf[0] as char,
1225             Err(..) => break
1226         };
1227         match c {
1228             '%' => {
1229                 let ch = match (&mut rdr).read(&mut buf) {
1230                     Ok(..) => buf[0] as char,
1231                     Err(..) => break
1232                 };
1233                 match parse_type(s, pos, ch, &mut tm) {
1234                     Ok(next) => pos = next,
1235                     Err(e) => { result = Err(e); break; }
1236                 }
1237             },
1238             c => {
1239                 if c != ch { break }
1240                 pos = next;
1241             }
1242         }
1243     }
1244
1245     if pos == len && (&mut rdr).is_empty() {
1246         Ok(Tm {
1247             tm_sec: tm.tm_sec,
1248             tm_min: tm.tm_min,
1249             tm_hour: tm.tm_hour,
1250             tm_mday: tm.tm_mday,
1251             tm_mon: tm.tm_mon,
1252             tm_year: tm.tm_year,
1253             tm_wday: tm.tm_wday,
1254             tm_yday: tm.tm_yday,
1255             tm_isdst: tm.tm_isdst,
1256             tm_gmtoff: tm.tm_gmtoff,
1257             tm_nsec: tm.tm_nsec,
1258         })
1259     } else { result }
1260 }
1261
1262 /// Formats the time according to the format string.
1263 pub fn strftime(format: &str, tm: &Tm) -> Result<String, ParseError> {
1264     tm.strftime(format).map(|fmt| fmt.to_string())
1265 }
1266
1267 #[cfg(test)]
1268 mod tests {
1269     extern crate test;
1270     use super::{Timespec, InvalidTime, InvalidYear, get_time, precise_time_ns,
1271                 precise_time_s, tzset, at_utc, at, strptime, MissingFormatConverter,
1272                 InvalidFormatSpecifier};
1273
1274     use std::f64;
1275     use std::result::Result::{Err, Ok};
1276     use std::time::Duration;
1277     use self::test::Bencher;
1278
1279     #[cfg(windows)]
1280     fn set_time_zone() {
1281         use libc;
1282         // Windows crt doesn't see any environment variable set by
1283         // `SetEnvironmentVariable`, which `os::setenv` internally uses.
1284         // It is why we use `putenv` here.
1285         extern {
1286             fn _putenv(envstring: *const libc::c_char) -> libc::c_int;
1287         }
1288
1289         unsafe {
1290             // Windows does not understand "America/Los_Angeles".
1291             // PST+08 may look wrong, but not! "PST" indicates
1292             // the name of timezone. "+08" means UTC = local + 08.
1293             "TZ=PST+08".with_c_str(|env| {
1294                 _putenv(env);
1295             })
1296         }
1297         tzset();
1298     }
1299     #[cfg(not(windows))]
1300     fn set_time_zone() {
1301         use std::os;
1302         os::setenv("TZ", "America/Los_Angeles");
1303         tzset();
1304     }
1305
1306     fn test_get_time() {
1307         static SOME_RECENT_DATE: i64 = 1325376000i64; // 2012-01-01T00:00:00Z
1308         static SOME_FUTURE_DATE: i64 = 1577836800i64; // 2020-01-01T00:00:00Z
1309
1310         let tv1 = get_time();
1311         debug!("tv1={} sec + {} nsec", tv1.sec as uint, tv1.nsec as uint);
1312
1313         assert!(tv1.sec > SOME_RECENT_DATE);
1314         assert!(tv1.nsec < 1000000000i32);
1315
1316         let tv2 = get_time();
1317         debug!("tv2={} sec + {} nsec", tv2.sec as uint, tv2.nsec as uint);
1318
1319         assert!(tv2.sec >= tv1.sec);
1320         assert!(tv2.sec < SOME_FUTURE_DATE);
1321         assert!(tv2.nsec < 1000000000i32);
1322         if tv2.sec == tv1.sec {
1323             assert!(tv2.nsec >= tv1.nsec);
1324         }
1325     }
1326
1327     fn test_precise_time() {
1328         let s0 = precise_time_s();
1329         debug!("s0={} sec", f64::to_str_digits(s0, 9u));
1330         assert!(s0 > 0.);
1331
1332         let ns0 = precise_time_ns();
1333         let ns1 = precise_time_ns();
1334         debug!("ns0={} ns", ns0);
1335         debug!("ns1={} ns", ns1);
1336         assert!(ns1 >= ns0);
1337
1338         let ns2 = precise_time_ns();
1339         debug!("ns2={} ns", ns2);
1340         assert!(ns2 >= ns1);
1341     }
1342
1343     fn test_at_utc() {
1344         set_time_zone();
1345
1346         let time = Timespec::new(1234567890, 54321);
1347         let utc = at_utc(time);
1348
1349         assert_eq!(utc.tm_sec, 30_i32);
1350         assert_eq!(utc.tm_min, 31_i32);
1351         assert_eq!(utc.tm_hour, 23_i32);
1352         assert_eq!(utc.tm_mday, 13_i32);
1353         assert_eq!(utc.tm_mon, 1_i32);
1354         assert_eq!(utc.tm_year, 109_i32);
1355         assert_eq!(utc.tm_wday, 5_i32);
1356         assert_eq!(utc.tm_yday, 43_i32);
1357         assert_eq!(utc.tm_isdst, 0_i32);
1358         assert_eq!(utc.tm_gmtoff, 0_i32);
1359         assert_eq!(utc.tm_nsec, 54321_i32);
1360     }
1361
1362     fn test_at() {
1363         set_time_zone();
1364
1365         let time = Timespec::new(1234567890, 54321);
1366         let local = at(time);
1367
1368         debug!("time_at: {}", local);
1369
1370         assert_eq!(local.tm_sec, 30_i32);
1371         assert_eq!(local.tm_min, 31_i32);
1372         assert_eq!(local.tm_hour, 15_i32);
1373         assert_eq!(local.tm_mday, 13_i32);
1374         assert_eq!(local.tm_mon, 1_i32);
1375         assert_eq!(local.tm_year, 109_i32);
1376         assert_eq!(local.tm_wday, 5_i32);
1377         assert_eq!(local.tm_yday, 43_i32);
1378         assert_eq!(local.tm_isdst, 0_i32);
1379         assert_eq!(local.tm_gmtoff, -28800_i32);
1380         assert_eq!(local.tm_nsec, 54321_i32);
1381     }
1382
1383     fn test_to_timespec() {
1384         set_time_zone();
1385
1386         let time = Timespec::new(1234567890, 54321);
1387         let utc = at_utc(time);
1388
1389         assert_eq!(utc.to_timespec(), time);
1390         assert_eq!(utc.to_local().to_timespec(), time);
1391     }
1392
1393     fn test_conversions() {
1394         set_time_zone();
1395
1396         let time = Timespec::new(1234567890, 54321);
1397         let utc = at_utc(time);
1398         let local = at(time);
1399
1400         assert!(local.to_local() == local);
1401         assert!(local.to_utc() == utc);
1402         assert!(local.to_utc().to_local() == local);
1403         assert!(utc.to_utc() == utc);
1404         assert!(utc.to_local() == local);
1405         assert!(utc.to_local().to_utc() == utc);
1406     }
1407
1408     fn test_strptime() {
1409         set_time_zone();
1410
1411         match strptime("", "") {
1412           Ok(ref tm) => {
1413             assert!(tm.tm_sec == 0_i32);
1414             assert!(tm.tm_min == 0_i32);
1415             assert!(tm.tm_hour == 0_i32);
1416             assert!(tm.tm_mday == 0_i32);
1417             assert!(tm.tm_mon == 0_i32);
1418             assert!(tm.tm_year == 0_i32);
1419             assert!(tm.tm_wday == 0_i32);
1420             assert!(tm.tm_isdst == 0_i32);
1421             assert!(tm.tm_gmtoff == 0_i32);
1422             assert!(tm.tm_nsec == 0_i32);
1423           }
1424           Err(_) => ()
1425         }
1426
1427         let format = "%a %b %e %T.%f %Y";
1428         assert_eq!(strptime("", format), Err(InvalidTime));
1429         assert!(strptime("Fri Feb 13 15:31:30", format)
1430             == Err(InvalidTime));
1431
1432         match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
1433           Err(e) => panic!(e),
1434           Ok(ref tm) => {
1435             assert!(tm.tm_sec == 30_i32);
1436             assert!(tm.tm_min == 31_i32);
1437             assert!(tm.tm_hour == 15_i32);
1438             assert!(tm.tm_mday == 13_i32);
1439             assert!(tm.tm_mon == 1_i32);
1440             assert!(tm.tm_year == 109_i32);
1441             assert!(tm.tm_wday == 5_i32);
1442             assert!(tm.tm_yday == 0_i32);
1443             assert!(tm.tm_isdst == 0_i32);
1444             assert!(tm.tm_gmtoff == 0_i32);
1445             assert!(tm.tm_nsec == 12340000_i32);
1446           }
1447         }
1448
1449         fn test(s: &str, format: &str) -> bool {
1450             match strptime(s, format) {
1451               Ok(ref tm) => {
1452                 tm.strftime(format).unwrap().to_string() == s.to_string()
1453               },
1454               Err(e) => panic!(e)
1455             }
1456         }
1457
1458         let days = [
1459             "Sunday".to_string(),
1460             "Monday".to_string(),
1461             "Tuesday".to_string(),
1462             "Wednesday".to_string(),
1463             "Thursday".to_string(),
1464             "Friday".to_string(),
1465             "Saturday".to_string()
1466         ];
1467         for day in days.iter() {
1468             assert!(test(day.as_slice(), "%A"));
1469         }
1470
1471         let days = [
1472             "Sun".to_string(),
1473             "Mon".to_string(),
1474             "Tue".to_string(),
1475             "Wed".to_string(),
1476             "Thu".to_string(),
1477             "Fri".to_string(),
1478             "Sat".to_string()
1479         ];
1480         for day in days.iter() {
1481             assert!(test(day.as_slice(), "%a"));
1482         }
1483
1484         let months = [
1485             "January".to_string(),
1486             "February".to_string(),
1487             "March".to_string(),
1488             "April".to_string(),
1489             "May".to_string(),
1490             "June".to_string(),
1491             "July".to_string(),
1492             "August".to_string(),
1493             "September".to_string(),
1494             "October".to_string(),
1495             "November".to_string(),
1496             "December".to_string()
1497         ];
1498         for day in months.iter() {
1499             assert!(test(day.as_slice(), "%B"));
1500         }
1501
1502         let months = [
1503             "Jan".to_string(),
1504             "Feb".to_string(),
1505             "Mar".to_string(),
1506             "Apr".to_string(),
1507             "May".to_string(),
1508             "Jun".to_string(),
1509             "Jul".to_string(),
1510             "Aug".to_string(),
1511             "Sep".to_string(),
1512             "Oct".to_string(),
1513             "Nov".to_string(),
1514             "Dec".to_string()
1515         ];
1516         for day in months.iter() {
1517             assert!(test(day.as_slice(), "%b"));
1518         }
1519
1520         assert!(test("19", "%C"));
1521         assert!(test("Fri Feb 13 23:31:30 2009", "%c"));
1522         assert!(test("02/13/09", "%D"));
1523         assert!(test("03", "%d"));
1524         assert!(test("13", "%d"));
1525         assert!(test(" 3", "%e"));
1526         assert!(test("13", "%e"));
1527         assert!(test("2009-02-13", "%F"));
1528         assert!(test("03", "%H"));
1529         assert!(test("13", "%H"));
1530         assert!(test("03", "%I")); // FIXME (#2350): flesh out
1531         assert!(test("11", "%I")); // FIXME (#2350): flesh out
1532         assert!(test("044", "%j"));
1533         assert!(test(" 3", "%k"));
1534         assert!(test("13", "%k"));
1535         assert!(test(" 1", "%l"));
1536         assert!(test("11", "%l"));
1537         assert!(test("03", "%M"));
1538         assert!(test("13", "%M"));
1539         assert!(test("\n", "%n"));
1540         assert!(test("am", "%P"));
1541         assert!(test("pm", "%P"));
1542         assert!(test("AM", "%p"));
1543         assert!(test("PM", "%p"));
1544         assert!(test("23:31", "%R"));
1545         assert!(test("11:31:30 AM", "%r"));
1546         assert!(test("11:31:30 PM", "%r"));
1547         assert!(test("03", "%S"));
1548         assert!(test("13", "%S"));
1549         assert!(test("15:31:30", "%T"));
1550         assert!(test("\t", "%t"));
1551         assert!(test("1", "%u"));
1552         assert!(test("7", "%u"));
1553         assert!(test("13-Feb-2009", "%v"));
1554         assert!(test("0", "%w"));
1555         assert!(test("6", "%w"));
1556         assert!(test("2009", "%Y"));
1557         assert!(test("09", "%y"));
1558         assert!(strptime("-0000", "%z").unwrap().tm_gmtoff ==
1559             0);
1560         assert!(strptime("-0800", "%z").unwrap().tm_gmtoff ==
1561             0);
1562         assert!(test("%", "%%"));
1563
1564         // Test for #7256
1565         assert_eq!(strptime("360", "%Y-%m-%d"), Err(InvalidYear));
1566     }
1567
1568     fn test_asctime() {
1569         set_time_zone();
1570
1571         let time = Timespec::new(1234567890, 54321);
1572         let utc   = at_utc(time);
1573         let local = at(time);
1574
1575         debug!("test_ctime: {} {}", utc.asctime(), local.asctime());
1576
1577         assert_eq!(utc.asctime().to_string(), "Fri Feb 13 23:31:30 2009");
1578         assert_eq!(local.asctime().to_string(), "Fri Feb 13 15:31:30 2009");
1579     }
1580
1581     fn test_ctime() {
1582         set_time_zone();
1583
1584         let time = Timespec::new(1234567890, 54321);
1585         let utc   = at_utc(time);
1586         let local = at(time);
1587
1588         debug!("test_ctime: {} {}", utc.ctime(), local.ctime());
1589
1590         assert_eq!(utc.ctime().to_string(), "Fri Feb 13 15:31:30 2009");
1591         assert_eq!(local.ctime().to_string(), "Fri Feb 13 15:31:30 2009");
1592     }
1593
1594     fn test_strftime() {
1595         set_time_zone();
1596
1597         let time = Timespec::new(1234567890, 54321);
1598         let utc = at_utc(time);
1599         let local = at(time);
1600
1601         assert_eq!(local.strftime("").unwrap().to_string(), "");
1602         assert_eq!(local.strftime("%A").unwrap().to_string(), "Friday");
1603         assert_eq!(local.strftime("%a").unwrap().to_string(), "Fri");
1604         assert_eq!(local.strftime("%B").unwrap().to_string(), "February");
1605         assert_eq!(local.strftime("%b").unwrap().to_string(), "Feb");
1606         assert_eq!(local.strftime("%C").unwrap().to_string(), "20");
1607         assert_eq!(local.strftime("%c").unwrap().to_string(),
1608                    "Fri Feb 13 15:31:30 2009");
1609         assert_eq!(local.strftime("%D").unwrap().to_string(), "02/13/09");
1610         assert_eq!(local.strftime("%d").unwrap().to_string(), "13");
1611         assert_eq!(local.strftime("%e").unwrap().to_string(), "13");
1612         assert_eq!(local.strftime("%F").unwrap().to_string(), "2009-02-13");
1613         assert_eq!(local.strftime("%f").unwrap().to_string(), "000054321");
1614         assert_eq!(local.strftime("%G").unwrap().to_string(), "2009");
1615         assert_eq!(local.strftime("%g").unwrap().to_string(), "09");
1616         assert_eq!(local.strftime("%H").unwrap().to_string(), "15");
1617         assert_eq!(local.strftime("%h").unwrap().to_string(), "Feb");
1618         assert_eq!(local.strftime("%I").unwrap().to_string(), "03");
1619         assert_eq!(local.strftime("%j").unwrap().to_string(), "044");
1620         assert_eq!(local.strftime("%k").unwrap().to_string(), "15");
1621         assert_eq!(local.strftime("%l").unwrap().to_string(), " 3");
1622         assert_eq!(local.strftime("%M").unwrap().to_string(), "31");
1623         assert_eq!(local.strftime("%m").unwrap().to_string(), "02");
1624         assert_eq!(local.strftime("%n").unwrap().to_string(), "\n");
1625         assert_eq!(local.strftime("%P").unwrap().to_string(), "pm");
1626         assert_eq!(local.strftime("%p").unwrap().to_string(), "PM");
1627         assert_eq!(local.strftime("%R").unwrap().to_string(), "15:31");
1628         assert_eq!(local.strftime("%r").unwrap().to_string(), "03:31:30 PM");
1629         assert_eq!(local.strftime("%S").unwrap().to_string(), "30");
1630         assert_eq!(local.strftime("%s").unwrap().to_string(), "1234567890");
1631         assert_eq!(local.strftime("%T").unwrap().to_string(), "15:31:30");
1632         assert_eq!(local.strftime("%t").unwrap().to_string(), "\t");
1633         assert_eq!(local.strftime("%U").unwrap().to_string(), "06");
1634         assert_eq!(local.strftime("%u").unwrap().to_string(), "5");
1635         assert_eq!(local.strftime("%V").unwrap().to_string(), "07");
1636         assert_eq!(local.strftime("%v").unwrap().to_string(), "13-Feb-2009");
1637         assert_eq!(local.strftime("%W").unwrap().to_string(), "06");
1638         assert_eq!(local.strftime("%w").unwrap().to_string(), "5");
1639         // FIXME (#2350): support locale
1640         assert_eq!(local.strftime("%X").unwrap().to_string(), "15:31:30");
1641         // FIXME (#2350): support locale
1642         assert_eq!(local.strftime("%x").unwrap().to_string(), "02/13/09");
1643         assert_eq!(local.strftime("%Y").unwrap().to_string(), "2009");
1644         assert_eq!(local.strftime("%y").unwrap().to_string(), "09");
1645         // FIXME (#2350): support locale
1646         assert_eq!(local.strftime("%Z").unwrap().to_string(), "");
1647         assert_eq!(local.strftime("%z").unwrap().to_string(), "-0800");
1648         assert_eq!(local.strftime("%+").unwrap().to_string(),
1649                    "2009-02-13T15:31:30-08:00");
1650         assert_eq!(local.strftime("%%").unwrap().to_string(), "%");
1651
1652          let invalid_specifiers = ["%E", "%J", "%K", "%L", "%N", "%O", "%o", "%Q", "%q"];
1653         for &sp in invalid_specifiers.iter() {
1654             assert_eq!(local.strftime(sp).unwrap_err(), InvalidFormatSpecifier(sp.char_at(1)));
1655         }
1656         assert_eq!(local.strftime("%").unwrap_err(), MissingFormatConverter);
1657         assert_eq!(local.strftime("%A %").unwrap_err(), MissingFormatConverter);
1658
1659         assert_eq!(local.asctime().to_string(), "Fri Feb 13 15:31:30 2009");
1660         assert_eq!(local.ctime().to_string(), "Fri Feb 13 15:31:30 2009");
1661         assert_eq!(local.rfc822z().to_string(), "Fri, 13 Feb 2009 15:31:30 -0800");
1662         assert_eq!(local.rfc3339().to_string(), "2009-02-13T15:31:30-08:00");
1663
1664         assert_eq!(utc.asctime().to_string(), "Fri Feb 13 23:31:30 2009");
1665         assert_eq!(utc.ctime().to_string(), "Fri Feb 13 15:31:30 2009");
1666         assert_eq!(utc.rfc822().to_string(), "Fri, 13 Feb 2009 23:31:30 GMT");
1667         assert_eq!(utc.rfc822z().to_string(), "Fri, 13 Feb 2009 23:31:30 -0000");
1668         assert_eq!(utc.rfc3339().to_string(), "2009-02-13T23:31:30Z");
1669     }
1670
1671     fn test_timespec_eq_ord() {
1672         let a = &Timespec::new(-2, 1);
1673         let b = &Timespec::new(-1, 2);
1674         let c = &Timespec::new(1, 2);
1675         let d = &Timespec::new(2, 1);
1676         let e = &Timespec::new(2, 1);
1677
1678         assert!(d.eq(e));
1679         assert!(c.ne(e));
1680
1681         assert!(a.lt(b));
1682         assert!(b.lt(c));
1683         assert!(c.lt(d));
1684
1685         assert!(a.le(b));
1686         assert!(b.le(c));
1687         assert!(c.le(d));
1688         assert!(d.le(e));
1689         assert!(e.le(d));
1690
1691         assert!(b.ge(a));
1692         assert!(c.ge(b));
1693         assert!(d.ge(c));
1694         assert!(e.ge(d));
1695         assert!(d.ge(e));
1696
1697         assert!(b.gt(a));
1698         assert!(c.gt(b));
1699         assert!(d.gt(c));
1700     }
1701
1702     fn test_timespec_add() {
1703         let a = Timespec::new(1, 2);
1704         let b = Duration::seconds(2) + Duration::nanoseconds(3);
1705         let c = a + b;
1706         assert_eq!(c.sec, 3);
1707         assert_eq!(c.nsec, 5);
1708
1709         let p = Timespec::new(1, super::NSEC_PER_SEC - 2);
1710         let q = Duration::seconds(2) + Duration::nanoseconds(2);
1711         let r = p + q;
1712         assert_eq!(r.sec, 4);
1713         assert_eq!(r.nsec, 0);
1714
1715         let u = Timespec::new(1, super::NSEC_PER_SEC - 2);
1716         let v = Duration::seconds(2) + Duration::nanoseconds(3);
1717         let w = u + v;
1718         assert_eq!(w.sec, 4);
1719         assert_eq!(w.nsec, 1);
1720
1721         let k = Timespec::new(1, 0);
1722         let l = Duration::nanoseconds(-1);
1723         let m = k + l;
1724         assert_eq!(m.sec, 0);
1725         assert_eq!(m.nsec, 999_999_999);
1726     }
1727
1728     fn test_timespec_sub() {
1729         let a = Timespec::new(2, 3);
1730         let b = Timespec::new(1, 2);
1731         let c = a - b;
1732         assert_eq!(c.num_nanoseconds(), Some(super::NSEC_PER_SEC as i64 + 1));
1733
1734         let p = Timespec::new(2, 0);
1735         let q = Timespec::new(1, 2);
1736         let r = p - q;
1737         assert_eq!(r.num_nanoseconds(), Some(super::NSEC_PER_SEC as i64 - 2));
1738
1739         let u = Timespec::new(1, 2);
1740         let v = Timespec::new(2, 3);
1741         let w = u - v;
1742         assert_eq!(w.num_nanoseconds(), Some(-super::NSEC_PER_SEC as i64 - 1));
1743     }
1744
1745     #[test]
1746     #[cfg_attr(target_os = "android", ignore)] // FIXME #10958
1747     fn run_tests() {
1748         // The tests race on tzset. So instead of having many independent
1749         // tests, we will just call the functions now.
1750         test_get_time();
1751         test_precise_time();
1752         test_at_utc();
1753         test_at();
1754         test_to_timespec();
1755         test_conversions();
1756         test_strptime();
1757         test_asctime();
1758         test_ctime();
1759         test_strftime();
1760         test_timespec_eq_ord();
1761         test_timespec_add();
1762         test_timespec_sub();
1763     }
1764
1765     #[bench]
1766     fn bench_precise_time_ns(b: &mut Bencher) {
1767         b.iter(|| precise_time_ns())
1768     }
1769 }