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