]> git.lizzy.rs Git - rust.git/blob - src/libextra/time.rs
Merge remote-tracking branch 'remotes/origin/master' into str-remove-null
[rust.git] / src / libextra / time.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 #[allow(missing_doc)];
12
13
14 use std::int;
15 use std::io;
16 use std::num;
17 use std::str;
18
19 static NSEC_PER_SEC: i32 = 1_000_000_000_i32;
20
21 pub mod rustrt {
22     use super::Tm;
23
24     #[abi = "cdecl"]
25     extern {
26         pub fn get_time(sec: &mut i64, nsec: &mut i32);
27         pub fn precise_time_ns(ns: &mut u64);
28         pub fn rust_tzset();
29         pub fn rust_gmtime(sec: i64, nsec: i32, result: &mut Tm);
30         pub fn rust_localtime(sec: i64, nsec: i32, result: &mut Tm);
31         pub fn rust_timegm(tm: &Tm) -> i64;
32         pub fn rust_mktime(tm: &Tm) -> i64;
33     }
34 }
35
36 /// A record specifying a time value in seconds and nanoseconds.
37 #[deriving(Eq, Encodable, Decodable)]
38 pub struct Timespec { sec: i64, nsec: i32 }
39
40 /*
41  * Timespec assumes that pre-epoch Timespecs have negative sec and positive
42  * nsec fields. Darwin's and Linux's struct timespec functions handle pre-
43  * epoch timestamps using a "two steps back, one step forward" representation,
44  * though the man pages do not actually document this. For example, the time
45  * -1.2 seconds before the epoch is represented by `Timespec { sec: -2_i64,
46  * nsec: 800_000_000_i32 }`.
47  */
48 impl Timespec {
49     pub fn new(sec: i64, nsec: i32) -> Timespec {
50         assert!(nsec >= 0 && nsec < NSEC_PER_SEC);
51         Timespec { sec: sec, nsec: nsec }
52     }
53 }
54
55 impl Ord for Timespec {
56     fn lt(&self, other: &Timespec) -> bool {
57         self.sec < other.sec ||
58             (self.sec == other.sec && self.nsec < other.nsec)
59     }
60     fn le(&self, other: &Timespec) -> bool { !other.lt(self) }
61     fn ge(&self, other: &Timespec) -> bool { !self.lt(other) }
62     fn gt(&self, other: &Timespec) -> bool { !self.le(other) }
63 }
64
65 /**
66  * Returns the current time as a `timespec` containing the seconds and
67  * nanoseconds since 1970-01-01T00:00:00Z.
68  */
69 pub fn get_time() -> Timespec {
70     unsafe {
71         let mut sec = 0i64;
72         let mut nsec = 0i32;
73         rustrt::get_time(&mut sec, &mut nsec);
74         return Timespec::new(sec, nsec);
75     }
76 }
77
78
79 /**
80  * Returns the current value of a high-resolution performance counter
81  * in nanoseconds since an unspecified epoch.
82  */
83 pub fn precise_time_ns() -> u64 {
84     unsafe {
85         let mut ns = 0u64;
86         rustrt::precise_time_ns(&mut ns);
87         ns
88     }
89 }
90
91
92 /**
93  * Returns the current value of a high-resolution performance counter
94  * in seconds since an unspecified epoch.
95  */
96 pub fn precise_time_s() -> float {
97     return (precise_time_ns() as float) / 1000000000.;
98 }
99
100 pub fn tzset() {
101     unsafe {
102         rustrt::rust_tzset();
103     }
104 }
105
106 #[deriving(Eq, Encodable, Decodable)]
107 pub struct Tm {
108     tm_sec: i32, // seconds after the minute ~[0-60]
109     tm_min: i32, // minutes after the hour ~[0-59]
110     tm_hour: i32, // hours after midnight ~[0-23]
111     tm_mday: i32, // days of the month ~[1-31]
112     tm_mon: i32, // months since January ~[0-11]
113     tm_year: i32, // years since 1900
114     tm_wday: i32, // days since Sunday ~[0-6]
115     tm_yday: i32, // days since January 1 ~[0-365]
116     tm_isdst: i32, // Daylight Savings Time flag
117     tm_gmtoff: i32, // offset from UTC in seconds
118     tm_zone: ~str, // timezone abbreviation
119     tm_nsec: i32, // nanoseconds
120 }
121
122 pub fn empty_tm() -> Tm {
123     Tm {
124         tm_sec: 0_i32,
125         tm_min: 0_i32,
126         tm_hour: 0_i32,
127         tm_mday: 0_i32,
128         tm_mon: 0_i32,
129         tm_year: 0_i32,
130         tm_wday: 0_i32,
131         tm_yday: 0_i32,
132         tm_isdst: 0_i32,
133         tm_gmtoff: 0_i32,
134         tm_zone: ~"",
135         tm_nsec: 0_i32,
136     }
137 }
138
139 /// Returns the specified time in UTC
140 pub fn at_utc(clock: Timespec) -> Tm {
141     unsafe {
142         let Timespec { sec, nsec } = clock;
143         let mut tm = empty_tm();
144         rustrt::rust_gmtime(sec, nsec, &mut tm);
145         tm
146     }
147 }
148
149 /// Returns the current time in UTC
150 pub fn now_utc() -> Tm {
151     at_utc(get_time())
152 }
153
154 /// Returns the specified time in the local timezone
155 pub fn at(clock: Timespec) -> Tm {
156     unsafe {
157         let Timespec { sec, nsec } = clock;
158         let mut tm = empty_tm();
159         rustrt::rust_localtime(sec, nsec, &mut tm);
160         tm
161     }
162 }
163
164 /// Returns the current time in the local timezone
165 pub fn now() -> Tm {
166     at(get_time())
167 }
168
169 /// Parses the time from the string according to the format string.
170 pub fn strptime(s: &str, format: &str) -> Result<Tm, ~str> {
171     do_strptime(s, format)
172 }
173
174 /// Formats the time according to the format string.
175 pub fn strftime(format: &str, tm: &Tm) -> ~str {
176     do_strftime(format, tm)
177 }
178
179 impl Tm {
180     /// Convert time to the seconds from January 1, 1970
181     pub fn to_timespec(&self) -> Timespec {
182         unsafe {
183             let sec = match self.tm_gmtoff {
184                 0_i32 => rustrt::rust_timegm(self),
185                 _     => rustrt::rust_mktime(self)
186             };
187
188             Timespec::new(sec, self.tm_nsec)
189         }
190     }
191
192     /// Convert time to the local timezone
193     pub fn to_local(&self) -> Tm {
194         at(self.to_timespec())
195     }
196
197     /// Convert time to the UTC
198     pub fn to_utc(&self) -> Tm {
199         at_utc(self.to_timespec())
200     }
201
202     /**
203      * Return a string of the current time in the form
204      * "Thu Jan  1 00:00:00 1970".
205      */
206     pub fn ctime(&self) -> ~str { self.strftime("%c") }
207
208     /// Formats the time according to the format string.
209     pub fn strftime(&self, format: &str) -> ~str {
210         strftime(format, self)
211     }
212
213     /**
214      * Returns a time string formatted according to RFC 822.
215      *
216      * local: "Thu, 22 Mar 2012 07:53:18 PST"
217      * utc:   "Thu, 22 Mar 2012 14:53:18 UTC"
218      */
219     pub fn rfc822(&self) -> ~str {
220         if self.tm_gmtoff == 0_i32 {
221             self.strftime("%a, %d %b %Y %T GMT")
222         } else {
223             self.strftime("%a, %d %b %Y %T %Z")
224         }
225     }
226
227     /**
228      * Returns a time string formatted according to RFC 822 with Zulu time.
229      *
230      * local: "Thu, 22 Mar 2012 07:53:18 -0700"
231      * utc:   "Thu, 22 Mar 2012 14:53:18 -0000"
232      */
233     pub fn rfc822z(&self) -> ~str {
234         self.strftime("%a, %d %b %Y %T %z")
235     }
236
237     /**
238      * Returns a time string formatted according to ISO 8601.
239      *
240      * local: "2012-02-22T07:53:18-07:00"
241      * utc:   "2012-02-22T14:53:18Z"
242      */
243     pub fn rfc3339(&self) -> ~str {
244         if self.tm_gmtoff == 0_i32 {
245             self.strftime("%Y-%m-%dT%H:%M:%SZ")
246         } else {
247             let s = self.strftime("%Y-%m-%dT%H:%M:%S");
248             let sign = if self.tm_gmtoff > 0_i32 { '+' } else { '-' };
249             let mut m = num::abs(self.tm_gmtoff) / 60_i32;
250             let h = m / 60_i32;
251             m -= h * 60_i32;
252             s + fmt!("%c%02d:%02d", sign, h as int, m as int)
253         }
254     }
255 }
256
257 priv fn do_strptime(s: &str, format: &str) -> Result<Tm, ~str> {
258     fn match_str(s: &str, pos: uint, needle: &str) -> bool {
259         let mut i = pos;
260         for ch in needle.byte_iter() {
261             if s[i] != ch {
262                 return false;
263             }
264             i += 1u;
265         }
266         return true;
267     }
268
269     fn match_strs(ss: &str, pos: uint, strs: &[(~str, i32)])
270       -> Option<(i32, uint)> {
271         let mut i = 0u;
272         let len = strs.len();
273         while i < len {
274             match strs[i] { // can't use let due to let-pattern bugs
275                 (ref needle, value) => {
276                     if match_str(ss, pos, *needle) {
277                         return Some((value, pos + needle.len()));
278                     }
279                 }
280             }
281             i += 1u;
282         }
283
284         None
285     }
286
287     fn match_digits(ss: &str, pos: uint, digits: uint, ws: bool)
288       -> Option<(i32, uint)> {
289         let mut pos = pos;
290         let len = ss.len();
291         let mut value = 0_i32;
292
293         let mut i = 0u;
294         while i < digits {
295             if pos >= len {
296                 return None;
297             }
298             let range = ss.char_range_at(pos);
299             pos = range.next;
300
301             match range.ch {
302               '0' .. '9' => {
303                 value = value * 10_i32 + (range.ch as i32 - '0' as i32);
304               }
305               ' ' if ws => (),
306               _ => return None
307             }
308             i += 1u;
309         }
310
311         Some((value, pos))
312     }
313
314     fn match_digits_in_range(ss: &str, pos: uint, digits: uint, ws: bool,
315                              min: i32, max: i32) -> Option<(i32, uint)> {
316         match match_digits(ss, pos, digits, ws) {
317           Some((val, pos)) if val >= min && val <= max => {
318             Some((val, pos))
319           }
320           _ => None
321         }
322     }
323
324     fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, ~str> {
325         let range = s.char_range_at(pos);
326
327         if c == range.ch {
328             Ok(range.next)
329         } else {
330             Err(fmt!("Expected %?, found %?",
331                 str::from_char(c),
332                 str::from_char(range.ch)))
333         }
334     }
335
336     fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
337       -> Result<uint, ~str> {
338         match ch {
339           'A' => match match_strs(s, pos, [
340               (~"Sunday", 0_i32),
341               (~"Monday", 1_i32),
342               (~"Tuesday", 2_i32),
343               (~"Wednesday", 3_i32),
344               (~"Thursday", 4_i32),
345               (~"Friday", 5_i32),
346               (~"Saturday", 6_i32)
347           ]) {
348             Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
349             None => Err(~"Invalid day")
350           },
351           'a' => match match_strs(s, pos, [
352               (~"Sun", 0_i32),
353               (~"Mon", 1_i32),
354               (~"Tue", 2_i32),
355               (~"Wed", 3_i32),
356               (~"Thu", 4_i32),
357               (~"Fri", 5_i32),
358               (~"Sat", 6_i32)
359           ]) {
360             Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
361             None => Err(~"Invalid day")
362           },
363           'B' => match match_strs(s, pos, [
364               (~"January", 0_i32),
365               (~"February", 1_i32),
366               (~"March", 2_i32),
367               (~"April", 3_i32),
368               (~"May", 4_i32),
369               (~"June", 5_i32),
370               (~"July", 6_i32),
371               (~"August", 7_i32),
372               (~"September", 8_i32),
373               (~"October", 9_i32),
374               (~"November", 10_i32),
375               (~"December", 11_i32)
376           ]) {
377             Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
378             None => Err(~"Invalid month")
379           },
380           'b' | 'h' => match match_strs(s, pos, [
381               (~"Jan", 0_i32),
382               (~"Feb", 1_i32),
383               (~"Mar", 2_i32),
384               (~"Apr", 3_i32),
385               (~"May", 4_i32),
386               (~"Jun", 5_i32),
387               (~"Jul", 6_i32),
388               (~"Aug", 7_i32),
389               (~"Sep", 8_i32),
390               (~"Oct", 9_i32),
391               (~"Nov", 10_i32),
392               (~"Dec", 11_i32)
393           ]) {
394             Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
395             None => Err(~"Invalid month")
396           },
397           'C' => match match_digits_in_range(s, pos, 2u, false, 0_i32,
398                                              99_i32) {
399             Some(item) => {
400                 let (v, pos) = item;
401                   tm.tm_year += (v * 100_i32) - 1900_i32;
402                   Ok(pos)
403               }
404             None => Err(~"Invalid year")
405           },
406           'c' => {
407             parse_type(s, pos, 'a', &mut *tm)
408                 .chain(|pos| parse_char(s, pos, ' '))
409                 .chain(|pos| parse_type(s, pos, 'b', &mut *tm))
410                 .chain(|pos| parse_char(s, pos, ' '))
411                 .chain(|pos| parse_type(s, pos, 'e', &mut *tm))
412                 .chain(|pos| parse_char(s, pos, ' '))
413                 .chain(|pos| parse_type(s, pos, 'T', &mut *tm))
414                 .chain(|pos| parse_char(s, pos, ' '))
415                 .chain(|pos| parse_type(s, pos, 'Y', &mut *tm))
416           }
417           'D' | 'x' => {
418             parse_type(s, pos, 'm', &mut *tm)
419                 .chain(|pos| parse_char(s, pos, '/'))
420                 .chain(|pos| parse_type(s, pos, 'd', &mut *tm))
421                 .chain(|pos| parse_char(s, pos, '/'))
422                 .chain(|pos| parse_type(s, pos, 'y', &mut *tm))
423           }
424           'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
425                                              31_i32) {
426             Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
427             None => Err(~"Invalid day of the month")
428           },
429           'e' => match match_digits_in_range(s, pos, 2u, true, 1_i32,
430                                              31_i32) {
431             Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
432             None => Err(~"Invalid day of the month")
433           },
434           'F' => {
435             parse_type(s, pos, 'Y', &mut *tm)
436                 .chain(|pos| parse_char(s, pos, '-'))
437                 .chain(|pos| parse_type(s, pos, 'm', &mut *tm))
438                 .chain(|pos| parse_char(s, pos, '-'))
439                 .chain(|pos| parse_type(s, pos, 'd', &mut *tm))
440           }
441           'H' => {
442             match match_digits_in_range(s, pos, 2u, false, 0_i32, 23_i32) {
443               Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
444               None => Err(~"Invalid hour")
445             }
446           }
447           'I' => {
448             match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
449               Some(item) => {
450                   let (v, pos) = item;
451                   tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
452                   Ok(pos)
453               }
454               None => Err(~"Invalid hour")
455             }
456           }
457           'j' => {
458             match match_digits_in_range(s, pos, 3u, false, 1_i32, 366_i32) {
459               Some(item) => {
460                 let (v, pos) = item;
461                 tm.tm_yday = v - 1_i32;
462                 Ok(pos)
463               }
464               None => Err(~"Invalid day of year")
465             }
466           }
467           'k' => {
468             match match_digits_in_range(s, pos, 2u, true, 0_i32, 23_i32) {
469               Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
470               None => Err(~"Invalid hour")
471             }
472           }
473           'l' => {
474             match match_digits_in_range(s, pos, 2u, true, 1_i32, 12_i32) {
475               Some(item) => {
476                   let (v, pos) = item;
477                   tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
478                   Ok(pos)
479               }
480               None => Err(~"Invalid hour")
481             }
482           }
483           'M' => {
484             match match_digits_in_range(s, pos, 2u, false, 0_i32, 59_i32) {
485               Some(item) => { let (v, pos) = item; tm.tm_min = v; Ok(pos) }
486               None => Err(~"Invalid minute")
487             }
488           }
489           'm' => {
490             match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
491               Some(item) => {
492                 let (v, pos) = item;
493                 tm.tm_mon = v - 1_i32;
494                 Ok(pos)
495               }
496               None => Err(~"Invalid month")
497             }
498           }
499           'n' => parse_char(s, pos, '\n'),
500           'P' => match match_strs(s, pos,
501                                   [(~"am", 0_i32), (~"pm", 12_i32)]) {
502
503             Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
504             None => Err(~"Invalid hour")
505           },
506           'p' => match match_strs(s, pos,
507                                   [(~"AM", 0_i32), (~"PM", 12_i32)]) {
508
509             Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
510             None => Err(~"Invalid hour")
511           },
512           'R' => {
513             parse_type(s, pos, 'H', &mut *tm)
514                 .chain(|pos| parse_char(s, pos, ':'))
515                 .chain(|pos| parse_type(s, pos, 'M', &mut *tm))
516           }
517           'r' => {
518             parse_type(s, pos, 'I', &mut *tm)
519                 .chain(|pos| parse_char(s, pos, ':'))
520                 .chain(|pos| parse_type(s, pos, 'M', &mut *tm))
521                 .chain(|pos| parse_char(s, pos, ':'))
522                 .chain(|pos| parse_type(s, pos, 'S', &mut *tm))
523                 .chain(|pos| parse_char(s, pos, ' '))
524                 .chain(|pos| parse_type(s, pos, 'p', &mut *tm))
525           }
526           'S' => {
527             match match_digits_in_range(s, pos, 2u, false, 0_i32, 60_i32) {
528               Some(item) => {
529                 let (v, pos) = item;
530                 tm.tm_sec = v;
531                 Ok(pos)
532               }
533               None => Err(~"Invalid second")
534             }
535           }
536           //'s' {}
537           'T' | 'X' => {
538             parse_type(s, pos, 'H', &mut *tm)
539                 .chain(|pos| parse_char(s, pos, ':'))
540                 .chain(|pos| parse_type(s, pos, 'M', &mut *tm))
541                 .chain(|pos| parse_char(s, pos, ':'))
542                 .chain(|pos| parse_type(s, pos, 'S', &mut *tm))
543           }
544           't' => parse_char(s, pos, '\t'),
545           'u' => {
546             match match_digits_in_range(s, pos, 1u, false, 1_i32, 7_i32) {
547               Some(item) => {
548                 let (v, pos) = item;
549                 tm.tm_wday = if v == 7 { 0 } else { v };
550                 Ok(pos)
551               }
552               None => Err(~"Invalid day of week")
553             }
554           }
555           'v' => {
556             parse_type(s, pos, 'e', &mut *tm)
557                 .chain(|pos|  parse_char(s, pos, '-'))
558                 .chain(|pos| parse_type(s, pos, 'b', &mut *tm))
559                 .chain(|pos| parse_char(s, pos, '-'))
560                 .chain(|pos| parse_type(s, pos, 'Y', &mut *tm))
561           }
562           //'W' {}
563           'w' => {
564             match match_digits_in_range(s, pos, 1u, false, 0_i32, 6_i32) {
565               Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
566               None => Err(~"Invalid day of week")
567             }
568           }
569           //'X' {}
570           //'x' {}
571           'Y' => {
572             match match_digits(s, pos, 4u, false) {
573               Some(item) => {
574                 let (v, pos) = item;
575                 tm.tm_year = v - 1900_i32;
576                 Ok(pos)
577               }
578               None => Err(~"Invalid year")
579             }
580           }
581           'y' => {
582             match match_digits_in_range(s, pos, 2u, false, 0_i32, 99_i32) {
583               Some(item) => {
584                 let (v, pos) = item;
585                 tm.tm_year = v;
586                 Ok(pos)
587               }
588               None => Err(~"Invalid year")
589             }
590           }
591           'Z' => {
592             if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") {
593                 tm.tm_gmtoff = 0_i32;
594                 tm.tm_zone = ~"UTC";
595                 Ok(pos + 3u)
596             } else {
597                 // It's odd, but to maintain compatibility with c's
598                 // strptime we ignore the timezone.
599                 let mut pos = pos;
600                 let len = s.len();
601                 while pos < len {
602                     let range = s.char_range_at(pos);
603                     pos = range.next;
604                     if range.ch == ' ' { break; }
605                 }
606
607                 Ok(pos)
608             }
609           }
610           'z' => {
611             let range = s.char_range_at(pos);
612
613             if range.ch == '+' || range.ch == '-' {
614                 match match_digits(s, range.next, 4u, false) {
615                   Some(item) => {
616                     let (v, pos) = item;
617                     if v == 0_i32 {
618                         tm.tm_gmtoff = 0_i32;
619                         tm.tm_zone = ~"UTC";
620                     }
621
622                     Ok(pos)
623                   }
624                   None => Err(~"Invalid zone offset")
625                 }
626             } else {
627                 Err(~"Invalid zone offset")
628             }
629           }
630           '%' => parse_char(s, pos, '%'),
631           ch => {
632             Err(fmt!("unknown formatting type: %?", str::from_char(ch)))
633           }
634         }
635     }
636
637     do io::with_str_reader(format) |rdr| {
638         let mut tm = Tm {
639             tm_sec: 0_i32,
640             tm_min: 0_i32,
641             tm_hour: 0_i32,
642             tm_mday: 0_i32,
643             tm_mon: 0_i32,
644             tm_year: 0_i32,
645             tm_wday: 0_i32,
646             tm_yday: 0_i32,
647             tm_isdst: 0_i32,
648             tm_gmtoff: 0_i32,
649             tm_zone: ~"",
650             tm_nsec: 0_i32,
651         };
652         let mut pos = 0u;
653         let len = s.len();
654         let mut result = Err(~"Invalid time");
655
656         while !rdr.eof() && pos < len {
657             let range = s.char_range_at(pos);
658             let ch = range.ch;
659             let next = range.next;
660
661             match rdr.read_char() {
662                 '%' => {
663                     match parse_type(s, pos, rdr.read_char(), &mut tm) {
664                         Ok(next) => pos = next,
665                         Err(e) => { result = Err(e); break; }
666                     }
667                 },
668                 c => {
669                     if c != ch { break }
670                     pos = next;
671                 }
672             }
673         }
674
675         if pos == len && rdr.eof() {
676             Ok(Tm {
677                 tm_sec: tm.tm_sec,
678                 tm_min: tm.tm_min,
679                 tm_hour: tm.tm_hour,
680                 tm_mday: tm.tm_mday,
681                 tm_mon: tm.tm_mon,
682                 tm_year: tm.tm_year,
683                 tm_wday: tm.tm_wday,
684                 tm_yday: tm.tm_yday,
685                 tm_isdst: tm.tm_isdst,
686                 tm_gmtoff: tm.tm_gmtoff,
687                 tm_zone: tm.tm_zone.clone(),
688                 tm_nsec: tm.tm_nsec,
689             })
690         } else { result }
691     }
692 }
693
694 priv fn do_strftime(format: &str, tm: &Tm) -> ~str {
695     fn parse_type(ch: char, tm: &Tm) -> ~str {
696         //FIXME (#2350): Implement missing types.
697       let die = || fmt!("strftime: can't understand this format %c ", ch);
698         match ch {
699           'A' => match tm.tm_wday as int {
700             0 => ~"Sunday",
701             1 => ~"Monday",
702             2 => ~"Tuesday",
703             3 => ~"Wednesday",
704             4 => ~"Thursday",
705             5 => ~"Friday",
706             6 => ~"Saturday",
707             _ => die()
708           },
709          'a' => match tm.tm_wday as int {
710             0 => ~"Sun",
711             1 => ~"Mon",
712             2 => ~"Tue",
713             3 => ~"Wed",
714             4 => ~"Thu",
715             5 => ~"Fri",
716             6 => ~"Sat",
717             _ => die()
718           },
719           'B' => match tm.tm_mon as int {
720             0 => ~"January",
721             1 => ~"February",
722             2 => ~"March",
723             3 => ~"April",
724             4 => ~"May",
725             5 => ~"June",
726             6 => ~"July",
727             7 => ~"August",
728             8 => ~"September",
729             9 => ~"October",
730             10 => ~"November",
731             11 => ~"December",
732             _ => die()
733           },
734           'b' | 'h' => match tm.tm_mon as int {
735             0 => ~"Jan",
736             1 => ~"Feb",
737             2 => ~"Mar",
738             3 => ~"Apr",
739             4 => ~"May",
740             5 => ~"Jun",
741             6 => ~"Jul",
742             7 => ~"Aug",
743             8 => ~"Sep",
744             9 => ~"Oct",
745             10 => ~"Nov",
746             11 => ~"Dec",
747             _  => die()
748           },
749           'C' => fmt!("%02d", (tm.tm_year as int + 1900) / 100),
750           'c' => {
751             fmt!("%s %s %s %s %s",
752                 parse_type('a', tm),
753                 parse_type('b', tm),
754                 parse_type('e', tm),
755                 parse_type('T', tm),
756                 parse_type('Y', tm))
757           }
758           'D' | 'x' => {
759             fmt!("%s/%s/%s",
760                 parse_type('m', tm),
761                 parse_type('d', tm),
762                 parse_type('y', tm))
763           }
764           'd' => fmt!("%02d", tm.tm_mday as int),
765           'e' => fmt!("%2d", tm.tm_mday as int),
766           'F' => {
767             fmt!("%s-%s-%s",
768                 parse_type('Y', tm),
769                 parse_type('m', tm),
770                 parse_type('d', tm))
771           }
772           //'G' {}
773           //'g' {}
774           'H' => fmt!("%02d", tm.tm_hour as int),
775           'I' => {
776             let mut h = tm.tm_hour as int;
777             if h == 0 { h = 12 }
778             if h > 12 { h -= 12 }
779             fmt!("%02d", h)
780           }
781           'j' => fmt!("%03d", tm.tm_yday as int + 1),
782           'k' => fmt!("%2d", tm.tm_hour as int),
783           'l' => {
784             let mut h = tm.tm_hour as int;
785             if h == 0 { h = 12 }
786             if h > 12 { h -= 12 }
787             fmt!("%2d", h)
788           }
789           'M' => fmt!("%02d", tm.tm_min as int),
790           'm' => fmt!("%02d", tm.tm_mon as int + 1),
791           'n' => ~"\n",
792           'P' => if (tm.tm_hour as int) < 12 { ~"am" } else { ~"pm" },
793           'p' => if (tm.tm_hour as int) < 12 { ~"AM" } else { ~"PM" },
794           'R' => {
795             fmt!("%s:%s",
796                 parse_type('H', tm),
797                 parse_type('M', tm))
798           }
799           'r' => {
800             fmt!("%s:%s:%s %s",
801                 parse_type('I', tm),
802                 parse_type('M', tm),
803                 parse_type('S', tm),
804                 parse_type('p', tm))
805           }
806           'S' => fmt!("%02d", tm.tm_sec as int),
807           's' => fmt!("%d", tm.to_timespec().sec as int),
808           'T' | 'X' => {
809             fmt!("%s:%s:%s",
810                 parse_type('H', tm),
811                 parse_type('M', tm),
812                 parse_type('S', tm))
813           }
814           't' => ~"\t",
815           //'U' {}
816           'u' => {
817             let i = tm.tm_wday as int;
818             int::to_str(if i == 0 { 7 } else { i })
819           }
820           //'V' {}
821           'v' => {
822             fmt!("%s-%s-%s",
823                 parse_type('e', tm),
824                 parse_type('b', tm),
825                 parse_type('Y', tm))
826           }
827           //'W' {}
828           'w' => int::to_str(tm.tm_wday as int),
829           //'X' {}
830           //'x' {}
831           'Y' => int::to_str(tm.tm_year as int + 1900),
832           'y' => fmt!("%02d", (tm.tm_year as int + 1900) % 100),
833           'Z' => tm.tm_zone.clone(),
834           'z' => {
835             let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
836             let mut m = num::abs(tm.tm_gmtoff) / 60_i32;
837             let h = m / 60_i32;
838             m -= h * 60_i32;
839             fmt!("%c%02d%02d", sign, h as int, m as int)
840           }
841           //'+' {}
842           '%' => ~"%",
843           _   => die()
844         }
845     }
846
847     let mut buf = ~"";
848
849     do io::with_str_reader(format) |rdr| {
850         while !rdr.eof() {
851             match rdr.read_char() {
852                 '%' => buf.push_str(parse_type(rdr.read_char(), tm)),
853                 ch => buf.push_char(ch)
854             }
855         }
856     }
857
858     buf
859 }
860
861 #[cfg(test)]
862 mod tests {
863     use super::*;
864
865     use std::float;
866     use std::os;
867     use std::result::{Err, Ok};
868
869     fn test_get_time() {
870         static SOME_RECENT_DATE: i64 = 1325376000i64; // 2012-01-01T00:00:00Z
871         static SOME_FUTURE_DATE: i64 = 1577836800i64; // 2020-01-01T00:00:00Z
872
873         let tv1 = get_time();
874         debug!("tv1=%? sec + %? nsec", tv1.sec as uint, tv1.nsec as uint);
875
876         assert!(tv1.sec > SOME_RECENT_DATE);
877         assert!(tv1.nsec < 1000000000i32);
878
879         let tv2 = get_time();
880         debug!("tv2=%? sec + %? nsec", tv2.sec as uint, tv2.nsec as uint);
881
882         assert!(tv2.sec >= tv1.sec);
883         assert!(tv2.sec < SOME_FUTURE_DATE);
884         assert!(tv2.nsec < 1000000000i32);
885         if tv2.sec == tv1.sec {
886             assert!(tv2.nsec >= tv1.nsec);
887         }
888     }
889
890     fn test_precise_time() {
891         let s0 = precise_time_s();
892         let ns1 = precise_time_ns();
893
894         debug!("s0=%s sec", float::to_str_digits(s0, 9u));
895         assert!(s0 > 0.);
896         let ns0 = (s0 * 1000000000.) as u64;
897         debug!("ns0=%? ns", ns0);
898
899         debug!("ns1=%? ns", ns0);
900         assert!(ns1 >= ns0);
901
902         let ns2 = precise_time_ns();
903         debug!("ns2=%? ns", ns0);
904         assert!(ns2 >= ns1);
905     }
906
907     fn test_at_utc() {
908         os::setenv("TZ", "America/Los_Angeles");
909         tzset();
910
911         let time = Timespec::new(1234567890, 54321);
912         let utc = at_utc(time);
913
914         assert!(utc.tm_sec == 30_i32);
915         assert!(utc.tm_min == 31_i32);
916         assert!(utc.tm_hour == 23_i32);
917         assert!(utc.tm_mday == 13_i32);
918         assert!(utc.tm_mon == 1_i32);
919         assert!(utc.tm_year == 109_i32);
920         assert!(utc.tm_wday == 5_i32);
921         assert!(utc.tm_yday == 43_i32);
922         assert!(utc.tm_isdst == 0_i32);
923         assert!(utc.tm_gmtoff == 0_i32);
924         assert!(utc.tm_zone == ~"UTC");
925         assert!(utc.tm_nsec == 54321_i32);
926     }
927
928     fn test_at() {
929         os::setenv("TZ", "America/Los_Angeles");
930         tzset();
931
932         let time = Timespec::new(1234567890, 54321);
933         let local = at(time);
934
935         error!("time_at: %?", local);
936
937         assert!(local.tm_sec == 30_i32);
938         assert!(local.tm_min == 31_i32);
939         assert!(local.tm_hour == 15_i32);
940         assert!(local.tm_mday == 13_i32);
941         assert!(local.tm_mon == 1_i32);
942         assert!(local.tm_year == 109_i32);
943         assert!(local.tm_wday == 5_i32);
944         assert!(local.tm_yday == 43_i32);
945         assert!(local.tm_isdst == 0_i32);
946         assert!(local.tm_gmtoff == -28800_i32);
947
948         // FIXME (#2350): We should probably standardize on the timezone
949         // abbreviation.
950         let zone = &local.tm_zone;
951         assert!(*zone == ~"PST" || *zone == ~"Pacific Standard Time");
952
953         assert!(local.tm_nsec == 54321_i32);
954     }
955
956     fn test_to_timespec() {
957         os::setenv("TZ", "America/Los_Angeles");
958         tzset();
959
960         let time = Timespec::new(1234567890, 54321);
961         let utc = at_utc(time);
962
963         assert_eq!(utc.to_timespec(), time);
964         assert_eq!(utc.to_local().to_timespec(), time);
965     }
966
967     fn test_conversions() {
968         os::setenv("TZ", "America/Los_Angeles");
969         tzset();
970
971         let time = Timespec::new(1234567890, 54321);
972         let utc = at_utc(time);
973         let local = at(time);
974
975         assert!(local.to_local() == local);
976         assert!(local.to_utc() == utc);
977         assert!(local.to_utc().to_local() == local);
978         assert!(utc.to_utc() == utc);
979         assert!(utc.to_local() == local);
980         assert!(utc.to_local().to_utc() == utc);
981     }
982
983     fn test_strptime() {
984         os::setenv("TZ", "America/Los_Angeles");
985         tzset();
986
987         match strptime("", "") {
988           Ok(ref tm) => {
989             assert!(tm.tm_sec == 0_i32);
990             assert!(tm.tm_min == 0_i32);
991             assert!(tm.tm_hour == 0_i32);
992             assert!(tm.tm_mday == 0_i32);
993             assert!(tm.tm_mon == 0_i32);
994             assert!(tm.tm_year == 0_i32);
995             assert!(tm.tm_wday == 0_i32);
996             assert!(tm.tm_isdst == 0_i32);
997             assert!(tm.tm_gmtoff == 0_i32);
998             assert!(tm.tm_zone == ~"");
999             assert!(tm.tm_nsec == 0_i32);
1000           }
1001           Err(_) => ()
1002         }
1003
1004         let format = "%a %b %e %T %Y";
1005         assert_eq!(strptime("", format), Err(~"Invalid time"));
1006         assert!(strptime("Fri Feb 13 15:31:30", format)
1007             == Err(~"Invalid time"));
1008
1009         match strptime("Fri Feb 13 15:31:30 2009", format) {
1010           Err(e) => fail!(e),
1011           Ok(ref tm) => {
1012             assert!(tm.tm_sec == 30_i32);
1013             assert!(tm.tm_min == 31_i32);
1014             assert!(tm.tm_hour == 15_i32);
1015             assert!(tm.tm_mday == 13_i32);
1016             assert!(tm.tm_mon == 1_i32);
1017             assert!(tm.tm_year == 109_i32);
1018             assert!(tm.tm_wday == 5_i32);
1019             assert!(tm.tm_yday == 0_i32);
1020             assert!(tm.tm_isdst == 0_i32);
1021             assert!(tm.tm_gmtoff == 0_i32);
1022             assert!(tm.tm_zone == ~"");
1023             assert!(tm.tm_nsec == 0_i32);
1024           }
1025         }
1026
1027         fn test(s: &str, format: &str) -> bool {
1028             match strptime(s, format) {
1029               Ok(ref tm) => tm.strftime(format) == s.to_owned(),
1030               Err(e) => fail!(e)
1031             }
1032         }
1033
1034         let days = [
1035             ~"Sunday",
1036             ~"Monday",
1037             ~"Tuesday",
1038             ~"Wednesday",
1039             ~"Thursday",
1040             ~"Friday",
1041             ~"Saturday"
1042         ];
1043         for day in days.iter() {
1044             assert!(test(*day, "%A"));
1045         }
1046
1047         let days = [
1048             ~"Sun",
1049             ~"Mon",
1050             ~"Tue",
1051             ~"Wed",
1052             ~"Thu",
1053             ~"Fri",
1054             ~"Sat"
1055         ];
1056         for day in days.iter() {
1057             assert!(test(*day, "%a"));
1058         }
1059
1060         let months = [
1061             ~"January",
1062             ~"February",
1063             ~"March",
1064             ~"April",
1065             ~"May",
1066             ~"June",
1067             ~"July",
1068             ~"August",
1069             ~"September",
1070             ~"October",
1071             ~"November",
1072             ~"December"
1073         ];
1074         for day in months.iter() {
1075             assert!(test(*day, "%B"));
1076         }
1077
1078         let months = [
1079             ~"Jan",
1080             ~"Feb",
1081             ~"Mar",
1082             ~"Apr",
1083             ~"May",
1084             ~"Jun",
1085             ~"Jul",
1086             ~"Aug",
1087             ~"Sep",
1088             ~"Oct",
1089             ~"Nov",
1090             ~"Dec"
1091         ];
1092         for day in months.iter() {
1093             assert!(test(*day, "%b"));
1094         }
1095
1096         assert!(test("19", "%C"));
1097         assert!(test("Fri Feb 13 23:31:30 2009", "%c"));
1098         assert!(test("02/13/09", "%D"));
1099         assert!(test("03", "%d"));
1100         assert!(test("13", "%d"));
1101         assert!(test(" 3", "%e"));
1102         assert!(test("13", "%e"));
1103         assert!(test("2009-02-13", "%F"));
1104         assert!(test("03", "%H"));
1105         assert!(test("13", "%H"));
1106         assert!(test("03", "%I")); // FIXME (#2350): flesh out
1107         assert!(test("11", "%I")); // FIXME (#2350): flesh out
1108         assert!(test("044", "%j"));
1109         assert!(test(" 3", "%k"));
1110         assert!(test("13", "%k"));
1111         assert!(test(" 1", "%l"));
1112         assert!(test("11", "%l"));
1113         assert!(test("03", "%M"));
1114         assert!(test("13", "%M"));
1115         assert!(test("\n", "%n"));
1116         assert!(test("am", "%P"));
1117         assert!(test("pm", "%P"));
1118         assert!(test("AM", "%p"));
1119         assert!(test("PM", "%p"));
1120         assert!(test("23:31", "%R"));
1121         assert!(test("11:31:30 AM", "%r"));
1122         assert!(test("11:31:30 PM", "%r"));
1123         assert!(test("03", "%S"));
1124         assert!(test("13", "%S"));
1125         assert!(test("15:31:30", "%T"));
1126         assert!(test("\t", "%t"));
1127         assert!(test("1", "%u"));
1128         assert!(test("7", "%u"));
1129         assert!(test("13-Feb-2009", "%v"));
1130         assert!(test("0", "%w"));
1131         assert!(test("6", "%w"));
1132         assert!(test("2009", "%Y"));
1133         assert!(test("09", "%y"));
1134         assert!(strptime("UTC", "%Z").unwrap().tm_zone ==
1135             ~"UTC");
1136         assert!(strptime("PST", "%Z").unwrap().tm_zone ==
1137             ~"");
1138         assert!(strptime("-0000", "%z").unwrap().tm_gmtoff ==
1139             0);
1140         assert!(strptime("-0800", "%z").unwrap().tm_gmtoff ==
1141             0);
1142         assert!(test("%", "%%"));
1143
1144         // Test for #7256
1145         assert_eq!(strptime("360", "%Y-%m-%d"), Err(~"Invalid year"))
1146     }
1147
1148     fn test_ctime() {
1149         os::setenv("TZ", "America/Los_Angeles");
1150         tzset();
1151
1152         let time = Timespec::new(1234567890, 54321);
1153         let utc   = at_utc(time);
1154         let local = at(time);
1155
1156         error!("test_ctime: %? %?", utc.ctime(), local.ctime());
1157
1158         assert_eq!(utc.ctime(), ~"Fri Feb 13 23:31:30 2009");
1159         assert_eq!(local.ctime(), ~"Fri Feb 13 15:31:30 2009");
1160     }
1161
1162     fn test_strftime() {
1163         os::setenv("TZ", "America/Los_Angeles");
1164         tzset();
1165
1166         let time = Timespec::new(1234567890, 54321);
1167         let utc = at_utc(time);
1168         let local = at(time);
1169
1170         assert_eq!(local.strftime(""), ~"");
1171         assert_eq!(local.strftime("%A"), ~"Friday");
1172         assert_eq!(local.strftime("%a"), ~"Fri");
1173         assert_eq!(local.strftime("%B"), ~"February");
1174         assert_eq!(local.strftime("%b"), ~"Feb");
1175         assert_eq!(local.strftime("%C"), ~"20");
1176         assert_eq!(local.strftime("%c"), ~"Fri Feb 13 15:31:30 2009");
1177         assert_eq!(local.strftime("%D"), ~"02/13/09");
1178         assert_eq!(local.strftime("%d"), ~"13");
1179         assert_eq!(local.strftime("%e"), ~"13");
1180         assert_eq!(local.strftime("%F"), ~"2009-02-13");
1181         // assert!(local.strftime("%G") == "2009");
1182         // assert!(local.strftime("%g") == "09");
1183         assert_eq!(local.strftime("%H"), ~"15");
1184         assert_eq!(local.strftime("%I"), ~"03");
1185         assert_eq!(local.strftime("%j"), ~"044");
1186         assert_eq!(local.strftime("%k"), ~"15");
1187         assert_eq!(local.strftime("%l"), ~" 3");
1188         assert_eq!(local.strftime("%M"), ~"31");
1189         assert_eq!(local.strftime("%m"), ~"02");
1190         assert_eq!(local.strftime("%n"), ~"\n");
1191         assert_eq!(local.strftime("%P"), ~"pm");
1192         assert_eq!(local.strftime("%p"), ~"PM");
1193         assert_eq!(local.strftime("%R"), ~"15:31");
1194         assert_eq!(local.strftime("%r"), ~"03:31:30 PM");
1195         assert_eq!(local.strftime("%S"), ~"30");
1196         assert_eq!(local.strftime("%s"), ~"1234567890");
1197         assert_eq!(local.strftime("%T"), ~"15:31:30");
1198         assert_eq!(local.strftime("%t"), ~"\t");
1199         // assert!(local.strftime("%U") == "06");
1200         assert_eq!(local.strftime("%u"), ~"5");
1201         // assert!(local.strftime("%V") == "07");
1202         assert_eq!(local.strftime("%v"), ~"13-Feb-2009");
1203         // assert!(local.strftime("%W") == "06");
1204         assert_eq!(local.strftime("%w"), ~"5");
1205         // handle "%X"
1206         // handle "%x"
1207         assert_eq!(local.strftime("%Y"), ~"2009");
1208         assert_eq!(local.strftime("%y"), ~"09");
1209
1210         // FIXME (#2350): We should probably standardize on the timezone
1211         // abbreviation.
1212         let zone = local.strftime("%Z");
1213         assert!(zone == ~"PST" || zone == ~"Pacific Standard Time");
1214
1215         assert_eq!(local.strftime("%z"), ~"-0800");
1216         assert_eq!(local.strftime("%%"), ~"%");
1217
1218         // FIXME (#2350): We should probably standardize on the timezone
1219         // abbreviation.
1220         let rfc822 = local.rfc822();
1221         let prefix = ~"Fri, 13 Feb 2009 15:31:30 ";
1222         assert!(rfc822 == prefix + "PST" ||
1223                      rfc822 == prefix + "Pacific Standard Time");
1224
1225         assert_eq!(local.ctime(), ~"Fri Feb 13 15:31:30 2009");
1226         assert_eq!(local.rfc822z(), ~"Fri, 13 Feb 2009 15:31:30 -0800");
1227         assert_eq!(local.rfc3339(), ~"2009-02-13T15:31:30-08:00");
1228
1229         assert_eq!(utc.ctime(), ~"Fri Feb 13 23:31:30 2009");
1230         assert_eq!(utc.rfc822(), ~"Fri, 13 Feb 2009 23:31:30 GMT");
1231         assert_eq!(utc.rfc822z(), ~"Fri, 13 Feb 2009 23:31:30 -0000");
1232         assert_eq!(utc.rfc3339(), ~"2009-02-13T23:31:30Z");
1233     }
1234
1235     fn test_timespec_eq_ord() {
1236         let a = &Timespec::new(-2, 1);
1237         let b = &Timespec::new(-1, 2);
1238         let c = &Timespec::new(1, 2);
1239         let d = &Timespec::new(2, 1);
1240         let e = &Timespec::new(2, 1);
1241
1242         assert!(d.eq(e));
1243         assert!(c.ne(e));
1244
1245         assert!(a.lt(b));
1246         assert!(b.lt(c));
1247         assert!(c.lt(d));
1248
1249         assert!(a.le(b));
1250         assert!(b.le(c));
1251         assert!(c.le(d));
1252         assert!(d.le(e));
1253         assert!(e.le(d));
1254
1255         assert!(b.ge(a));
1256         assert!(c.ge(b));
1257         assert!(d.ge(c));
1258         assert!(e.ge(d));
1259         assert!(d.ge(e));
1260
1261         assert!(b.gt(a));
1262         assert!(c.gt(b));
1263         assert!(d.gt(c));
1264     }
1265
1266     #[test]
1267     fn run_tests() {
1268         // The tests race on tzset. So instead of having many independent
1269         // tests, we will just call the functions now.
1270         test_get_time();
1271         test_precise_time();
1272         test_at_utc();
1273         test_at();
1274         test_to_timespec();
1275         test_conversions();
1276         test_strptime();
1277         test_ctime();
1278         test_strftime();
1279         test_timespec_eq_ord();
1280     }
1281 }