-
Notifications
You must be signed in to change notification settings - Fork 12.1k
/
time.rs
1286 lines (1174 loc) · 40.7 KB
/
time.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::cmp::{Eq, Ord};
use core::int;
use core::i32;
use core::io::{Reader, ReaderUtil};
use core::io;
use core::prelude::*;
use core::result::{Result, Ok, Err};
use core::str;
static NSEC_PER_SEC: i32 = 1_000_000_000_i32;
pub mod rustrt {
use super::Tm;
#[abi = "cdecl"]
pub extern {
pub unsafe fn get_time(sec: &mut i64, nsec: &mut i32);
pub unsafe fn precise_time_ns(ns: &mut u64);
pub unsafe fn rust_tzset();
// FIXME: The i64 values can be passed by-val when #2064 is fixed.
pub unsafe fn rust_gmtime(sec: i64, nsec: i32, result: &mut Tm);
pub unsafe fn rust_localtime(sec: i64, nsec: i32, result: &mut Tm);
pub unsafe fn rust_timegm(tm: &Tm, sec: &mut i64);
pub unsafe fn rust_mktime(tm: &Tm, sec: &mut i64);
}
}
/// A record specifying a time value in seconds and nanoseconds.
#[auto_encode]
#[auto_decode]
#[deriving(Eq)]
pub struct Timespec { sec: i64, nsec: i32 }
/*
* Timespec assumes that pre-epoch Timespecs have negative sec and positive
* nsec fields. Darwin's and Linux's struct timespec functions handle pre-
* epoch timestamps using a "two steps back, one step forward" representation,
* though the man pages do not actually document this. For example, the time
* -1.2 seconds before the epoch is represented by `Timespec { sec: -2_i64,
* nsec: 800_000_000_i32 }`.
*/
pub impl Timespec {
fn new(sec: i64, nsec: i32) -> Timespec {
fail_unless!(nsec >= 0 && nsec < NSEC_PER_SEC);
Timespec { sec: sec, nsec: nsec }
}
}
impl Ord for Timespec {
fn lt(&self, other: &Timespec) -> bool {
self.sec < other.sec ||
(self.sec == other.sec && self.nsec < other.nsec)
}
fn le(&self, other: &Timespec) -> bool { !other.lt(self) }
fn ge(&self, other: &Timespec) -> bool { !self.lt(other) }
fn gt(&self, other: &Timespec) -> bool { !self.le(other) }
}
/**
* Returns the current time as a `timespec` containing the seconds and
* nanoseconds since 1970-01-01T00:00:00Z.
*/
pub fn get_time() -> Timespec {
unsafe {
let mut sec = 0i64;
let mut nsec = 0i32;
rustrt::get_time(&mut sec, &mut nsec);
return Timespec::new(sec, nsec);
}
}
/**
* Returns the current value of a high-resolution performance counter
* in nanoseconds since an unspecified epoch.
*/
pub fn precise_time_ns() -> u64 {
unsafe {
let mut ns = 0u64;
rustrt::precise_time_ns(&mut ns);
ns
}
}
/**
* Returns the current value of a high-resolution performance counter
* in seconds since an unspecified epoch.
*/
pub fn precise_time_s() -> float {
return (precise_time_ns() as float) / 1000000000.;
}
pub fn tzset() {
unsafe {
rustrt::rust_tzset();
}
}
#[auto_encode]
#[auto_decode]
#[deriving(Eq)]
pub struct Tm {
tm_sec: i32, // seconds after the minute ~[0-60]
tm_min: i32, // minutes after the hour ~[0-59]
tm_hour: i32, // hours after midnight ~[0-23]
tm_mday: i32, // days of the month ~[1-31]
tm_mon: i32, // months since January ~[0-11]
tm_year: i32, // years since 1900
tm_wday: i32, // days since Sunday ~[0-6]
tm_yday: i32, // days since January 1 ~[0-365]
tm_isdst: i32, // Daylight Savings Time flag
tm_gmtoff: i32, // offset from UTC in seconds
tm_zone: ~str, // timezone abbreviation
tm_nsec: i32, // nanoseconds
}
pub fn empty_tm() -> Tm {
Tm {
tm_sec: 0_i32,
tm_min: 0_i32,
tm_hour: 0_i32,
tm_mday: 0_i32,
tm_mon: 0_i32,
tm_year: 0_i32,
tm_wday: 0_i32,
tm_yday: 0_i32,
tm_isdst: 0_i32,
tm_gmtoff: 0_i32,
tm_zone: ~"",
tm_nsec: 0_i32,
}
}
/// Returns the specified time in UTC
pub fn at_utc(clock: Timespec) -> Tm {
unsafe {
let mut Timespec { sec, nsec } = clock;
let mut tm = empty_tm();
rustrt::rust_gmtime(sec, nsec, &mut tm);
tm
}
}
/// Returns the current time in UTC
pub fn now_utc() -> Tm {
at_utc(get_time())
}
/// Returns the specified time in the local timezone
pub fn at(clock: Timespec) -> Tm {
unsafe {
let mut Timespec { sec, nsec } = clock;
let mut tm = empty_tm();
rustrt::rust_localtime(sec, nsec, &mut tm);
tm
}
}
/// Returns the current time in the local timezone
pub fn now() -> Tm {
at(get_time())
}
/// Parses the time from the string according to the format string.
pub fn strptime(s: &str, format: &str) -> Result<Tm, ~str> {
// unsafe only because do_strptime is annoying to make pure
// (it does IO with a str_reader)
unsafe {do_strptime(s, format)}
}
/// Formats the time according to the format string.
pub fn strftime(format: &str, tm: &Tm) -> ~str {
// unsafe only because do_strftime is annoying to make pure
// (it does IO with a str_reader)
unsafe { do_strftime(format, tm) }
}
pub impl Tm {
/// Convert time to the seconds from January 1, 1970
fn to_timespec(&self) -> Timespec {
unsafe {
let mut sec = 0i64;
if self.tm_gmtoff == 0_i32 {
rustrt::rust_timegm(self, &mut sec);
} else {
rustrt::rust_mktime(self, &mut sec);
}
Timespec::new(sec, self.tm_nsec)
}
}
/// Convert time to the local timezone
fn to_local(&self) -> Tm {
at(self.to_timespec())
}
/// Convert time to the UTC
fn to_utc(&self) -> Tm {
at_utc(self.to_timespec())
}
/**
* Return a string of the current time in the form
* "Thu Jan 1 00:00:00 1970".
*/
fn ctime(&self) -> ~str { self.strftime(~"%c") }
/// Formats the time according to the format string.
fn strftime(&self, format: &str) -> ~str {
strftime(format, self)
}
/**
* Returns a time string formatted according to RFC 822.
*
* local: "Thu, 22 Mar 2012 07:53:18 PST"
* utc: "Thu, 22 Mar 2012 14:53:18 UTC"
*/
fn rfc822(&self) -> ~str {
if self.tm_gmtoff == 0_i32 {
self.strftime(~"%a, %d %b %Y %T GMT")
} else {
self.strftime(~"%a, %d %b %Y %T %Z")
}
}
/**
* Returns a time string formatted according to RFC 822 with Zulu time.
*
* local: "Thu, 22 Mar 2012 07:53:18 -0700"
* utc: "Thu, 22 Mar 2012 14:53:18 -0000"
*/
fn rfc822z(&self) -> ~str {
self.strftime(~"%a, %d %b %Y %T %z")
}
/**
* Returns a time string formatted according to ISO 8601.
*
* local: "2012-02-22T07:53:18-07:00"
* utc: "2012-02-22T14:53:18Z"
*/
fn rfc3339(&self) -> ~str {
if self.tm_gmtoff == 0_i32 {
self.strftime(~"%Y-%m-%dT%H:%M:%SZ")
} else {
let s = self.strftime(~"%Y-%m-%dT%H:%M:%S");
let sign = if self.tm_gmtoff > 0_i32 { '+' } else { '-' };
let mut m = i32::abs(self.tm_gmtoff) / 60_i32;
let h = m / 60_i32;
m -= h * 60_i32;
s + fmt!("%c%02d:%02d", sign, h as int, m as int)
}
}
}
priv fn do_strptime(s: &str, format: &str) -> Result<Tm, ~str> {
fn match_str(s: &str, pos: uint, needle: &str) -> bool {
let mut i = pos;
for str::each(needle) |ch| {
if s[i] != ch {
return false;
}
i += 1u;
}
return true;
}
fn match_strs(ss: &str, pos: uint, strs: &[(~str, i32)])
-> Option<(i32, uint)> {
let mut i = 0u;
let len = strs.len();
while i < len {
let &(needle, value) = &strs[i];
if match_str(ss, pos, needle) {
return Some((value, pos + str::len(needle)));
}
i += 1u;
}
None
}
fn match_digits(ss: &str, pos: uint, digits: uint, ws: bool)
-> Option<(i32, uint)> {
let mut pos = pos;
let mut value = 0_i32;
let mut i = 0u;
while i < digits {
let range = str::char_range_at(str::from_slice(ss), pos);
pos = range.next;
match range.ch {
'0' .. '9' => {
value = value * 10_i32 + (range.ch as i32 - '0' as i32);
}
' ' if ws => (),
_ => return None
}
i += 1u;
}
Some((value, pos))
}
fn match_digits_in_range(ss: &str, pos: uint, digits: uint, ws: bool,
min: i32, max: i32) -> Option<(i32, uint)> {
match match_digits(ss, pos, digits, ws) {
Some((val, pos)) if val >= min && val <= max => {
Some((val, pos))
}
_ => None
}
}
fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, ~str> {
let range = str::char_range_at(s, pos);
if c == range.ch {
Ok(range.next)
} else {
Err(fmt!("Expected %?, found %?",
str::from_char(c),
str::from_char(range.ch)))
}
}
fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
-> Result<uint, ~str> {
match ch {
'A' => match match_strs(s, pos, ~[
(~"Sunday", 0_i32),
(~"Monday", 1_i32),
(~"Tuesday", 2_i32),
(~"Wednesday", 3_i32),
(~"Thursday", 4_i32),
(~"Friday", 5_i32),
(~"Saturday", 6_i32)
]) {
Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
None => Err(~"Invalid day")
},
'a' => match match_strs(s, pos, ~[
(~"Sun", 0_i32),
(~"Mon", 1_i32),
(~"Tue", 2_i32),
(~"Wed", 3_i32),
(~"Thu", 4_i32),
(~"Fri", 5_i32),
(~"Sat", 6_i32)
]) {
Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
None => Err(~"Invalid day")
},
'B' => match match_strs(s, pos, ~[
(~"January", 0_i32),
(~"February", 1_i32),
(~"March", 2_i32),
(~"April", 3_i32),
(~"May", 4_i32),
(~"June", 5_i32),
(~"July", 6_i32),
(~"August", 7_i32),
(~"September", 8_i32),
(~"October", 9_i32),
(~"November", 10_i32),
(~"December", 11_i32)
]) {
Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
None => Err(~"Invalid month")
},
'b' | 'h' => match match_strs(s, pos, ~[
(~"Jan", 0_i32),
(~"Feb", 1_i32),
(~"Mar", 2_i32),
(~"Apr", 3_i32),
(~"May", 4_i32),
(~"Jun", 5_i32),
(~"Jul", 6_i32),
(~"Aug", 7_i32),
(~"Sep", 8_i32),
(~"Oct", 9_i32),
(~"Nov", 10_i32),
(~"Dec", 11_i32)
]) {
Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
None => Err(~"Invalid month")
},
'C' => match match_digits_in_range(s, pos, 2u, false, 0_i32,
99_i32) {
Some(item) => {
let (v, pos) = item;
tm.tm_year += (v * 100_i32) - 1900_i32;
Ok(pos)
}
None => Err(~"Invalid year")
},
'c' => {
parse_type(s, pos, 'a', &mut *tm)
.chain(|pos| parse_char(s, pos, ' '))
.chain(|pos| parse_type(s, pos, 'b', &mut *tm))
.chain(|pos| parse_char(s, pos, ' '))
.chain(|pos| parse_type(s, pos, 'e', &mut *tm))
.chain(|pos| parse_char(s, pos, ' '))
.chain(|pos| parse_type(s, pos, 'T', &mut *tm))
.chain(|pos| parse_char(s, pos, ' '))
.chain(|pos| parse_type(s, pos, 'Y', &mut *tm))
}
'D' | 'x' => {
parse_type(s, pos, 'm', &mut *tm)
.chain(|pos| parse_char(s, pos, '/'))
.chain(|pos| parse_type(s, pos, 'd', &mut *tm))
.chain(|pos| parse_char(s, pos, '/'))
.chain(|pos| parse_type(s, pos, 'y', &mut *tm))
}
'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
31_i32) {
Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
None => Err(~"Invalid day of the month")
},
'e' => match match_digits_in_range(s, pos, 2u, true, 1_i32,
31_i32) {
Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
None => Err(~"Invalid day of the month")
},
'F' => {
parse_type(s, pos, 'Y', &mut *tm)
.chain(|pos| parse_char(s, pos, '-'))
.chain(|pos| parse_type(s, pos, 'm', &mut *tm))
.chain(|pos| parse_char(s, pos, '-'))
.chain(|pos| parse_type(s, pos, 'd', &mut *tm))
}
'H' => {
match match_digits_in_range(s, pos, 2u, false, 0_i32, 23_i32) {
Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
None => Err(~"Invalid hour")
}
}
'I' => {
match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
Some(item) => {
let (v, pos) = item;
tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
Ok(pos)
}
None => Err(~"Invalid hour")
}
}
'j' => {
match match_digits_in_range(s, pos, 3u, false, 1_i32, 366_i32) {
Some(item) => {
let (v, pos) = item;
tm.tm_yday = v - 1_i32;
Ok(pos)
}
None => Err(~"Invalid day of year")
}
}
'k' => {
match match_digits_in_range(s, pos, 2u, true, 0_i32, 23_i32) {
Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
None => Err(~"Invalid hour")
}
}
'l' => {
match match_digits_in_range(s, pos, 2u, true, 1_i32, 12_i32) {
Some(item) => {
let (v, pos) = item;
tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
Ok(pos)
}
None => Err(~"Invalid hour")
}
}
'M' => {
match match_digits_in_range(s, pos, 2u, false, 0_i32, 59_i32) {
Some(item) => { let (v, pos) = item; tm.tm_min = v; Ok(pos) }
None => Err(~"Invalid minute")
}
}
'm' => {
match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
Some(item) => {
let (v, pos) = item;
tm.tm_mon = v - 1_i32;
Ok(pos)
}
None => Err(~"Invalid month")
}
}
'n' => parse_char(s, pos, '\n'),
'P' => match match_strs(s, pos,
~[(~"am", 0_i32), (~"pm", 12_i32)]) {
Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
None => Err(~"Invalid hour")
},
'p' => match match_strs(s, pos,
~[(~"AM", 0_i32), (~"PM", 12_i32)]) {
Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
None => Err(~"Invalid hour")
},
'R' => {
parse_type(s, pos, 'H', &mut *tm)
.chain(|pos| parse_char(s, pos, ':'))
.chain(|pos| parse_type(s, pos, 'M', &mut *tm))
}
'r' => {
parse_type(s, pos, 'I', &mut *tm)
.chain(|pos| parse_char(s, pos, ':'))
.chain(|pos| parse_type(s, pos, 'M', &mut *tm))
.chain(|pos| parse_char(s, pos, ':'))
.chain(|pos| parse_type(s, pos, 'S', &mut *tm))
.chain(|pos| parse_char(s, pos, ' '))
.chain(|pos| parse_type(s, pos, 'p', &mut *tm))
}
'S' => {
match match_digits_in_range(s, pos, 2u, false, 0_i32, 60_i32) {
Some(item) => {
let (v, pos) = item;
tm.tm_sec = v;
Ok(pos)
}
None => Err(~"Invalid second")
}
}
//'s' {}
'T' | 'X' => {
parse_type(s, pos, 'H', &mut *tm)
.chain(|pos| parse_char(s, pos, ':'))
.chain(|pos| parse_type(s, pos, 'M', &mut *tm))
.chain(|pos| parse_char(s, pos, ':'))
.chain(|pos| parse_type(s, pos, 'S', &mut *tm))
}
't' => parse_char(s, pos, '\t'),
'u' => {
match match_digits_in_range(s, pos, 1u, false, 1_i32, 7_i32) {
Some(item) => {
let (v, pos) = item;
tm.tm_wday = if v == 7 { 0 } else { v };
Ok(pos)
}
None => Err(~"Invalid day of week")
}
}
'v' => {
parse_type(s, pos, 'e', &mut *tm)
.chain(|pos| parse_char(s, pos, '-'))
.chain(|pos| parse_type(s, pos, 'b', &mut *tm))
.chain(|pos| parse_char(s, pos, '-'))
.chain(|pos| parse_type(s, pos, 'Y', &mut *tm))
}
//'W' {}
'w' => {
match match_digits_in_range(s, pos, 1u, false, 0_i32, 6_i32) {
Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
None => Err(~"Invalid day of week")
}
}
//'X' {}
//'x' {}
'Y' => {
match match_digits(s, pos, 4u, false) {
Some(item) => {
let (v, pos) = item;
tm.tm_year = v - 1900_i32;
Ok(pos)
}
None => Err(~"Invalid year")
}
}
'y' => {
match match_digits_in_range(s, pos, 2u, false, 0_i32, 99_i32) {
Some(item) => {
let (v, pos) = item;
tm.tm_year = v;
Ok(pos)
}
None => Err(~"Invalid year")
}
}
'Z' => {
if match_str(s, pos, ~"UTC") || match_str(s, pos, ~"GMT") {
tm.tm_gmtoff = 0_i32;
tm.tm_zone = ~"UTC";
Ok(pos + 3u)
} else {
// It's odd, but to maintain compatibility with c's
// strptime we ignore the timezone.
let mut pos = pos;
let len = str::len(s);
while pos < len {
let range = str::char_range_at(s, pos);
pos = range.next;
if range.ch == ' ' { break; }
}
Ok(pos)
}
}
'z' => {
let range = str::char_range_at(s, pos);
if range.ch == '+' || range.ch == '-' {
match match_digits(s, range.next, 4u, false) {
Some(item) => {
let (v, pos) = item;
if v == 0_i32 {
tm.tm_gmtoff = 0_i32;
tm.tm_zone = ~"UTC";
}
Ok(pos)
}
None => Err(~"Invalid zone offset")
}
} else {
Err(~"Invalid zone offset")
}
}
'%' => parse_char(s, pos, '%'),
ch => {
Err(fmt!("unknown formatting type: %?", str::from_char(ch)))
}
}
}
do io::with_str_reader(str::from_slice(format)) |rdr| {
let mut tm = Tm {
tm_sec: 0_i32,
tm_min: 0_i32,
tm_hour: 0_i32,
tm_mday: 0_i32,
tm_mon: 0_i32,
tm_year: 0_i32,
tm_wday: 0_i32,
tm_yday: 0_i32,
tm_isdst: 0_i32,
tm_gmtoff: 0_i32,
tm_zone: ~"",
tm_nsec: 0_i32,
};
let mut pos = 0u;
let len = str::len(s);
let mut result = Err(~"Invalid time");
while !rdr.eof() && pos < len {
let range = str::char_range_at(s, pos);
let ch = range.ch;
let next = range.next;
match rdr.read_char() {
'%' => {
match parse_type(s, pos, rdr.read_char(), &mut tm) {
Ok(next) => pos = next,
Err(e) => { result = Err(e); break; }
}
},
c => {
if c != ch { break }
pos = next;
}
}
}
if pos == len && rdr.eof() {
Ok(Tm {
tm_sec: tm.tm_sec,
tm_min: tm.tm_min,
tm_hour: tm.tm_hour,
tm_mday: tm.tm_mday,
tm_mon: tm.tm_mon,
tm_year: tm.tm_year,
tm_wday: tm.tm_wday,
tm_yday: tm.tm_yday,
tm_isdst: tm.tm_isdst,
tm_gmtoff: tm.tm_gmtoff,
tm_zone: copy tm.tm_zone,
tm_nsec: tm.tm_nsec,
})
} else { result }
}
}
priv fn do_strftime(format: &str, tm: &Tm) -> ~str {
fn parse_type(ch: char, tm: &Tm) -> ~str {
//FIXME (#2350): Implement missing types.
let die = || fmt!("strftime: can't understand this format %c ", ch);
match ch {
'A' => match tm.tm_wday as int {
0 => ~"Sunday",
1 => ~"Monday",
2 => ~"Tuesday",
3 => ~"Wednesday",
4 => ~"Thursday",
5 => ~"Friday",
6 => ~"Saturday",
_ => die()
},
'a' => match tm.tm_wday as int {
0 => ~"Sun",
1 => ~"Mon",
2 => ~"Tue",
3 => ~"Wed",
4 => ~"Thu",
5 => ~"Fri",
6 => ~"Sat",
_ => die()
},
'B' => match tm.tm_mon as int {
0 => ~"January",
1 => ~"February",
2 => ~"March",
3 => ~"April",
4 => ~"May",
5 => ~"June",
6 => ~"July",
7 => ~"August",
8 => ~"September",
9 => ~"October",
10 => ~"November",
11 => ~"December",
_ => die()
},
'b' | 'h' => match tm.tm_mon as int {
0 => ~"Jan",
1 => ~"Feb",
2 => ~"Mar",
3 => ~"Apr",
4 => ~"May",
5 => ~"Jun",
6 => ~"Jul",
7 => ~"Aug",
8 => ~"Sep",
9 => ~"Oct",
10 => ~"Nov",
11 => ~"Dec",
_ => die()
},
'C' => fmt!("%02d", (tm.tm_year as int + 1900) / 100),
'c' => {
fmt!("%s %s %s %s %s",
parse_type('a', tm),
parse_type('b', tm),
parse_type('e', tm),
parse_type('T', tm),
parse_type('Y', tm))
}
'D' | 'x' => {
fmt!("%s/%s/%s",
parse_type('m', tm),
parse_type('d', tm),
parse_type('y', tm))
}
'd' => fmt!("%02d", tm.tm_mday as int),
'e' => fmt!("%2d", tm.tm_mday as int),
'F' => {
fmt!("%s-%s-%s",
parse_type('Y', tm),
parse_type('m', tm),
parse_type('d', tm))
}
//'G' {}
//'g' {}
'H' => fmt!("%02d", tm.tm_hour as int),
'I' => {
let mut h = tm.tm_hour as int;
if h == 0 { h = 12 }
if h > 12 { h -= 12 }
fmt!("%02d", h)
}
'j' => fmt!("%03d", tm.tm_yday as int + 1),
'k' => fmt!("%2d", tm.tm_hour as int),
'l' => {
let mut h = tm.tm_hour as int;
if h == 0 { h = 12 }
if h > 12 { h -= 12 }
fmt!("%2d", h)
}
'M' => fmt!("%02d", tm.tm_min as int),
'm' => fmt!("%02d", tm.tm_mon as int + 1),
'n' => ~"\n",
'P' => if (tm.tm_hour as int) < 12 { ~"am" } else { ~"pm" },
'p' => if (tm.tm_hour as int) < 12 { ~"AM" } else { ~"PM" },
'R' => {
fmt!("%s:%s",
parse_type('H', tm),
parse_type('M', tm))
}
'r' => {
fmt!("%s:%s:%s %s",
parse_type('I', tm),
parse_type('M', tm),
parse_type('S', tm),
parse_type('p', tm))
}
'S' => fmt!("%02d", tm.tm_sec as int),
's' => fmt!("%d", tm.to_timespec().sec as int),
'T' | 'X' => {
fmt!("%s:%s:%s",
parse_type('H', tm),
parse_type('M', tm),
parse_type('S', tm))
}
't' => ~"\t",
//'U' {}
'u' => {
let i = tm.tm_wday as int;
int::to_str(if i == 0 { 7 } else { i })
}
//'V' {}
'v' => {
fmt!("%s-%s-%s",
parse_type('e', tm),
parse_type('b', tm),
parse_type('Y', tm))
}
//'W' {}
'w' => int::to_str(tm.tm_wday as int),
//'X' {}
//'x' {}
'Y' => int::to_str(tm.tm_year as int + 1900),
'y' => fmt!("%02d", (tm.tm_year as int + 1900) % 100),
'Z' => copy tm.tm_zone,
'z' => {
let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
let mut m = i32::abs(tm.tm_gmtoff) / 60_i32;
let h = m / 60_i32;
m -= h * 60_i32;
fmt!("%c%02d%02d", sign, h as int, m as int)
}
//'+' {}
'%' => ~"%",
_ => die()
}
}
let mut buf = ~"";
do io::with_str_reader(str::from_slice(format)) |rdr| {
while !rdr.eof() {
match rdr.read_char() {
'%' => buf += parse_type(rdr.read_char(), tm),
ch => str::push_char(&mut buf, ch)
}
}
}
buf
}
#[cfg(test)]
mod tests {
use time::*;
use core::float;
use core::os;
use core::result;
use core::result::{Err, Ok};
use core::str;
use core::vec;
pub fn test_get_time() {
static some_recent_date: i64 = 1325376000i64; // 2012-01-01T00:00:00Z
static some_future_date: i64 = 1577836800i64; // 2020-01-01T00:00:00Z
let tv1 = get_time();
debug!("tv1=%? sec + %? nsec", tv1.sec as uint, tv1.nsec as uint);
fail_unless!(tv1.sec > some_recent_date);
fail_unless!(tv1.nsec < 1000000000i32);
let tv2 = get_time();
debug!("tv2=%? sec + %? nsec", tv2.sec as uint, tv2.nsec as uint);
fail_unless!(tv2.sec >= tv1.sec);
fail_unless!(tv2.sec < some_future_date);
fail_unless!(tv2.nsec < 1000000000i32);
if tv2.sec == tv1.sec {
fail_unless!(tv2.nsec >= tv1.nsec);
}
}
pub fn test_precise_time() {
let s0 = precise_time_s();
let ns1 = precise_time_ns();
debug!("s0=%s sec", float::to_str_digits(s0, 9u));
fail_unless!(s0 > 0.);
let ns0 = (s0 * 1000000000.) as u64;
debug!("ns0=%? ns", ns0);
debug!("ns1=%? ns", ns0);
fail_unless!(ns1 >= ns0);
let ns2 = precise_time_ns();
debug!("ns2=%? ns", ns0);
fail_unless!(ns2 >= ns1);
}
pub fn test_at_utc() {
os::setenv(~"TZ", ~"America/Los_Angeles");
tzset();
let time = ::time::Timespec::new(1234567890, 54321);
let utc = at_utc(time);
fail_unless!(utc.tm_sec == 30_i32);
fail_unless!(utc.tm_min == 31_i32);
fail_unless!(utc.tm_hour == 23_i32);
fail_unless!(utc.tm_mday == 13_i32);
fail_unless!(utc.tm_mon == 1_i32);
fail_unless!(utc.tm_year == 109_i32);
fail_unless!(utc.tm_wday == 5_i32);
fail_unless!(utc.tm_yday == 43_i32);
fail_unless!(utc.tm_isdst == 0_i32);
fail_unless!(utc.tm_gmtoff == 0_i32);
fail_unless!(utc.tm_zone == ~"UTC");
fail_unless!(utc.tm_nsec == 54321_i32);
}
pub fn test_at() {
os::setenv(~"TZ", ~"America/Los_Angeles");
tzset();
let time = ::time::Timespec::new(1234567890, 54321);
let local = at(time);
error!("time_at: %?", local);
fail_unless!(local.tm_sec == 30_i32);
fail_unless!(local.tm_min == 31_i32);
fail_unless!(local.tm_hour == 15_i32);
fail_unless!(local.tm_mday == 13_i32);
fail_unless!(local.tm_mon == 1_i32);
fail_unless!(local.tm_year == 109_i32);
fail_unless!(local.tm_wday == 5_i32);
fail_unless!(local.tm_yday == 43_i32);
fail_unless!(local.tm_isdst == 0_i32);
fail_unless!(local.tm_gmtoff == -28800_i32);
// FIXME (#2350): We should probably standardize on the timezone
// abbreviation.
let zone = &local.tm_zone;
fail_unless!(*zone == ~"PST" || *zone == ~"Pacific Standard Time");
fail_unless!(local.tm_nsec == 54321_i32);
}
pub fn test_to_timespec() {
os::setenv(~"TZ", ~"America/Los_Angeles");
tzset();
let time = ::time::Timespec::new(1234567890, 54321);
let utc = at_utc(time);
fail_unless!(utc.to_timespec() == time);
fail_unless!(utc.to_local().to_timespec() == time);
}
pub fn test_conversions() {
os::setenv(~"TZ", ~"America/Los_Angeles");
tzset();
let time = ::time::Timespec::new(1234567890, 54321);
let utc = at_utc(time);
let local = at(time);
fail_unless!(local.to_local() == local);
fail_unless!(local.to_utc() == utc);
fail_unless!(local.to_utc().to_local() == local);
fail_unless!(utc.to_utc() == utc);
fail_unless!(utc.to_local() == local);
fail_unless!(utc.to_local().to_utc() == utc);
}
pub fn test_strptime() {
os::setenv(~"TZ", ~"America/Los_Angeles");
tzset();
match strptime(~"", ~"") {
Ok(ref tm) => {
fail_unless!(tm.tm_sec == 0_i32);
fail_unless!(tm.tm_min == 0_i32);