]> git.lizzy.rs Git - rust.git/blob - src/libtime/lib.rs
rustc: Remove `&str` indexing from the language.
[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-pre"]
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/",
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      * Return a string of the current time in the form
320      * "Thu Jan  1 00:00:00 1970".
321      */
322     pub fn ctime(&self) -> String { self.strftime("%c") }
323
324     /// Formats the time according to the format string.
325     pub fn strftime(&self, format: &str) -> String {
326         strftime(format, self)
327     }
328
329     /**
330      * Returns a time string formatted according to RFC 822.
331      *
332      * local: "Thu, 22 Mar 2012 07:53:18 PST"
333      * utc:   "Thu, 22 Mar 2012 14:53:18 UTC"
334      */
335     pub fn rfc822(&self) -> String {
336         if self.tm_gmtoff == 0_i32 {
337             self.strftime("%a, %d %b %Y %T GMT")
338         } else {
339             self.strftime("%a, %d %b %Y %T %Z")
340         }
341     }
342
343     /**
344      * Returns a time string formatted according to RFC 822 with Zulu time.
345      *
346      * local: "Thu, 22 Mar 2012 07:53:18 -0700"
347      * utc:   "Thu, 22 Mar 2012 14:53:18 -0000"
348      */
349     pub fn rfc822z(&self) -> String {
350         self.strftime("%a, %d %b %Y %T %z")
351     }
352
353     /**
354      * Returns a time string formatted according to ISO 8601.
355      *
356      * local: "2012-02-22T07:53:18-07:00"
357      * utc:   "2012-02-22T14:53:18Z"
358      */
359     pub fn rfc3339(&self) -> String {
360         if self.tm_gmtoff == 0_i32 {
361             self.strftime("%Y-%m-%dT%H:%M:%SZ")
362         } else {
363             let s = self.strftime("%Y-%m-%dT%H:%M:%S");
364             let sign = if self.tm_gmtoff > 0_i32 { '+' } else { '-' };
365             let mut m = num::abs(self.tm_gmtoff) / 60_i32;
366             let h = m / 60_i32;
367             m -= h * 60_i32;
368             format!("{}{}{:02d}:{:02d}", s, sign, h as int, m as int)
369         }
370     }
371 }
372
373 /// Parses the time from the string according to the format string.
374 pub fn strptime(s: &str, format: &str) -> Result<Tm, String> {
375     fn match_str(s: &str, pos: uint, needle: &str) -> bool {
376         let mut i = pos;
377         for ch in needle.bytes() {
378             if s.as_bytes()[i] != ch {
379                 return false;
380             }
381             i += 1u;
382         }
383         return true;
384     }
385
386     fn match_strs(ss: &str, pos: uint, strs: &[(String, i32)])
387       -> Option<(i32, uint)> {
388         let mut i = 0u;
389         let len = strs.len();
390         while i < len {
391             match strs[i] { // can't use let due to let-pattern bugs
392                 (ref needle, value) => {
393                     if match_str(ss, pos, needle.as_slice()) {
394                         return Some((value, pos + needle.len()));
395                     }
396                 }
397             }
398             i += 1u;
399         }
400
401         None
402     }
403
404     fn match_digits(ss: &str, pos: uint, digits: uint, ws: bool)
405       -> Option<(i32, uint)> {
406         let mut pos = pos;
407         let len = ss.len();
408         let mut value = 0_i32;
409
410         let mut i = 0u;
411         while i < digits {
412             if pos >= len {
413                 return None;
414             }
415             let range = ss.char_range_at(pos);
416             pos = range.next;
417
418             match range.ch {
419               '0' .. '9' => {
420                 value = value * 10_i32 + (range.ch as i32 - '0' as i32);
421               }
422               ' ' if ws => (),
423               _ => return None
424             }
425             i += 1u;
426         }
427
428         Some((value, pos))
429     }
430
431     fn match_fractional_seconds(ss: &str, pos: uint) -> (i32, uint) {
432         let len = ss.len();
433         let mut value = 0_i32;
434         let mut multiplier = NSEC_PER_SEC / 10;
435         let mut pos = pos;
436
437         loop {
438             if pos >= len {
439                 break;
440             }
441             let range = ss.char_range_at(pos);
442
443             match range.ch {
444                 '0' .. '9' => {
445                     pos = range.next;
446                     // This will drop digits after the nanoseconds place
447                     let digit = range.ch as i32 - '0' as i32;
448                     value += digit * multiplier;
449                     multiplier /= 10;
450                 }
451                 _ => break
452             }
453         }
454
455         (value, pos)
456     }
457
458     fn match_digits_in_range(ss: &str, pos: uint, digits: uint, ws: bool,
459                              min: i32, max: i32) -> Option<(i32, uint)> {
460         match match_digits(ss, pos, digits, ws) {
461           Some((val, pos)) if val >= min && val <= max => {
462             Some((val, pos))
463           }
464           _ => None
465         }
466     }
467
468     fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, String> {
469         let range = s.char_range_at(pos);
470
471         if c == range.ch {
472             Ok(range.next)
473         } else {
474             Err(format!("Expected {}, found {}",
475                 str::from_char(c),
476                 str::from_char(range.ch)))
477         }
478     }
479
480     fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
481       -> Result<uint, String> {
482         match ch {
483           'A' => match match_strs(s, pos, [
484               ("Sunday".to_string(), 0_i32),
485               ("Monday".to_string(), 1_i32),
486               ("Tuesday".to_string(), 2_i32),
487               ("Wednesday".to_string(), 3_i32),
488               ("Thursday".to_string(), 4_i32),
489               ("Friday".to_string(), 5_i32),
490               ("Saturday".to_string(), 6_i32)
491           ]) {
492             Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
493             None => Err("Invalid day".to_string())
494           },
495           'a' => match match_strs(s, pos, [
496               ("Sun".to_string(), 0_i32),
497               ("Mon".to_string(), 1_i32),
498               ("Tue".to_string(), 2_i32),
499               ("Wed".to_string(), 3_i32),
500               ("Thu".to_string(), 4_i32),
501               ("Fri".to_string(), 5_i32),
502               ("Sat".to_string(), 6_i32)
503           ]) {
504             Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
505             None => Err("Invalid day".to_string())
506           },
507           'B' => match match_strs(s, pos, [
508               ("January".to_string(), 0_i32),
509               ("February".to_string(), 1_i32),
510               ("March".to_string(), 2_i32),
511               ("April".to_string(), 3_i32),
512               ("May".to_string(), 4_i32),
513               ("June".to_string(), 5_i32),
514               ("July".to_string(), 6_i32),
515               ("August".to_string(), 7_i32),
516               ("September".to_string(), 8_i32),
517               ("October".to_string(), 9_i32),
518               ("November".to_string(), 10_i32),
519               ("December".to_string(), 11_i32)
520           ]) {
521             Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
522             None => Err("Invalid month".to_string())
523           },
524           'b' | 'h' => match match_strs(s, pos, [
525               ("Jan".to_string(), 0_i32),
526               ("Feb".to_string(), 1_i32),
527               ("Mar".to_string(), 2_i32),
528               ("Apr".to_string(), 3_i32),
529               ("May".to_string(), 4_i32),
530               ("Jun".to_string(), 5_i32),
531               ("Jul".to_string(), 6_i32),
532               ("Aug".to_string(), 7_i32),
533               ("Sep".to_string(), 8_i32),
534               ("Oct".to_string(), 9_i32),
535               ("Nov".to_string(), 10_i32),
536               ("Dec".to_string(), 11_i32)
537           ]) {
538             Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
539             None => Err("Invalid month".to_string())
540           },
541           'C' => match match_digits_in_range(s, pos, 2u, false, 0_i32,
542                                              99_i32) {
543             Some(item) => {
544                 let (v, pos) = item;
545                   tm.tm_year += (v * 100_i32) - 1900_i32;
546                   Ok(pos)
547               }
548             None => Err("Invalid year".to_string())
549           },
550           'c' => {
551             parse_type(s, pos, 'a', &mut *tm)
552                 .and_then(|pos| parse_char(s, pos, ' '))
553                 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
554                 .and_then(|pos| parse_char(s, pos, ' '))
555                 .and_then(|pos| parse_type(s, pos, 'e', &mut *tm))
556                 .and_then(|pos| parse_char(s, pos, ' '))
557                 .and_then(|pos| parse_type(s, pos, 'T', &mut *tm))
558                 .and_then(|pos| parse_char(s, pos, ' '))
559                 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
560           }
561           'D' | 'x' => {
562             parse_type(s, pos, 'm', &mut *tm)
563                 .and_then(|pos| parse_char(s, pos, '/'))
564                 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
565                 .and_then(|pos| parse_char(s, pos, '/'))
566                 .and_then(|pos| parse_type(s, pos, 'y', &mut *tm))
567           }
568           'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
569                                              31_i32) {
570             Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
571             None => Err("Invalid day of the month".to_string())
572           },
573           'e' => match match_digits_in_range(s, pos, 2u, true, 1_i32,
574                                              31_i32) {
575             Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
576             None => Err("Invalid day of the month".to_string())
577           },
578           'f' => {
579             let (val, pos) = match_fractional_seconds(s, pos);
580             tm.tm_nsec = val;
581             Ok(pos)
582           }
583           'F' => {
584             parse_type(s, pos, 'Y', &mut *tm)
585                 .and_then(|pos| parse_char(s, pos, '-'))
586                 .and_then(|pos| parse_type(s, pos, 'm', &mut *tm))
587                 .and_then(|pos| parse_char(s, pos, '-'))
588                 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
589           }
590           'H' => {
591             match match_digits_in_range(s, pos, 2u, false, 0_i32, 23_i32) {
592               Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
593               None => Err("Invalid hour".to_string())
594             }
595           }
596           'I' => {
597             match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
598               Some(item) => {
599                   let (v, pos) = item;
600                   tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
601                   Ok(pos)
602               }
603               None => Err("Invalid hour".to_string())
604             }
605           }
606           'j' => {
607             match match_digits_in_range(s, pos, 3u, false, 1_i32, 366_i32) {
608               Some(item) => {
609                 let (v, pos) = item;
610                 tm.tm_yday = v - 1_i32;
611                 Ok(pos)
612               }
613               None => Err("Invalid day of year".to_string())
614             }
615           }
616           'k' => {
617             match match_digits_in_range(s, pos, 2u, true, 0_i32, 23_i32) {
618               Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
619               None => Err("Invalid hour".to_string())
620             }
621           }
622           'l' => {
623             match match_digits_in_range(s, pos, 2u, true, 1_i32, 12_i32) {
624               Some(item) => {
625                   let (v, pos) = item;
626                   tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
627                   Ok(pos)
628               }
629               None => Err("Invalid hour".to_string())
630             }
631           }
632           'M' => {
633             match match_digits_in_range(s, pos, 2u, false, 0_i32, 59_i32) {
634               Some(item) => { let (v, pos) = item; tm.tm_min = v; Ok(pos) }
635               None => Err("Invalid minute".to_string())
636             }
637           }
638           'm' => {
639             match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
640               Some(item) => {
641                 let (v, pos) = item;
642                 tm.tm_mon = v - 1_i32;
643                 Ok(pos)
644               }
645               None => Err("Invalid month".to_string())
646             }
647           }
648           'n' => parse_char(s, pos, '\n'),
649           'P' => match match_strs(s, pos,
650                                   [("am".to_string(), 0_i32), ("pm".to_string(), 12_i32)]) {
651
652             Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
653             None => Err("Invalid hour".to_string())
654           },
655           'p' => match match_strs(s, pos,
656                                   [("AM".to_string(), 0_i32), ("PM".to_string(), 12_i32)]) {
657
658             Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
659             None => Err("Invalid hour".to_string())
660           },
661           'R' => {
662             parse_type(s, pos, 'H', &mut *tm)
663                 .and_then(|pos| parse_char(s, pos, ':'))
664                 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
665           }
666           'r' => {
667             parse_type(s, pos, 'I', &mut *tm)
668                 .and_then(|pos| parse_char(s, pos, ':'))
669                 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
670                 .and_then(|pos| parse_char(s, pos, ':'))
671                 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
672                 .and_then(|pos| parse_char(s, pos, ' '))
673                 .and_then(|pos| parse_type(s, pos, 'p', &mut *tm))
674           }
675           'S' => {
676             match match_digits_in_range(s, pos, 2u, false, 0_i32, 60_i32) {
677               Some(item) => {
678                 let (v, pos) = item;
679                 tm.tm_sec = v;
680                 Ok(pos)
681               }
682               None => Err("Invalid second".to_string())
683             }
684           }
685           //'s' {}
686           'T' | 'X' => {
687             parse_type(s, pos, 'H', &mut *tm)
688                 .and_then(|pos| parse_char(s, pos, ':'))
689                 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
690                 .and_then(|pos| parse_char(s, pos, ':'))
691                 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
692           }
693           't' => parse_char(s, pos, '\t'),
694           'u' => {
695             match match_digits_in_range(s, pos, 1u, false, 1_i32, 7_i32) {
696               Some(item) => {
697                 let (v, pos) = item;
698                 tm.tm_wday = if v == 7 { 0 } else { v };
699                 Ok(pos)
700               }
701               None => Err("Invalid day of week".to_string())
702             }
703           }
704           'v' => {
705             parse_type(s, pos, 'e', &mut *tm)
706                 .and_then(|pos|  parse_char(s, pos, '-'))
707                 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
708                 .and_then(|pos| parse_char(s, pos, '-'))
709                 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
710           }
711           //'W' {}
712           'w' => {
713             match match_digits_in_range(s, pos, 1u, false, 0_i32, 6_i32) {
714               Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
715               None => Err("Invalid day of week".to_string())
716             }
717           }
718           'Y' => {
719             match match_digits(s, pos, 4u, false) {
720               Some(item) => {
721                 let (v, pos) = item;
722                 tm.tm_year = v - 1900_i32;
723                 Ok(pos)
724               }
725               None => Err("Invalid year".to_string())
726             }
727           }
728           'y' => {
729             match match_digits_in_range(s, pos, 2u, false, 0_i32, 99_i32) {
730               Some(item) => {
731                 let (v, pos) = item;
732                 tm.tm_year = v;
733                 Ok(pos)
734               }
735               None => Err("Invalid year".to_string())
736             }
737           }
738           'Z' => {
739             if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") {
740                 tm.tm_gmtoff = 0_i32;
741                 Ok(pos + 3u)
742             } else {
743                 // It's odd, but to maintain compatibility with c's
744                 // strptime we ignore the timezone.
745                 let mut pos = pos;
746                 let len = s.len();
747                 while pos < len {
748                     let range = s.char_range_at(pos);
749                     pos = range.next;
750                     if range.ch == ' ' { break; }
751                 }
752
753                 Ok(pos)
754             }
755           }
756           'z' => {
757             let range = s.char_range_at(pos);
758
759             if range.ch == '+' || range.ch == '-' {
760                 match match_digits(s, range.next, 4u, false) {
761                   Some(item) => {
762                     let (v, pos) = item;
763                     if v == 0_i32 {
764                         tm.tm_gmtoff = 0_i32;
765                     }
766
767                     Ok(pos)
768                   }
769                   None => Err("Invalid zone offset".to_string())
770                 }
771             } else {
772                 Err("Invalid zone offset".to_string())
773             }
774           }
775           '%' => parse_char(s, pos, '%'),
776           ch => {
777             Err(format!("unknown formatting type: {}", str::from_char(ch)))
778           }
779         }
780     }
781
782     let mut rdr = BufReader::new(format.as_bytes());
783     let mut tm = Tm {
784         tm_sec: 0_i32,
785         tm_min: 0_i32,
786         tm_hour: 0_i32,
787         tm_mday: 0_i32,
788         tm_mon: 0_i32,
789         tm_year: 0_i32,
790         tm_wday: 0_i32,
791         tm_yday: 0_i32,
792         tm_isdst: 0_i32,
793         tm_gmtoff: 0_i32,
794         tm_nsec: 0_i32,
795     };
796     let mut pos = 0u;
797     let len = s.len();
798     let mut result = Err("Invalid time".to_string());
799
800     while pos < len {
801         let range = s.char_range_at(pos);
802         let ch = range.ch;
803         let next = range.next;
804
805         let mut buf = [0];
806         let c = match rdr.read(buf) {
807             Ok(..) => buf[0] as char,
808             Err(..) => break
809         };
810         match c {
811             '%' => {
812                 let ch = match rdr.read(buf) {
813                     Ok(..) => buf[0] as char,
814                     Err(..) => break
815                 };
816                 match parse_type(s, pos, ch, &mut tm) {
817                     Ok(next) => pos = next,
818                     Err(e) => { result = Err(e); break; }
819                 }
820             },
821             c => {
822                 if c != ch { break }
823                 pos = next;
824             }
825         }
826     }
827
828     if pos == len && rdr.tell().unwrap() == format.len() as u64 {
829         Ok(Tm {
830             tm_sec: tm.tm_sec,
831             tm_min: tm.tm_min,
832             tm_hour: tm.tm_hour,
833             tm_mday: tm.tm_mday,
834             tm_mon: tm.tm_mon,
835             tm_year: tm.tm_year,
836             tm_wday: tm.tm_wday,
837             tm_yday: tm.tm_yday,
838             tm_isdst: tm.tm_isdst,
839             tm_gmtoff: tm.tm_gmtoff,
840             tm_nsec: tm.tm_nsec,
841         })
842     } else { result }
843 }
844
845 /// Formats the time according to the format string.
846 pub fn strftime(format: &str, tm: &Tm) -> String {
847     fn days_in_year(year: int) -> i32 {
848         if (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) {
849             366    /* Days in a leap year */
850         } else {
851             365    /* Days in a non-leap year */
852         }
853     }
854
855     fn iso_week_days(yday: i32, wday: i32) -> int {
856         /* The number of days from the first day of the first ISO week of this
857         * year to the year day YDAY with week day WDAY.
858         * ISO weeks start on Monday. The first ISO week has the year's first
859         * Thursday.
860         * YDAY may be as small as yday_minimum.
861         */
862         let yday: int = yday as int;
863         let wday: int = wday as int;
864         let iso_week_start_wday: int = 1;                     /* Monday */
865         let iso_week1_wday: int = 4;                          /* Thursday */
866         let yday_minimum: int = 366;
867         /* Add enough to the first operand of % to make it nonnegative. */
868         let big_enough_multiple_of_7: int = (yday_minimum / 7 + 2) * 7;
869
870         yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
871             + iso_week1_wday - iso_week_start_wday
872     }
873
874     fn iso_week(ch:char, tm: &Tm) -> String {
875         let mut year: int = tm.tm_year as int + 1900;
876         let mut days: int = iso_week_days (tm.tm_yday, tm.tm_wday);
877
878         if days < 0 {
879             /* This ISO week belongs to the previous year. */
880             year -= 1;
881             days = iso_week_days (tm.tm_yday + (days_in_year(year)), tm.tm_wday);
882         } else {
883             let d: int = iso_week_days (tm.tm_yday - (days_in_year(year)),
884                                         tm.tm_wday);
885             if 0 <= d {
886                 /* This ISO week belongs to the next year. */
887                 year += 1;
888                 days = d;
889             }
890         }
891
892         match ch {
893             'G' => format!("{}", year),
894             'g' => format!("{:02d}", (year % 100 + 100) % 100),
895             'V' => format!("{:02d}", days / 7 + 1),
896             _ => "".to_string()
897         }
898     }
899
900     fn parse_type(ch: char, tm: &Tm) -> String {
901       let die = || {
902           format!("strftime: can't understand this format {} ", ch)
903       };
904         match ch {
905           'A' => match tm.tm_wday as int {
906             0 => "Sunday".to_string(),
907             1 => "Monday".to_string(),
908             2 => "Tuesday".to_string(),
909             3 => "Wednesday".to_string(),
910             4 => "Thursday".to_string(),
911             5 => "Friday".to_string(),
912             6 => "Saturday".to_string(),
913             _ => die()
914           },
915          'a' => match tm.tm_wday as int {
916             0 => "Sun".to_string(),
917             1 => "Mon".to_string(),
918             2 => "Tue".to_string(),
919             3 => "Wed".to_string(),
920             4 => "Thu".to_string(),
921             5 => "Fri".to_string(),
922             6 => "Sat".to_string(),
923             _ => die()
924           },
925           'B' => match tm.tm_mon as int {
926             0 => "January".to_string(),
927             1 => "February".to_string(),
928             2 => "March".to_string(),
929             3 => "April".to_string(),
930             4 => "May".to_string(),
931             5 => "June".to_string(),
932             6 => "July".to_string(),
933             7 => "August".to_string(),
934             8 => "September".to_string(),
935             9 => "October".to_string(),
936             10 => "November".to_string(),
937             11 => "December".to_string(),
938             _ => die()
939           },
940           'b' | 'h' => match tm.tm_mon as int {
941             0 => "Jan".to_string(),
942             1 => "Feb".to_string(),
943             2 => "Mar".to_string(),
944             3 => "Apr".to_string(),
945             4 => "May".to_string(),
946             5 => "Jun".to_string(),
947             6 => "Jul".to_string(),
948             7 => "Aug".to_string(),
949             8 => "Sep".to_string(),
950             9 => "Oct".to_string(),
951             10 => "Nov".to_string(),
952             11 => "Dec".to_string(),
953             _  => die()
954           },
955           'C' => format!("{:02d}", (tm.tm_year as int + 1900) / 100),
956           'c' => {
957             format!("{} {} {} {} {}",
958                 parse_type('a', tm),
959                 parse_type('b', tm),
960                 parse_type('e', tm),
961                 parse_type('T', tm),
962                 parse_type('Y', tm))
963           }
964           'D' | 'x' => {
965             format!("{}/{}/{}",
966                 parse_type('m', tm),
967                 parse_type('d', tm),
968                 parse_type('y', tm))
969           }
970           'd' => format!("{:02d}", tm.tm_mday),
971           'e' => format!("{:2d}", tm.tm_mday),
972           'f' => format!("{:09d}", tm.tm_nsec),
973           'F' => {
974             format!("{}-{}-{}",
975                 parse_type('Y', tm),
976                 parse_type('m', tm),
977                 parse_type('d', tm))
978           }
979           'G' => iso_week('G', tm),
980           'g' => iso_week('g', tm),
981           'H' => format!("{:02d}", tm.tm_hour),
982           'I' => {
983             let mut h = tm.tm_hour;
984             if h == 0 { h = 12 }
985             if h > 12 { h -= 12 }
986             format!("{:02d}", h)
987           }
988           'j' => format!("{:03d}", tm.tm_yday + 1),
989           'k' => format!("{:2d}", tm.tm_hour),
990           'l' => {
991             let mut h = tm.tm_hour;
992             if h == 0 { h = 12 }
993             if h > 12 { h -= 12 }
994             format!("{:2d}", h)
995           }
996           'M' => format!("{:02d}", tm.tm_min),
997           'm' => format!("{:02d}", tm.tm_mon + 1),
998           'n' => "\n".to_string(),
999           'P' => if (tm.tm_hour as int) < 12 { "am".to_string() } else { "pm".to_string() },
1000           'p' => if (tm.tm_hour as int) < 12 { "AM".to_string() } else { "PM".to_string() },
1001           'R' => {
1002             format!("{}:{}",
1003                 parse_type('H', tm),
1004                 parse_type('M', tm))
1005           }
1006           'r' => {
1007             format!("{}:{}:{} {}",
1008                 parse_type('I', tm),
1009                 parse_type('M', tm),
1010                 parse_type('S', tm),
1011                 parse_type('p', tm))
1012           }
1013           'S' => format!("{:02d}", tm.tm_sec),
1014           's' => format!("{}", tm.to_timespec().sec),
1015           'T' | 'X' => {
1016             format!("{}:{}:{}",
1017                 parse_type('H', tm),
1018                 parse_type('M', tm),
1019                 parse_type('S', tm))
1020           }
1021           't' => "\t".to_string(),
1022           'U' => format!("{:02d}", (tm.tm_yday - tm.tm_wday + 7) / 7),
1023           'u' => {
1024             let i = tm.tm_wday as int;
1025             (if i == 0 { 7 } else { i }).to_str()
1026           }
1027           'V' => iso_week('V', tm),
1028           'v' => {
1029             format!("{}-{}-{}",
1030                 parse_type('e', tm),
1031                 parse_type('b', tm),
1032                 parse_type('Y', tm))
1033           }
1034           'W' => {
1035               format!("{:02d}",
1036                              (tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7) / 7)
1037           }
1038           'w' => (tm.tm_wday as int).to_str(),
1039           'Y' => (tm.tm_year as int + 1900).to_str(),
1040           'y' => format!("{:02d}", (tm.tm_year as int + 1900) % 100),
1041           'Z' => "".to_string(),    // FIXME(pcwalton): Implement this.
1042           'z' => {
1043             let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
1044             let mut m = num::abs(tm.tm_gmtoff) / 60_i32;
1045             let h = m / 60_i32;
1046             m -= h * 60_i32;
1047             format!("{}{:02d}{:02d}", sign, h, m)
1048           }
1049           '+' => tm.rfc3339(),
1050           '%' => "%".to_string(),
1051           _   => die()
1052         }
1053     }
1054
1055     let mut buf = Vec::new();
1056
1057     let mut rdr = BufReader::new(format.as_bytes());
1058     loop {
1059         let mut b = [0];
1060         let ch = match rdr.read(b) {
1061             Ok(..) => b[0],
1062             Err(..) => break,
1063         };
1064         match ch as char {
1065             '%' => {
1066                 rdr.read(b).unwrap();
1067                 let s = parse_type(b[0] as char, tm);
1068                 buf.push_all(s.as_bytes());
1069             }
1070             ch => buf.push(ch as u8)
1071         }
1072     }
1073
1074     str::from_utf8(buf.as_slice()).unwrap().to_string()
1075 }
1076
1077 #[cfg(test)]
1078 mod tests {
1079     extern crate test;
1080     use super::{Timespec, get_time, precise_time_ns, precise_time_s, tzset,
1081                 at_utc, at, strptime};
1082
1083     use std::f64;
1084     use std::result::{Err, Ok};
1085     use self::test::Bencher;
1086
1087     #[cfg(windows)]
1088     fn set_time_zone() {
1089         use libc;
1090         // Windows crt doesn't see any environment variable set by
1091         // `SetEnvironmentVariable`, which `os::setenv` internally uses.
1092         // It is why we use `putenv` here.
1093         extern {
1094             fn _putenv(envstring: *const libc::c_char) -> libc::c_int;
1095         }
1096
1097         unsafe {
1098             // Windows does not understand "America/Los_Angeles".
1099             // PST+08 may look wrong, but not! "PST" indicates
1100             // the name of timezone. "+08" means UTC = local + 08.
1101             "TZ=PST+08".with_c_str(|env| {
1102                 _putenv(env);
1103             })
1104         }
1105         tzset();
1106     }
1107     #[cfg(not(windows))]
1108     fn set_time_zone() {
1109         use std::os;
1110         os::setenv("TZ", "America/Los_Angeles");
1111         tzset();
1112     }
1113
1114     fn test_get_time() {
1115         static SOME_RECENT_DATE: i64 = 1325376000i64; // 2012-01-01T00:00:00Z
1116         static SOME_FUTURE_DATE: i64 = 1577836800i64; // 2020-01-01T00:00:00Z
1117
1118         let tv1 = get_time();
1119         debug!("tv1={:?} sec + {:?} nsec", tv1.sec as uint, tv1.nsec as uint);
1120
1121         assert!(tv1.sec > SOME_RECENT_DATE);
1122         assert!(tv1.nsec < 1000000000i32);
1123
1124         let tv2 = get_time();
1125         debug!("tv2={:?} sec + {:?} nsec", tv2.sec as uint, tv2.nsec as uint);
1126
1127         assert!(tv2.sec >= tv1.sec);
1128         assert!(tv2.sec < SOME_FUTURE_DATE);
1129         assert!(tv2.nsec < 1000000000i32);
1130         if tv2.sec == tv1.sec {
1131             assert!(tv2.nsec >= tv1.nsec);
1132         }
1133     }
1134
1135     fn test_precise_time() {
1136         let s0 = precise_time_s();
1137         debug!("s0={} sec", f64::to_str_digits(s0, 9u));
1138         assert!(s0 > 0.);
1139
1140         let ns0 = precise_time_ns();
1141         let ns1 = precise_time_ns();
1142         debug!("ns0={:?} ns", ns0);
1143         debug!("ns1={:?} ns", ns1);
1144         assert!(ns1 >= ns0);
1145
1146         let ns2 = precise_time_ns();
1147         debug!("ns2={:?} ns", ns2);
1148         assert!(ns2 >= ns1);
1149     }
1150
1151     fn test_at_utc() {
1152         set_time_zone();
1153
1154         let time = Timespec::new(1234567890, 54321);
1155         let utc = at_utc(time);
1156
1157         assert_eq!(utc.tm_sec, 30_i32);
1158         assert_eq!(utc.tm_min, 31_i32);
1159         assert_eq!(utc.tm_hour, 23_i32);
1160         assert_eq!(utc.tm_mday, 13_i32);
1161         assert_eq!(utc.tm_mon, 1_i32);
1162         assert_eq!(utc.tm_year, 109_i32);
1163         assert_eq!(utc.tm_wday, 5_i32);
1164         assert_eq!(utc.tm_yday, 43_i32);
1165         assert_eq!(utc.tm_isdst, 0_i32);
1166         assert_eq!(utc.tm_gmtoff, 0_i32);
1167         assert_eq!(utc.tm_nsec, 54321_i32);
1168     }
1169
1170     fn test_at() {
1171         set_time_zone();
1172
1173         let time = Timespec::new(1234567890, 54321);
1174         let local = at(time);
1175
1176         debug!("time_at: {:?}", local);
1177
1178         assert_eq!(local.tm_sec, 30_i32);
1179         assert_eq!(local.tm_min, 31_i32);
1180         assert_eq!(local.tm_hour, 15_i32);
1181         assert_eq!(local.tm_mday, 13_i32);
1182         assert_eq!(local.tm_mon, 1_i32);
1183         assert_eq!(local.tm_year, 109_i32);
1184         assert_eq!(local.tm_wday, 5_i32);
1185         assert_eq!(local.tm_yday, 43_i32);
1186         assert_eq!(local.tm_isdst, 0_i32);
1187         assert_eq!(local.tm_gmtoff, -28800_i32);
1188         assert_eq!(local.tm_nsec, 54321_i32);
1189     }
1190
1191     fn test_to_timespec() {
1192         set_time_zone();
1193
1194         let time = Timespec::new(1234567890, 54321);
1195         let utc = at_utc(time);
1196
1197         assert_eq!(utc.to_timespec(), time);
1198         assert_eq!(utc.to_local().to_timespec(), time);
1199     }
1200
1201     fn test_conversions() {
1202         set_time_zone();
1203
1204         let time = Timespec::new(1234567890, 54321);
1205         let utc = at_utc(time);
1206         let local = at(time);
1207
1208         assert!(local.to_local() == local);
1209         assert!(local.to_utc() == utc);
1210         assert!(local.to_utc().to_local() == local);
1211         assert!(utc.to_utc() == utc);
1212         assert!(utc.to_local() == local);
1213         assert!(utc.to_local().to_utc() == utc);
1214     }
1215
1216     fn test_strptime() {
1217         set_time_zone();
1218
1219         match strptime("", "") {
1220           Ok(ref tm) => {
1221             assert!(tm.tm_sec == 0_i32);
1222             assert!(tm.tm_min == 0_i32);
1223             assert!(tm.tm_hour == 0_i32);
1224             assert!(tm.tm_mday == 0_i32);
1225             assert!(tm.tm_mon == 0_i32);
1226             assert!(tm.tm_year == 0_i32);
1227             assert!(tm.tm_wday == 0_i32);
1228             assert!(tm.tm_isdst == 0_i32);
1229             assert!(tm.tm_gmtoff == 0_i32);
1230             assert!(tm.tm_nsec == 0_i32);
1231           }
1232           Err(_) => ()
1233         }
1234
1235         let format = "%a %b %e %T.%f %Y";
1236         assert_eq!(strptime("", format), Err("Invalid time".to_string()));
1237         assert!(strptime("Fri Feb 13 15:31:30", format)
1238             == Err("Invalid time".to_string()));
1239
1240         match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
1241           Err(e) => fail!(e),
1242           Ok(ref tm) => {
1243             assert!(tm.tm_sec == 30_i32);
1244             assert!(tm.tm_min == 31_i32);
1245             assert!(tm.tm_hour == 15_i32);
1246             assert!(tm.tm_mday == 13_i32);
1247             assert!(tm.tm_mon == 1_i32);
1248             assert!(tm.tm_year == 109_i32);
1249             assert!(tm.tm_wday == 5_i32);
1250             assert!(tm.tm_yday == 0_i32);
1251             assert!(tm.tm_isdst == 0_i32);
1252             assert!(tm.tm_gmtoff == 0_i32);
1253             assert!(tm.tm_nsec == 12340000_i32);
1254           }
1255         }
1256
1257         fn test(s: &str, format: &str) -> bool {
1258             match strptime(s, format) {
1259               Ok(ref tm) => tm.strftime(format) == s.to_string(),
1260               Err(e) => fail!(e)
1261             }
1262         }
1263
1264         let days = [
1265             "Sunday".to_string(),
1266             "Monday".to_string(),
1267             "Tuesday".to_string(),
1268             "Wednesday".to_string(),
1269             "Thursday".to_string(),
1270             "Friday".to_string(),
1271             "Saturday".to_string()
1272         ];
1273         for day in days.iter() {
1274             assert!(test(day.as_slice(), "%A"));
1275         }
1276
1277         let days = [
1278             "Sun".to_string(),
1279             "Mon".to_string(),
1280             "Tue".to_string(),
1281             "Wed".to_string(),
1282             "Thu".to_string(),
1283             "Fri".to_string(),
1284             "Sat".to_string()
1285         ];
1286         for day in days.iter() {
1287             assert!(test(day.as_slice(), "%a"));
1288         }
1289
1290         let months = [
1291             "January".to_string(),
1292             "February".to_string(),
1293             "March".to_string(),
1294             "April".to_string(),
1295             "May".to_string(),
1296             "June".to_string(),
1297             "July".to_string(),
1298             "August".to_string(),
1299             "September".to_string(),
1300             "October".to_string(),
1301             "November".to_string(),
1302             "December".to_string()
1303         ];
1304         for day in months.iter() {
1305             assert!(test(day.as_slice(), "%B"));
1306         }
1307
1308         let months = [
1309             "Jan".to_string(),
1310             "Feb".to_string(),
1311             "Mar".to_string(),
1312             "Apr".to_string(),
1313             "May".to_string(),
1314             "Jun".to_string(),
1315             "Jul".to_string(),
1316             "Aug".to_string(),
1317             "Sep".to_string(),
1318             "Oct".to_string(),
1319             "Nov".to_string(),
1320             "Dec".to_string()
1321         ];
1322         for day in months.iter() {
1323             assert!(test(day.as_slice(), "%b"));
1324         }
1325
1326         assert!(test("19", "%C"));
1327         assert!(test("Fri Feb 13 23:31:30 2009", "%c"));
1328         assert!(test("02/13/09", "%D"));
1329         assert!(test("03", "%d"));
1330         assert!(test("13", "%d"));
1331         assert!(test(" 3", "%e"));
1332         assert!(test("13", "%e"));
1333         assert!(test("2009-02-13", "%F"));
1334         assert!(test("03", "%H"));
1335         assert!(test("13", "%H"));
1336         assert!(test("03", "%I")); // FIXME (#2350): flesh out
1337         assert!(test("11", "%I")); // FIXME (#2350): flesh out
1338         assert!(test("044", "%j"));
1339         assert!(test(" 3", "%k"));
1340         assert!(test("13", "%k"));
1341         assert!(test(" 1", "%l"));
1342         assert!(test("11", "%l"));
1343         assert!(test("03", "%M"));
1344         assert!(test("13", "%M"));
1345         assert!(test("\n", "%n"));
1346         assert!(test("am", "%P"));
1347         assert!(test("pm", "%P"));
1348         assert!(test("AM", "%p"));
1349         assert!(test("PM", "%p"));
1350         assert!(test("23:31", "%R"));
1351         assert!(test("11:31:30 AM", "%r"));
1352         assert!(test("11:31:30 PM", "%r"));
1353         assert!(test("03", "%S"));
1354         assert!(test("13", "%S"));
1355         assert!(test("15:31:30", "%T"));
1356         assert!(test("\t", "%t"));
1357         assert!(test("1", "%u"));
1358         assert!(test("7", "%u"));
1359         assert!(test("13-Feb-2009", "%v"));
1360         assert!(test("0", "%w"));
1361         assert!(test("6", "%w"));
1362         assert!(test("2009", "%Y"));
1363         assert!(test("09", "%y"));
1364         assert!(strptime("-0000", "%z").unwrap().tm_gmtoff ==
1365             0);
1366         assert!(strptime("-0800", "%z").unwrap().tm_gmtoff ==
1367             0);
1368         assert!(test("%", "%%"));
1369
1370         // Test for #7256
1371         assert_eq!(strptime("360", "%Y-%m-%d"), Err("Invalid year".to_string()))
1372     }
1373
1374     fn test_ctime() {
1375         set_time_zone();
1376
1377         let time = Timespec::new(1234567890, 54321);
1378         let utc   = at_utc(time);
1379         let local = at(time);
1380
1381         debug!("test_ctime: {:?} {:?}", utc.ctime(), local.ctime());
1382
1383         assert_eq!(utc.ctime(), "Fri Feb 13 23:31:30 2009".to_string());
1384         assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1385     }
1386
1387     fn test_strftime() {
1388         set_time_zone();
1389
1390         let time = Timespec::new(1234567890, 54321);
1391         let utc = at_utc(time);
1392         let local = at(time);
1393
1394         assert_eq!(local.strftime(""), "".to_string());
1395         assert_eq!(local.strftime("%A"), "Friday".to_string());
1396         assert_eq!(local.strftime("%a"), "Fri".to_string());
1397         assert_eq!(local.strftime("%B"), "February".to_string());
1398         assert_eq!(local.strftime("%b"), "Feb".to_string());
1399         assert_eq!(local.strftime("%C"), "20".to_string());
1400         assert_eq!(local.strftime("%c"), "Fri Feb 13 15:31:30 2009".to_string());
1401         assert_eq!(local.strftime("%D"), "02/13/09".to_string());
1402         assert_eq!(local.strftime("%d"), "13".to_string());
1403         assert_eq!(local.strftime("%e"), "13".to_string());
1404         assert_eq!(local.strftime("%f"), "000054321".to_string());
1405         assert_eq!(local.strftime("%F"), "2009-02-13".to_string());
1406         assert_eq!(local.strftime("%G"), "2009".to_string());
1407         assert_eq!(local.strftime("%g"), "09".to_string());
1408         assert_eq!(local.strftime("%H"), "15".to_string());
1409         assert_eq!(local.strftime("%I"), "03".to_string());
1410         assert_eq!(local.strftime("%j"), "044".to_string());
1411         assert_eq!(local.strftime("%k"), "15".to_string());
1412         assert_eq!(local.strftime("%l"), " 3".to_string());
1413         assert_eq!(local.strftime("%M"), "31".to_string());
1414         assert_eq!(local.strftime("%m"), "02".to_string());
1415         assert_eq!(local.strftime("%n"), "\n".to_string());
1416         assert_eq!(local.strftime("%P"), "pm".to_string());
1417         assert_eq!(local.strftime("%p"), "PM".to_string());
1418         assert_eq!(local.strftime("%R"), "15:31".to_string());
1419         assert_eq!(local.strftime("%r"), "03:31:30 PM".to_string());
1420         assert_eq!(local.strftime("%S"), "30".to_string());
1421         assert_eq!(local.strftime("%s"), "1234567890".to_string());
1422         assert_eq!(local.strftime("%T"), "15:31:30".to_string());
1423         assert_eq!(local.strftime("%t"), "\t".to_string());
1424         assert_eq!(local.strftime("%U"), "06".to_string());
1425         assert_eq!(local.strftime("%u"), "5".to_string());
1426         assert_eq!(local.strftime("%V"), "07".to_string());
1427         assert_eq!(local.strftime("%v"), "13-Feb-2009".to_string());
1428         assert_eq!(local.strftime("%W"), "06".to_string());
1429         assert_eq!(local.strftime("%w"), "5".to_string());
1430         assert_eq!(local.strftime("%X"), "15:31:30".to_string()); // FIXME (#2350): support locale
1431         assert_eq!(local.strftime("%x"), "02/13/09".to_string()); // FIXME (#2350): support locale
1432         assert_eq!(local.strftime("%Y"), "2009".to_string());
1433         assert_eq!(local.strftime("%y"), "09".to_string());
1434         assert_eq!(local.strftime("%+"), "2009-02-13T15:31:30-08:00".to_string());
1435         assert_eq!(local.strftime("%z"), "-0800".to_string());
1436         assert_eq!(local.strftime("%%"), "%".to_string());
1437
1438         assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1439         assert_eq!(local.rfc822z(), "Fri, 13 Feb 2009 15:31:30 -0800".to_string());
1440         assert_eq!(local.rfc3339(), "2009-02-13T15:31:30-08:00".to_string());
1441
1442         assert_eq!(utc.ctime(), "Fri Feb 13 23:31:30 2009".to_string());
1443         assert_eq!(utc.rfc822(), "Fri, 13 Feb 2009 23:31:30 GMT".to_string());
1444         assert_eq!(utc.rfc822z(), "Fri, 13 Feb 2009 23:31:30 -0000".to_string());
1445         assert_eq!(utc.rfc3339(), "2009-02-13T23:31:30Z".to_string());
1446     }
1447
1448     fn test_timespec_eq_ord() {
1449         let a = &Timespec::new(-2, 1);
1450         let b = &Timespec::new(-1, 2);
1451         let c = &Timespec::new(1, 2);
1452         let d = &Timespec::new(2, 1);
1453         let e = &Timespec::new(2, 1);
1454
1455         assert!(d.eq(e));
1456         assert!(c.ne(e));
1457
1458         assert!(a.lt(b));
1459         assert!(b.lt(c));
1460         assert!(c.lt(d));
1461
1462         assert!(a.le(b));
1463         assert!(b.le(c));
1464         assert!(c.le(d));
1465         assert!(d.le(e));
1466         assert!(e.le(d));
1467
1468         assert!(b.ge(a));
1469         assert!(c.ge(b));
1470         assert!(d.ge(c));
1471         assert!(e.ge(d));
1472         assert!(d.ge(e));
1473
1474         assert!(b.gt(a));
1475         assert!(c.gt(b));
1476         assert!(d.gt(c));
1477     }
1478
1479     #[test]
1480     #[ignore(cfg(target_os = "android"))] // FIXME #10958
1481     fn run_tests() {
1482         // The tests race on tzset. So instead of having many independent
1483         // tests, we will just call the functions now.
1484         test_get_time();
1485         test_precise_time();
1486         test_at_utc();
1487         test_at();
1488         test_to_timespec();
1489         test_conversions();
1490         test_strptime();
1491         test_ctime();
1492         test_strftime();
1493         test_timespec_eq_ord();
1494     }
1495
1496     #[bench]
1497     fn bench_precise_time_ns(b: &mut Bencher) {
1498         b.iter(|| precise_time_ns())
1499     }
1500 }