Repository navigation
Expand file tree
/
Copy pathtime.zig
More file actions
835 lines (726 loc) · 25 KB
/
Copy pathtime.zig
File metadata and controls
835 lines (726 loc) · 25 KB
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
const std = @import("std");
const builtin = @import("builtin");
const string = []const u8;
const extras = @import("extras");
const nio = @import("nio");
const sys = @import("sys").impl;
const time = @This();
pub const Zone = @import("./zone.zig").Zone;
/// all fields are 0-indexed unless otherwise specified
pub const DateTime = struct {
ms: u16,
seconds: u8,
minutes: u8,
hours: u8,
days: u8,
months: u8,
years: u16,
/// minutes
z_offset: i16,
pub fn initUnixMs(unix: u64) DateTime {
return epoch_unix.addMs(unix);
}
pub fn initUnix(unix: u64) DateTime {
return epoch_unix.addSecs(unix);
}
pub fn initOffsetUnix(unix: u64, offset: i16) DateTime {
var result: DateTime = .initUnix(extras.safeAdd(unix, (@as(i32, offset) * s_per_min)));
result.z_offset = offset;
return result;
}
pub fn initOffsetUnixMs(unix: u64, offset: i16) DateTime {
var result: DateTime = .initUnixMs(extras.safeAdd(unix, (@as(i32, offset) * ms_per_min)));
result.z_offset = offset;
return result;
}
pub fn init(year: u16, month: u16, day: u16, hr: u16, min: u16, sec: u16, ms: u16) DateTime {
return epoch
.addYears(year - 1) // AD starts in year 1
.addMonths(month)
.addDays(day)
.addHours(hr)
.addMins(min)
.addSecs(sec)
.addMs(ms);
}
pub fn now() DateTime {
return initUnixMs(@intCast(milliTimestamp()));
}
pub fn nowAtOffset(offset: i16) DateTime {
return initOffsetUnixMs(@intCast(milliTimestamp()), offset);
}
pub const epoch = DateTime{
.ms = 0,
.seconds = 0,
.minutes = 0,
.hours = 0,
.days = 0,
.months = 0,
.years = 0,
.z_offset = 0,
};
pub const epoch_unix = blk: {
@setEvalBranchQuota(std.math.maxInt(u32));
break :blk epoch.addYears(1969);
};
pub fn toRFCString(self: DateTime) [25]u8 {
// "2021-10-21 23:20:30+00:00"
var result: [25]u8 = @splat(' ');
var fbs: nio.FixedBufferStream([]u8) = .init(&result);
self.formatFmt("YYYY-MM-DD HH:mm:ss", &fbs) catch unreachable;
fbs = .init(result[19..]);
self.formatFmt("Z", &fbs) catch unreachable;
return result;
}
pub fn toISOString(self: DateTime) [25]u8 {
// "2021-10-21T23:20:30+00:00"
var result = self.toRFCString();
result[10] = 'T';
return result;
}
pub fn eql(self: DateTime, other: DateTime) bool {
return self.ms == other.ms and
self.seconds == other.seconds and
self.minutes == other.minutes and
self.hours == other.hours and
self.days == other.days and
self.months == other.months and
self.years == other.years and
self.z_offset == other.z_offset;
}
pub fn addMs(self: DateTime, count: u64) DateTime {
if (count == 0) return self;
var result = self;
result.ms += @intCast(count % 1000);
return result.addSecs(count / 1000);
}
pub fn addSecs(self: DateTime, count: u64) DateTime {
if (count == 0) return self;
var result = self;
result.seconds += @intCast(count % 60);
return result.addMins(count / 60);
}
pub fn addMins(self: DateTime, count: u64) DateTime {
if (count == 0) return self;
var result = self;
result.minutes += @intCast(count % 60);
return result.addHours(count / 60);
}
pub fn addHours(self: DateTime, count: u64) DateTime {
if (count == 0) return self;
var result = self;
result.hours += @intCast(count % 24);
return result.addDays(count / 24);
}
pub fn addDays(self: DateTime, count: u64) DateTime {
if (count == 0) return self;
var result = self;
var input = count;
while (true) {
const year_len = result.daysThisYear();
if (input >= year_len) {
result.years += 1;
input -= year_len;
continue;
}
break;
}
while (true) {
const month_len = result.daysThisMonth();
if (input >= month_len) {
result.months += 1;
input -= month_len;
if (result.months == 12) {
result.years += 1;
result.months = 0;
}
continue;
}
break;
}
{
const month_len = result.daysThisMonth();
if (result.days + input > month_len) {
const left = month_len -| result.days;
input -= left;
result.months += 1;
result.days = 0;
}
if (result.months == 12) {
result.years += 1;
result.months = 0;
}
result.days += @intCast(input);
if (result.days == result.daysThisMonth()) {
result.months += 1;
result.days = 0;
}
if (result.months == 12) {
result.years += 1;
result.months = 0;
}
}
std.debug.assert(result.ms < 1000);
std.debug.assert(result.seconds < 60);
std.debug.assert(result.minutes < 60);
std.debug.assert(result.hours < 24);
std.debug.assert(result.days < result.daysThisMonth());
std.debug.assert(result.months < 12);
return result;
}
pub fn addWeeks(self: DateTime, count: u64) DateTime {
if (count == 0) return self;
return self.addDays(7).addWeeks(count - 1);
}
pub fn addMonths(self: DateTime, count: u64) DateTime {
if (count == 0) return self;
var result = self;
var input = count;
result.years += @intCast(input / 12);
input %= 12;
result.months += @intCast(input);
if (result.months >= 12) result.years += 1;
result.months %= 12;
result.days = @min(result.days, result.daysInMonth(result.months) - 1);
return result;
}
pub fn addYears(self: DateTime, count: u64) DateTime {
var result = self;
for (0..count) |_| {
result = result.addDays(result.daysThisYear());
}
return result;
}
pub fn addQuarters(self: DateTime, count: u64) DateTime {
if (count == 0) return self;
return self.addMonths(3).addQuarters(count - 1);
}
pub fn isLeapYear(self: DateTime) bool {
return time.isLeapYear(self.years + 1);
}
pub fn daysThisYear(self: DateTime) u16 {
return time.daysInYear(self.years + 1);
}
pub fn daysThisMonth(self: DateTime) u16 {
return self.daysInMonth(self.months);
}
fn daysInMonth(self: DateTime, month: u16) u16 {
return time.daysInMonth(self.years + 1, month);
}
pub fn dayOfThisYear(self: DateTime) u16 {
var ret: u16 = 0;
for (0..self.months) |item| {
ret += self.daysInMonth(@intCast(item));
}
ret += self.days;
return ret;
}
pub fn weekOfThisYear(self: DateTime, weekstart: WeekDay) u16 {
var remaining = self.dayOfThisYear();
var current = DateTime.epoch.addYears(self.years).weekday();
var result: u16 = 1;
while (remaining > 0) {
current = current.next();
remaining -= 1;
if (current == weekstart) {
result += 1;
break;
}
}
if (remaining > 0) {
result += @intCast(remaining / 7);
}
return result;
}
pub fn toUnix(self: DateTime) u64 {
return self.toUnixMilli() / 1000;
}
pub fn toUnixMilli(self: DateTime) u64 {
var res: u64 = 0;
res += self.ms;
res += @as(u64, self.seconds) * ms_per_s;
res += @as(u64, self.minutes) * ms_per_min;
res += @as(u64, self.hours) * ms_per_hour;
res += self.daysSinceUnixEpoch() * ms_per_day;
res = extras.safeAdd(res, @as(i32, -self.z_offset) * ms_per_min);
return res;
}
pub fn to_timespec(self: DateTime) sys.struct_timespec {
return .{
.sec = @intCast(self.toUnix()),
.nsec = @as(isize, self.ms) * ns_per_ms,
};
}
fn daysSinceUnixEpoch(self: DateTime) u64 {
var res: u64 = 0;
res += self.days;
for (epoch_unix.years + 1..self.years + 1) |i| res += time.daysInYear(@intCast(i));
for (0..self.months) |i| res += self.daysInMonth(@intCast(i));
return res;
}
/// the timezone offset is stored as a signed amount of minutes.
/// the structure of the return value is .{ sign, hrs, mins }.
/// 'sign' will be either '+' or '-'
pub fn tz_parts(self: DateTime) struct { u8, u16, u16 } {
const o = self.z_offset;
const a = @abs(o);
return .{
if (o < 0) '-' else '+',
a / 60,
a % 60,
};
}
/// fmt is based on https://momentjs.com/docs/#/displaying/format/
pub fn formatFmt(self: DateTime, comptime fmt: string, writer: anytype) !void {
if (fmt.len == 0) @compileError("DateTime: format string can't be empty");
@setEvalBranchQuota(100000);
comptime var s = 0;
comptime var e = 0;
comptime var next: ?FormatSeq = null;
inline for (fmt, 0..) |c, i| {
e = i + 1;
if (comptime std.meta.stringToEnum(FormatSeq, fmt[s..e])) |tag| {
next = tag;
if (i < fmt.len - 1) continue;
}
if (next) |tag| {
switch (tag) {
.MM => try writer.print("{:0>2}", .{self.months + 1}),
.M => try writer.print("{}", .{self.months + 1}),
.Mo => try printOrdinal(writer, self.months + 1),
.MMM => try printLongName(writer, self.months, &[_]string{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }),
.MMMM => try printLongName(writer, self.months, &[_]string{ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }),
.Q => try writer.print("{}", .{self.months / 3 + 1}),
.Qo => try printOrdinal(writer, self.months / 3 + 1),
.D => try writer.print("{}", .{self.days + 1}),
.Do => try printOrdinal(writer, self.days + 1),
.DD => try writer.print("{:0>2}", .{self.days + 1}),
.DDD => try writer.print("{}", .{self.dayOfThisYear() + 1}),
.DDDo => try printOrdinal(writer, self.dayOfThisYear() + 1),
.DDDD => try writer.print("{:0>3}", .{self.dayOfThisYear() + 1}),
.d => try writer.print("{}", .{@backingInt(self.weekday())}),
.do => try printOrdinal(writer, @backingInt(self.weekday())),
.dd => try writer.writeAll(@tagName(self.weekday())[0..2]),
.ddd => try writer.writeAll(@tagName(self.weekday())),
.dddd => try printLongName(writer, @backingInt(self.weekday()), &[_]string{ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }),
.e => try writer.print("{}", .{@backingInt(self.weekday())}),
.E => try writer.print("{}", .{@backingInt(self.weekday()) + 1}),
.w => try writer.print("{}", .{self.weekOfThisYear(.Sun)}),
.wo => try printOrdinal(writer, self.weekOfThisYear(.Sun)),
.ww => try writer.print("{:0>2}", .{self.weekOfThisYear(.Sun)}),
.W => try writer.print("{}", .{self.weekOfThisYear(.Mon)}),
.Wo => try printOrdinal(writer, self.weekOfThisYear(.Mon)),
.WW => try writer.print("{:0>2}", .{self.weekOfThisYear(.Mon)}),
.Y => try writer.print("{}", .{(self.years + 1) + 10000}),
.YY => try writer.print("{:0>2}", .{(self.years + 1) % 100}),
.YYY => try writer.print("{}", .{(self.years + 1)}),
.YYYY => try writer.print("{:0>4}", .{(self.years + 1)}),
.N => try writer.writeAll(@tagName(self.era())),
.NN => try writer.writeAll("Anno Domini"),
.A => try printLongName(writer, self.hours / 12, &[_]string{ "AM", "PM" }),
.a => try printLongName(writer, self.hours / 12, &[_]string{ "am", "pm" }),
.H => try writer.print("{}", .{self.hours}),
.HH => try writer.print("{:0>2}", .{self.hours}),
.h => try writer.print("{}", .{wrap(self.hours, 12)}),
.hh => try writer.print("{:0>2}", .{wrap(self.hours, 12)}),
.k => try writer.print("{}", .{wrap(self.hours, 24)}),
.kk => try writer.print("{:0>2}", .{wrap(self.hours, 24)}),
.m => try writer.print("{}", .{self.minutes}),
.mm => try writer.print("{:0>2}", .{self.minutes}),
.s => try writer.print("{}", .{self.seconds}),
.ss => try writer.print("{:0>2}", .{self.seconds}),
.S => try writer.print("{}", .{self.ms / 100}),
.SS => try writer.print("{:0>2}", .{self.ms / 10}),
.SSS => try writer.print("{:0>3}", .{self.ms}),
.Z => try writer.print("{c}{:0>2}:{:0>2}", self.tz_parts()),
.ZZ => try writer.print("{c}{:0>2}{:0>2}", self.tz_parts()),
.x => try writer.print("{}", .{self.toUnixMilli()}),
.X => try writer.print("{}", .{self.toUnix()}),
}
next = null;
s = i;
}
switch (c) {
',',
' ',
':',
'-',
'.',
'T',
'/',
=> {
try writer.writeAll(&.{c});
s = i + 1;
continue;
},
else => {},
}
}
}
pub fn formatAlloc(self: DateTime, alloc: std.mem.Allocator, comptime fmt: string) !string {
var list = std.Io.Writer.Allocating.init(alloc);
defer list.deinit();
try self.formatFmt(fmt, &list.writer);
return list.toOwnedSlice();
}
pub fn formatStatic(self: DateTime, comptime fmt: string) [fmtLen(fmt):0]u8 {
var buf: [fmtLen(fmt):0]u8 = @splat(0);
var w: nio.FixedBufferStream([]u8) = .init(&buf);
self.formatFmt(fmt, &w) catch unreachable;
return buf;
}
pub fn fmtLen(fmt: string) usize {
var result: usize = 0;
@setEvalBranchQuota(1000000);
var s = 0;
var e = 0;
var next: ?FormatSeq = null;
inline for (fmt, 0..) |c, i| {
e = i + 1;
if (comptime std.meta.stringToEnum(FormatSeq, fmt[s..e])) |tag| {
next = tag;
if (i < fmt.len - 1) continue;
}
if (next) |tag| {
result += tag.len().?;
next = null;
s = i;
}
switch (c) {
',',
' ',
':',
'-',
'.',
'T',
'/',
=> {
result += 1;
s = i + 1;
continue;
},
else => {},
}
}
return result;
}
const FormatSeq = enum {
M, // 1 2 ... 11 12
Mo, // 1st 2nd ... 11th 12th
MM, // 01 02 ... 11 12
MMM, // Jan Feb ... Nov Dec
MMMM, // January February ... November December
Q, // 1 2 3 4
Qo, // 1st 2nd 3rd 4th
D, // 1 2 ... 30 31
Do, // 1st 2nd ... 30th 31st
DD, // 01 02 ... 30 31
DDD, // 1 2 ... 364 365
DDDo, // 1st 2nd ... 364th 365th
DDDD, // 001 002 ... 364 365
d, // 0 1 ... 5 6
do, // 0th 1st ... 5th 6th
dd, // Su Mo ... Fr Sa
ddd, // Sun Mon ... Fri Sat
dddd, // Sunday Monday ... Friday Saturday
e, // 0 1 ... 5 6 (locale)
E, // 1 2 ... 6 7 (ISO)
w, // 1 2 ... 52 53
wo, // 1st 2nd ... 52nd 53rd
ww, // 01 02 ... 52 53
W, // 1 2 ... 52 53
Wo, // 1st 2nd ... 52nd 53rd
WW, // 01 02 ... 52 53
Y, // 11970 11971 ... 19999 20000 20001 (Holocene calendar)
YY, // 70 71 ... 29 30
YYY, // 1 2 ... 1970 1971 ... 2029 2030
YYYY, // 0001 0002 ... 1970 1971 ... 2029 2030
N, // BC AD
NN, // Before Christ ... Anno Domini
A, // AM PM
a, // am pm
H, // 0 1 ... 22 23
HH, // 00 01 ... 22 23
h, // 1 2 ... 11 12
hh, // 01 02 ... 11 12
k, // 1 2 ... 23 24
kk, // 01 02 ... 23 24
m, // 0 1 ... 58 59
mm, // 00 01 ... 58 59
s, // 0 1 ... 58 59
ss, // 00 01 ... 58 59
S, // 0 1 ... 8 9 (second fraction)
SS, // 00 01 ... 98 99
SSS, // 000 001 ... 998 999
Z, // -07:00 -06:00 ... +06:00 +07:00
ZZ, // -0700 -0600 ... +0600 +0700
x, // unix milli
X, // unix
/// the length of the output of a tag or null if the length is variable
pub fn len(tag: FormatSeq) ?usize {
return switch (tag) {
.MM => 2,
.M => null,
.Mo => null,
.MMM => 3,
.MMMM => null,
.Q => null,
.Qo => null,
.D => null,
.Do => null,
.DD => 2,
.DDD => null,
.DDDo => null,
.DDDD => 3,
.d => 1,
.do => null,
.dd => 2,
.ddd => 3,
.dddd => null,
.e => 1,
.E => 1,
.w => null,
.wo => null,
.ww => 2,
.W => null,
.Wo => null,
.WW => 2,
.Y => null,
.YY => 2,
.YYY => null,
.YYYY => 4,
.N => 2,
.NN => null,
.A => 2,
.a => 2,
.H => null,
.HH => 2,
.h => null,
.hh => 2,
.k => null,
.kk => 2,
.m => null,
.mm => 2,
.s => null,
.ss => 2,
.S => null,
.SS => 2,
.SSS => 3,
.Z => 5,
.ZZ => 5,
.x => null,
.X => null,
};
}
};
pub fn since(self: DateTime, other: DateTime) Duration {
return Duration{
.ms = @as(i64, @intCast(self.toUnixMilli())) - @as(i64, @intCast(other.toUnixMilli())),
};
}
pub fn era(self: DateTime) Era {
if (self.years >= 0) return .AD;
@compileError("TODO");
}
pub fn weekday(self: DateTime) WeekDay {
var result = WeekDay.Mon; // weekday of .unix
var i = blk: {
var res: u64 = 0;
res += self.days;
for (0..self.years) |i| res += time.daysInYear(@intCast(i + 1));
for (0..self.months) |i| res += self.daysInMonth(@intCast(i));
break :blk res % 7;
};
while (i > 0) : (i -= 1) {
result = result.next();
}
return result;
}
pub fn stringifyJson(self: DateTime, writer: anytype, options: std.json.Stringify.Options, json: type) !void {
return json.stringify(writer, &self.toISOString(), options);
}
pub fn normal(self: DateTime) DateTime {
return .initUnixMs(self.toUnixMilli());
}
};
pub const PlainYearMonth = struct {
years: u16,
months: u8,
};
pub const PlainMonthDay = struct {
months: u8,
days: u8,
};
pub const PlainDate = struct {
years: u16,
months: u8,
days: u8,
};
pub const PlainTime = struct {
hours: u8,
minutes: u8,
seconds: u8,
ms: u16,
};
pub const PlainDateTime = struct {
years: u16,
months: u8,
days: u8,
hours: u8,
minutes: u8,
seconds: u8,
ms: u16,
};
pub const format = struct {
pub const LT = "h:mm A";
pub const LTS = "h:mm:ss A";
pub const L = "MM/DD/YYYY";
pub const l = "M/D/YYY";
pub const LL = "MMMM D, YYYY";
pub const ll = "MMM D, YYY";
pub const LLL = LL ++ " " ++ LT;
pub const lll = ll ++ " " ++ LT;
pub const LLLL = "dddd, " ++ LLL;
pub const llll = "ddd, " ++ lll;
};
pub const WeekDay = enum {
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat,
pub fn next(self: WeekDay) WeekDay {
return switch (self) {
.Sun => .Mon,
.Mon => .Tue,
.Tue => .Wed,
.Wed => .Thu,
.Thu => .Fri,
.Fri => .Sat,
.Sat => .Sun,
};
}
pub fn jsonStringify(self: @This(), json_stream: anytype) !void {
try json_stream.write(@tagName(self));
}
};
pub const Era = enum {
// BC,
AD,
pub fn jsonStringify(self: @This(), json_stream: anytype) !void {
try json_stream.write(@tagName(self));
}
};
// https://hueffner.de/falk/blog/a-leap-year-check-in-three-instructions.html
pub fn isLeapYear(year: u16) bool {
if (year % 4 != 0) return false;
if (year % 25 != 0) return true;
if (year % 16 == 0) return true;
return false;
}
pub fn daysInYear(year: u16) u16 {
return if (isLeapYear(year)) 366 else 365;
}
fn daysInMonth(year: u16, month: u16) u16 {
const norm = [12]u16{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
const leap = [12]u16{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
const month_days = if (!isLeapYear(year)) norm else leap;
return month_days[month];
}
fn printOrdinal(writer: anytype, num: u16) !void {
try writer.print("{}", .{num});
try writer.writeAll(switch (num) {
1 => "st",
2 => "nd",
3 => "rd",
else => "th",
});
}
fn printLongName(writer: anytype, index: u16, names: []const string) !void {
try writer.writeAll(names[index]);
}
fn wrap(val: u16, at: u16) u16 {
const tmp = val % at;
return if (tmp == 0) at else tmp;
}
pub const Duration = struct {
ms: i64,
};
// Divisions of a nanosecond.
pub const ns_per_us = 1000;
pub const ns_per_ms = 1000 * ns_per_us;
pub const ns_per_s = 1000 * ns_per_ms;
pub const ns_per_min = 60 * ns_per_s;
pub const ns_per_hour = 60 * ns_per_min;
pub const ns_per_day = 24 * ns_per_hour;
pub const ns_per_week = 7 * ns_per_day;
// Divisions of a microsecond.
pub const us_per_ms = 1000;
pub const us_per_s = 1000 * us_per_ms;
pub const us_per_min = 60 * us_per_s;
pub const us_per_hour = 60 * us_per_min;
pub const us_per_day = 24 * us_per_hour;
pub const us_per_week = 7 * us_per_day;
// Divisions of a millisecond.
pub const ms_per_s = 1000;
pub const ms_per_min = 60 * ms_per_s;
pub const ms_per_hour = 60 * ms_per_min;
pub const ms_per_day = 24 * ms_per_hour;
pub const ms_per_week = 7 * ms_per_day;
// Divisions of a second.
pub const s_per_min = 60;
pub const s_per_hour = s_per_min * 60;
pub const s_per_day = s_per_hour * 24;
pub const s_per_week = s_per_day * 7;
pub fn nanoTimestamp() i128 {
const ts = sys.clock_gettime(sys.CLOCK.REALTIME) catch return 0;
var result: i128 = 0;
result += ts.sec;
result *= ns_per_s;
result += ts.nsec;
return result;
}
pub fn microTimestamp() i64 {
return @intCast(@divFloor(nanoTimestamp(), ns_per_us));
}
pub fn milliTimestamp() i64 {
return @intCast(@divFloor(nanoTimestamp(), ns_per_ms));
}
pub fn timestamp() i64 {
return @intCast(@divFloor(nanoTimestamp(), ns_per_s));
}
pub const Instant = struct {
timestamp_ns: u64,
pub fn now() !Instant {
const ts = try sys.clock_gettime(sys.CLOCK.REALTIME);
return .{ .timestamp_ns = @as(u64, @intCast(ts.nsec)) + @as(u64, @intCast(ts.sec)) * ns_per_s };
}
pub fn since(self: Instant, earlier: Instant) u64 {
return self.timestamp_ns - earlier.timestamp_ns;
}
pub fn order(self: Instant, other: Instant) std.math.Order {
return std.math.order(self.timestamp_ns, other.timestamp_ns);
}
};
pub const Timer = struct {
started: Instant,
pub fn start() !Timer {
return .{ .started = try .now() };
}
fn sample() Instant {
return Instant.now() catch unreachable;
}
pub fn read(self: *const Timer) u64 {
return sample().since(self.started);
}
pub fn reset(self: *Timer) void {
self.started = sample();
}
pub fn lap(self: *Timer) u64 {
const current = sample();
defer self.started = current;
return current.since(self.started);
}
};