]> git.lizzy.rs Git - rust.git/blob - src/libtime/lib.rs
prefer "FIXME" to "TODO".
[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 { pub sec: i64, pub nsec: i32 }
81 /*
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 }`.
88  */
89 impl Timespec {
90     pub fn new(sec: i64, nsec: i32) -> Timespec {
91         assert!(nsec >= 0 && nsec < NSEC_PER_SEC);
92         Timespec { sec: sec, nsec: nsec }
93     }
94 }
95
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;
107             sec += 1;
108         } else if nsec < 0 {
109             nsec += NSEC_PER_SEC;
110             sec -= 1;
111         }
112         Timespec::new(sec, nsec)
113     }
114 }
115
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)
121     }
122 }
123
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 {
127     unsafe {
128         let (sec, nsec) = os_get_time();
129         return Timespec::new(sec, nsec);
130     }
131
132     #[cfg(windows)]
133     unsafe fn os_get_time() -> (i64, i32) {
134         static NANOSECONDS_FROM_1601_TO_1970: u64 = 11644473600000000;
135
136         let mut time = libc::FILETIME {
137             dwLowDateTime: 0,
138             dwHighDateTime: 0,
139         };
140         libc::GetSystemTimeAsFileTime(&mut time);
141
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;
148
149         ((ns_since_1970 / 1000000) as i64,
150          ((ns_since_1970 % 1000000) * 1000) as i32)
151     }
152
153     #[cfg(any(target_os = "macos", target_os = "ios"))]
154     unsafe fn os_get_time() -> (i64, i32) {
155         use std::ptr;
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)
159     }
160
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)
166     }
167 }
168
169
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();
174
175     #[cfg(windows)]
176     fn os_precise_time_ns() -> u64 {
177         let mut ticks_per_s = 0;
178         assert_eq!(unsafe {
179             libc::QueryPerformanceFrequency(&mut ticks_per_s)
180         }, 1);
181         let ticks_per_s = if ticks_per_s == 0 {1} else {ticks_per_s};
182         let mut ticks = 0;
183         assert_eq!(unsafe {
184             libc::QueryPerformanceCounter(&mut ticks)
185         }, 1);
186
187         return (ticks as u64 * 1000000000) / (ticks_per_s as u64);
188     }
189
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,
193                                                                                    denom: 0 };
194         static ONCE: std::sync::Once = std::sync::ONCE_INIT;
195         unsafe {
196             ONCE.doit(|| {
197                 imp::mach_timebase_info(&mut TIMEBASE);
198             });
199             let time = imp::mach_absolute_time();
200             time * TIMEBASE.numer as u64 / TIMEBASE.denom as u64
201         }
202     }
203
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 };
207         unsafe {
208             imp::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
209         }
210         return (ts.tv_sec as u64) * 1000000000 + (ts.tv_nsec as u64)
211     }
212 }
213
214
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.;
219 }
220
221 pub fn tzset() {
222     unsafe {
223         rustrt::rust_tzset();
224     }
225 }
226
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?
230 #[repr(C)]
231 #[deriving(Clone, PartialEq, Eq, Show)]
232 pub struct Tm {
233     /// Seconds after the minute - [0, 60]
234     pub tm_sec: i32,
235
236     /// Minutes after the hour - [0, 59]
237     pub tm_min: i32,
238
239     /// Hours after midnight - [0, 23]
240     pub tm_hour: i32,
241
242     /// Day of the month - [1, 31]
243     pub tm_mday: i32,
244
245     /// Months since January - [0, 11]
246     pub tm_mon: i32,
247
248     /// Years since 1900
249     pub tm_year: i32,
250
251     /// Days since Sunday - [0, 6]. 0 = Sunday, 1 = Monday, ..., 6 = Saturday.
252     pub tm_wday: i32,
253
254     /// Days since January 1 - [0, 365]
255     pub tm_yday: i32,
256
257     /// Daylight Saving Time flag.
258     ///
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.
261     pub tm_isdst: i32,
262
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.
266     pub tm_gmtoff: i32,
267
268     /// Nanoseconds after the second - [0, 10<sup>9</sup> - 1]
269     pub tm_nsec: i32,
270 }
271
272 pub fn empty_tm() -> Tm {
273     Tm {
274         tm_sec: 0_i32,
275         tm_min: 0_i32,
276         tm_hour: 0_i32,
277         tm_mday: 0_i32,
278         tm_mon: 0_i32,
279         tm_year: 0_i32,
280         tm_wday: 0_i32,
281         tm_yday: 0_i32,
282         tm_isdst: 0_i32,
283         tm_gmtoff: 0_i32,
284         tm_nsec: 0_i32,
285     }
286 }
287
288 /// Returns the specified time in UTC
289 pub fn at_utc(clock: Timespec) -> Tm {
290     unsafe {
291         let Timespec { sec, nsec } = clock;
292         let mut tm = empty_tm();
293         rustrt::rust_gmtime(sec, nsec, &mut tm);
294         tm
295     }
296 }
297
298 /// Returns the current time in UTC
299 pub fn now_utc() -> Tm {
300     at_utc(get_time())
301 }
302
303 /// Returns the specified time in the local timezone
304 pub fn at(clock: Timespec) -> Tm {
305     unsafe {
306         let Timespec { sec, nsec } = clock;
307         let mut tm = empty_tm();
308         rustrt::rust_localtime(sec, nsec, &mut tm);
309         tm
310     }
311 }
312
313 /// Returns the current time in the local timezone
314 pub fn now() -> Tm {
315     at(get_time())
316 }
317
318 impl Tm {
319     /// Convert time to the seconds from January 1, 1970
320     pub fn to_timespec(&self) -> Timespec {
321         unsafe {
322             let sec = match self.tm_gmtoff {
323                 0_i32 => rustrt::rust_timegm(self),
324                 _     => rustrt::rust_mktime(self)
325             };
326
327             Timespec::new(sec, self.tm_nsec)
328         }
329     }
330
331     /// Convert time to the local timezone
332     pub fn to_local(&self) -> Tm {
333         at(self.to_timespec())
334     }
335
336     /// Convert time to the UTC
337     pub fn to_utc(&self) -> Tm {
338         at_utc(self.to_timespec())
339     }
340
341     /// Returns a TmFmt that outputs according to the `asctime` format in ISO
342     /// C, in the local timezone.
343     ///
344     /// Example: "Thu Jan  1 00:00:00 1970"
345     pub fn ctime(&self) -> TmFmt {
346         TmFmt {
347             tm: self,
348             format: FmtCtime,
349         }
350     }
351
352     /// Returns a TmFmt that outputs according to the `asctime` format in ISO
353     /// C.
354     ///
355     /// Example: "Thu Jan  1 00:00:00 1970"
356     pub fn asctime(&self) -> TmFmt {
357         TmFmt {
358             tm: self,
359             format: FmtStr("%c"),
360         }
361     }
362
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 {
366             tm: self,
367             format: FmtStr(format),
368         })
369     }
370
371     /// Returns a TmFmt that outputs according to RFC 822.
372     ///
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 {
377             TmFmt {
378                 tm: self,
379                 format: FmtStr("%a, %d %b %Y %T GMT"),
380             }
381         } else {
382             TmFmt {
383                 tm: self,
384                 format: FmtStr("%a, %d %b %Y %T %Z"),
385             }
386         }
387     }
388
389     /// Returns a TmFmt that outputs according to RFC 822 with Zulu time.
390     ///
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 {
394         TmFmt {
395             tm: self,
396             format: FmtStr("%a, %d %b %Y %T %z"),
397         }
398     }
399
400     /// Returns a TmFmt that outputs according to RFC 3339. RFC 3339 is
401     /// compatible with ISO 8601.
402     ///
403     /// local: "2012-02-22T07:53:18-07:00"
404     /// utc:   "2012-02-22T14:53:18Z"
405     pub fn rfc3339<'a>(&'a self) -> TmFmt {
406         TmFmt {
407             tm: self,
408             format: FmtRfc3339,
409         }
410     }
411 }
412
413 #[deriving(PartialEq)]
414 pub enum ParseError {
415     InvalidSecond,
416     InvalidMinute,
417     InvalidHour,
418     InvalidDay,
419     InvalidMonth,
420     InvalidYear,
421     InvalidDayOfWeek,
422     InvalidDayOfMonth,
423     InvalidDayOfYear,
424     InvalidZoneOffset,
425     InvalidTime,
426     MissingFormatConverter,
427     InvalidFormatSpecifier(char),
428     UnexpectedCharacter(char, char),
429 }
430
431 impl Show for ParseError {
432     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
433         match *self {
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),
448         }
449     }
450 }
451
452 /// A wrapper around a `Tm` and format string that implements Show.
453 pub struct TmFmt<'a> {
454     tm: &'a Tm,
455     format: Fmt<'a>
456 }
457
458 enum Fmt<'a> {
459     FmtStr(&'a str),
460     FmtRfc3339,
461     FmtCtime,
462 }
463
464 fn validate_format<'a>(fmt: TmFmt<'a>) -> Result<TmFmt<'a>, ParseError> {
465
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)
471     }
472     match fmt.format {
473         FmtStr(ref s) => {
474             let mut chars = s.chars();
475             loop {
476                 match chars.next() {
477                     Some('%') => {
478                         match chars.next() {
479                             Some('A') |
480                             Some('a') |
481                             Some('B') |
482                             Some('b') |
483                             Some('C') |
484                             Some('c') |
485                             Some('D') |
486                             Some('d') |
487                             Some('e') |
488                             Some('F') |
489                             Some('f') |
490                             Some('G') |
491                             Some('g') |
492                             Some('H') |
493                             Some('h') |
494                             Some('I') |
495                             Some('j') |
496                             Some('k') |
497                             Some('l') |
498                             Some('M') |
499                             Some('m') |
500                             Some('n') |
501                             Some('P') |
502                             Some('p') |
503                             Some('R') |
504                             Some('r') |
505                             Some('S') |
506                             Some('s') |
507                             Some('T') |
508                             Some('t') |
509                             Some('U') |
510                             Some('u') |
511                             Some('V') |
512                             Some('v') |
513                             Some('W') |
514                             Some('w') |
515                             Some('X') |
516                             Some('x') |
517                             Some('Y') |
518                             Some('y') |
519                             Some('Z') |
520                             Some('z') |
521                             Some('+') |
522                             Some('%')
523                                 => (),
524                             Some(c) => return Err(InvalidFormatSpecifier(c)),
525                             None => return Err(MissingFormatConverter),
526                         }
527                     },
528                     None => break,
529                     _ => ()
530                 }
531             }
532         },
533         _ => ()
534     }
535     Ok(fmt)
536 }
537
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 */
543             } else {
544                 365    /* Days in a non-leap year */
545             }
546         }
547
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
552             * Thursday.
553             * YDAY may be as small as yday_minimum.
554             */
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;
562
563             yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
564                 + iso_week1_wday - iso_week_start_wday
565         }
566
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);
570
571             if days < 0 {
572                 /* This ISO week belongs to the previous year. */
573                 year -= 1;
574                 days = iso_week_days (tm.tm_yday + (days_in_year(year)), tm.tm_wday);
575             } else {
576                 let d: int = iso_week_days (tm.tm_yday - (days_in_year(year)),
577                                             tm.tm_wday);
578                 if 0 <= d {
579                     /* This ISO week belongs to the next year. */
580                     year += 1;
581                     days = d;
582                 }
583             }
584
585             match ch {
586                 'G' => write!(fmt, "{}", year),
587                 'g' => write!(fmt, "{:02}", (year % 100 + 100) % 100),
588                 'V' => write!(fmt, "{:02}", days / 7 + 1),
589                 _ => Ok(())
590             }
591         }
592
593         fn parse_type(fmt: &mut fmt::Formatter, ch: char, tm: &Tm) -> fmt::Result {
594             let die = || {
595                 unreachable!()
596             };
597             match ch {
598               'A' => match tm.tm_wday as int {
599                 0 => "Sunday",
600                 1 => "Monday",
601                 2 => "Tuesday",
602                 3 => "Wednesday",
603                 4 => "Thursday",
604                 5 => "Friday",
605                 6 => "Saturday",
606                 _ => return die()
607               },
608              'a' => match tm.tm_wday as int {
609                 0 => "Sun",
610                 1 => "Mon",
611                 2 => "Tue",
612                 3 => "Wed",
613                 4 => "Thu",
614                 5 => "Fri",
615                 6 => "Sat",
616                 _ => return die()
617               },
618               'B' => match tm.tm_mon as int {
619                 0 => "January",
620                 1 => "February",
621                 2 => "March",
622                 3 => "April",
623                 4 => "May",
624                 5 => "June",
625                 6 => "July",
626                 7 => "August",
627                 8 => "September",
628                 9 => "October",
629                 10 => "November",
630                 11 => "December",
631                 _ => return die()
632               },
633               'b' | 'h' => match tm.tm_mon as int {
634                 0 => "Jan",
635                 1 => "Feb",
636                 2 => "Mar",
637                 3 => "Apr",
638                 4 => "May",
639                 5 => "Jun",
640                 6 => "Jul",
641                 7 => "Aug",
642                 8 => "Sep",
643                 9 => "Oct",
644                 10 => "Nov",
645                 11 => "Dec",
646                 _  => return die()
647               },
648               'C' => return write!(fmt, "{:02}", (tm.tm_year as int + 1900) / 100),
649               'c' => {
650                     try!(parse_type(fmt, 'a', tm));
651                     try!(' '.fmt(fmt));
652                     try!(parse_type(fmt, 'b', tm));
653                     try!(' '.fmt(fmt));
654                     try!(parse_type(fmt, 'e', tm));
655                     try!(' '.fmt(fmt));
656                     try!(parse_type(fmt, 'T', tm));
657                     try!(' '.fmt(fmt));
658                     return parse_type(fmt, 'Y', tm);
659               }
660               'D' | 'x' => {
661                     try!(parse_type(fmt, 'm', tm));
662                     try!('/'.fmt(fmt));
663                     try!(parse_type(fmt, 'd', tm));
664                     try!('/'.fmt(fmt));
665                     return parse_type(fmt, 'y', tm);
666               }
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),
670               'F' => {
671                     try!(parse_type(fmt, 'Y', tm));
672                     try!('-'.fmt(fmt));
673                     try!(parse_type(fmt, 'm', tm));
674                     try!('-'.fmt(fmt));
675                     return parse_type(fmt, 'd', tm);
676               }
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),
680               'I' => {
681                 let mut h = tm.tm_hour;
682                 if h == 0 { h = 12 }
683                 if h > 12 { h -= 12 }
684                 return write!(fmt, "{:02}", h)
685               }
686               'j' => return write!(fmt, "{:03}", tm.tm_yday + 1),
687               'k' => return write!(fmt, "{:2}", tm.tm_hour),
688               'l' => {
689                 let mut h = tm.tm_hour;
690                 if h == 0 { h = 12 }
691                 if h > 12 { h -= 12 }
692                 return write!(fmt, "{:2}", h)
693               }
694               'M' => return write!(fmt, "{:02}", tm.tm_min),
695               'm' => return write!(fmt, "{:02}", tm.tm_mon + 1),
696               'n' => "\n",
697               'P' => if (tm.tm_hour as int) < 12 { "am" } else { "pm" },
698               'p' => if (tm.tm_hour as int) < 12 { "AM" } else { "PM" },
699               'R' => {
700                     try!(parse_type(fmt, 'H', tm));
701                     try!(':'.fmt(fmt));
702                     return parse_type(fmt, 'M', tm);
703               }
704               'r' => {
705                     try!(parse_type(fmt, 'I', tm));
706                     try!(':'.fmt(fmt));
707                     try!(parse_type(fmt, 'M', tm));
708                     try!(':'.fmt(fmt));
709                     try!(parse_type(fmt, 'S', tm));
710                     try!(' '.fmt(fmt));
711                     return parse_type(fmt, 'p', tm);
712               }
713               'S' => return write!(fmt, "{:02}", tm.tm_sec),
714               's' => return write!(fmt, "{}", tm.to_timespec().sec),
715               'T' | 'X' => {
716                     try!(parse_type(fmt, 'H', tm));
717                     try!(':'.fmt(fmt));
718                     try!(parse_type(fmt, 'M', tm));
719                     try!(':'.fmt(fmt));
720                     return parse_type(fmt, 'S', tm);
721               }
722               't' => "\t",
723               'U' => return write!(fmt, "{:02}", (tm.tm_yday - tm.tm_wday + 7) / 7),
724               'u' => {
725                 let i = tm.tm_wday as int;
726                 return (if i == 0 { 7 } else { i }).fmt(fmt);
727               }
728               'V' => return iso_week(fmt, 'V', tm),
729               'v' => {
730                   try!(parse_type(fmt, 'e', tm));
731                   try!('-'.fmt(fmt));
732                   try!(parse_type(fmt, 'b', tm));
733                   try!('-'.fmt(fmt));
734                   return parse_type(fmt, 'Y', tm);
735               }
736               'W' => {
737                   return write!(fmt, "{:02}",
738                                  (tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7) / 7)
739               }
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
744               'z' => {
745                 let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
746                 let mut m = tm.tm_gmtoff.abs() / 60_i32;
747                 let h = m / 60_i32;
748                 m -= h * 60_i32;
749                 return write!(fmt, "{}{:02}{:02}", sign, h, m);
750               }
751               '+' => return tm.rfc3339().fmt(fmt),
752               '%' => "%",
753               _   => return die()
754             }.fmt(fmt)
755         }
756
757         match self.format {
758             FmtStr(ref s) => {
759                 let mut chars = s.chars();
760                 loop {
761                     match chars.next() {
762                         Some('%') => {
763                             // we've already validated that % always precedes another char
764                             try!(parse_type(fmt, chars.next().unwrap(), self.tm));
765                         }
766                         Some(ch) => try!(ch.fmt(fmt)),
767                         None => break,
768                     }
769                 }
770
771                 Ok(())
772             }
773             FmtCtime => {
774                 self.tm.to_local().asctime().fmt(fmt)
775             }
776             FmtRfc3339 => {
777                 if self.tm.tm_gmtoff == 0_i32 {
778                     TmFmt {
779                         tm: self.tm,
780                         format: FmtStr("%Y-%m-%dT%H:%M:%SZ"),
781                     }.fmt(fmt)
782                 } else {
783                     let s = TmFmt {
784                         tm: self.tm,
785                         format: FmtStr("%Y-%m-%dT%H:%M:%S"),
786                     };
787                     let sign = if self.tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
788                     let mut m = self.tm.tm_gmtoff.abs() / 60_i32;
789                     let h = m / 60_i32;
790                     m -= h * 60_i32;
791                     write!(fmt, "{}{}{:02}:{:02}", s, sign, h as int, m as int)
792                 }
793             }
794         }
795     }
796 }
797
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)
802     }
803
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()));
809             }
810         }
811
812         None
813     }
814
815     fn match_digits(ss: &str, pos: uint, digits: uint, ws: bool)
816       -> Option<(i32, uint)> {
817         let mut pos = pos;
818         let len = ss.len();
819         let mut value = 0_i32;
820
821         let mut i = 0u;
822         while i < digits {
823             if pos >= len {
824                 return None;
825             }
826             let range = ss.char_range_at(pos);
827             pos = range.next;
828
829             match range.ch {
830               '0' ... '9' => {
831                 value = value * 10_i32 + (range.ch as i32 - '0' as i32);
832               }
833               ' ' if ws => (),
834               _ => return None
835             }
836             i += 1u;
837         }
838
839         Some((value, pos))
840     }
841
842     fn match_fractional_seconds(ss: &str, pos: uint) -> (i32, uint) {
843         let len = ss.len();
844         let mut value = 0_i32;
845         let mut multiplier = NSEC_PER_SEC / 10;
846         let mut pos = pos;
847
848         loop {
849             if pos >= len {
850                 break;
851             }
852             let range = ss.char_range_at(pos);
853
854             match range.ch {
855                 '0' ... '9' => {
856                     pos = range.next;
857                     // This will drop digits after the nanoseconds place
858                     let digit = range.ch as i32 - '0' as i32;
859                     value += digit * multiplier;
860                     multiplier /= 10;
861                 }
862                 _ => break
863             }
864         }
865
866         (value, pos)
867     }
868
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 => {
873             Some((val, pos))
874           }
875           _ => None
876         }
877     }
878
879     fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, ParseError> {
880         let range = s.char_range_at(pos);
881
882         if c == range.ch {
883             Ok(range.next)
884         } else {
885             Err(UnexpectedCharacter(c, range.ch))
886         }
887     }
888
889     fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
890       -> Result<uint, ParseError> {
891         match ch {
892           'A' => match match_strs(s, pos, &[
893               ("Sunday", 0_i32),
894               ("Monday", 1_i32),
895               ("Tuesday", 2_i32),
896               ("Wednesday", 3_i32),
897               ("Thursday", 4_i32),
898               ("Friday", 5_i32),
899               ("Saturday", 6_i32)
900           ]) {
901             Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
902             None => Err(InvalidDay)
903           },
904           'a' => match match_strs(s, pos, &[
905               ("Sun", 0_i32),
906               ("Mon", 1_i32),
907               ("Tue", 2_i32),
908               ("Wed", 3_i32),
909               ("Thu", 4_i32),
910               ("Fri", 5_i32),
911               ("Sat", 6_i32)
912           ]) {
913             Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
914             None => Err(InvalidDay)
915           },
916           'B' => match match_strs(s, pos, &[
917               ("January", 0_i32),
918               ("February", 1_i32),
919               ("March", 2_i32),
920               ("April", 3_i32),
921               ("May", 4_i32),
922               ("June", 5_i32),
923               ("July", 6_i32),
924               ("August", 7_i32),
925               ("September", 8_i32),
926               ("October", 9_i32),
927               ("November", 10_i32),
928               ("December", 11_i32)
929           ]) {
930             Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
931             None => Err(InvalidMonth)
932           },
933           'b' | 'h' => match match_strs(s, pos, &[
934               ("Jan", 0_i32),
935               ("Feb", 1_i32),
936               ("Mar", 2_i32),
937               ("Apr", 3_i32),
938               ("May", 4_i32),
939               ("Jun", 5_i32),
940               ("Jul", 6_i32),
941               ("Aug", 7_i32),
942               ("Sep", 8_i32),
943               ("Oct", 9_i32),
944               ("Nov", 10_i32),
945               ("Dec", 11_i32)
946           ]) {
947             Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
948             None => Err(InvalidMonth)
949           },
950           'C' => match match_digits_in_range(s, pos, 2u, false, 0_i32,
951                                              99_i32) {
952             Some(item) => {
953                 let (v, pos) = item;
954                   tm.tm_year += (v * 100_i32) - 1900_i32;
955                   Ok(pos)
956               }
957             None => Err(InvalidYear)
958           },
959           'c' => {
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))
969           }
970           'D' | 'x' => {
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))
976           }
977           'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
978                                              31_i32) {
979             Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
980             None => Err(InvalidDayOfMonth)
981           },
982           'e' => match match_digits_in_range(s, pos, 2u, true, 1_i32,
983                                              31_i32) {
984             Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
985             None => Err(InvalidDayOfMonth)
986           },
987           'f' => {
988             let (val, pos) = match_fractional_seconds(s, pos);
989             tm.tm_nsec = val;
990             Ok(pos)
991           }
992           'F' => {
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))
998           }
999           'H' => {
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)
1003             }
1004           }
1005           'I' => {
1006             match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
1007               Some(item) => {
1008                   let (v, pos) = item;
1009                   tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
1010                   Ok(pos)
1011               }
1012               None => Err(InvalidHour)
1013             }
1014           }
1015           'j' => {
1016             match match_digits_in_range(s, pos, 3u, false, 1_i32, 366_i32) {
1017               Some(item) => {
1018                 let (v, pos) = item;
1019                 tm.tm_yday = v - 1_i32;
1020                 Ok(pos)
1021               }
1022               None => Err(InvalidDayOfYear)
1023             }
1024           }
1025           'k' => {
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)
1029             }
1030           }
1031           'l' => {
1032             match match_digits_in_range(s, pos, 2u, true, 1_i32, 12_i32) {
1033               Some(item) => {
1034                   let (v, pos) = item;
1035                   tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
1036                   Ok(pos)
1037               }
1038               None => Err(InvalidHour)
1039             }
1040           }
1041           'M' => {
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)
1045             }
1046           }
1047           'm' => {
1048             match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
1049               Some(item) => {
1050                 let (v, pos) = item;
1051                 tm.tm_mon = v - 1_i32;
1052                 Ok(pos)
1053               }
1054               None => Err(InvalidMonth)
1055             }
1056           }
1057           'n' => parse_char(s, pos, '\n'),
1058           'P' => match match_strs(s, pos,
1059                                   &[("am", 0_i32), ("pm", 12_i32)]) {
1060
1061             Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
1062             None => Err(InvalidHour)
1063           },
1064           'p' => match match_strs(s, pos,
1065                                   &[("AM", 0_i32), ("PM", 12_i32)]) {
1066
1067             Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
1068             None => Err(InvalidHour)
1069           },
1070           'R' => {
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))
1074           }
1075           'r' => {
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))
1083           }
1084           'S' => {
1085             match match_digits_in_range(s, pos, 2u, false, 0_i32, 60_i32) {
1086               Some(item) => {
1087                 let (v, pos) = item;
1088                 tm.tm_sec = v;
1089                 Ok(pos)
1090               }
1091               None => Err(InvalidSecond)
1092             }
1093           }
1094           //'s' {}
1095           'T' | 'X' => {
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))
1101           }
1102           't' => parse_char(s, pos, '\t'),
1103           'u' => {
1104             match match_digits_in_range(s, pos, 1u, false, 1_i32, 7_i32) {
1105               Some(item) => {
1106                 let (v, pos) = item;
1107                 tm.tm_wday = if v == 7 { 0 } else { v };
1108                 Ok(pos)
1109               }
1110               None => Err(InvalidDayOfWeek)
1111             }
1112           }
1113           'v' => {
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))
1119           }
1120           //'W' {}
1121           'w' => {
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)
1125             }
1126           }
1127           'Y' => {
1128             match match_digits(s, pos, 4u, false) {
1129               Some(item) => {
1130                 let (v, pos) = item;
1131                 tm.tm_year = v - 1900_i32;
1132                 Ok(pos)
1133               }
1134               None => Err(InvalidYear)
1135             }
1136           }
1137           'y' => {
1138             match match_digits_in_range(s, pos, 2u, false, 0_i32, 99_i32) {
1139               Some(item) => {
1140                 let (v, pos) = item;
1141                 tm.tm_year = v;
1142                 Ok(pos)
1143               }
1144               None => Err(InvalidYear)
1145             }
1146           }
1147           'Z' => {
1148             if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") {
1149                 tm.tm_gmtoff = 0_i32;
1150                 Ok(pos + 3u)
1151             } else {
1152                 // It's odd, but to maintain compatibility with c's
1153                 // strptime we ignore the timezone.
1154                 let mut pos = pos;
1155                 let len = s.len();
1156                 while pos < len {
1157                     let range = s.char_range_at(pos);
1158                     pos = range.next;
1159                     if range.ch == ' ' { break; }
1160                 }
1161
1162                 Ok(pos)
1163             }
1164           }
1165           'z' => {
1166             let range = s.char_range_at(pos);
1167
1168             if range.ch == '+' || range.ch == '-' {
1169                 match match_digits(s, range.next, 4u, false) {
1170                   Some(item) => {
1171                     let (v, pos) = item;
1172                     if v == 0_i32 {
1173                         tm.tm_gmtoff = 0_i32;
1174                     }
1175
1176                     Ok(pos)
1177                   }
1178                   None => Err(InvalidZoneOffset)
1179                 }
1180             } else {
1181                 Err(InvalidZoneOffset)
1182             }
1183           }
1184           '%' => parse_char(s, pos, '%'),
1185           ch => Err(InvalidFormatSpecifier(ch))
1186         }
1187     }
1188
1189     let mut rdr: &[u8] = format.as_bytes();
1190     let mut tm = Tm {
1191         tm_sec: 0_i32,
1192         tm_min: 0_i32,
1193         tm_hour: 0_i32,
1194         tm_mday: 0_i32,
1195         tm_mon: 0_i32,
1196         tm_year: 0_i32,
1197         tm_wday: 0_i32,
1198         tm_yday: 0_i32,
1199         tm_isdst: 0_i32,
1200         tm_gmtoff: 0_i32,
1201         tm_nsec: 0_i32,
1202     };
1203     let mut pos = 0u;
1204     let len = s.len();
1205     let mut result = Err(InvalidTime);
1206
1207     while pos < len {
1208         let range = s.char_range_at(pos);
1209         let ch = range.ch;
1210         let next = range.next;
1211
1212         let mut buf = [0];
1213         let c = match (&mut rdr).read(&mut buf) {
1214             Ok(..) => buf[0] as char,
1215             Err(..) => break
1216         };
1217         match c {
1218             '%' => {
1219                 let ch = match (&mut rdr).read(&mut buf) {
1220                     Ok(..) => buf[0] as char,
1221                     Err(..) => break
1222                 };
1223                 match parse_type(s, pos, ch, &mut tm) {
1224                     Ok(next) => pos = next,
1225                     Err(e) => { result = Err(e); break; }
1226                 }
1227             },
1228             c => {
1229                 if c != ch { break }
1230                 pos = next;
1231             }
1232         }
1233     }
1234
1235     if pos == len && (&mut rdr).is_empty() {
1236         Ok(Tm {
1237             tm_sec: tm.tm_sec,
1238             tm_min: tm.tm_min,
1239             tm_hour: tm.tm_hour,
1240             tm_mday: tm.tm_mday,
1241             tm_mon: tm.tm_mon,
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,
1248         })
1249     } else { result }
1250 }
1251
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())
1255 }
1256
1257 #[cfg(test)]
1258 mod tests {
1259     extern crate test;
1260     use super::{Timespec, InvalidTime, InvalidYear, get_time, precise_time_ns,
1261                 precise_time_s, tzset, at_utc, at, strptime, MissingFormatConverter,
1262                 InvalidFormatSpecifier};
1263
1264     use std::f64;
1265     use std::result::{Err, Ok};
1266     use std::time::Duration;
1267     use self::test::Bencher;
1268
1269     #[cfg(windows)]
1270     fn set_time_zone() {
1271         use libc;
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.
1275         extern {
1276             fn _putenv(envstring: *const libc::c_char) -> libc::c_int;
1277         }
1278
1279         unsafe {
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| {
1284                 _putenv(env);
1285             })
1286         }
1287         tzset();
1288     }
1289     #[cfg(not(windows))]
1290     fn set_time_zone() {
1291         use std::os;
1292         os::setenv("TZ", "America/Los_Angeles");
1293         tzset();
1294     }
1295
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
1299
1300         let tv1 = get_time();
1301         debug!("tv1={} sec + {} nsec", tv1.sec as uint, tv1.nsec as uint);
1302
1303         assert!(tv1.sec > SOME_RECENT_DATE);
1304         assert!(tv1.nsec < 1000000000i32);
1305
1306         let tv2 = get_time();
1307         debug!("tv2={} sec + {} nsec", tv2.sec as uint, tv2.nsec as uint);
1308
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);
1314         }
1315     }
1316
1317     fn test_precise_time() {
1318         let s0 = precise_time_s();
1319         debug!("s0={} sec", f64::to_str_digits(s0, 9u));
1320         assert!(s0 > 0.);
1321
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);
1327
1328         let ns2 = precise_time_ns();
1329         debug!("ns2={} ns", ns2);
1330         assert!(ns2 >= ns1);
1331     }
1332
1333     fn test_at_utc() {
1334         set_time_zone();
1335
1336         let time = Timespec::new(1234567890, 54321);
1337         let utc = at_utc(time);
1338
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);
1350     }
1351
1352     fn test_at() {
1353         set_time_zone();
1354
1355         let time = Timespec::new(1234567890, 54321);
1356         let local = at(time);
1357
1358         debug!("time_at: {}", local);
1359
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);
1371     }
1372
1373     fn test_to_timespec() {
1374         set_time_zone();
1375
1376         let time = Timespec::new(1234567890, 54321);
1377         let utc = at_utc(time);
1378
1379         assert_eq!(utc.to_timespec(), time);
1380         assert_eq!(utc.to_local().to_timespec(), time);
1381     }
1382
1383     fn test_conversions() {
1384         set_time_zone();
1385
1386         let time = Timespec::new(1234567890, 54321);
1387         let utc = at_utc(time);
1388         let local = at(time);
1389
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);
1396     }
1397
1398     fn test_strptime() {
1399         set_time_zone();
1400
1401         match strptime("", "") {
1402           Ok(ref tm) => {
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);
1413           }
1414           Err(_) => ()
1415         }
1416
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));
1421
1422         match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
1423           Err(e) => panic!(e),
1424           Ok(ref tm) => {
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);
1436           }
1437         }
1438
1439         fn test(s: &str, format: &str) -> bool {
1440             match strptime(s, format) {
1441               Ok(ref tm) => {
1442                 tm.strftime(format).unwrap().to_string() == s.to_string()
1443               },
1444               Err(e) => panic!(e)
1445             }
1446         }
1447
1448         let days = [
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()
1456         ];
1457         for day in days.iter() {
1458             assert!(test(day.as_slice(), "%A"));
1459         }
1460
1461         let days = [
1462             "Sun".to_string(),
1463             "Mon".to_string(),
1464             "Tue".to_string(),
1465             "Wed".to_string(),
1466             "Thu".to_string(),
1467             "Fri".to_string(),
1468             "Sat".to_string()
1469         ];
1470         for day in days.iter() {
1471             assert!(test(day.as_slice(), "%a"));
1472         }
1473
1474         let months = [
1475             "January".to_string(),
1476             "February".to_string(),
1477             "March".to_string(),
1478             "April".to_string(),
1479             "May".to_string(),
1480             "June".to_string(),
1481             "July".to_string(),
1482             "August".to_string(),
1483             "September".to_string(),
1484             "October".to_string(),
1485             "November".to_string(),
1486             "December".to_string()
1487         ];
1488         for day in months.iter() {
1489             assert!(test(day.as_slice(), "%B"));
1490         }
1491
1492         let months = [
1493             "Jan".to_string(),
1494             "Feb".to_string(),
1495             "Mar".to_string(),
1496             "Apr".to_string(),
1497             "May".to_string(),
1498             "Jun".to_string(),
1499             "Jul".to_string(),
1500             "Aug".to_string(),
1501             "Sep".to_string(),
1502             "Oct".to_string(),
1503             "Nov".to_string(),
1504             "Dec".to_string()
1505         ];
1506         for day in months.iter() {
1507             assert!(test(day.as_slice(), "%b"));
1508         }
1509
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 ==
1549             0);
1550         assert!(strptime("-0800", "%z").unwrap().tm_gmtoff ==
1551             0);
1552         assert!(test("%", "%%"));
1553
1554         // Test for #7256
1555         assert_eq!(strptime("360", "%Y-%m-%d"), Err(InvalidYear));
1556     }
1557
1558     fn test_asctime() {
1559         set_time_zone();
1560
1561         let time = Timespec::new(1234567890, 54321);
1562         let utc   = at_utc(time);
1563         let local = at(time);
1564
1565         debug!("test_ctime: {} {}", utc.asctime(), local.asctime());
1566
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());
1569     }
1570
1571     fn test_ctime() {
1572         set_time_zone();
1573
1574         let time = Timespec::new(1234567890, 54321);
1575         let utc   = at_utc(time);
1576         let local = at(time);
1577
1578         debug!("test_ctime: {} {}", utc.ctime(), local.ctime());
1579
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());
1582     }
1583
1584     fn test_strftime() {
1585         set_time_zone();
1586
1587         let time = Timespec::new(1234567890, 54321);
1588         let utc = at_utc(time);
1589         let local = at(time);
1590
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());
1641
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)));
1645         }
1646         assert_eq!(local.strftime("%").unwrap_err(), MissingFormatConverter);
1647         assert_eq!(local.strftime("%A %").unwrap_err(), MissingFormatConverter);
1648
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());
1653
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());
1659     }
1660
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);
1667
1668         assert!(d.eq(e));
1669         assert!(c.ne(e));
1670
1671         assert!(a.lt(b));
1672         assert!(b.lt(c));
1673         assert!(c.lt(d));
1674
1675         assert!(a.le(b));
1676         assert!(b.le(c));
1677         assert!(c.le(d));
1678         assert!(d.le(e));
1679         assert!(e.le(d));
1680
1681         assert!(b.ge(a));
1682         assert!(c.ge(b));
1683         assert!(d.ge(c));
1684         assert!(e.ge(d));
1685         assert!(d.ge(e));
1686
1687         assert!(b.gt(a));
1688         assert!(c.gt(b));
1689         assert!(d.gt(c));
1690     }
1691
1692     fn test_timespec_add() {
1693         let a = Timespec::new(1, 2);
1694         let b = Duration::seconds(2) + Duration::nanoseconds(3);
1695         let c = a + b;
1696         assert_eq!(c.sec, 3);
1697         assert_eq!(c.nsec, 5);
1698
1699         let p = Timespec::new(1, super::NSEC_PER_SEC - 2);
1700         let q = Duration::seconds(2) + Duration::nanoseconds(2);
1701         let r = p + q;
1702         assert_eq!(r.sec, 4);
1703         assert_eq!(r.nsec, 0);
1704
1705         let u = Timespec::new(1, super::NSEC_PER_SEC - 2);
1706         let v = Duration::seconds(2) + Duration::nanoseconds(3);
1707         let w = u + v;
1708         assert_eq!(w.sec, 4);
1709         assert_eq!(w.nsec, 1);
1710
1711         let k = Timespec::new(1, 0);
1712         let l = Duration::nanoseconds(-1);
1713         let m = k + l;
1714         assert_eq!(m.sec, 0);
1715         assert_eq!(m.nsec, 999_999_999);
1716     }
1717
1718     fn test_timespec_sub() {
1719         let a = Timespec::new(2, 3);
1720         let b = Timespec::new(1, 2);
1721         let c = a - b;
1722         assert_eq!(c.num_nanoseconds(), Some(super::NSEC_PER_SEC as i64 + 1));
1723
1724         let p = Timespec::new(2, 0);
1725         let q = Timespec::new(1, 2);
1726         let r = p - q;
1727         assert_eq!(r.num_nanoseconds(), Some(super::NSEC_PER_SEC as i64 - 2));
1728
1729         let u = Timespec::new(1, 2);
1730         let v = Timespec::new(2, 3);
1731         let w = u - v;
1732         assert_eq!(w.num_nanoseconds(), Some(-super::NSEC_PER_SEC as i64 - 1));
1733     }
1734
1735     #[test]
1736     #[cfg_attr(target_os = "android", ignore)] // FIXME #10958
1737     fn run_tests() {
1738         // The tests race on tzset. So instead of having many independent
1739         // tests, we will just call the functions now.
1740         test_get_time();
1741         test_precise_time();
1742         test_at_utc();
1743         test_at();
1744         test_to_timespec();
1745         test_conversions();
1746         test_strptime();
1747         test_asctime();
1748         test_ctime();
1749         test_strftime();
1750         test_timespec_eq_ord();
1751         test_timespec_add();
1752         test_timespec_sub();
1753     }
1754
1755     #[bench]
1756     fn bench_precise_time_ns(b: &mut Bencher) {
1757         b.iter(|| precise_time_ns())
1758     }
1759 }