]> git.lizzy.rs Git - rust.git/blob - src/libextra/time.rs
efc3dc87adc00f02887a3980fb20c7931cae69f6
[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 mut value = 0_i32;
291
292         let mut i = 0u;
293         while i < digits {
294             let range = ss.char_range_at(pos);
295             pos = range.next;
296
297             match range.ch {
298               '0' .. '9' => {
299                 value = value * 10_i32 + (range.ch as i32 - '0' as i32);
300               }
301               ' ' if ws => (),
302               _ => return None
303             }
304             i += 1u;
305         }
306
307         Some((value, pos))
308     }
309
310     fn match_digits_in_range(ss: &str, pos: uint, digits: uint, ws: bool,
311                              min: i32, max: i32) -> Option<(i32, uint)> {
312         match match_digits(ss, pos, digits, ws) {
313           Some((val, pos)) if val >= min && val <= max => {
314             Some((val, pos))
315           }
316           _ => None
317         }
318     }
319
320     fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, ~str> {
321         let range = s.char_range_at(pos);
322
323         if c == range.ch {
324             Ok(range.next)
325         } else {
326             Err(fmt!("Expected %?, found %?",
327                 str::from_char(c),
328                 str::from_char(range.ch)))
329         }
330     }
331
332     fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
333       -> Result<uint, ~str> {
334         match ch {
335           'A' => match match_strs(s, pos, [
336               (~"Sunday", 0_i32),
337               (~"Monday", 1_i32),
338               (~"Tuesday", 2_i32),
339               (~"Wednesday", 3_i32),
340               (~"Thursday", 4_i32),
341               (~"Friday", 5_i32),
342               (~"Saturday", 6_i32)
343           ]) {
344             Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
345             None => Err(~"Invalid day")
346           },
347           'a' => match match_strs(s, pos, [
348               (~"Sun", 0_i32),
349               (~"Mon", 1_i32),
350               (~"Tue", 2_i32),
351               (~"Wed", 3_i32),
352               (~"Thu", 4_i32),
353               (~"Fri", 5_i32),
354               (~"Sat", 6_i32)
355           ]) {
356             Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
357             None => Err(~"Invalid day")
358           },
359           'B' => match match_strs(s, pos, [
360               (~"January", 0_i32),
361               (~"February", 1_i32),
362               (~"March", 2_i32),
363               (~"April", 3_i32),
364               (~"May", 4_i32),
365               (~"June", 5_i32),
366               (~"July", 6_i32),
367               (~"August", 7_i32),
368               (~"September", 8_i32),
369               (~"October", 9_i32),
370               (~"November", 10_i32),
371               (~"December", 11_i32)
372           ]) {
373             Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
374             None => Err(~"Invalid month")
375           },
376           'b' | 'h' => match match_strs(s, pos, [
377               (~"Jan", 0_i32),
378               (~"Feb", 1_i32),
379               (~"Mar", 2_i32),
380               (~"Apr", 3_i32),
381               (~"May", 4_i32),
382               (~"Jun", 5_i32),
383               (~"Jul", 6_i32),
384               (~"Aug", 7_i32),
385               (~"Sep", 8_i32),
386               (~"Oct", 9_i32),
387               (~"Nov", 10_i32),
388               (~"Dec", 11_i32)
389           ]) {
390             Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
391             None => Err(~"Invalid month")
392           },
393           'C' => match match_digits_in_range(s, pos, 2u, false, 0_i32,
394                                              99_i32) {
395             Some(item) => {
396                 let (v, pos) = item;
397                   tm.tm_year += (v * 100_i32) - 1900_i32;
398                   Ok(pos)
399               }
400             None => Err(~"Invalid year")
401           },
402           'c' => {
403             parse_type(s, pos, 'a', &mut *tm)
404                 .chain(|pos| parse_char(s, pos, ' '))
405                 .chain(|pos| parse_type(s, pos, 'b', &mut *tm))
406                 .chain(|pos| parse_char(s, pos, ' '))
407                 .chain(|pos| parse_type(s, pos, 'e', &mut *tm))
408                 .chain(|pos| parse_char(s, pos, ' '))
409                 .chain(|pos| parse_type(s, pos, 'T', &mut *tm))
410                 .chain(|pos| parse_char(s, pos, ' '))
411                 .chain(|pos| parse_type(s, pos, 'Y', &mut *tm))
412           }
413           'D' | 'x' => {
414             parse_type(s, pos, 'm', &mut *tm)
415                 .chain(|pos| parse_char(s, pos, '/'))
416                 .chain(|pos| parse_type(s, pos, 'd', &mut *tm))
417                 .chain(|pos| parse_char(s, pos, '/'))
418                 .chain(|pos| parse_type(s, pos, 'y', &mut *tm))
419           }
420           'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
421                                              31_i32) {
422             Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
423             None => Err(~"Invalid day of the month")
424           },
425           'e' => match match_digits_in_range(s, pos, 2u, true, 1_i32,
426                                              31_i32) {
427             Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
428             None => Err(~"Invalid day of the month")
429           },
430           'F' => {
431             parse_type(s, pos, 'Y', &mut *tm)
432                 .chain(|pos| parse_char(s, pos, '-'))
433                 .chain(|pos| parse_type(s, pos, 'm', &mut *tm))
434                 .chain(|pos| parse_char(s, pos, '-'))
435                 .chain(|pos| parse_type(s, pos, 'd', &mut *tm))
436           }
437           'H' => {
438             match match_digits_in_range(s, pos, 2u, false, 0_i32, 23_i32) {
439               Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
440               None => Err(~"Invalid hour")
441             }
442           }
443           'I' => {
444             match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
445               Some(item) => {
446                   let (v, pos) = item;
447                   tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
448                   Ok(pos)
449               }
450               None => Err(~"Invalid hour")
451             }
452           }
453           'j' => {
454             match match_digits_in_range(s, pos, 3u, false, 1_i32, 366_i32) {
455               Some(item) => {
456                 let (v, pos) = item;
457                 tm.tm_yday = v - 1_i32;
458                 Ok(pos)
459               }
460               None => Err(~"Invalid day of year")
461             }
462           }
463           'k' => {
464             match match_digits_in_range(s, pos, 2u, true, 0_i32, 23_i32) {
465               Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
466               None => Err(~"Invalid hour")
467             }
468           }
469           'l' => {
470             match match_digits_in_range(s, pos, 2u, true, 1_i32, 12_i32) {
471               Some(item) => {
472                   let (v, pos) = item;
473                   tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
474                   Ok(pos)
475               }
476               None => Err(~"Invalid hour")
477             }
478           }
479           'M' => {
480             match match_digits_in_range(s, pos, 2u, false, 0_i32, 59_i32) {
481               Some(item) => { let (v, pos) = item; tm.tm_min = v; Ok(pos) }
482               None => Err(~"Invalid minute")
483             }
484           }
485           'm' => {
486             match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
487               Some(item) => {
488                 let (v, pos) = item;
489                 tm.tm_mon = v - 1_i32;
490                 Ok(pos)
491               }
492               None => Err(~"Invalid month")
493             }
494           }
495           'n' => parse_char(s, pos, '\n'),
496           'P' => match match_strs(s, pos,
497                                   [(~"am", 0_i32), (~"pm", 12_i32)]) {
498
499             Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
500             None => Err(~"Invalid hour")
501           },
502           'p' => match match_strs(s, pos,
503                                   [(~"AM", 0_i32), (~"PM", 12_i32)]) {
504
505             Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
506             None => Err(~"Invalid hour")
507           },
508           'R' => {
509             parse_type(s, pos, 'H', &mut *tm)
510                 .chain(|pos| parse_char(s, pos, ':'))
511                 .chain(|pos| parse_type(s, pos, 'M', &mut *tm))
512           }
513           'r' => {
514             parse_type(s, pos, 'I', &mut *tm)
515                 .chain(|pos| parse_char(s, pos, ':'))
516                 .chain(|pos| parse_type(s, pos, 'M', &mut *tm))
517                 .chain(|pos| parse_char(s, pos, ':'))
518                 .chain(|pos| parse_type(s, pos, 'S', &mut *tm))
519                 .chain(|pos| parse_char(s, pos, ' '))
520                 .chain(|pos| parse_type(s, pos, 'p', &mut *tm))
521           }
522           'S' => {
523             match match_digits_in_range(s, pos, 2u, false, 0_i32, 60_i32) {
524               Some(item) => {
525                 let (v, pos) = item;
526                 tm.tm_sec = v;
527                 Ok(pos)
528               }
529               None => Err(~"Invalid second")
530             }
531           }
532           //'s' {}
533           'T' | 'X' => {
534             parse_type(s, pos, 'H', &mut *tm)
535                 .chain(|pos| parse_char(s, pos, ':'))
536                 .chain(|pos| parse_type(s, pos, 'M', &mut *tm))
537                 .chain(|pos| parse_char(s, pos, ':'))
538                 .chain(|pos| parse_type(s, pos, 'S', &mut *tm))
539           }
540           't' => parse_char(s, pos, '\t'),
541           'u' => {
542             match match_digits_in_range(s, pos, 1u, false, 1_i32, 7_i32) {
543               Some(item) => {
544                 let (v, pos) = item;
545                 tm.tm_wday = if v == 7 { 0 } else { v };
546                 Ok(pos)
547               }
548               None => Err(~"Invalid day of week")
549             }
550           }
551           'v' => {
552             parse_type(s, pos, 'e', &mut *tm)
553                 .chain(|pos|  parse_char(s, pos, '-'))
554                 .chain(|pos| parse_type(s, pos, 'b', &mut *tm))
555                 .chain(|pos| parse_char(s, pos, '-'))
556                 .chain(|pos| parse_type(s, pos, 'Y', &mut *tm))
557           }
558           //'W' {}
559           'w' => {
560             match match_digits_in_range(s, pos, 1u, false, 0_i32, 6_i32) {
561               Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
562               None => Err(~"Invalid day of week")
563             }
564           }
565           //'X' {}
566           //'x' {}
567           'Y' => {
568             match match_digits(s, pos, 4u, false) {
569               Some(item) => {
570                 let (v, pos) = item;
571                 tm.tm_year = v - 1900_i32;
572                 Ok(pos)
573               }
574               None => Err(~"Invalid year")
575             }
576           }
577           'y' => {
578             match match_digits_in_range(s, pos, 2u, false, 0_i32, 99_i32) {
579               Some(item) => {
580                 let (v, pos) = item;
581                 tm.tm_year = v;
582                 Ok(pos)
583               }
584               None => Err(~"Invalid year")
585             }
586           }
587           'Z' => {
588             if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") {
589                 tm.tm_gmtoff = 0_i32;
590                 tm.tm_zone = ~"UTC";
591                 Ok(pos + 3u)
592             } else {
593                 // It's odd, but to maintain compatibility with c's
594                 // strptime we ignore the timezone.
595                 let mut pos = pos;
596                 let len = s.len();
597                 while pos < len {
598                     let range = s.char_range_at(pos);
599                     pos = range.next;
600                     if range.ch == ' ' { break; }
601                 }
602
603                 Ok(pos)
604             }
605           }
606           'z' => {
607             let range = s.char_range_at(pos);
608
609             if range.ch == '+' || range.ch == '-' {
610                 match match_digits(s, range.next, 4u, false) {
611                   Some(item) => {
612                     let (v, pos) = item;
613                     if v == 0_i32 {
614                         tm.tm_gmtoff = 0_i32;
615                         tm.tm_zone = ~"UTC";
616                     }
617
618                     Ok(pos)
619                   }
620                   None => Err(~"Invalid zone offset")
621                 }
622             } else {
623                 Err(~"Invalid zone offset")
624             }
625           }
626           '%' => parse_char(s, pos, '%'),
627           ch => {
628             Err(fmt!("unknown formatting type: %?", str::from_char(ch)))
629           }
630         }
631     }
632
633     do io::with_str_reader(format) |rdr| {
634         let mut tm = Tm {
635             tm_sec: 0_i32,
636             tm_min: 0_i32,
637             tm_hour: 0_i32,
638             tm_mday: 0_i32,
639             tm_mon: 0_i32,
640             tm_year: 0_i32,
641             tm_wday: 0_i32,
642             tm_yday: 0_i32,
643             tm_isdst: 0_i32,
644             tm_gmtoff: 0_i32,
645             tm_zone: ~"",
646             tm_nsec: 0_i32,
647         };
648         let mut pos = 0u;
649         let len = s.len();
650         let mut result = Err(~"Invalid time");
651
652         while !rdr.eof() && pos < len {
653             let range = s.char_range_at(pos);
654             let ch = range.ch;
655             let next = range.next;
656
657             match rdr.read_char() {
658                 '%' => {
659                     match parse_type(s, pos, rdr.read_char(), &mut tm) {
660                         Ok(next) => pos = next,
661                         Err(e) => { result = Err(e); break; }
662                     }
663                 },
664                 c => {
665                     if c != ch { break }
666                     pos = next;
667                 }
668             }
669         }
670
671         if pos == len && rdr.eof() {
672             Ok(Tm {
673                 tm_sec: tm.tm_sec,
674                 tm_min: tm.tm_min,
675                 tm_hour: tm.tm_hour,
676                 tm_mday: tm.tm_mday,
677                 tm_mon: tm.tm_mon,
678                 tm_year: tm.tm_year,
679                 tm_wday: tm.tm_wday,
680                 tm_yday: tm.tm_yday,
681                 tm_isdst: tm.tm_isdst,
682                 tm_gmtoff: tm.tm_gmtoff,
683                 tm_zone: tm.tm_zone.clone(),
684                 tm_nsec: tm.tm_nsec,
685             })
686         } else { result }
687     }
688 }
689
690 priv fn do_strftime(format: &str, tm: &Tm) -> ~str {
691     fn parse_type(ch: char, tm: &Tm) -> ~str {
692         //FIXME (#2350): Implement missing types.
693       let die = || fmt!("strftime: can't understand this format %c ", ch);
694         match ch {
695           'A' => match tm.tm_wday as int {
696             0 => ~"Sunday",
697             1 => ~"Monday",
698             2 => ~"Tuesday",
699             3 => ~"Wednesday",
700             4 => ~"Thursday",
701             5 => ~"Friday",
702             6 => ~"Saturday",
703             _ => die()
704           },
705          'a' => match tm.tm_wday as int {
706             0 => ~"Sun",
707             1 => ~"Mon",
708             2 => ~"Tue",
709             3 => ~"Wed",
710             4 => ~"Thu",
711             5 => ~"Fri",
712             6 => ~"Sat",
713             _ => die()
714           },
715           'B' => match tm.tm_mon as int {
716             0 => ~"January",
717             1 => ~"February",
718             2 => ~"March",
719             3 => ~"April",
720             4 => ~"May",
721             5 => ~"June",
722             6 => ~"July",
723             7 => ~"August",
724             8 => ~"September",
725             9 => ~"October",
726             10 => ~"November",
727             11 => ~"December",
728             _ => die()
729           },
730           'b' | 'h' => match tm.tm_mon as int {
731             0 => ~"Jan",
732             1 => ~"Feb",
733             2 => ~"Mar",
734             3 => ~"Apr",
735             4 => ~"May",
736             5 => ~"Jun",
737             6 => ~"Jul",
738             7 => ~"Aug",
739             8 => ~"Sep",
740             9 => ~"Oct",
741             10 => ~"Nov",
742             11 => ~"Dec",
743             _  => die()
744           },
745           'C' => fmt!("%02d", (tm.tm_year as int + 1900) / 100),
746           'c' => {
747             fmt!("%s %s %s %s %s",
748                 parse_type('a', tm),
749                 parse_type('b', tm),
750                 parse_type('e', tm),
751                 parse_type('T', tm),
752                 parse_type('Y', tm))
753           }
754           'D' | 'x' => {
755             fmt!("%s/%s/%s",
756                 parse_type('m', tm),
757                 parse_type('d', tm),
758                 parse_type('y', tm))
759           }
760           'd' => fmt!("%02d", tm.tm_mday as int),
761           'e' => fmt!("%2d", tm.tm_mday as int),
762           'F' => {
763             fmt!("%s-%s-%s",
764                 parse_type('Y', tm),
765                 parse_type('m', tm),
766                 parse_type('d', tm))
767           }
768           //'G' {}
769           //'g' {}
770           'H' => fmt!("%02d", tm.tm_hour as int),
771           'I' => {
772             let mut h = tm.tm_hour as int;
773             if h == 0 { h = 12 }
774             if h > 12 { h -= 12 }
775             fmt!("%02d", h)
776           }
777           'j' => fmt!("%03d", tm.tm_yday as int + 1),
778           'k' => fmt!("%2d", tm.tm_hour as int),
779           'l' => {
780             let mut h = tm.tm_hour as int;
781             if h == 0 { h = 12 }
782             if h > 12 { h -= 12 }
783             fmt!("%2d", h)
784           }
785           'M' => fmt!("%02d", tm.tm_min as int),
786           'm' => fmt!("%02d", tm.tm_mon as int + 1),
787           'n' => ~"\n",
788           'P' => if (tm.tm_hour as int) < 12 { ~"am" } else { ~"pm" },
789           'p' => if (tm.tm_hour as int) < 12 { ~"AM" } else { ~"PM" },
790           'R' => {
791             fmt!("%s:%s",
792                 parse_type('H', tm),
793                 parse_type('M', tm))
794           }
795           'r' => {
796             fmt!("%s:%s:%s %s",
797                 parse_type('I', tm),
798                 parse_type('M', tm),
799                 parse_type('S', tm),
800                 parse_type('p', tm))
801           }
802           'S' => fmt!("%02d", tm.tm_sec as int),
803           's' => fmt!("%d", tm.to_timespec().sec as int),
804           'T' | 'X' => {
805             fmt!("%s:%s:%s",
806                 parse_type('H', tm),
807                 parse_type('M', tm),
808                 parse_type('S', tm))
809           }
810           't' => ~"\t",
811           //'U' {}
812           'u' => {
813             let i = tm.tm_wday as int;
814             int::to_str(if i == 0 { 7 } else { i })
815           }
816           //'V' {}
817           'v' => {
818             fmt!("%s-%s-%s",
819                 parse_type('e', tm),
820                 parse_type('b', tm),
821                 parse_type('Y', tm))
822           }
823           //'W' {}
824           'w' => int::to_str(tm.tm_wday as int),
825           //'X' {}
826           //'x' {}
827           'Y' => int::to_str(tm.tm_year as int + 1900),
828           'y' => fmt!("%02d", (tm.tm_year as int + 1900) % 100),
829           'Z' => tm.tm_zone.clone(),
830           'z' => {
831             let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
832             let mut m = num::abs(tm.tm_gmtoff) / 60_i32;
833             let h = m / 60_i32;
834             m -= h * 60_i32;
835             fmt!("%c%02d%02d", sign, h as int, m as int)
836           }
837           //'+' {}
838           '%' => ~"%",
839           _   => die()
840         }
841     }
842
843     let mut buf = ~"";
844
845     do io::with_str_reader(format) |rdr| {
846         while !rdr.eof() {
847             match rdr.read_char() {
848                 '%' => buf.push_str(parse_type(rdr.read_char(), tm)),
849                 ch => buf.push_char(ch)
850             }
851         }
852     }
853
854     buf
855 }
856
857 #[cfg(test)]
858 mod tests {
859     use time::*;
860
861     use std::float;
862     use std::os;
863     use std::result::{Err, Ok};
864
865     fn test_get_time() {
866         static SOME_RECENT_DATE: i64 = 1325376000i64; // 2012-01-01T00:00:00Z
867         static SOME_FUTURE_DATE: i64 = 1577836800i64; // 2020-01-01T00:00:00Z
868
869         let tv1 = get_time();
870         debug!("tv1=%? sec + %? nsec", tv1.sec as uint, tv1.nsec as uint);
871
872         assert!(tv1.sec > SOME_RECENT_DATE);
873         assert!(tv1.nsec < 1000000000i32);
874
875         let tv2 = get_time();
876         debug!("tv2=%? sec + %? nsec", tv2.sec as uint, tv2.nsec as uint);
877
878         assert!(tv2.sec >= tv1.sec);
879         assert!(tv2.sec < SOME_FUTURE_DATE);
880         assert!(tv2.nsec < 1000000000i32);
881         if tv2.sec == tv1.sec {
882             assert!(tv2.nsec >= tv1.nsec);
883         }
884     }
885
886     fn test_precise_time() {
887         let s0 = precise_time_s();
888         let ns1 = precise_time_ns();
889
890         debug!("s0=%s sec", float::to_str_digits(s0, 9u));
891         assert!(s0 > 0.);
892         let ns0 = (s0 * 1000000000.) as u64;
893         debug!("ns0=%? ns", ns0);
894
895         debug!("ns1=%? ns", ns0);
896         assert!(ns1 >= ns0);
897
898         let ns2 = precise_time_ns();
899         debug!("ns2=%? ns", ns0);
900         assert!(ns2 >= ns1);
901     }
902
903     fn test_at_utc() {
904         os::setenv("TZ", "America/Los_Angeles");
905         tzset();
906
907         let time = ::time::Timespec::new(1234567890, 54321);
908         let utc = at_utc(time);
909
910         assert!(utc.tm_sec == 30_i32);
911         assert!(utc.tm_min == 31_i32);
912         assert!(utc.tm_hour == 23_i32);
913         assert!(utc.tm_mday == 13_i32);
914         assert!(utc.tm_mon == 1_i32);
915         assert!(utc.tm_year == 109_i32);
916         assert!(utc.tm_wday == 5_i32);
917         assert!(utc.tm_yday == 43_i32);
918         assert!(utc.tm_isdst == 0_i32);
919         assert!(utc.tm_gmtoff == 0_i32);
920         assert!(utc.tm_zone == ~"UTC");
921         assert!(utc.tm_nsec == 54321_i32);
922     }
923
924     fn test_at() {
925         os::setenv("TZ", "America/Los_Angeles");
926         tzset();
927
928         let time = ::time::Timespec::new(1234567890, 54321);
929         let local = at(time);
930
931         error!("time_at: %?", local);
932
933         assert!(local.tm_sec == 30_i32);
934         assert!(local.tm_min == 31_i32);
935         assert!(local.tm_hour == 15_i32);
936         assert!(local.tm_mday == 13_i32);
937         assert!(local.tm_mon == 1_i32);
938         assert!(local.tm_year == 109_i32);
939         assert!(local.tm_wday == 5_i32);
940         assert!(local.tm_yday == 43_i32);
941         assert!(local.tm_isdst == 0_i32);
942         assert!(local.tm_gmtoff == -28800_i32);
943
944         // FIXME (#2350): We should probably standardize on the timezone
945         // abbreviation.
946         let zone = &local.tm_zone;
947         assert!(*zone == ~"PST" || *zone == ~"Pacific Standard Time");
948
949         assert!(local.tm_nsec == 54321_i32);
950     }
951
952     fn test_to_timespec() {
953         os::setenv("TZ", "America/Los_Angeles");
954         tzset();
955
956         let time = ::time::Timespec::new(1234567890, 54321);
957         let utc = at_utc(time);
958
959         assert_eq!(utc.to_timespec(), time);
960         assert_eq!(utc.to_local().to_timespec(), time);
961     }
962
963     fn test_conversions() {
964         os::setenv("TZ", "America/Los_Angeles");
965         tzset();
966
967         let time = ::time::Timespec::new(1234567890, 54321);
968         let utc = at_utc(time);
969         let local = at(time);
970
971         assert!(local.to_local() == local);
972         assert!(local.to_utc() == utc);
973         assert!(local.to_utc().to_local() == local);
974         assert!(utc.to_utc() == utc);
975         assert!(utc.to_local() == local);
976         assert!(utc.to_local().to_utc() == utc);
977     }
978
979     fn test_strptime() {
980         os::setenv("TZ", "America/Los_Angeles");
981         tzset();
982
983         match strptime("", "") {
984           Ok(ref tm) => {
985             assert!(tm.tm_sec == 0_i32);
986             assert!(tm.tm_min == 0_i32);
987             assert!(tm.tm_hour == 0_i32);
988             assert!(tm.tm_mday == 0_i32);
989             assert!(tm.tm_mon == 0_i32);
990             assert!(tm.tm_year == 0_i32);
991             assert!(tm.tm_wday == 0_i32);
992             assert!(tm.tm_isdst == 0_i32);
993             assert!(tm.tm_gmtoff == 0_i32);
994             assert!(tm.tm_zone == ~"");
995             assert!(tm.tm_nsec == 0_i32);
996           }
997           Err(_) => ()
998         }
999
1000         let format = "%a %b %e %T %Y";
1001         assert_eq!(strptime("", format), Err(~"Invalid time"));
1002         assert!(strptime("Fri Feb 13 15:31:30", format)
1003             == Err(~"Invalid time"));
1004
1005         match strptime("Fri Feb 13 15:31:30 2009", format) {
1006           Err(e) => fail!(e),
1007           Ok(ref tm) => {
1008             assert!(tm.tm_sec == 30_i32);
1009             assert!(tm.tm_min == 31_i32);
1010             assert!(tm.tm_hour == 15_i32);
1011             assert!(tm.tm_mday == 13_i32);
1012             assert!(tm.tm_mon == 1_i32);
1013             assert!(tm.tm_year == 109_i32);
1014             assert!(tm.tm_wday == 5_i32);
1015             assert!(tm.tm_yday == 0_i32);
1016             assert!(tm.tm_isdst == 0_i32);
1017             assert!(tm.tm_gmtoff == 0_i32);
1018             assert!(tm.tm_zone == ~"");
1019             assert!(tm.tm_nsec == 0_i32);
1020           }
1021         }
1022
1023         fn test(s: &str, format: &str) -> bool {
1024             match strptime(s, format) {
1025               Ok(ref tm) => tm.strftime(format) == s.to_owned(),
1026               Err(e) => fail!(e)
1027             }
1028         }
1029
1030         let days = [
1031             ~"Sunday",
1032             ~"Monday",
1033             ~"Tuesday",
1034             ~"Wednesday",
1035             ~"Thursday",
1036             ~"Friday",
1037             ~"Saturday"
1038         ];
1039         for day in days.iter() {
1040             assert!(test(*day, "%A"));
1041         }
1042
1043         let days = [
1044             ~"Sun",
1045             ~"Mon",
1046             ~"Tue",
1047             ~"Wed",
1048             ~"Thu",
1049             ~"Fri",
1050             ~"Sat"
1051         ];
1052         for day in days.iter() {
1053             assert!(test(*day, "%a"));
1054         }
1055
1056         let months = [
1057             ~"January",
1058             ~"February",
1059             ~"March",
1060             ~"April",
1061             ~"May",
1062             ~"June",
1063             ~"July",
1064             ~"August",
1065             ~"September",
1066             ~"October",
1067             ~"November",
1068             ~"December"
1069         ];
1070         for day in months.iter() {
1071             assert!(test(*day, "%B"));
1072         }
1073
1074         let months = [
1075             ~"Jan",
1076             ~"Feb",
1077             ~"Mar",
1078             ~"Apr",
1079             ~"May",
1080             ~"Jun",
1081             ~"Jul",
1082             ~"Aug",
1083             ~"Sep",
1084             ~"Oct",
1085             ~"Nov",
1086             ~"Dec"
1087         ];
1088         for day in months.iter() {
1089             assert!(test(*day, "%b"));
1090         }
1091
1092         assert!(test("19", "%C"));
1093         assert!(test("Fri Feb 13 23:31:30 2009", "%c"));
1094         assert!(test("02/13/09", "%D"));
1095         assert!(test("03", "%d"));
1096         assert!(test("13", "%d"));
1097         assert!(test(" 3", "%e"));
1098         assert!(test("13", "%e"));
1099         assert!(test("2009-02-13", "%F"));
1100         assert!(test("03", "%H"));
1101         assert!(test("13", "%H"));
1102         assert!(test("03", "%I")); // FIXME (#2350): flesh out
1103         assert!(test("11", "%I")); // FIXME (#2350): flesh out
1104         assert!(test("044", "%j"));
1105         assert!(test(" 3", "%k"));
1106         assert!(test("13", "%k"));
1107         assert!(test(" 1", "%l"));
1108         assert!(test("11", "%l"));
1109         assert!(test("03", "%M"));
1110         assert!(test("13", "%M"));
1111         assert!(test("\n", "%n"));
1112         assert!(test("am", "%P"));
1113         assert!(test("pm", "%P"));
1114         assert!(test("AM", "%p"));
1115         assert!(test("PM", "%p"));
1116         assert!(test("23:31", "%R"));
1117         assert!(test("11:31:30 AM", "%r"));
1118         assert!(test("11:31:30 PM", "%r"));
1119         assert!(test("03", "%S"));
1120         assert!(test("13", "%S"));
1121         assert!(test("15:31:30", "%T"));
1122         assert!(test("\t", "%t"));
1123         assert!(test("1", "%u"));
1124         assert!(test("7", "%u"));
1125         assert!(test("13-Feb-2009", "%v"));
1126         assert!(test("0", "%w"));
1127         assert!(test("6", "%w"));
1128         assert!(test("2009", "%Y"));
1129         assert!(test("09", "%y"));
1130         assert!(strptime("UTC", "%Z").unwrap().tm_zone ==
1131             ~"UTC");
1132         assert!(strptime("PST", "%Z").unwrap().tm_zone ==
1133             ~"");
1134         assert!(strptime("-0000", "%z").unwrap().tm_gmtoff ==
1135             0);
1136         assert!(strptime("-0800", "%z").unwrap().tm_gmtoff ==
1137             0);
1138         assert!(test("%", "%%"));
1139
1140         // Test for #7256
1141         assert_eq!(strptime("360", "%Y-%m-%d"), Err(~"Invalid year"))
1142     }
1143
1144     fn test_ctime() {
1145         os::setenv("TZ", "America/Los_Angeles");
1146         tzset();
1147
1148         let time = ::time::Timespec::new(1234567890, 54321);
1149         let utc   = at_utc(time);
1150         let local = at(time);
1151
1152         error!("test_ctime: %? %?", utc.ctime(), local.ctime());
1153
1154         assert_eq!(utc.ctime(), ~"Fri Feb 13 23:31:30 2009");
1155         assert_eq!(local.ctime(), ~"Fri Feb 13 15:31:30 2009");
1156     }
1157
1158     fn test_strftime() {
1159         os::setenv("TZ", "America/Los_Angeles");
1160         tzset();
1161
1162         let time = ::time::Timespec::new(1234567890, 54321);
1163         let utc = at_utc(time);
1164         let local = at(time);
1165
1166         assert_eq!(local.strftime(""), ~"");
1167         assert_eq!(local.strftime("%A"), ~"Friday");
1168         assert_eq!(local.strftime("%a"), ~"Fri");
1169         assert_eq!(local.strftime("%B"), ~"February");
1170         assert_eq!(local.strftime("%b"), ~"Feb");
1171         assert_eq!(local.strftime("%C"), ~"20");
1172         assert_eq!(local.strftime("%c"), ~"Fri Feb 13 15:31:30 2009");
1173         assert_eq!(local.strftime("%D"), ~"02/13/09");
1174         assert_eq!(local.strftime("%d"), ~"13");
1175         assert_eq!(local.strftime("%e"), ~"13");
1176         assert_eq!(local.strftime("%F"), ~"2009-02-13");
1177         // assert!(local.strftime("%G") == "2009");
1178         // assert!(local.strftime("%g") == "09");
1179         assert_eq!(local.strftime("%H"), ~"15");
1180         assert_eq!(local.strftime("%I"), ~"03");
1181         assert_eq!(local.strftime("%j"), ~"044");
1182         assert_eq!(local.strftime("%k"), ~"15");
1183         assert_eq!(local.strftime("%l"), ~" 3");
1184         assert_eq!(local.strftime("%M"), ~"31");
1185         assert_eq!(local.strftime("%m"), ~"02");
1186         assert_eq!(local.strftime("%n"), ~"\n");
1187         assert_eq!(local.strftime("%P"), ~"pm");
1188         assert_eq!(local.strftime("%p"), ~"PM");
1189         assert_eq!(local.strftime("%R"), ~"15:31");
1190         assert_eq!(local.strftime("%r"), ~"03:31:30 PM");
1191         assert_eq!(local.strftime("%S"), ~"30");
1192         assert_eq!(local.strftime("%s"), ~"1234567890");
1193         assert_eq!(local.strftime("%T"), ~"15:31:30");
1194         assert_eq!(local.strftime("%t"), ~"\t");
1195         // assert!(local.strftime("%U") == "06");
1196         assert_eq!(local.strftime("%u"), ~"5");
1197         // assert!(local.strftime("%V") == "07");
1198         assert_eq!(local.strftime("%v"), ~"13-Feb-2009");
1199         // assert!(local.strftime("%W") == "06");
1200         assert_eq!(local.strftime("%w"), ~"5");
1201         // handle "%X"
1202         // handle "%x"
1203         assert_eq!(local.strftime("%Y"), ~"2009");
1204         assert_eq!(local.strftime("%y"), ~"09");
1205
1206         // FIXME (#2350): We should probably standardize on the timezone
1207         // abbreviation.
1208         let zone = local.strftime("%Z");
1209         assert!(zone == ~"PST" || zone == ~"Pacific Standard Time");
1210
1211         assert_eq!(local.strftime("%z"), ~"-0800");
1212         assert_eq!(local.strftime("%%"), ~"%");
1213
1214         // FIXME (#2350): We should probably standardize on the timezone
1215         // abbreviation.
1216         let rfc822 = local.rfc822();
1217         let prefix = ~"Fri, 13 Feb 2009 15:31:30 ";
1218         assert!(rfc822 == prefix + "PST" ||
1219                      rfc822 == prefix + "Pacific Standard Time");
1220
1221         assert_eq!(local.ctime(), ~"Fri Feb 13 15:31:30 2009");
1222         assert_eq!(local.rfc822z(), ~"Fri, 13 Feb 2009 15:31:30 -0800");
1223         assert_eq!(local.rfc3339(), ~"2009-02-13T15:31:30-08:00");
1224
1225         assert_eq!(utc.ctime(), ~"Fri Feb 13 23:31:30 2009");
1226         assert_eq!(utc.rfc822(), ~"Fri, 13 Feb 2009 23:31:30 GMT");
1227         assert_eq!(utc.rfc822z(), ~"Fri, 13 Feb 2009 23:31:30 -0000");
1228         assert_eq!(utc.rfc3339(), ~"2009-02-13T23:31:30Z");
1229     }
1230
1231     fn test_timespec_eq_ord() {
1232         let a = &Timespec::new(-2, 1);
1233         let b = &Timespec::new(-1, 2);
1234         let c = &Timespec::new(1, 2);
1235         let d = &Timespec::new(2, 1);
1236         let e = &Timespec::new(2, 1);
1237
1238         assert!(d.eq(e));
1239         assert!(c.ne(e));
1240
1241         assert!(a.lt(b));
1242         assert!(b.lt(c));
1243         assert!(c.lt(d));
1244
1245         assert!(a.le(b));
1246         assert!(b.le(c));
1247         assert!(c.le(d));
1248         assert!(d.le(e));
1249         assert!(e.le(d));
1250
1251         assert!(b.ge(a));
1252         assert!(c.ge(b));
1253         assert!(d.ge(c));
1254         assert!(e.ge(d));
1255         assert!(d.ge(e));
1256
1257         assert!(b.gt(a));
1258         assert!(c.gt(b));
1259         assert!(d.gt(c));
1260     }
1261
1262     #[test]
1263     fn run_tests() {
1264         // The tests race on tzset. So instead of having many independent
1265         // tests, we will just call the functions now.
1266         test_get_time();
1267         test_precise_time();
1268         test_at_utc();
1269         test_at();
1270         test_to_timespec();
1271         test_conversions();
1272         test_strptime();
1273         test_ctime();
1274         test_strftime();
1275         test_timespec_eq_ord();
1276     }
1277 }