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