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