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