const std = @import("std"); const Parser = @import("Parser.zig"); const u = @import("utils.zig"); const Order = std.math.Order; const Io = std.Io; const Writer = Io.Writer; const Allocator = std.mem.Allocator; const Scanner = std.json.Scanner; const paddingTwoDigits = u.paddingTwoDigits; const Timestamp = Io.Clock.Timestamp; pub const Weekday = enum(u3) { sunday = 0, monday = 1, tuesday = 2, wednesday = 3, thursday = 4, friday = 5, saturday = 6, pub fn name(self: Weekday) []const u8 { return u.titleCase(Weekday, self); } pub fn short(self: Weekday) []const u8 { return self.name()[0..3]; } }; pub const Month = enum(u4) { january = 1, february = 2, march = 3, april = 4, may = 5, june = 6, july = 7, august = 8, september = 9, october = 10, november = 11, december = 12, /// Convert int to Month, months are 1 indexed. /// invalid options will set month to .invalid. pub fn fromInt(int: u4) error{InvalidMonth}!Month { return if (int > 0 and int <= 12) @fromBackingInt(@intCast(int)) else error.InvalidMonth; } pub fn name(self: Month) []const u8 { return u.titleCase(Month, self); } pub fn short(self: Month) []const u8 { return self.name()[0..3]; } }; pub const DateTime = struct { timestamp: Timestamp, 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; const Format = enum { rfc3339, }; const TimeUnit = enum { days, hours, minutes, seconds, milliseconds, microseconds, }; pub const Error = error{ InvalidTime, InvalidDate }; // https://blog.reverberate.org/2020/05/12/optimizing-date-algorithms.html pub fn fromUtc(year: i16, month: u8, day: u8, hour: u8, minute: u8, second: u8, micros: u32) Error!DateTime { _ = try Date.verify(.new(year, month, day)); _ = try Time.verify(.new(hour, minute, second, micros)); const base_year = 4800; const month_adjust = @as(i32, @intCast(month)) - 3; const carry: u8 = if (month_adjust < 0) 1 else 0; const adjust: u8 = if (carry == 1) 12 else 0; const year_adjust: i64 = year + base_year - carry; const month_days = @divTrunc(((month_adjust + adjust) * 62719 + 769), 2048); const leap_days = @divTrunc(year_adjust, 4) - @divTrunc(year_adjust, 100) + @divTrunc(year_adjust, 400); const date_ms: i96 = (year_adjust * 365 + leap_days + month_days + (day - 1) - 2472632) * std.time.us_per_day; const h: i96 = @as(i96, @intCast(hour)) * std.time.us_per_hour; const m: i96 = @as(i96, @intCast(minute)) * std.time.us_per_min; const s: i96 = @as(i96, @intCast(second)) * std.time.us_per_s; const ms: i96 = @as(i96, @intCast(micros)) * std.time.us_per_ms; const time_ms = h + m + s + ms; return fromUnix(date_ms + time_ms, .microseconds); } pub fn fromTimestamp(timestamp: anytype) !DateTime { const T = @TypeOf(timestamp); switch (T) { Io.Clock.Timestamp => { const t: Io.Clock.Timestamp = timestamp; if (t.clock != .real) return error.WrongClock; return .{ .timestamp = timestamp }; }, Io.Timestamp => { const t: Io.Timestamp = timestamp; return .{ .timestamp = .{ .clock = .real, .raw = t, } }; }, else => return error.Unsupported, } } pub fn fromUnix(value: i96, precision: Precision) DateTime { const multiplier: i96 = switch (precision) { .s => std.time.ns_per_s, .ms => std.time.ns_per_ms, .us => std.time.ns_per_us, .ns => 1, }; return .{ .timestamp = .{ .clock = .real, .raw = .{ .nanoseconds = value * multiplier }, } }; } // 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 }; // }, // .nanoseconds => { // return .{ // .timestamp = .{ // .clock = .real, // .raw = .{ // .nanoseconds = value, // }, // }, // }; // }, // } // } pub fn now(io: Io) DateTime { return .{ .timestamp = .now(io, .real) }; } pub fn parse(input: []const u8, fmt: Format) !DateTime { return switch (fmt) { .rfc3339 => parseRFC3339(input), }; } const ParseError = error{ OutsideJulianPeriod, InvalidDateTime, NonUTCNotSupported, }; fn parseRFC3339(input: []const u8) ParseError!DateTime { var parser: Parser = .new(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(); 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 .fromUtc(dt.ear, dt.month, dt.day, tm.hour, tm.min, tm.sec, tm.mircos); } pub fn add(datetime: DateTime, ns: i96) DateTime { return .{ .timestamp = .{ .clock = .real, .raw = .{ .nanoseconds = datetime.timestamp.raw + ns }, } }; } // https://git.musl-libc.org/cgit/musl/tree/src/time/__secs_to_tm.c?h=v0.9.15 pub fn date(datetime: 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(datetime.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(datetime: DateTime) Time { // TODO: verify this works on negative timestamps const ns: i96 = @mod(datetime.timestamp.raw.nanoseconds, std.time.ns_per_day); return .{ // TODO: verify these values won't overflow .hour = @intCast(@divTrunc(ns, std.time.ns_per_hour)), .minute = @intCast(@divTrunc(@rem(ns, std.time.ns_per_hour), std.time.ns_per_min)), .second = @intCast(@divTrunc(@rem(ns, std.time.ns_per_min), std.time.ns_per_s)), .micros = @intCast(@divTrunc(@rem(ns, std.time.ns_per_s), std.time.ns_per_ms)), }; } pub fn unix(self: DateTime, precision: Precision) i96 { const ns = self.timestamp.raw.nanoseconds; return switch (precision) { .s => @divTrunc(ns, std.time.ns_per_s), .ms => @divTrunc(ns, std.time.ns_per_ms), .us => @divTrunc(ns, std.time.ns_per_us), .ns => ns, }; } pub fn order(a: DateTime, b: DateTime) Order { return std.math.order( a.timestamp.raw.nanoseconds, b.timestamp.raw.nanoseconds, ); } pub fn format(self: DateTime, writer: *Writer) !void { var buf: [28]u8 = undefined; const n = self.bufWrite(&buf); try writer.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: Scanner, 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; } }; pub const Time = packed struct(u64) { _: u8 = 0, microsecond: u32, second: u8, minute: u8, hour: u8, const Format = enum { rfc3339, }; pub fn new(hour: u8, minute: u8, second: u8, microsecond: u32) Time { return .{ .hour = hour, .minute = minute, .second = second, .microsecond = microsecond, }; } /// Errors if time is invalid pub fn verify(time: Time) error{InvalidTime}!Time { return if (time.hour < 24 and time.minute < 60 and time.second < 60 and time.microsecond < 1_000_000) time else error.InvalidTime; } pub fn parse(input: []const u8, fmt: Format) error{InvalidTime}!Time { var parser: Parser = .new(input); const t = switch (fmt) { .rfc3339 => try parser.time(), }; return if (parser.isDone()) t else error.InvalidTime; } pub fn order(a: Time, b: Time) Order { return std.math.order(@backingInt(a), @backingInt(b)); } pub fn format(self: Time, writer: *Writer) !void { var buf: [15]u8 = undefined; const n = writeTime(&buf, self); try writer.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: Scanner, _: anytype) !Time { const token = try source.nextAlloc(allocator, .alloc_if_needed); return switch (token) { inline .string, .allocated_string => |str| Time.parse(str, .rfc3339) catch return error.InvalidCharacter, else => error.UnexpectedToken, }; } }; pub const Date = packed struct(i32) { day: u8, month: u8, year: i16, pub fn new(year: i16, month: u8, day: u8) Date { return .{ .day = day, .month = month, .year = year }; } pub fn verify(date: Date) error{InvalidDate}!Date { if (date.month == 0 or date.month > 12) return error.InvalidDate; if (date.day == 0) return error.InvalidDate; const month_days = [_]u8{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; const max_days = if (date.month == 2 and (@rem(date.year, 400) == 0 or (@rem(date.year, 100) != 0 and @rem(date.year, 4) == 0))) 29 else month_days[date.month - 1]; return if (date.day <= max_days) date else error.InvalidDate; } const Format = enum { iso8601, rfc3339, }; pub fn parse(input: []const u8, fmt: Format) error{InvalidDate}!Date { var parser = Parser.init(input); const date = switch (fmt) { .rfc3339 => try parser.rfc3339Date(), .iso8601 => try parser.iso8601Date(), }; return if (parser.isDone()) date else error.InvalidDate; } pub fn order(a: Date, b: Date) Order { return std.math.order(@backingInt(a), @backingInt(b)); } pub fn format(self: Date, writer: *Writer) !void { var buf: [11]u8 = undefined; const n = writeDate(&buf, self); try writer.writeAll(buf[0..n]); } pub fn jsonStringify(self: Date, out: *Writer) !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]}); } const JsonError = error{ InvalidDate, UnexpectedToken, InvalidCharacter }; pub fn jsonParse(allocator: Allocator, source: Scanner, options: anytype) JsonError!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 fn weekday(self: Date) Weekday { var year: i16 = self.year; var day: i16 = undefined; if (self.month < 3) { day = @as(i16, self.day) + year; year -= 1; } else { day = @as(i16, self.day) + year - 2; } const dow = std.math.cast(u3, @mod(@divTrunc(23 * @as(i16, self.month), 9) + day + 4 + @divTrunc(year, 4) - @divTrunc(year, 100) + @divTrunc(year, 400), 7)).?; return @fromBackingInt(@intCast(dow)); } /// Returns the day of the week, eg. "Sunday" pub fn weekdayName(self: Date) []const u8 { return @tagName(self.weekday()); } }; 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) { into[0] = '-'; var writer: Writer = .fixed(into[1..]); writer.printInt(@as(u16, @intCast(year * -1)), 10, .lower, .{ .width = 4, .fill = '0' }) catch unreachable; buf = into[5..]; } else { var writer: Writer = .fixed(into); writer.printInt(@as(u16, @intCast(year)), 10, .lower, .{ .width = 4, .fill = '0' }) catch unreachable; 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; into[8] = '.'; if (@rem(micros, 1000) == 0) { var writer: Writer = .fixed(into[9..12]); writer.printInt(micros / 1000, 10, .lower, .{ .width = 3, .fill = '0' }) catch unreachable; return 12; } var writer: Writer = .fixed(into[9..15]); writer.printInt(micros, 10, .lower, .{ .width = 6, .fill = '0' }) catch unreachable; return 15; } const Precision = enum { s, ms, us, ns, };