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