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