]> git.lizzy.rs Git - rust.git/blob - src/libtime/lib.rs
9b5bbbadc9c5eb0b3e0ef6157552179a38bee3f8
[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 #![feature(phase)]
22 #![deny(deprecated_owned_vector)]
23
24 #[cfg(test)] extern crate debug;
25 #[cfg(test)] #[phase(syntax, link)] extern crate log;
26
27 extern crate serialize;
28 extern crate libc;
29 #[cfg(target_os = "macos")]
30 extern crate sync;
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, Eq, TotalEq, Ord, TotalOrd, 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: sync::one::Once = sync::one::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, Eq, 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_strbuf!("{}{}{: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_strbuf!("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_strbuf!("unknown formatting type: {}",
776                                str::from_char(ch)))
777           }
778         }
779     }
780
781     let mut rdr = BufReader::new(format.as_bytes());
782     let mut tm = Tm {
783         tm_sec: 0_i32,
784         tm_min: 0_i32,
785         tm_hour: 0_i32,
786         tm_mday: 0_i32,
787         tm_mon: 0_i32,
788         tm_year: 0_i32,
789         tm_wday: 0_i32,
790         tm_yday: 0_i32,
791         tm_isdst: 0_i32,
792         tm_gmtoff: 0_i32,
793         tm_nsec: 0_i32,
794     };
795     let mut pos = 0u;
796     let len = s.len();
797     let mut result = Err("Invalid time".to_string());
798
799     while pos < len {
800         let range = s.char_range_at(pos);
801         let ch = range.ch;
802         let next = range.next;
803
804         let mut buf = [0];
805         let c = match rdr.read(buf) {
806             Ok(..) => buf[0] as char,
807             Err(..) => break
808         };
809         match c {
810             '%' => {
811                 let ch = match rdr.read(buf) {
812                     Ok(..) => buf[0] as char,
813                     Err(..) => break
814                 };
815                 match parse_type(s, pos, ch, &mut tm) {
816                     Ok(next) => pos = next,
817                     Err(e) => { result = Err(e); break; }
818                 }
819             },
820             c => {
821                 if c != ch { break }
822                 pos = next;
823             }
824         }
825     }
826
827     if pos == len && rdr.tell().unwrap() == format.len() as u64 {
828         Ok(Tm {
829             tm_sec: tm.tm_sec,
830             tm_min: tm.tm_min,
831             tm_hour: tm.tm_hour,
832             tm_mday: tm.tm_mday,
833             tm_mon: tm.tm_mon,
834             tm_year: tm.tm_year,
835             tm_wday: tm.tm_wday,
836             tm_yday: tm.tm_yday,
837             tm_isdst: tm.tm_isdst,
838             tm_gmtoff: tm.tm_gmtoff,
839             tm_nsec: tm.tm_nsec,
840         })
841     } else { result }
842 }
843
844 /// Formats the time according to the format string.
845 pub fn strftime(format: &str, tm: &Tm) -> String {
846     fn days_in_year(year: int) -> i32 {
847         if (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) {
848             366    /* Days in a leap year */
849         } else {
850             365    /* Days in a non-leap year */
851         }
852     }
853
854     fn iso_week_days(yday: i32, wday: i32) -> int {
855         /* The number of days from the first day of the first ISO week of this
856         * year to the year day YDAY with week day WDAY.
857         * ISO weeks start on Monday. The first ISO week has the year's first
858         * Thursday.
859         * YDAY may be as small as yday_minimum.
860         */
861         let yday: int = yday as int;
862         let wday: int = wday as int;
863         let iso_week_start_wday: int = 1;                     /* Monday */
864         let iso_week1_wday: int = 4;                          /* Thursday */
865         let yday_minimum: int = 366;
866         /* Add enough to the first operand of % to make it nonnegative. */
867         let big_enough_multiple_of_7: int = (yday_minimum / 7 + 2) * 7;
868
869         yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
870             + iso_week1_wday - iso_week_start_wday
871     }
872
873     fn iso_week(ch:char, tm: &Tm) -> String {
874         let mut year: int = tm.tm_year as int + 1900;
875         let mut days: int = iso_week_days (tm.tm_yday, tm.tm_wday);
876
877         if days < 0 {
878             /* This ISO week belongs to the previous year. */
879             year -= 1;
880             days = iso_week_days (tm.tm_yday + (days_in_year(year)), tm.tm_wday);
881         } else {
882             let d: int = iso_week_days (tm.tm_yday - (days_in_year(year)),
883                                         tm.tm_wday);
884             if 0 <= d {
885                 /* This ISO week belongs to the next year. */
886                 year += 1;
887                 days = d;
888             }
889         }
890
891         match ch {
892             'G' => format_strbuf!("{}", year),
893             'g' => format_strbuf!("{:02d}", (year % 100 + 100) % 100),
894             'V' => format_strbuf!("{:02d}", days / 7 + 1),
895             _ => "".to_string()
896         }
897     }
898
899     fn parse_type(ch: char, tm: &Tm) -> String {
900       let die = || {
901           format_strbuf!("strftime: can't understand this format {} ", ch)
902       };
903         match ch {
904           'A' => match tm.tm_wday as int {
905             0 => "Sunday".to_string(),
906             1 => "Monday".to_string(),
907             2 => "Tuesday".to_string(),
908             3 => "Wednesday".to_string(),
909             4 => "Thursday".to_string(),
910             5 => "Friday".to_string(),
911             6 => "Saturday".to_string(),
912             _ => die()
913           },
914          'a' => match tm.tm_wday as int {
915             0 => "Sun".to_string(),
916             1 => "Mon".to_string(),
917             2 => "Tue".to_string(),
918             3 => "Wed".to_string(),
919             4 => "Thu".to_string(),
920             5 => "Fri".to_string(),
921             6 => "Sat".to_string(),
922             _ => die()
923           },
924           'B' => match tm.tm_mon as int {
925             0 => "January".to_string(),
926             1 => "February".to_string(),
927             2 => "March".to_string(),
928             3 => "April".to_string(),
929             4 => "May".to_string(),
930             5 => "June".to_string(),
931             6 => "July".to_string(),
932             7 => "August".to_string(),
933             8 => "September".to_string(),
934             9 => "October".to_string(),
935             10 => "November".to_string(),
936             11 => "December".to_string(),
937             _ => die()
938           },
939           'b' | 'h' => match tm.tm_mon as int {
940             0 => "Jan".to_string(),
941             1 => "Feb".to_string(),
942             2 => "Mar".to_string(),
943             3 => "Apr".to_string(),
944             4 => "May".to_string(),
945             5 => "Jun".to_string(),
946             6 => "Jul".to_string(),
947             7 => "Aug".to_string(),
948             8 => "Sep".to_string(),
949             9 => "Oct".to_string(),
950             10 => "Nov".to_string(),
951             11 => "Dec".to_string(),
952             _  => die()
953           },
954           'C' => format_strbuf!("{:02d}", (tm.tm_year as int + 1900) / 100),
955           'c' => {
956             format_strbuf!("{} {} {} {} {}",
957                 parse_type('a', tm),
958                 parse_type('b', tm),
959                 parse_type('e', tm),
960                 parse_type('T', tm),
961                 parse_type('Y', tm))
962           }
963           'D' | 'x' => {
964             format_strbuf!("{}/{}/{}",
965                 parse_type('m', tm),
966                 parse_type('d', tm),
967                 parse_type('y', tm))
968           }
969           'd' => format_strbuf!("{:02d}", tm.tm_mday),
970           'e' => format_strbuf!("{:2d}", tm.tm_mday),
971           'f' => format_strbuf!("{:09d}", tm.tm_nsec),
972           'F' => {
973             format_strbuf!("{}-{}-{}",
974                 parse_type('Y', tm),
975                 parse_type('m', tm),
976                 parse_type('d', tm))
977           }
978           'G' => iso_week('G', tm),
979           'g' => iso_week('g', tm),
980           'H' => format_strbuf!("{:02d}", tm.tm_hour),
981           'I' => {
982             let mut h = tm.tm_hour;
983             if h == 0 { h = 12 }
984             if h > 12 { h -= 12 }
985             format_strbuf!("{:02d}", h)
986           }
987           'j' => format_strbuf!("{:03d}", tm.tm_yday + 1),
988           'k' => format_strbuf!("{:2d}", tm.tm_hour),
989           'l' => {
990             let mut h = tm.tm_hour;
991             if h == 0 { h = 12 }
992             if h > 12 { h -= 12 }
993             format_strbuf!("{:2d}", h)
994           }
995           'M' => format_strbuf!("{:02d}", tm.tm_min),
996           'm' => format_strbuf!("{:02d}", tm.tm_mon + 1),
997           'n' => "\n".to_string(),
998           'P' => if (tm.tm_hour as int) < 12 { "am".to_string() } else { "pm".to_string() },
999           'p' => if (tm.tm_hour as int) < 12 { "AM".to_string() } else { "PM".to_string() },
1000           'R' => {
1001             format_strbuf!("{}:{}",
1002                 parse_type('H', tm),
1003                 parse_type('M', tm))
1004           }
1005           'r' => {
1006             format_strbuf!("{}:{}:{} {}",
1007                 parse_type('I', tm),
1008                 parse_type('M', tm),
1009                 parse_type('S', tm),
1010                 parse_type('p', tm))
1011           }
1012           'S' => format_strbuf!("{:02d}", tm.tm_sec),
1013           's' => format_strbuf!("{}", tm.to_timespec().sec),
1014           'T' | 'X' => {
1015             format_strbuf!("{}:{}:{}",
1016                 parse_type('H', tm),
1017                 parse_type('M', tm),
1018                 parse_type('S', tm))
1019           }
1020           't' => "\t".to_string(),
1021           'U' => format_strbuf!("{:02d}", (tm.tm_yday - tm.tm_wday + 7) / 7),
1022           'u' => {
1023             let i = tm.tm_wday as int;
1024             (if i == 0 { 7 } else { i }).to_str().to_string()
1025           }
1026           'V' => iso_week('V', tm),
1027           'v' => {
1028             format_strbuf!("{}-{}-{}",
1029                 parse_type('e', tm),
1030                 parse_type('b', tm),
1031                 parse_type('Y', tm))
1032           }
1033           'W' => {
1034               format_strbuf!("{:02d}",
1035                              (tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7) / 7)
1036           }
1037           'w' => (tm.tm_wday as int).to_str().to_string(),
1038           'Y' => (tm.tm_year as int + 1900).to_str().to_string(),
1039           'y' => format_strbuf!("{:02d}", (tm.tm_year as int + 1900) % 100),
1040           'Z' => "".to_string(),    // FIXME(pcwalton): Implement this.
1041           'z' => {
1042             let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
1043             let mut m = num::abs(tm.tm_gmtoff) / 60_i32;
1044             let h = m / 60_i32;
1045             m -= h * 60_i32;
1046             format_strbuf!("{}{:02d}{:02d}", sign, h, m)
1047           }
1048           '+' => tm.rfc3339(),
1049           '%' => "%".to_string(),
1050           _   => die()
1051         }
1052     }
1053
1054     let mut buf = Vec::new();
1055
1056     let mut rdr = BufReader::new(format.as_bytes());
1057     loop {
1058         let mut b = [0];
1059         let ch = match rdr.read(b) {
1060             Ok(..) => b[0],
1061             Err(..) => break,
1062         };
1063         match ch as char {
1064             '%' => {
1065                 rdr.read(b).unwrap();
1066                 let s = parse_type(b[0] as char, tm);
1067                 buf.push_all(s.as_bytes());
1068             }
1069             ch => buf.push(ch as u8)
1070         }
1071     }
1072
1073     str::from_utf8(buf.as_slice()).unwrap().to_string()
1074 }
1075
1076 #[cfg(test)]
1077 mod tests {
1078     extern crate test;
1079     use super::{Timespec, get_time, precise_time_ns, precise_time_s, tzset,
1080                 at_utc, at, strptime};
1081
1082     use std::f64;
1083     use std::result::{Err, Ok};
1084     use self::test::Bencher;
1085
1086     #[cfg(windows)]
1087     fn set_time_zone() {
1088         use libc;
1089         // Windows crt doesn't see any environment variable set by
1090         // `SetEnvironmentVariable`, which `os::setenv` internally uses.
1091         // It is why we use `putenv` here.
1092         extern {
1093             fn _putenv(envstring: *libc::c_char) -> libc::c_int;
1094         }
1095
1096         unsafe {
1097             // Windows does not understand "America/Los_Angeles".
1098             // PST+08 may look wrong, but not! "PST" indicates
1099             // the name of timezone. "+08" means UTC = local + 08.
1100             "TZ=PST+08".with_c_str(|env| {
1101                 _putenv(env);
1102             })
1103         }
1104         tzset();
1105     }
1106     #[cfg(not(windows))]
1107     fn set_time_zone() {
1108         use std::os;
1109         os::setenv("TZ", "America/Los_Angeles");
1110         tzset();
1111     }
1112
1113     fn test_get_time() {
1114         static SOME_RECENT_DATE: i64 = 1325376000i64; // 2012-01-01T00:00:00Z
1115         static SOME_FUTURE_DATE: i64 = 1577836800i64; // 2020-01-01T00:00:00Z
1116
1117         let tv1 = get_time();
1118         debug!("tv1={:?} sec + {:?} nsec", tv1.sec as uint, tv1.nsec as uint);
1119
1120         assert!(tv1.sec > SOME_RECENT_DATE);
1121         assert!(tv1.nsec < 1000000000i32);
1122
1123         let tv2 = get_time();
1124         debug!("tv2={:?} sec + {:?} nsec", tv2.sec as uint, tv2.nsec as uint);
1125
1126         assert!(tv2.sec >= tv1.sec);
1127         assert!(tv2.sec < SOME_FUTURE_DATE);
1128         assert!(tv2.nsec < 1000000000i32);
1129         if tv2.sec == tv1.sec {
1130             assert!(tv2.nsec >= tv1.nsec);
1131         }
1132     }
1133
1134     fn test_precise_time() {
1135         let s0 = precise_time_s();
1136         debug!("s0={} sec", f64::to_str_digits(s0, 9u));
1137         assert!(s0 > 0.);
1138
1139         let ns0 = precise_time_ns();
1140         let ns1 = precise_time_ns();
1141         debug!("ns0={:?} ns", ns0);
1142         debug!("ns1={:?} ns", ns1);
1143         assert!(ns1 >= ns0);
1144
1145         let ns2 = precise_time_ns();
1146         debug!("ns2={:?} ns", ns2);
1147         assert!(ns2 >= ns1);
1148     }
1149
1150     fn test_at_utc() {
1151         set_time_zone();
1152
1153         let time = Timespec::new(1234567890, 54321);
1154         let utc = at_utc(time);
1155
1156         assert_eq!(utc.tm_sec, 30_i32);
1157         assert_eq!(utc.tm_min, 31_i32);
1158         assert_eq!(utc.tm_hour, 23_i32);
1159         assert_eq!(utc.tm_mday, 13_i32);
1160         assert_eq!(utc.tm_mon, 1_i32);
1161         assert_eq!(utc.tm_year, 109_i32);
1162         assert_eq!(utc.tm_wday, 5_i32);
1163         assert_eq!(utc.tm_yday, 43_i32);
1164         assert_eq!(utc.tm_isdst, 0_i32);
1165         assert_eq!(utc.tm_gmtoff, 0_i32);
1166         assert_eq!(utc.tm_nsec, 54321_i32);
1167     }
1168
1169     fn test_at() {
1170         set_time_zone();
1171
1172         let time = Timespec::new(1234567890, 54321);
1173         let local = at(time);
1174
1175         debug!("time_at: {:?}", local);
1176
1177         assert_eq!(local.tm_sec, 30_i32);
1178         assert_eq!(local.tm_min, 31_i32);
1179         assert_eq!(local.tm_hour, 15_i32);
1180         assert_eq!(local.tm_mday, 13_i32);
1181         assert_eq!(local.tm_mon, 1_i32);
1182         assert_eq!(local.tm_year, 109_i32);
1183         assert_eq!(local.tm_wday, 5_i32);
1184         assert_eq!(local.tm_yday, 43_i32);
1185         assert_eq!(local.tm_isdst, 0_i32);
1186         assert_eq!(local.tm_gmtoff, -28800_i32);
1187         assert_eq!(local.tm_nsec, 54321_i32);
1188     }
1189
1190     fn test_to_timespec() {
1191         set_time_zone();
1192
1193         let time = Timespec::new(1234567890, 54321);
1194         let utc = at_utc(time);
1195
1196         assert_eq!(utc.to_timespec(), time);
1197         assert_eq!(utc.to_local().to_timespec(), time);
1198     }
1199
1200     fn test_conversions() {
1201         set_time_zone();
1202
1203         let time = Timespec::new(1234567890, 54321);
1204         let utc = at_utc(time);
1205         let local = at(time);
1206
1207         assert!(local.to_local() == local);
1208         assert!(local.to_utc() == utc);
1209         assert!(local.to_utc().to_local() == local);
1210         assert!(utc.to_utc() == utc);
1211         assert!(utc.to_local() == local);
1212         assert!(utc.to_local().to_utc() == utc);
1213     }
1214
1215     fn test_strptime() {
1216         set_time_zone();
1217
1218         match strptime("", "") {
1219           Ok(ref tm) => {
1220             assert!(tm.tm_sec == 0_i32);
1221             assert!(tm.tm_min == 0_i32);
1222             assert!(tm.tm_hour == 0_i32);
1223             assert!(tm.tm_mday == 0_i32);
1224             assert!(tm.tm_mon == 0_i32);
1225             assert!(tm.tm_year == 0_i32);
1226             assert!(tm.tm_wday == 0_i32);
1227             assert!(tm.tm_isdst == 0_i32);
1228             assert!(tm.tm_gmtoff == 0_i32);
1229             assert!(tm.tm_nsec == 0_i32);
1230           }
1231           Err(_) => ()
1232         }
1233
1234         let format = "%a %b %e %T.%f %Y";
1235         assert_eq!(strptime("", format), Err("Invalid time".to_string()));
1236         assert!(strptime("Fri Feb 13 15:31:30", format)
1237             == Err("Invalid time".to_string()));
1238
1239         match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
1240           Err(e) => fail!(e),
1241           Ok(ref tm) => {
1242             assert!(tm.tm_sec == 30_i32);
1243             assert!(tm.tm_min == 31_i32);
1244             assert!(tm.tm_hour == 15_i32);
1245             assert!(tm.tm_mday == 13_i32);
1246             assert!(tm.tm_mon == 1_i32);
1247             assert!(tm.tm_year == 109_i32);
1248             assert!(tm.tm_wday == 5_i32);
1249             assert!(tm.tm_yday == 0_i32);
1250             assert!(tm.tm_isdst == 0_i32);
1251             assert!(tm.tm_gmtoff == 0_i32);
1252             assert!(tm.tm_nsec == 12340000_i32);
1253           }
1254         }
1255
1256         fn test(s: &str, format: &str) -> bool {
1257             match strptime(s, format) {
1258               Ok(ref tm) => tm.strftime(format) == s.to_string(),
1259               Err(e) => fail!(e)
1260             }
1261         }
1262
1263         let days = [
1264             "Sunday".to_string(),
1265             "Monday".to_string(),
1266             "Tuesday".to_string(),
1267             "Wednesday".to_string(),
1268             "Thursday".to_string(),
1269             "Friday".to_string(),
1270             "Saturday".to_string()
1271         ];
1272         for day in days.iter() {
1273             assert!(test(day.as_slice(), "%A"));
1274         }
1275
1276         let days = [
1277             "Sun".to_string(),
1278             "Mon".to_string(),
1279             "Tue".to_string(),
1280             "Wed".to_string(),
1281             "Thu".to_string(),
1282             "Fri".to_string(),
1283             "Sat".to_string()
1284         ];
1285         for day in days.iter() {
1286             assert!(test(day.as_slice(), "%a"));
1287         }
1288
1289         let months = [
1290             "January".to_string(),
1291             "February".to_string(),
1292             "March".to_string(),
1293             "April".to_string(),
1294             "May".to_string(),
1295             "June".to_string(),
1296             "July".to_string(),
1297             "August".to_string(),
1298             "September".to_string(),
1299             "October".to_string(),
1300             "November".to_string(),
1301             "December".to_string()
1302         ];
1303         for day in months.iter() {
1304             assert!(test(day.as_slice(), "%B"));
1305         }
1306
1307         let months = [
1308             "Jan".to_string(),
1309             "Feb".to_string(),
1310             "Mar".to_string(),
1311             "Apr".to_string(),
1312             "May".to_string(),
1313             "Jun".to_string(),
1314             "Jul".to_string(),
1315             "Aug".to_string(),
1316             "Sep".to_string(),
1317             "Oct".to_string(),
1318             "Nov".to_string(),
1319             "Dec".to_string()
1320         ];
1321         for day in months.iter() {
1322             assert!(test(day.as_slice(), "%b"));
1323         }
1324
1325         assert!(test("19", "%C"));
1326         assert!(test("Fri Feb 13 23:31:30 2009", "%c"));
1327         assert!(test("02/13/09", "%D"));
1328         assert!(test("03", "%d"));
1329         assert!(test("13", "%d"));
1330         assert!(test(" 3", "%e"));
1331         assert!(test("13", "%e"));
1332         assert!(test("2009-02-13", "%F"));
1333         assert!(test("03", "%H"));
1334         assert!(test("13", "%H"));
1335         assert!(test("03", "%I")); // FIXME (#2350): flesh out
1336         assert!(test("11", "%I")); // FIXME (#2350): flesh out
1337         assert!(test("044", "%j"));
1338         assert!(test(" 3", "%k"));
1339         assert!(test("13", "%k"));
1340         assert!(test(" 1", "%l"));
1341         assert!(test("11", "%l"));
1342         assert!(test("03", "%M"));
1343         assert!(test("13", "%M"));
1344         assert!(test("\n", "%n"));
1345         assert!(test("am", "%P"));
1346         assert!(test("pm", "%P"));
1347         assert!(test("AM", "%p"));
1348         assert!(test("PM", "%p"));
1349         assert!(test("23:31", "%R"));
1350         assert!(test("11:31:30 AM", "%r"));
1351         assert!(test("11:31:30 PM", "%r"));
1352         assert!(test("03", "%S"));
1353         assert!(test("13", "%S"));
1354         assert!(test("15:31:30", "%T"));
1355         assert!(test("\t", "%t"));
1356         assert!(test("1", "%u"));
1357         assert!(test("7", "%u"));
1358         assert!(test("13-Feb-2009", "%v"));
1359         assert!(test("0", "%w"));
1360         assert!(test("6", "%w"));
1361         assert!(test("2009", "%Y"));
1362         assert!(test("09", "%y"));
1363         assert!(strptime("-0000", "%z").unwrap().tm_gmtoff ==
1364             0);
1365         assert!(strptime("-0800", "%z").unwrap().tm_gmtoff ==
1366             0);
1367         assert!(test("%", "%%"));
1368
1369         // Test for #7256
1370         assert_eq!(strptime("360", "%Y-%m-%d"), Err("Invalid year".to_string()))
1371     }
1372
1373     fn test_ctime() {
1374         set_time_zone();
1375
1376         let time = Timespec::new(1234567890, 54321);
1377         let utc   = at_utc(time);
1378         let local = at(time);
1379
1380         debug!("test_ctime: {:?} {:?}", utc.ctime(), local.ctime());
1381
1382         assert_eq!(utc.ctime(), "Fri Feb 13 23:31:30 2009".to_string());
1383         assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1384     }
1385
1386     fn test_strftime() {
1387         set_time_zone();
1388
1389         let time = Timespec::new(1234567890, 54321);
1390         let utc = at_utc(time);
1391         let local = at(time);
1392
1393         assert_eq!(local.strftime(""), "".to_string());
1394         assert_eq!(local.strftime("%A"), "Friday".to_string());
1395         assert_eq!(local.strftime("%a"), "Fri".to_string());
1396         assert_eq!(local.strftime("%B"), "February".to_string());
1397         assert_eq!(local.strftime("%b"), "Feb".to_string());
1398         assert_eq!(local.strftime("%C"), "20".to_string());
1399         assert_eq!(local.strftime("%c"), "Fri Feb 13 15:31:30 2009".to_string());
1400         assert_eq!(local.strftime("%D"), "02/13/09".to_string());
1401         assert_eq!(local.strftime("%d"), "13".to_string());
1402         assert_eq!(local.strftime("%e"), "13".to_string());
1403         assert_eq!(local.strftime("%f"), "000054321".to_string());
1404         assert_eq!(local.strftime("%F"), "2009-02-13".to_string());
1405         assert_eq!(local.strftime("%G"), "2009".to_string());
1406         assert_eq!(local.strftime("%g"), "09".to_string());
1407         assert_eq!(local.strftime("%H"), "15".to_string());
1408         assert_eq!(local.strftime("%I"), "03".to_string());
1409         assert_eq!(local.strftime("%j"), "044".to_string());
1410         assert_eq!(local.strftime("%k"), "15".to_string());
1411         assert_eq!(local.strftime("%l"), " 3".to_string());
1412         assert_eq!(local.strftime("%M"), "31".to_string());
1413         assert_eq!(local.strftime("%m"), "02".to_string());
1414         assert_eq!(local.strftime("%n"), "\n".to_string());
1415         assert_eq!(local.strftime("%P"), "pm".to_string());
1416         assert_eq!(local.strftime("%p"), "PM".to_string());
1417         assert_eq!(local.strftime("%R"), "15:31".to_string());
1418         assert_eq!(local.strftime("%r"), "03:31:30 PM".to_string());
1419         assert_eq!(local.strftime("%S"), "30".to_string());
1420         assert_eq!(local.strftime("%s"), "1234567890".to_string());
1421         assert_eq!(local.strftime("%T"), "15:31:30".to_string());
1422         assert_eq!(local.strftime("%t"), "\t".to_string());
1423         assert_eq!(local.strftime("%U"), "06".to_string());
1424         assert_eq!(local.strftime("%u"), "5".to_string());
1425         assert_eq!(local.strftime("%V"), "07".to_string());
1426         assert_eq!(local.strftime("%v"), "13-Feb-2009".to_string());
1427         assert_eq!(local.strftime("%W"), "06".to_string());
1428         assert_eq!(local.strftime("%w"), "5".to_string());
1429         assert_eq!(local.strftime("%X"), "15:31:30".to_string()); // FIXME (#2350): support locale
1430         assert_eq!(local.strftime("%x"), "02/13/09".to_string()); // FIXME (#2350): support locale
1431         assert_eq!(local.strftime("%Y"), "2009".to_string());
1432         assert_eq!(local.strftime("%y"), "09".to_string());
1433         assert_eq!(local.strftime("%+"), "2009-02-13T15:31:30-08:00".to_string());
1434         assert_eq!(local.strftime("%z"), "-0800".to_string());
1435         assert_eq!(local.strftime("%%"), "%".to_string());
1436
1437         assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1438         assert_eq!(local.rfc822z(), "Fri, 13 Feb 2009 15:31:30 -0800".to_string());
1439         assert_eq!(local.rfc3339(), "2009-02-13T15:31:30-08:00".to_string());
1440
1441         assert_eq!(utc.ctime(), "Fri Feb 13 23:31:30 2009".to_string());
1442         assert_eq!(utc.rfc822(), "Fri, 13 Feb 2009 23:31:30 GMT".to_string());
1443         assert_eq!(utc.rfc822z(), "Fri, 13 Feb 2009 23:31:30 -0000".to_string());
1444         assert_eq!(utc.rfc3339(), "2009-02-13T23:31:30Z".to_string());
1445     }
1446
1447     fn test_timespec_eq_ord() {
1448         let a = &Timespec::new(-2, 1);
1449         let b = &Timespec::new(-1, 2);
1450         let c = &Timespec::new(1, 2);
1451         let d = &Timespec::new(2, 1);
1452         let e = &Timespec::new(2, 1);
1453
1454         assert!(d.eq(e));
1455         assert!(c.ne(e));
1456
1457         assert!(a.lt(b));
1458         assert!(b.lt(c));
1459         assert!(c.lt(d));
1460
1461         assert!(a.le(b));
1462         assert!(b.le(c));
1463         assert!(c.le(d));
1464         assert!(d.le(e));
1465         assert!(e.le(d));
1466
1467         assert!(b.ge(a));
1468         assert!(c.ge(b));
1469         assert!(d.ge(c));
1470         assert!(e.ge(d));
1471         assert!(d.ge(e));
1472
1473         assert!(b.gt(a));
1474         assert!(c.gt(b));
1475         assert!(d.gt(c));
1476     }
1477
1478     #[test]
1479     #[ignore(cfg(target_os = "android"))] // FIXME #10958
1480     fn run_tests() {
1481         // The tests race on tzset. So instead of having many independent
1482         // tests, we will just call the functions now.
1483         test_get_time();
1484         test_precise_time();
1485         test_at_utc();
1486         test_at();
1487         test_to_timespec();
1488         test_conversions();
1489         test_strptime();
1490         test_ctime();
1491         test_strftime();
1492         test_timespec_eq_ord();
1493     }
1494
1495     #[bench]
1496     fn bench_precise_time_ns(b: &mut Bencher) {
1497         b.iter(|| precise_time_ns())
1498     }
1499 }