-
Notifications
You must be signed in to change notification settings - Fork 175
/
Copy pathdatetime.zig
2086 lines (1845 loc) · 124 KB
/
datetime.zig
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
const std = @import("std");
const Allocator = std.mem.Allocator;
pub const Date = struct {
year: i16,
month: u8,
day: u8,
pub const Format = enum {
iso8601,
rfc3339,
};
pub fn init(year: i16, month: u8, day: u8) !Date {
if (!Date.valid(year, month, day)) {
return error.InvalidDate;
}
return .{
.year = year,
.month = month,
.day = day,
};
}
pub fn valid(year: i16, month: u8, day: u8) bool {
if (month == 0 or month > 12) {
return false;
}
if (day == 0) {
return false;
}
const month_days = [_]u8{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
const max_days = if (month == 2 and (@rem(year, 400) == 0 or (@rem(year, 100) != 0 and @rem(year, 4) == 0))) 29 else month_days[month - 1];
if (day > max_days) {
return false;
}
return true;
}
pub fn parse(input: []const u8, fmt: Format) !Date {
var parser = Parser.init(input);
const date = switch (fmt) {
.rfc3339 => try parser.rfc3339Date(),
.iso8601 => try parser.iso8601Date(),
};
if (parser.unconsumed() != 0) {
return error.InvalidDate;
}
return date;
}
pub fn order(a: Date, b: Date) std.math.Order {
const year_order = std.math.order(a.year, b.year);
if (year_order != .eq) return year_order;
const month_order = std.math.order(a.month, b.month);
if (month_order != .eq) return month_order;
return std.math.order(a.day, b.day);
}
pub fn format(self: Date, comptime _: []const u8, _: std.fmt.FormatOptions, out: anytype) !void {
var buf: [11]u8 = undefined;
const n = writeDate(&buf, self);
try out.writeAll(buf[0..n]);
}
pub fn jsonStringify(self: Date, out: anytype) !void {
// Our goal here isn't to validate the date. It's to write what we have
// in a YYYY-MM-DD format. If the data in Date isn't valid, that's not
// our problem and we don't guarantee any reasonable output in such cases.
// std.fmt.formatInt is difficult to work with. The padding with signs
// doesn't work and it'll always put a + sign given a signed integer with padding
// So, for year, we always feed it an unsigned number (which avoids both issues)
// and prepend the - if we need it.s
var buf: [13]u8 = undefined;
const n = writeDate(buf[1..12], self);
buf[0] = '"';
buf[n + 1] = '"';
try out.print("{s}", .{buf[0 .. n + 2]});
}
pub fn jsonParse(allocator: Allocator, source: anytype, options: anytype) !Date {
_ = options;
switch (try source.nextAlloc(allocator, .alloc_if_needed)) {
inline .string, .allocated_string => |str| return Date.parse(str, .rfc3339) catch return error.InvalidCharacter,
else => return error.UnexpectedToken,
}
}
};
pub const Time = struct {
hour: u8,
min: u8,
sec: u8,
micros: u32,
pub const Format = enum {
rfc3339,
};
pub fn init(hour: u8, min: u8, sec: u8, micros: u32) !Time {
if (!Time.valid(hour, min, sec, micros)) {
return error.InvalidTime;
}
return .{
.hour = hour,
.min = min,
.sec = sec,
.micros = micros,
};
}
pub fn valid(hour: u8, min: u8, sec: u8, micros: u32) bool {
if (hour > 23) {
return false;
}
if (min > 59) {
return false;
}
if (sec > 59) {
return false;
}
if (micros > 999999) {
return false;
}
return true;
}
pub fn parse(input: []const u8, fmt: Format) !Time {
var parser = Parser.init(input);
const time = switch (fmt) {
.rfc3339 => try parser.time(true),
};
if (parser.unconsumed() != 0) {
return error.InvalidTime;
}
return time;
}
pub fn order(a: Time, b: Time) std.math.Order {
const hour_order = std.math.order(a.hour, b.hour);
if (hour_order != .eq) return hour_order;
const min_order = std.math.order(a.min, b.min);
if (min_order != .eq) return min_order;
const sec_order = std.math.order(a.sec, b.sec);
if (sec_order != .eq) return sec_order;
return std.math.order(a.micros, b.micros);
}
pub fn format(self: Time, comptime _: []const u8, _: std.fmt.FormatOptions, out: anytype) !void {
var buf: [15]u8 = undefined;
const n = writeTime(&buf, self);
try out.writeAll(buf[0..n]);
}
pub fn jsonStringify(self: Time, out: anytype) !void {
// Our goal here isn't to validate the time. It's to write what we have
// in a hh:mm:ss.sss format. If the data in Time isn't valid, that's not
// our problem and we don't guarantee any reasonable output in such cases.
var buf: [17]u8 = undefined;
const n = writeTime(buf[1..16], self);
buf[0] = '"';
buf[n + 1] = '"';
try out.print("{s}", .{buf[0 .. n + 2]});
}
pub fn jsonParse(allocator: Allocator, source: anytype, options: anytype) !Time {
_ = options;
switch (try source.nextAlloc(allocator, .alloc_if_needed)) {
inline .string, .allocated_string => |str| return Time.parse(str, .rfc3339) catch return error.InvalidCharacter,
else => return error.UnexpectedToken,
}
}
};
pub const DateTime = struct {
micros: i64,
const MICROSECONDS_IN_A_DAY = 86_400_000_000;
const MICROSECONDS_IN_AN_HOUR = 3_600_000_000;
const MICROSECONDS_IN_A_MIN = 60_000_000;
const MICROSECONDS_IN_A_SEC = 1_000_000;
pub const Format = enum {
rfc822,
rfc3339,
};
pub const TimestampPrecision = enum {
seconds,
milliseconds,
microseconds,
};
pub const TimeUnit = enum {
days,
hours,
minutes,
seconds,
milliseconds,
microseconds,
};
// https://blog.reverberate.org/2020/05/12/optimizing-date-algorithms.html
pub fn initUTC(year: i16, month: u8, day: u8, hour: u8, min: u8, sec: u8, micros: u32) !DateTime {
if (Date.valid(year, month, day) == false) {
return error.InvalidDate;
}
if (Time.valid(hour, min, sec, micros) == false) {
return error.InvalidTime;
}
const year_base = 4800;
const month_adj = @as(i32, @intCast(month)) - 3; // March-based month
const carry: u8 = if (month_adj < 0) 1 else 0;
const adjust: u8 = if (carry == 1) 12 else 0;
const year_adj: i64 = year + year_base - carry;
const month_days = @divTrunc(((month_adj + adjust) * 62719 + 769), 2048);
const leap_days = @divTrunc(year_adj, 4) - @divTrunc(year_adj, 100) + @divTrunc(year_adj, 400);
const date_micros: i64 = (year_adj * 365 + leap_days + month_days + (day - 1) - 2472632) * MICROSECONDS_IN_A_DAY;
const time_micros = (@as(i64, @intCast(hour)) * MICROSECONDS_IN_AN_HOUR) + (@as(i64, @intCast(min)) * MICROSECONDS_IN_A_MIN) + (@as(i64, @intCast(sec)) * MICROSECONDS_IN_A_SEC) + micros;
return fromUnix(date_micros + time_micros, .microseconds);
}
pub fn fromUnix(value: i64, precision: TimestampPrecision) !DateTime {
switch (precision) {
.seconds => {
if (value < -210863520000 or value > 253402300799) {
return error.OutsideJulianPeriod;
}
return .{ .micros = value * 1_000_000 };
},
.milliseconds => {
if (value < -210863520000000 or value > 253402300799999) {
return error.OutsideJulianPeriod;
}
return .{ .micros = value * 1_000 };
},
.microseconds => {
if (value < -210863520000000000 or value > 253402300799999999) {
return error.OutsideJulianPeriod;
}
return .{ .micros = value };
},
}
}
pub fn now() DateTime {
return .{
.micros = std.time.microTimestamp(),
};
}
pub fn parse(input: []const u8, fmt: Format) !DateTime {
switch (fmt) {
.rfc822 => return parseRFC822(input),
.rfc3339 => return parseRFC3339(input),
}
}
pub fn parseRFC822(input: []const u8) !DateTime {
if (input.len < 10) {
return error.InvalidDateTime;
}
var parser = Parser.init(input);
if (input[3] == ',' and input[4] == ' ') {
_ = std.meta.stringToEnum(enum { Mon, Tue, Wed, Thu, Fri, Sat, Sun }, input[0..3]) orelse return error.InvalidDate;
// skip over the "DoW, "
parser.pos = 5;
}
const day = parser.paddedInt(u8, 2) orelse return error.InvalidDate;
if (parser.consumeIf(' ') == false) {
return error.InvalidDate;
}
const month = std.meta.stringToEnum(enum { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }, parser.consumeN(3) orelse return error.InvalidDate) orelse return error.InvalidDate;
if (parser.consumeIf(' ') == false) {
return error.InvalidDate;
}
const year = parser.paddedInt(i16, 4) orelse blk: {
const short_year = parser.paddedInt(u8, 2) orelse return error.InvalidDate;
break :blk if (short_year > 68) 1900 + @as(i16, short_year) else 2000 + @as(i16, short_year);
};
if (parser.consumeIf(' ') == false) {
return error.InvalidDateTime;
}
const tm = try parser.time(false);
if (parser.consumeIf(' ') == false) {
return error.InvalidTime;
}
_ = std.meta.stringToEnum(enum { UT, GMT, Z }, parser.rest()) orelse return error.UnsupportedTimeZone;
return initUTC(year, @intFromEnum(month) + 1, day, tm.hour, tm.min, tm.sec, tm.micros);
}
pub fn parseRFC3339(input: []const u8) !DateTime {
var parser = Parser.init(input);
const dt = try parser.rfc3339Date();
const year = dt.year;
if (year < -4712 or year > 9999) {
return error.OutsideJulianPeriod;
}
// Per the spec, it can be argued thatt 't' and even ' ' should be allowed,
// but certainly not encouraged.
if (parser.consumeIf('T') == false) {
return error.InvalidDateTime;
}
const tm = try parser.time(true);
switch (parser.unconsumed()) {
0 => return error.InvalidDateTime,
1 => if (parser.consumeIf('Z') == false) {
return error.InvalidDateTime;
},
6 => {
const suffix = parser.rest();
if (suffix[0] != '+' and suffix[0] != '-') {
return error.InvalidDateTime;
}
if (std.mem.eql(u8, suffix[1..], "00:00") == false) {
return error.NonUTCNotSupported;
}
},
else => return error.InvalidDateTime,
}
return initUTC(dt.year, dt.month, dt.day, tm.hour, tm.min, tm.sec, tm.micros);
}
pub fn add(dt: DateTime, value: i64, unit: TimeUnit) !DateTime {
const micros = dt.micros;
switch (unit) {
.days => return fromUnix(micros + value * MICROSECONDS_IN_A_DAY, .microseconds),
.hours => return fromUnix(micros + value * MICROSECONDS_IN_AN_HOUR, .microseconds),
.minutes => return fromUnix(micros + value * MICROSECONDS_IN_A_MIN, .microseconds),
.seconds => return fromUnix(micros + value * MICROSECONDS_IN_A_SEC, .microseconds),
.milliseconds => return fromUnix(micros + value * 1_000, .microseconds),
.microseconds => return fromUnix(micros + value, .microseconds),
}
}
pub fn sub(a: DateTime, b: DateTime, precision: TimestampPrecision) i64 {
return a.unix(precision) - b.unix(precision);
}
// https://git.musl-libc.org/cgit/musl/tree/src/time/__secs_to_tm.c?h=v0.9.15
pub fn date(dt: DateTime) Date {
// 2000-03-01 (mod 400 year, immediately after feb29
const leap_epoch = 946684800 + 86400 * (31 + 29);
const days_per_400y = 365 * 400 + 97;
const days_per_100y = 365 * 100 + 24;
const days_per_4y = 365 * 4 + 1;
// march-based
const month_days = [_]u8{ 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29 };
const secs = @divTrunc(dt.micros, 1_000_000) - leap_epoch;
var days = @divTrunc(secs, 86400);
if (@rem(secs, 86400) < 0) {
days -= 1;
}
var qc_cycles = @divTrunc(days, days_per_400y);
var rem_days = @rem(days, days_per_400y);
if (rem_days < 0) {
rem_days += days_per_400y;
qc_cycles -= 1;
}
var c_cycles = @divTrunc(rem_days, days_per_100y);
if (c_cycles == 4) {
c_cycles -= 1;
}
rem_days -= c_cycles * days_per_100y;
var q_cycles = @divTrunc(rem_days, days_per_4y);
if (q_cycles == 25) {
q_cycles -= 1;
}
rem_days -= q_cycles * days_per_4y;
var rem_years = @divTrunc(rem_days, 365);
if (rem_years == 4) {
rem_years -= 1;
}
rem_days -= rem_years * 365;
var year = rem_years + 4 * q_cycles + 100 * c_cycles + 400 * qc_cycles + 2000;
var month: u8 = 0;
while (month_days[month] <= rem_days) : (month += 1) {
rem_days -= month_days[month];
}
month += 2;
if (month >= 12) {
year += 1;
month -= 12;
}
return .{
.year = @intCast(year),
.month = month + 1,
.day = @intCast(rem_days + 1),
};
}
pub fn time(dt: DateTime) Time {
const micros = @mod(dt.micros, MICROSECONDS_IN_A_DAY);
return .{
.hour = @intCast(@divTrunc(micros, MICROSECONDS_IN_AN_HOUR)),
.min = @intCast(@divTrunc(@rem(micros, MICROSECONDS_IN_AN_HOUR), MICROSECONDS_IN_A_MIN)),
.sec = @intCast(@divTrunc(@rem(micros, MICROSECONDS_IN_A_MIN), MICROSECONDS_IN_A_SEC)),
.micros = @intCast(@rem(micros, MICROSECONDS_IN_A_SEC)),
};
}
pub fn unix(self: DateTime, precision: TimestampPrecision) i64 {
const micros = self.micros;
return switch (precision) {
.seconds => @divTrunc(micros, 1_000_000),
.milliseconds => @divTrunc(micros, 1_000),
.microseconds => micros,
};
}
pub fn order(a: DateTime, b: DateTime) std.math.Order {
return std.math.order(a.micros, b.micros);
}
pub fn format(self: DateTime, comptime _: []const u8, _: std.fmt.FormatOptions, out: anytype) !void {
var buf: [28]u8 = undefined;
const n = self.bufWrite(&buf);
try out.writeAll(buf[0..n]);
}
pub fn jsonStringify(self: DateTime, out: anytype) !void {
var buf: [30]u8 = undefined;
buf[0] = '"';
const n = self.bufWrite(buf[1..]);
buf[n + 1] = '"';
try out.print("{s}", .{buf[0 .. n + 2]});
}
pub fn jsonParse(allocator: Allocator, source: anytype, options: anytype) !DateTime {
_ = options;
switch (try source.nextAlloc(allocator, .alloc_if_needed)) {
inline .string, .allocated_string => |str| return parseRFC3339(str) catch return error.InvalidCharacter,
else => return error.UnexpectedToken,
}
}
fn bufWrite(self: DateTime, buf: []u8) usize {
const date_n = writeDate(buf, self.date());
buf[date_n] = 'T';
const time_start = date_n + 1;
const time_n = writeTime(buf[time_start..], self.time());
const time_stop = time_start + time_n;
buf[time_stop] = 'Z';
return time_stop + 1;
}
};
fn writeDate(into: []u8, date: Date) u8 {
var buf: []u8 = undefined;
// cast year to a u16 so it doesn't insert a sign
// we don't want the + sign, ever
// and we don't even want it to insert the - sign, because it screws up
// the padding (we need to do it ourselfs)
const year = date.year;
if (year < 0) {
_ = std.fmt.formatIntBuf(into[1..], @as(u16, @intCast(year * -1)), 10, .lower, .{ .width = 4, .fill = '0' });
into[0] = '-';
buf = into[5..];
} else {
_ = std.fmt.formatIntBuf(into, @as(u16, @intCast(year)), 10, .lower, .{ .width = 4, .fill = '0' });
buf = into[4..];
}
buf[0] = '-';
buf[1..3].* = paddingTwoDigits(date.month);
buf[3] = '-';
buf[4..6].* = paddingTwoDigits(date.day);
// return the length of the string. 10 for positive year, 11 for negative
return if (year < 0) 11 else 10;
}
fn writeTime(into: []u8, time: Time) u8 {
into[0..2].* = paddingTwoDigits(time.hour);
into[2] = ':';
into[3..5].* = paddingTwoDigits(time.min);
into[5] = ':';
into[6..8].* = paddingTwoDigits(time.sec);
const micros = time.micros;
if (micros == 0) {
return 8;
}
if (@rem(micros, 1000) == 0) {
into[8] = '.';
_ = std.fmt.formatIntBuf(into[9..12], micros / 1000, 10, .lower, .{ .width = 3, .fill = '0' });
return 12;
}
into[8] = '.';
_ = std.fmt.formatIntBuf(into[9..15], micros, 10, .lower, .{ .width = 6, .fill = '0' });
return 15;
}
fn paddingTwoDigits(value: usize) [2]u8 {
std.debug.assert(value < 61);
const digits = "0001020304050607080910111213141516171819" ++
"2021222324252627282930313233343536373839" ++
"4041424344454647484950515253545556575859" ++
"60";
return digits[value * 2 ..][0..2].*;
}
const Parser = struct {
input: []const u8,
pos: usize,
fn init(input: []const u8) Parser {
return .{
.pos = 0,
.input = input,
};
}
fn unconsumed(self: *const Parser) usize {
return self.input.len - self.pos;
}
fn rest(self: *const Parser) []const u8 {
return self.input[self.pos..];
}
// unsafe, assumes caller has checked remaining first
fn peek(self: *const Parser) u8 {
return self.input[self.pos];
}
// unsafe, assumes caller has checked remaining first
fn consumeIf(self: *Parser, c: u8) bool {
const pos = self.pos;
if (self.input[pos] != c) {
return false;
}
self.pos = pos + 1;
return true;
}
fn consumeN(self: *Parser, n: usize) ?[]const u8 {
const pos = self.pos;
const end = pos + n;
if (end > self.input.len) {
return null;
}
defer self.pos = end;
return self.input[pos..end];
}
fn nanoseconds(self: *Parser) ?usize {
const start = self.pos;
const input = self.input[start..];
var len = input.len;
if (len == 0) {
return null;
}
var value: usize = 0;
for (input, 0..) |b, i| {
const n = b -% '0'; // wrapping subtraction
if (n > 9) {
len = i;
break;
}
value = value * 10 + n;
}
if (len > 9) {
return null;
}
self.pos = start + len;
return value * std.math.pow(usize, 10, 9 - len);
}
fn paddedInt(self: *Parser, comptime T: type, size: u8) ?T {
const pos = self.pos;
const end = pos + size;
const input = self.input;
if (end > input.len) {
return null;
}
var value: T = 0;
for (input[pos..end]) |b| {
const n = b -% '0'; // wrapping subtraction
if (n > 9) return null;
value = value * 10 + n;
}
self.pos = end;
return value;
}
fn time(self: *Parser, allow_nano: bool) !Time {
const len = self.unconsumed();
if (len < 5) {
return error.InvalidTime;
}
const hour = self.paddedInt(u8, 2) orelse return error.InvalidTime;
if (self.consumeIf(':') == false) {
return error.InvalidTime;
}
const min = self.paddedInt(u8, 2) orelse return error.InvalidTime;
if (len == 5 or self.consumeIf(':') == false) {
return Time.init(hour, min, 0, 0);
}
const sec = self.paddedInt(u8, 2) orelse return error.InvalidTime;
if (allow_nano == false or len == 8 or self.consumeIf('.') == false) {
return Time.init(hour, min, sec, 0);
}
const nanos = self.nanoseconds() orelse return error.InvalidTime;
return Time.init(hour, min, sec, @intCast(nanos / 1000));
}
fn iso8601Date(self: *Parser) !Date {
const len = self.unconsumed();
if (len < 8) {
return error.InvalidDate;
}
const negative = self.consumeIf('-');
const year = self.paddedInt(i16, 4) orelse return error.InvalidDate;
var with_dashes = false;
if (self.consumeIf('-')) {
if (len < 10) {
return error.InvalidDate;
}
with_dashes = true;
}
const month = self.paddedInt(u8, 2) orelse return error.InvalidDate;
if (self.consumeIf('-') == !with_dashes) {
return error.InvalidDate;
}
const day = self.paddedInt(u8, 2) orelse return error.InvalidDate;
return Date.init(if (negative) -year else year, month, day);
}
fn rfc3339Date(self: *Parser) !Date {
const len = self.unconsumed();
if (len < 10) {
return error.InvalidDate;
}
const negative = self.consumeIf('-');
const year = self.paddedInt(i16, 4) orelse return error.InvalidDate;
if (self.consumeIf('-') == false) {
return error.InvalidDate;
}
const month = self.paddedInt(u8, 2) orelse return error.InvalidDate;
if (self.consumeIf('-') == false) {
return error.InvalidDate;
}
const day = self.paddedInt(u8, 2) orelse return error.InvalidDate;
return Date.init(if (negative) -year else year, month, day);
}
};
const testing = @import("testing.zig");
test "Date: json" {
{
// date, positive year
const date = Date{ .year = 2023, .month = 9, .day = 22 };
const out = try std.json.stringifyAlloc(testing.allocator, date, .{});
defer testing.allocator.free(out);
try testing.expectString("\"2023-09-22\"", out);
}
{
// date, negative year
const date = Date{ .year = -4, .month = 12, .day = 3 };
const out = try std.json.stringifyAlloc(testing.allocator, date, .{});
defer testing.allocator.free(out);
try testing.expectString("\"-0004-12-03\"", out);
}
{
// parse
const ts = try std.json.parseFromSlice(TestStruct, testing.allocator, "{\"date\":\"2023-09-22\"}", .{});
defer ts.deinit();
try testing.expectEqual(Date{ .year = 2023, .month = 9, .day = 22 }, ts.value.date.?);
}
}
test "Date: format" {
{
var buf: [20]u8 = undefined;
const out = try std.fmt.bufPrint(&buf, "{s}", .{Date{ .year = 2023, .month = 5, .day = 22 }});
try testing.expectString("2023-05-22", out);
}
{
var buf: [20]u8 = undefined;
const out = try std.fmt.bufPrint(&buf, "{s}", .{Date{ .year = -102, .month = 12, .day = 9 }});
try testing.expectString("-0102-12-09", out);
}
}
test "Date: parse ISO8601" {
{
//valid YYYY-MM-DD
try testing.expectEqual(Date{ .year = 2023, .month = 5, .day = 22 }, try Date.parse("2023-05-22", .iso8601));
try testing.expectEqual(Date{ .year = -2023, .month = 2, .day = 3 }, try Date.parse("-2023-02-03", .iso8601));
try testing.expectEqual(Date{ .year = 1, .month = 2, .day = 3 }, try Date.parse("0001-02-03", .iso8601));
try testing.expectEqual(Date{ .year = -1, .month = 2, .day = 3 }, try Date.parse("-0001-02-03", .iso8601));
}
{
//valid YYYYMMDD
try testing.expectEqual(Date{ .year = 2023, .month = 5, .day = 22 }, try Date.parse("20230522", .iso8601));
try testing.expectEqual(Date{ .year = -2023, .month = 2, .day = 3 }, try Date.parse("-20230203", .iso8601));
try testing.expectEqual(Date{ .year = 1, .month = 2, .day = 3 }, try Date.parse("00010203", .iso8601));
try testing.expectEqual(Date{ .year = -1, .month = 2, .day = 3 }, try Date.parse("-00010203", .iso8601));
}
}
test "Date: parse RFC339" {
{
//valid YYYY-MM-DD
try testing.expectEqual(Date{ .year = 2023, .month = 5, .day = 22 }, try Date.parse("2023-05-22", .rfc3339));
try testing.expectEqual(Date{ .year = -2023, .month = 2, .day = 3 }, try Date.parse("-2023-02-03", .rfc3339));
try testing.expectEqual(Date{ .year = 1, .month = 2, .day = 3 }, try Date.parse("0001-02-03", .rfc3339));
try testing.expectEqual(Date{ .year = -1, .month = 2, .day = 3 }, try Date.parse("-0001-02-03", .rfc3339));
}
{
//valid YYYYMMDD
try testing.expectError(error.InvalidDate, Date.parse("20230522", .rfc3339));
try testing.expectError(error.InvalidDate, Date.parse("-20230203", .rfc3339));
try testing.expectError(error.InvalidDate, Date.parse("00010203", .rfc3339));
try testing.expectError(error.InvalidDate, Date.parse("-00010203", .rfc3339));
}
}
test "Date: parse invalid common" {
for (&[_]Date.Format{ .rfc3339, .iso8601 }) |format| {
{
// invalid format
try testing.expectError(error.InvalidDate, Date.parse("", format));
try testing.expectError(error.InvalidDate, Date.parse("2023/01-02", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-01/02", format));
try testing.expectError(error.InvalidDate, Date.parse("0001-01-01 ", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-1-02", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-01-2", format));
try testing.expectError(error.InvalidDate, Date.parse("9-01-2", format));
try testing.expectError(error.InvalidDate, Date.parse("99-01-2", format));
try testing.expectError(error.InvalidDate, Date.parse("999-01-2", format));
try testing.expectError(error.InvalidDate, Date.parse("-999-01-2", format));
try testing.expectError(error.InvalidDate, Date.parse("-1-01-2", format));
}
{
// invalid month
try testing.expectError(error.InvalidDate, Date.parse("2023-00-22", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-0A-22", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-13-22", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-99-22", format));
try testing.expectError(error.InvalidDate, Date.parse("-2023-00-22", format));
try testing.expectError(error.InvalidDate, Date.parse("-2023-13-22", format));
try testing.expectError(error.InvalidDate, Date.parse("-2023-99-22", format));
}
{
// invalid day
try testing.expectError(error.InvalidDate, Date.parse("2023-01-00", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-01-32", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-02-29", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-03-32", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-04-31", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-05-32", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-06-31", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-07-32", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-08-32", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-09-31", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-10-32", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-11-31", format));
try testing.expectError(error.InvalidDate, Date.parse("2023-12-32", format));
}
{
// valid (max day)
try testing.expectEqual(Date{ .year = 2023, .month = 1, .day = 31 }, try Date.parse("2023-01-31", format));
try testing.expectEqual(Date{ .year = 2023, .month = 2, .day = 28 }, try Date.parse("2023-02-28", format));
try testing.expectEqual(Date{ .year = 2023, .month = 3, .day = 31 }, try Date.parse("2023-03-31", format));
try testing.expectEqual(Date{ .year = 2023, .month = 4, .day = 30 }, try Date.parse("2023-04-30", format));
try testing.expectEqual(Date{ .year = 2023, .month = 5, .day = 31 }, try Date.parse("2023-05-31", format));
try testing.expectEqual(Date{ .year = 2023, .month = 6, .day = 30 }, try Date.parse("2023-06-30", format));
try testing.expectEqual(Date{ .year = 2023, .month = 7, .day = 31 }, try Date.parse("2023-07-31", format));
try testing.expectEqual(Date{ .year = 2023, .month = 8, .day = 31 }, try Date.parse("2023-08-31", format));
try testing.expectEqual(Date{ .year = 2023, .month = 9, .day = 30 }, try Date.parse("2023-09-30", format));
try testing.expectEqual(Date{ .year = 2023, .month = 10, .day = 31 }, try Date.parse("2023-10-31", format));
try testing.expectEqual(Date{ .year = 2023, .month = 11, .day = 30 }, try Date.parse("2023-11-30", format));
try testing.expectEqual(Date{ .year = 2023, .month = 12, .day = 31 }, try Date.parse("2023-12-31", format));
}
{
// leap years
try testing.expectEqual(Date{ .year = 2000, .month = 2, .day = 29 }, try Date.parse("2000-02-29", format));
try testing.expectEqual(Date{ .year = 2400, .month = 2, .day = 29 }, try Date.parse("2400-02-29", format));
try testing.expectEqual(Date{ .year = 2012, .month = 2, .day = 29 }, try Date.parse("2012-02-29", format));
try testing.expectEqual(Date{ .year = 2024, .month = 2, .day = 29 }, try Date.parse("2024-02-29", format));
try testing.expectError(error.InvalidDate, Date.parse("2000-02-30", format));
try testing.expectError(error.InvalidDate, Date.parse("2400-02-30", format));
try testing.expectError(error.InvalidDate, Date.parse("2012-02-30", format));
try testing.expectError(error.InvalidDate, Date.parse("2024-02-30", format));
try testing.expectError(error.InvalidDate, Date.parse("2100-02-29", format));
try testing.expectError(error.InvalidDate, Date.parse("2200-02-29", format));
}
}
}
test "Date: order" {
{
const a = Date{ .year = 2023, .month = 5, .day = 22 };
const b = Date{ .year = 2023, .month = 5, .day = 22 };
try testing.expectEqual(std.math.Order.eq, a.order(b));
}
{
const a = Date{ .year = 2023, .month = 5, .day = 22 };
const b = Date{ .year = 2022, .month = 5, .day = 22 };
try testing.expectEqual(std.math.Order.gt, a.order(b));
try testing.expectEqual(std.math.Order.lt, b.order(a));
}
{
const a = Date{ .year = 2022, .month = 6, .day = 22 };
const b = Date{ .year = 2022, .month = 5, .day = 22 };
try testing.expectEqual(std.math.Order.gt, a.order(b));
try testing.expectEqual(std.math.Order.lt, b.order(a));
}
{
const a = Date{ .year = 2023, .month = 5, .day = 23 };
const b = Date{ .year = 2022, .month = 5, .day = 22 };
try testing.expectEqual(std.math.Order.gt, a.order(b));
try testing.expectEqual(std.math.Order.lt, b.order(a));
}
}
test "Time: json" {
{
// time no fraction
const time = Time{ .hour = 23, .min = 59, .sec = 2, .micros = 0 };
const out = try std.json.stringifyAlloc(testing.allocator, time, .{});
defer testing.allocator.free(out);
try testing.expectString("\"23:59:02\"", out);
}
{
// time, milliseconds only
const time = Time{ .hour = 7, .min = 9, .sec = 32, .micros = 202000 };
const out = try std.json.stringifyAlloc(testing.allocator, time, .{});
defer testing.allocator.free(out);
try testing.expectString("\"07:09:32.202\"", out);
}
{
// time, micros
const time = Time{ .hour = 1, .min = 2, .sec = 3, .micros = 123456 };
const out = try std.json.stringifyAlloc(testing.allocator, time, .{});
defer testing.allocator.free(out);
try testing.expectString("\"01:02:03.123456\"", out);
}
{
// parse
const ts = try std.json.parseFromSlice(TestStruct, testing.allocator, "{\"time\":\"01:02:03.123456\"}", .{});
defer ts.deinit();
try testing.expectEqual(Time{ .hour = 1, .min = 2, .sec = 3, .micros = 123456 }, ts.value.time.?);
}
}
test "Time: format" {
{
var buf: [20]u8 = undefined;
const out = try std.fmt.bufPrint(&buf, "{s}", .{Time{ .hour = 23, .min = 59, .sec = 59, .micros = 0 }});
try testing.expectString("23:59:59", out);
}
{
var buf: [20]u8 = undefined;
const out = try std.fmt.bufPrint(&buf, "{s}", .{Time{ .hour = 8, .min = 9, .sec = 10, .micros = 12 }});
try testing.expectString("08:09:10.000012", out);
}
{
var buf: [20]u8 = undefined;
const out = try std.fmt.bufPrint(&buf, "{s}", .{Time{ .hour = 8, .min = 9, .sec = 10, .micros = 123 }});
try testing.expectString("08:09:10.000123", out);
}
{
var buf: [20]u8 = undefined;
const out = try std.fmt.bufPrint(&buf, "{s}", .{Time{ .hour = 8, .min = 9, .sec = 10, .micros = 1234 }});
try testing.expectString("08:09:10.001234", out);
}
{
var buf: [20]u8 = undefined;
const out = try std.fmt.bufPrint(&buf, "{s}", .{Time{ .hour = 8, .min = 9, .sec = 10, .micros = 12345 }});
try testing.expectString("08:09:10.012345", out);
}
{
var buf: [20]u8 = undefined;
const out = try std.fmt.bufPrint(&buf, "{s}", .{Time{ .hour = 8, .min = 9, .sec = 10, .micros = 123456 }});
try testing.expectString("08:09:10.123456", out);
}
}
test "Time: parse" {
{
//valid
try testing.expectEqual(Time{ .hour = 9, .min = 8, .sec = 0, .micros = 0 }, try Time.parse("09:08", .rfc3339));
try testing.expectEqual(Time{ .hour = 9, .min = 8, .sec = 5, .micros = 123000 }, try Time.parse("09:08:05.123", .rfc3339));
try testing.expectEqual(Time{ .hour = 23, .min = 59, .sec = 59, .micros = 0 }, try Time.parse("23:59:59", .rfc3339));
try testing.expectEqual(Time{ .hour = 0, .min = 0, .sec = 0, .micros = 0 }, try Time.parse("00:00:00", .rfc3339));
try testing.expectEqual(Time{ .hour = 0, .min = 0, .sec = 0, .micros = 0 }, try Time.parse("00:00:00.0", .rfc3339));
try testing.expectEqual(Time{ .hour = 0, .min = 0, .sec = 0, .micros = 1 }, try Time.parse("00:00:00.000001", .rfc3339));
try testing.expectEqual(Time{ .hour = 0, .min = 0, .sec = 0, .micros = 12 }, try Time.parse("00:00:00.000012", .rfc3339));
try testing.expectEqual(Time{ .hour = 0, .min = 0, .sec = 0, .micros = 123 }, try Time.parse("00:00:00.000123", .rfc3339));
try testing.expectEqual(Time{ .hour = 0, .min = 0, .sec = 0, .micros = 1234 }, try Time.parse("00:00:00.001234", .rfc3339));
try testing.expectEqual(Time{ .hour = 0, .min = 0, .sec = 0, .micros = 12345 }, try Time.parse("00:00:00.012345", .rfc3339));
try testing.expectEqual(Time{ .hour = 0, .min = 0, .sec = 0, .micros = 123456 }, try Time.parse("00:00:00.123456", .rfc3339));
try testing.expectEqual(Time{ .hour = 0, .min = 0, .sec = 0, .micros = 123456 }, try Time.parse("00:00:00.1234567", .rfc3339));
try testing.expectEqual(Time{ .hour = 0, .min = 0, .sec = 0, .micros = 123456 }, try Time.parse("00:00:00.12345678", .rfc3339));
try testing.expectEqual(Time{ .hour = 0, .min = 0, .sec = 0, .micros = 123456 }, try Time.parse("00:00:00.123456789", .rfc3339));
}