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