diff --git a/src/Date.zig b/src/Date.zig index e9610b9..b2410a3 100644 --- a/src/Date.zig +++ b/src/Date.zig @@ -33,6 +33,15 @@ pub fn isRegular(self: Date) bool { return self.day >= 1 and self.day <= self.month.lastDay(self.year); } +test isRegular { + try std.testing.expect((Date{ .year = 2024, .month = .Feb, .day = 29 }).isRegular()); + + // 2025 is not a leap year, so the same date is not a day in it. + try std.testing.expect(!(Date{ .year = 2025, .month = .Feb, .day = 29 }).isRegular()); + try std.testing.expect(!(Date{ .year = 2024, .month = .Apr, .day = 31 }).isRegular()); + try std.testing.expect(!(Date{ .year = 2024, .month = .Jan, .day = 0 }).isRegular()); +} + /// A count of days since 1970-01-01, wide enough for every date a `Year` /// can hold: the whole span of years at the longest a year can be. pub const DaysType = std.math.IntFittingRange( @@ -77,6 +86,23 @@ pub fn fromDaysSinceStartOfEra(days: DaysType) Date { }; } +test fromDaysSinceStartOfEra { + try std.testing.expectEqual( + Date{ .year = 1970, .month = .Jan, .day = 1 }, + fromDaysSinceStartOfEra(0), + ); + try std.testing.expectEqual( + Date{ .year = 1970, .month = .Jan, .day = 2 }, + fromDaysSinceStartOfEra(1), + ); + + // Negative counts reach dates before the epoch. + try std.testing.expectEqual( + Date{ .year = 1969, .month = .Dec, .day = 31 }, + fromDaysSinceStartOfEra(-1), + ); +} + test "civilFromDays" { const tests = [_]struct { days: DaysType, result: Date }{ .{ @@ -154,6 +180,21 @@ pub fn toDaysSinceStartOfEra(self: Date) DaysType { return era * 146097 + day_of_era - 719468; } +test toDaysSinceStartOfEra { + try std.testing.expectEqual( + @as(DaysType, 0), + (Date{ .year = 1970, .month = .Jan, .day = 1 }).toDaysSinceStartOfEra(), + ); + try std.testing.expectEqual( + @as(DaysType, -1), + (Date{ .year = 1969, .month = .Dec, .day = 31 }).toDaysSinceStartOfEra(), + ); + + // It is the inverse of `fromDaysSinceStartOfEra`. + const date: Date = .{ .year = 2024, .month = .Mar, .day = 15 }; + try std.testing.expectEqual(date, fromDaysSinceStartOfEra(date.toDaysSinceStartOfEra())); +} + test "daysFromCivil" { const tests = [_]struct { date: Date, result: DaysType }{ .{ @@ -193,3 +234,9 @@ pub fn dayOfWeek(self: Date) DayOfWeek { const days = self.toDaysSinceStartOfEra(); return DayOfWeek.fromDaysSinceStartOfEra(days); } + +test dayOfWeek { + // The epoch was a Thursday. + try std.testing.expectEqual(DayOfWeek.Thu, (Date{ .year = 1970, .month = .Jan, .day = 1 }).dayOfWeek()); + try std.testing.expectEqual(DayOfWeek.Fri, (Date{ .year = 2024, .month = .Mar, .day = 15 }).dayOfWeek()); +} diff --git a/src/DateTime.zig b/src/DateTime.zig index 9d3fe2c..8e9dc12 100644 --- a/src/DateTime.zig +++ b/src/DateTime.zig @@ -72,11 +72,28 @@ pub fn utc(io: std.Io) DateTime { return Instant.utc(io).asDateTime(); } +test utc { + const datetime = utc(std.testing.io); + + // Nothing about the reading is fixed, but it is a real clock read as + // UTC, so it is past the epoch and carries no offset. + try std.testing.expect(datetime.year >= 1970); + try std.testing.expectEqual(@as(i32, 0), datetime.offset); +} + /// Writes the name at `index` in `names` to `writer`. fn printLongName(writer: anytype, index: u16, names: []const []const u8) !void { try writer.writeAll(names[index]); } +test printLongName { + var buf: [16]u8 = undefined; + var writer = std.Io.Writer.fixed(&buf); + + try printLongName(&writer, 1, &.{ "January", "February" }); + try std.testing.expectEqualStrings("February", writer.buffered()); +} + /// Wraps `val` into the range `[1, at]`, mapping a remainder of 0 to `at` /// (e.g. hour 0 becomes 12 on a 12-hour clock). fn wrap(val: anytype, at: @TypeOf(val)) @TypeOf(val) { @@ -84,6 +101,16 @@ fn wrap(val: anytype, at: @TypeOf(val)) @TypeOf(val) { return if (tmp == 0) at else tmp; } +test wrap { + // On a 12-hour clock the hours run 12, 1, 2 ... 11, so the hour that + // would divide exactly takes the top of the range instead of zero. + try std.testing.expectEqual(@as(u8, 12), wrap(@as(u8, 0), 12)); + try std.testing.expectEqual(@as(u8, 1), wrap(@as(u8, 1), 12)); + try std.testing.expectEqual(@as(u8, 11), wrap(@as(u8, 11), 12)); + try std.testing.expectEqual(@as(u8, 12), wrap(@as(u8, 12), 12)); + try std.testing.expectEqual(@as(u8, 1), wrap(@as(u8, 13), 12)); +} + /// Recomputes the `weekday` field from the current `year`, `month`, and `day`. pub fn updateDayOfWeek(self: *DateTime) void { const date: Date = .{ @@ -94,6 +121,16 @@ pub fn updateDayOfWeek(self: *DateTime) void { self.weekday = date.dayOfWeek(); } +test updateDayOfWeek { + // The weekday is a stored field, so a date assembled by hand carries + // whatever was put there until this puts it right. + var datetime: DateTime = .{ .year = 2024, .month = .Mar, .day = 15 }; + try std.testing.expectEqual(DayOfWeek.Thu, datetime.weekday); + + datetime.updateDayOfWeek(); + try std.testing.expectEqual(DayOfWeek.Fri, datetime.weekday); +} + /// Writes this date/time to `writer` according to `fmt`, a comptime format /// string made of `FormatTag` sequences (e.g. "YYYY-MM-DDTHH:mm:ss.SSS"). /// The literal characters `,`, ` `, `:`, `-`, `.`, `T`, and `W` are copied @@ -255,8 +292,21 @@ pub fn formatAlloc(self: DateTime, alloc: std.mem.Allocator, comptime fmt: []con return try buf.toOwnedSlice(); } -/// Like `formatAlloc`, but the returned slice is terminated with `sentinel`. -pub fn formatAllocSentinel(self: DateTime, alloc: std.mem.Allocator, comptime fmt: []const u8, comptime sentinel: u8) ![]const u8 { +test formatAlloc { + const datetime: DateTime = .{ .year = 2024, .month = .Mar, .day = 15, .weekday = .Fri }; + + const text = try datetime.formatAlloc(std.testing.allocator, "dddd, D MMMM YYYY"); + defer std.testing.allocator.free(text); + + try std.testing.expectEqualStrings("Friday, 15 March 2024", text); +} + +/// Like `formatAlloc`, but the returned slice is terminated with `sentinel`, +/// for handing to something that expects a terminator rather than a length. +/// +/// The sentinel is part of the return type and not of the length, so the +/// caller frees the whole allocation the same way as for `formatAlloc`. +pub fn formatAllocSentinel(self: DateTime, alloc: std.mem.Allocator, comptime fmt: []const u8, comptime sentinel: u8) ![:sentinel]const u8 { var buf: std.Io.Writer.Allocating = .init(alloc); errdefer buf.deinit(); @@ -264,15 +314,29 @@ pub fn formatAllocSentinel(self: DateTime, alloc: std.mem.Allocator, comptime fm return try buf.toOwnedSliceSentinel(sentinel); } +test formatAllocSentinel { + const datetime: DateTime = .{ .year = 2024, .month = .Mar, .day = 15, .weekday = .Fri }; + + // The sentinel is for handing the result to C, so it is written past + // the end rather than counted in the length. + const text = try datetime.formatAllocSentinel(std.testing.allocator, "YYYY-MM-DD", 0); + defer std.testing.allocator.free(text); + + try std.testing.expectEqualStrings("2024-03-15", text); + try std.testing.expectEqual(@as(u8, 0), text.ptr[text.len]); +} + const AmPm = enum { none, am, pm, }; -/// What `parse` can fail with. `IllegalToken` means the format string used -/// a sequence that cannot be parsed, such as the quarter or the week of -/// the year, neither of which pins down a date on its own. +/// What `parse` can fail with. +/// +/// `IllegalToken` is the odd one out: it is raised from the comptime block +/// that tokenizes the format string, so it is reported as a compile error +/// and is never returned to a caller at runtime. See `parseRelativeTo`. pub const ParseError = error{ IllegalToken, InvalidCharacter, @@ -297,13 +361,34 @@ pub fn parse(comptime format_string: []const u8, value: []const u8) ParseError!P return parseRelativeTo(format_string, .unix_epoch, value); } +test parse { + const result = try parse("YYYY-MM-DD", "2024-03-15"); + try std.testing.expectEqual(@as(Year, 2024), result.value.year); + try std.testing.expectEqual(Month.Mar, result.value.month); + try std.testing.expectEqual(@as(Day, 15), result.value.day); + + // The weekday is worked out from the date rather than taken on trust. + try std.testing.expectEqual(DayOfWeek.Fri, result.value.weekday); + + // Fields the format string does not mention come from the epoch, so a + // date alone leaves the time of day at midnight. + try std.testing.expectEqual(@as(Hour, 0), result.value.hour); + + // Only what was consumed is reported, so the caller can carry on. + try std.testing.expectEqualStrings("2024-03-15", result.str); +} + /// Parses `value` according to the comptime `format_string`, a string of /// `FormatTag` sequences (e.g. "MMM D H:mm:ss"). Date fields missing from /// the format string are taken from `relative_to`; time-of-day fields /// always default to zero. A parsed day of the week is checked against the -/// computed date and `error.ParseError` is returned on mismatch. The -/// quarter (`Q`) and week-of-year (`w`) sequences cannot be parsed and -/// cause `error.IllegalToken`. +/// computed date and `error.ParseError` is returned on mismatch. +/// +/// The quarter (`Q`) and week-of-year (`w`) sequences name no date on +/// their own and cannot be parsed. The tokenizer runs at comptime, so a +/// format string using one is rejected while this is being compiled: the +/// `error.IllegalToken` it raises there surfaces as a compile error and +/// never reaches a caller. pub fn parseRelativeTo(comptime format_string: []const u8, relative_to: DateTime, value: []const u8) ParseError!ParseResult { const tokens: []const FormatTag.Tokenizer.Token = comptime tokens: { @setEvalBranchQuota(200000); @@ -774,8 +859,18 @@ pub fn dayOfThisYear(self: DateTime) u9 { return self.month.daysBefore(self.year) + self.day; } +test dayOfThisYear { + try std.testing.expectEqual(@as(u9, 1), (DateTime{ .year = 2024, .month = .Jan, .day = 1 }).dayOfThisYear()); + + // 2024 is a leap year, so from March on it runs one day ahead of 2025. + try std.testing.expectEqual(@as(u9, 75), (DateTime{ .year = 2024, .month = .Mar, .day = 15 }).dayOfThisYear()); + try std.testing.expectEqual(@as(u9, 74), (DateTime{ .year = 2025, .month = .Mar, .day = 15 }).dayOfThisYear()); + + try std.testing.expectEqual(@as(u9, 366), (DateTime{ .year = 2024, .month = .Dec, .day = 31 }).dayOfThisYear()); +} + /// Returns the same point in time expressed in UTC, that is with the -/// fields shifted back by `offset` minutes and `offset` itself set to +/// fields shifted back by `offset` seconds and `offset` itself set to /// zero. The shift rolls over into the neighbouring day, month, and year /// as needed, and `weekday` is recomputed to match. Seconds and /// nanoseconds are carried through untouched, so a value holding a leap @@ -1274,6 +1369,31 @@ test "parseTest" { } } +test parseRelativeTo { + // A format string that names no year gets one from `relative_to` + // rather than from the epoch, which is what makes syslog timestamps + // and the like resolvable. + const relative_to: DateTime = .{ .year = 2024, .month = .Jan, .day = 1 }; + + const result = try parseRelativeTo("MMM D HH:mm:ss", relative_to, "Mar 22 12:40:39"); + try std.testing.expectEqual(@as(Year, 2024), result.value.year); + try std.testing.expectEqual(Month.Mar, result.value.month); + try std.testing.expectEqual(@as(Day, 22), result.value.day); + try std.testing.expectEqual(@as(Hour, 12), result.value.hour); + + // A weekday in the input is checked against the date rather than + // believed, so one that disagrees is a parse error. + _ = try parseRelativeTo("ddd, D MMM YYYY", relative_to, "Fri, 15 Mar 2024"); + try std.testing.expectError( + error.ParseError, + parseRelativeTo("ddd, D MMM YYYY", relative_to, "Mon, 15 Mar 2024"), + ); + + // Sequences that pin down no date cannot be parsed at all. That is + // settled while the format string is being tokenized, so asking for + // one is a compile error rather than something to catch here. +} + test "parseRelativeToTest" { const cases = [_]struct { value: []const u8, @@ -1309,6 +1429,35 @@ test "parseRelativeToTest" { } } +test format { + const datetime: DateTime = .{ + .year = 2024, + .month = .Mar, + .day = 15, + .hour = 14, + .minute = 30, + .second = 5, + .nanosecond = 123456789, + .weekday = .Fri, + }; + + var buf: [64]u8 = undefined; + + var iso = std.Io.Writer.fixed(&buf); + try datetime.format("YYYY-MM-DDTHH:mm:ss", &iso); + try std.testing.expectEqualStrings("2024-03-15T14:30:05", iso.buffered()); + + // Names, ordinals and a 12-hour clock, and a fraction cut to however + // many digits the sequence asks for. + var words = std.Io.Writer.fixed(&buf); + try datetime.format("dddd, Do MMMM YYYY, h:mma", &words); + try std.testing.expectEqualStrings("Friday, 15th March 2024, 2:30pm", words.buffered()); + + var millis = std.Io.Writer.fixed(&buf); + try datetime.format("ss.SSS", &millis); + try std.testing.expectEqualStrings("05.123", millis.buffered()); +} + test "formatTest" { const test_date = DateTime{ .nanosecond = 123456789, @@ -1431,6 +1580,41 @@ test "formatTest" { } } +test toUtc { + const local: DateTime = .{ + .year = 1994, + .month = .Nov, + .day = 6, + .hour = 8, + .minute = 49, + .second = 37, + .weekday = .Sun, + .offset = -5 * std.time.s_per_hour, + }; + + const utc_time = local.toUtc(); + try std.testing.expectEqual(@as(Hour, 13), utc_time.hour); + try std.testing.expectEqual(@as(i32, 0), utc_time.offset); + + // The shift rolls over the end of a day, and the weekday is + // recomputed to match rather than carried across. + const evening: DateTime = .{ + .year = 2024, + .month = .Mar, + .day = 15, + .hour = 20, + .weekday = .Fri, + .offset = -5 * std.time.s_per_hour, + }; + const next_day = evening.toUtc(); + try std.testing.expectEqual(@as(Day, 16), next_day.day); + try std.testing.expectEqual(@as(Hour, 1), next_day.hour); + try std.testing.expectEqual(DayOfWeek.Sat, next_day.weekday); + + // A value that is already UTC is returned untouched. + try std.testing.expectEqual(utc_time, utc_time.toUtc()); +} + test "toUtcTest" { const cases = [_]struct { local: DateTime, expected: DateTime }{ // A whole number of hours, staying within the same day. diff --git a/src/Instant.zig b/src/Instant.zig index 90d509e..a28d382 100644 --- a/src/Instant.zig +++ b/src/Instant.zig @@ -19,6 +19,9 @@ const Minute = @import("minute.zig").Minute; const Second = @import("second.zig").Second; const Nanosecond = @import("nanosecond.zig").Nanosecond; const DayOfWeek = @import("dayofweek.zig").DayOfWeek; +const Year = @import("year.zig").Year; +const Month = @import("month.zig").Month; +const Day = @import("day.zig").Day; timestamp: i128, @@ -29,6 +32,14 @@ pub fn now(io: std.Io) Instant { }; } +test now { + const instant = now(std.testing.io); + + // Nothing about the reading is fixed, but the clock is a real one, so + // it is somewhere after the epoch. + try std.testing.expect(instant.timestamp > 0); +} + /// Same as `now`: the current time read from the `.real` clock of `io`, in UTC. pub fn utc(io: std.Io) Instant { return .{ @@ -36,6 +47,13 @@ pub fn utc(io: std.Io) Instant { }; } +test utc { + // An instant carries no zone, so this is `now` under another name, + // kept for callers that would rather say which they meant. + const instant = utc(std.testing.io); + try std.testing.expect(instant.timestamp > 0); +} + /// Creates an `Instant` from a count of nanoseconds since the Unix epoch, in UTC. pub fn fromNanoTimeStamp(timestamp: i128) Instant { return .{ @@ -43,6 +61,16 @@ pub fn fromNanoTimeStamp(timestamp: i128) Instant { }; } +test fromNanoTimeStamp { + const instant: Instant = .fromNanoTimeStamp(1710512400_000000000); + try std.testing.expectEqual(@as(i128, 1710512400_000000000), instant.timestamp); + + const datetime = instant.asDateTime(); + try std.testing.expectEqual(@as(Year, 2024), datetime.year); + try std.testing.expectEqual(Month.Mar, datetime.month); + try std.testing.expectEqual(@as(Day, 15), datetime.day); +} + /// Creates an `Instant` from a count of microseconds since the Unix epoch, in UTC. pub fn fromMicroTimeStamp(timestamp: i64) Instant { return .{ @@ -50,6 +78,11 @@ pub fn fromMicroTimeStamp(timestamp: i64) Instant { }; } +test fromMicroTimeStamp { + const instant: Instant = .fromMicroTimeStamp(1_500_000); + try std.testing.expectEqual(@as(i128, 1_500_000_000), instant.timestamp); +} + /// Creates an `Instant` from a count of milliseconds since the Unix epoch, in UTC. pub fn fromMilliTimestamp(timestamp: i64) Instant { return .{ @@ -57,6 +90,11 @@ pub fn fromMilliTimestamp(timestamp: i64) Instant { }; } +test fromMilliTimestamp { + const instant: Instant = .fromMilliTimestamp(1_500); + try std.testing.expectEqual(@as(i128, 1_500_000_000), instant.timestamp); +} + /// Converts this instant to a calendar `DateTime` in UTC. Timestamps /// before the Unix epoch are supported and produce dates before 1970. pub fn asDateTime(self: Instant) DateTime { @@ -176,6 +214,23 @@ test "instantTest" { } } -test "asDateTime" { - _ = Instant.utc(std.testing.io).asDateTime(); +test asDateTime { + // The epoch itself, which was a Thursday. + const epoch = (Instant{ .timestamp = 0 }).asDateTime(); + try std.testing.expectEqual(@as(Year, 1970), epoch.year); + try std.testing.expectEqual(Month.Jan, epoch.month); + try std.testing.expectEqual(@as(Day, 1), epoch.day); + try std.testing.expectEqual(DayOfWeek.Thu, epoch.weekday); + + // One nanosecond earlier is the last instant of 1969, not a negative + // time of day: the split rounds towards the earlier date. + const before = (Instant{ .timestamp = -1 }).asDateTime(); + try std.testing.expectEqual(@as(Year, 1969), before.year); + try std.testing.expectEqual(Month.Dec, before.month); + try std.testing.expectEqual(@as(Day, 31), before.day); + try std.testing.expectEqual(@as(u5, 23), before.hour); + try std.testing.expectEqual(@as(u30, 999999999), before.nanosecond); + + // The result is always UTC, so it carries no offset. + try std.testing.expectEqual(@as(i32, 0), epoch.offset); } diff --git a/src/TimeZone.zig b/src/TimeZone.zig index a6ff9c4..3f9977a 100644 --- a/src/TimeZone.zig +++ b/src/TimeZone.zig @@ -47,11 +47,35 @@ pub fn fromBytes(name: []const u8, bytes: []const u8) Error!TimeZone { return init(name, bytes, false); } +test fromBytes { + // The zone borrows the bytes, so nothing is allocated and nothing has + // to be freed. This is the shape `tzdb.embedded` uses, where the data + // is already in the binary. + const bytes = try bytesForTest("America/Chicago"); + defer testing.allocator.free(bytes); + + const zone = try fromBytes("America/Chicago", bytes); + try testing.expectEqualStrings("America/Chicago", zone.name); + try testing.expectEqual(@as(i32, -6 * std.time.s_per_hour), zone.offsetAt(0)); +} + /// Builds a zone that takes ownership of `bytes`, which `deinit` frees. pub fn fromOwnedBytes(name: []const u8, bytes: []const u8) Error!TimeZone { return init(name, bytes, true); } +test fromOwnedBytes { + // The zone takes the bytes over, so `deinit` is what frees them. This + // is the shape `tzdb.system` uses, having just read a file. + var zone = try fromOwnedBytes( + try testing.allocator.dupe(u8, "America/Chicago"), + try bytesForTest("America/Chicago"), + ); + defer zone.deinit(testing.allocator); + + try testing.expectEqualStrings("America/Chicago", zone.name); +} + /// Parses `bytes` into a zone. The footer is parsed here rather than on /// demand so that a malformed rule is reported when the zone is built, /// not later at some lookup that happens to fall past the transitions. @@ -66,6 +90,20 @@ fn init(name: []const u8, bytes: []const u8, owned: bool) Error!TimeZone { }; } +test init { + const bytes = try bytesForTest("America/Chicago"); + defer testing.allocator.free(bytes); + + // The footer is parsed here and not on demand, so a zone that builds + // at all has a usable rule for the times past its last transition. + const zone = try init("America/Chicago", bytes, false); + try testing.expect(zone.rule != null); + try testing.expect(!zone.owned); + + // Bad bytes fail here rather than at some later lookup. + try testing.expectError(error.BadMagic, init("x", "XZif" ++ ("\x00" ** 40), false)); +} + /// Frees the bytes of a zone built by `fromOwnedBytes`, and the copy of /// its name. Does nothing for a zone built by `fromBytes`. pub fn deinit(self: *TimeZone, gpa: std.mem.Allocator) void { @@ -76,6 +114,23 @@ pub fn deinit(self: *TimeZone, gpa: std.mem.Allocator) void { self.* = undefined; } +test deinit { + // An owned zone frees its bytes and its name; the testing allocator + // is what checks that this happened. + var owned = try fromOwnedBytes( + try testing.allocator.dupe(u8, "America/Chicago"), + try bytesForTest("America/Chicago"), + ); + owned.deinit(testing.allocator); + + // A borrowed one frees nothing, so its bytes outlive it. + const bytes = try bytesForTest("America/Chicago"); + defer testing.allocator.free(bytes); + + var borrowed = try fromBytes("America/Chicago", bytes); + borrowed.deinit(testing.allocator); +} + /// Returns the local time type in effect at `timestamp`, a Unix time in /// seconds. pub fn typeAt(self: TimeZone, timestamp: i64) Type { @@ -87,11 +142,38 @@ pub fn typeAt(self: TimeZone, timestamp: i64) Type { return self.data.lastType(); } +test typeAt { + var zone = try loadForTest("America/Chicago"); + defer zone.deinit(testing.allocator); + + // Midwinter and midsummer 2024, either side of the switch. + const winter = zone.typeAt(1704067200); + try testing.expectEqualStrings("CST", winter.designation); + try testing.expect(!winter.is_dst); + + const summer = zone.typeAt(1720000000); + try testing.expectEqualStrings("CDT", summer.designation); + try testing.expect(summer.is_dst); + + // Far past the last stored transition the footer's rule answers, so + // a slim file keeps working rather than running out. + const distant = zone.typeAt(4102444800); + try testing.expect(distant.designation.len > 0); +} + /// Returns the offset from UTC in seconds in effect at `timestamp`. pub fn offsetAt(self: TimeZone, timestamp: i64) i32 { return self.typeAt(timestamp).offset; } +test offsetAt { + var zone = try loadForTest("America/Chicago"); + defer zone.deinit(testing.allocator); + + try testing.expectEqual(@as(i32, -6 * std.time.s_per_hour), zone.offsetAt(1704067200)); + try testing.expectEqual(@as(i32, -5 * std.time.s_per_hour), zone.offsetAt(1720000000)); +} + /// A stretch of time over which one local time type applies. pub const Span = struct { local_type: Type, @@ -153,11 +235,38 @@ pub fn atInstant(self: TimeZone, instant: Instant) DateTime { return datetime; } +test atInstant { + var zone = try loadForTest("America/Chicago"); + defer zone.deinit(testing.allocator); + + // 2024-07-03T09:46:40Z, in the middle of daylight saving time, reads + // five hours earlier on a Chicago clock. + const local = zone.atInstant(.fromNanoTimeStamp(1720000000 * @as(i128, std.time.ns_per_s))); + try testing.expectEqual(@as(i32, -5 * std.time.s_per_hour), local.offset); + try testing.expectEqual(Month.Jul, local.month); + try testing.expectEqual(@as(u5, 4), local.hour); + try testing.expectEqual(@as(u6, 46), local.minute); + + // The offset comes back on the value, so the reading can be turned + // round again without the zone. + try testing.expectEqual(@as(u5, 9), local.toUtc().hour); +} + /// Converts a Unix timestamp in seconds to local wall-clock time. pub fn atTimestamp(self: TimeZone, timestamp: i64) DateTime { return self.atInstant(.fromNanoTimeStamp(@as(i128, timestamp) * std.time.ns_per_s)); } +test atTimestamp { + var zone = try loadForTest("America/Chicago"); + defer zone.deinit(testing.allocator); + + // The same as `atInstant`, for callers holding whole seconds. + const local = zone.atTimestamp(1720000000); + try testing.expectEqual(@as(u5, 4), local.hour); + try testing.expectEqual(@as(i32, -5 * std.time.s_per_hour), local.offset); +} + /// What a local wall-clock reading corresponds to in UTC. /// /// Most readings name exactly one instant, but a clock that springs @@ -190,6 +299,19 @@ pub const Resolved = union(enum) { }; } + test earliest { + try testing.expectEqual(@as(i64, 100), (Resolved{ .unique = 100 }).earliest()); + + // For a repeated reading this is the first of the two instants, + // the one before the clocks went back. + const twice: Resolved = .{ .ambiguous = .{ .earlier = 100, .later = 3700 } }; + try testing.expectEqual(@as(i64, 100), twice.earliest()); + + // A skipped reading names one instant either way. + const skipped: Resolved = .{ .gap = .{ .at = 100, .before = 0, .after = 3600 } }; + try testing.expectEqual(@as(i64, 100), skipped.earliest()); + } + /// The latest instant matching the reading, taking the post-transition /// offset for a reading that falls in a gap. pub fn latest(self: Resolved) i64 { @@ -199,6 +321,14 @@ pub const Resolved = union(enum) { .ambiguous => |a| a.later, }; } + + test latest { + try testing.expectEqual(@as(i64, 100), (Resolved{ .unique = 100 }).latest()); + + // The second of the two instants a repeated reading names. + const twice: Resolved = .{ .ambiguous = .{ .earlier = 100, .later = 3700 } }; + try testing.expectEqual(@as(i64, 3700), twice.latest()); + } }; /// Resolves a local wall-clock reading to UTC. The `offset` field of @@ -279,6 +409,24 @@ fn localSeconds(local: DateTime) i64 { @as(i64, local.second); } +test localSeconds { + // The reading is counted as though it were UTC, which is what makes + // it comparable against a span's bounds shifted by that span's + // offset. The `offset` field is deliberately not applied here. + try testing.expectEqual( + @as(i64, 0), + localSeconds(.{ .year = 1970, .month = .Jan, .day = 1 }), + ); + try testing.expectEqual( + @as(i64, 3600), + localSeconds(.{ .year = 1970, .month = .Jan, .day = 1, .hour = 1 }), + ); + try testing.expectEqual( + localSeconds(.{ .year = 2024, .month = .Mar, .day = 15 }), + localSeconds(.{ .year = 2024, .month = .Mar, .day = 15, .offset = -5 * std.time.s_per_hour }), + ); +} + const testing = std.testing; /// Directories that different systems keep the TZif tree in. @@ -289,26 +437,86 @@ const test_directories = [_][]const u8{ "/usr/share/lib/zoneinfo", }; -/// Loads a zone for a test from whichever copy of the database this -/// machine has, or skips the test when it has none. -fn loadForTest(name: []const u8) !TimeZone { +/// Reads the TZif bytes of a named zone from whichever copy of the +/// database this machine has, or skips the test when it has none. The +/// caller owns the bytes. +fn bytesForTest(name: []const u8) ![]u8 { for (test_directories) |directory| { const path = try std.fs.path.join(testing.allocator, &.{ directory, name }); defer testing.allocator.free(path); - const bytes = std.Io.Dir.cwd().readFileAlloc( + return std.Io.Dir.cwd().readFileAlloc( testing.io, path, testing.allocator, .limited(1 << 20), ) catch continue; - errdefer testing.allocator.free(bytes); - - return fromOwnedBytes(try testing.allocator.dupe(u8, name), bytes); } return error.SkipZigTest; } +/// Loads a zone for a test from whichever copy of the database this +/// machine has, or skips the test when it has none. +fn loadForTest(name: []const u8) !TimeZone { + const bytes = try bytesForTest(name); + errdefer testing.allocator.free(bytes); + + return fromOwnedBytes(try testing.allocator.dupe(u8, name), bytes); +} + +test spanAt { + var zone = try loadForTest("America/Chicago"); + defer zone.deinit(testing.allocator); + + // Midsummer 2024 sits inside daylight saving time, bounded by the + // March and November switches. + const summer = zone.spanAt(1720000000); + try testing.expectEqualStrings("CDT", summer.local_type.designation); + try testing.expectEqual(@as(i64, 1710057600), summer.start); + try testing.expectEqual(@as(i64, 1730617200), summer.end); + + // The bounds are what save a second lookup: any instant inside them + // is governed by the same type. + try testing.expectEqual( + summer.local_type.offset, + zone.typeAt(summer.end - 1).offset, + ); + + // Past the last stored transition the footer's rule answers, and it + // cannot report a span reaching back before the handover. + const distant = zone.spanAt(4102444800); + try testing.expect(distant.start > 0); +} + +test resolve { + var zone = try loadForTest("America/Chicago"); + defer zone.deinit(testing.allocator); + + // An ordinary reading names exactly one instant. The `offset` field + // of the input is ignored; the zone is what decides it. + const ordinary = zone.resolve(.{ .year = 2024, .month = .Jul, .day = 3, .hour = 12 }); + try testing.expectEqual(@as(i64, 1720026000), ordinary.unique); + + // The hour the clocks skip forward over never happens, so there is no + // reading to name. `at` is where it would have fallen, between the + // offsets either side of the switch. + const skipped = zone.resolve(.{ .year = 2024, .month = .Mar, .day = 10, .hour = 2, .minute = 30 }); + try testing.expectEqual(@as(i32, -6 * std.time.s_per_hour), skipped.gap.before); + try testing.expectEqual(@as(i32, -5 * std.time.s_per_hour), skipped.gap.after); + + // The hour the clocks repeat happens twice, an hour apart. + const repeated = zone.resolve(.{ .year = 2024, .month = .Nov, .day = 3, .hour = 1, .minute = 30 }); + try testing.expectEqual( + @as(i64, std.time.s_per_hour), + repeated.ambiguous.later - repeated.ambiguous.earlier, + ); + + // `earliest` and `latest` pick one without the caller switching on + // which case it was. + try testing.expectEqual(repeated.ambiguous.earlier, repeated.earliest()); + try testing.expectEqual(repeated.ambiguous.later, repeated.latest()); +} + test "the offset in effect at an instant" { var zone = try loadForTest("America/Chicago"); defer zone.deinit(testing.allocator); diff --git a/src/datetime.zig b/src/datetime.zig index 2c86932..05315b7 100644 --- a/src/datetime.zig +++ b/src/datetime.zig @@ -101,4 +101,10 @@ pub const si = @import("si.zig"); test { std.testing.refAllDecls(@This()); + + // refAllDecls reaches everything this file re-exports, and through them + // every internal module but one: `ordinal` is named only from inside the + // comptime bodies of `DateTime.parseRelativeTo`, which are never + // instantiated by a reference alone, so its tests need asking for. + _ = @import("ordinal.zig"); } diff --git a/src/dayofweek.zig b/src/dayofweek.zig index 38ec661..148e4c0 100644 --- a/src/dayofweek.zig +++ b/src/dayofweek.zig @@ -44,18 +44,51 @@ pub const DayOfWeek = enum(u3) { return parseWithMap(DayOfWeek.very_short_map, left); } + test parseVeryShortStr { + const result = try parseVeryShortStr("We"); + try std.testing.expectEqual(DayOfWeek.Wed, result.value); + try std.testing.expectEqualStrings("We", result.str); + + // Only the two letters are consumed; the rest is the caller's. + const trailing = try parseVeryShortStr("Sa, 06 Nov 1994"); + try std.testing.expectEqual(DayOfWeek.Sat, trailing.value); + try std.testing.expectEqualStrings("Sa", trailing.str); + + try std.testing.expectError(error.ParseError, parseVeryShortStr("Xx")); + } + /// Parses a three-letter day name ("Sun" ... "Sat") at the start of /// `left`, case-insensitively. pub fn parseShortStr(left: []const u8) ParseError!ParseStringResult { return parseWithMap(DayOfWeek.short_map, left); } + test parseShortStr { + const result = try parseShortStr("Sun"); + try std.testing.expectEqual(DayOfWeek.Sun, result.value); + try std.testing.expectEqualStrings("Sun", result.str); + + // Matching ignores case, so any spelling of the name is accepted. + try std.testing.expectEqual(DayOfWeek.Fri, (try parseShortStr("FRI")).value); + try std.testing.expectEqual(DayOfWeek.Fri, (try parseShortStr("fri")).value); + } + /// Parses a full day name ("Sunday" ... "Saturday") at the start of /// `left`, case-insensitively. pub fn parseLongStr(left: []const u8) ParseError!ParseStringResult { return parseWithMap(DayOfWeek.long_map, left); } + test parseLongStr { + const result = try parseLongStr("Wednesday"); + try std.testing.expectEqual(DayOfWeek.Wed, result.value); + try std.testing.expectEqualStrings("Wednesday", result.str); + + // The long map holds only whole names, so an abbreviation of one + // is not a match. + try std.testing.expectError(error.ParseError, parseLongStr("Wed")); + } + /// Returns the shortest prefix of `left` found in `map` along with its /// value, or `error.ParseError` if no prefix matches. fn parseWithMap(map: MapType, left: []const u8) ParseError!ParseStringResult { @@ -70,6 +103,16 @@ pub const DayOfWeek = enum(u3) { return error.ParseError; } + test parseWithMap { + // The shortest matching prefix wins, which is why each caller + // passes the map for the one length it means to accept. + const short = try parseWithMap(short_map, "Sunday"); + try std.testing.expectEqualStrings("Sun", short.str); + + const long = try parseWithMap(long_map, "Sunday"); + try std.testing.expectEqualStrings("Sunday", long.str); + } + /// Returns the day after this one, wrapping from Saturday to Sunday. pub fn next(self: DayOfWeek) DayOfWeek { return switch (self) { @@ -83,6 +126,12 @@ pub const DayOfWeek = enum(u3) { }; } + test next { + try std.testing.expectEqual(DayOfWeek.Mon, DayOfWeek.Sun.next()); + // Saturday wraps round to Sunday. + try std.testing.expectEqual(DayOfWeek.Sun, DayOfWeek.Sat.next()); + } + /// Returns the day before this one, wrapping from Sunday to Saturday. pub fn prev(self: DayOfWeek) DayOfWeek { return switch (self) { @@ -96,6 +145,12 @@ pub const DayOfWeek = enum(u3) { }; } + test prev { + try std.testing.expectEqual(DayOfWeek.Fri, DayOfWeek.Sat.prev()); + // Sunday wraps back to Saturday. + try std.testing.expectEqual(DayOfWeek.Sat, DayOfWeek.Sun.prev()); + } + /// Returns the two-letter English name ("Su" ... "Sa"). pub fn veryShortName(self: DayOfWeek) []const u8 { return switch (self) { @@ -109,6 +164,11 @@ pub const DayOfWeek = enum(u3) { }; } + test veryShortName { + try std.testing.expectEqualStrings("Su", DayOfWeek.Sun.veryShortName()); + try std.testing.expectEqualStrings("Th", DayOfWeek.Thu.veryShortName()); + } + /// Returns the three-letter English name ("Sun" ... "Sat"). pub fn shortName(self: DayOfWeek) []const u8 { return switch (self) { @@ -122,6 +182,11 @@ pub const DayOfWeek = enum(u3) { }; } + test shortName { + try std.testing.expectEqualStrings("Sun", DayOfWeek.Sun.shortName()); + try std.testing.expectEqualStrings("Sat", DayOfWeek.Sat.shortName()); + } + /// Returns the full English name ("Sunday" ... "Saturday"). pub fn longName(self: DayOfWeek) []const u8 { return switch (self) { @@ -135,16 +200,34 @@ pub const DayOfWeek = enum(u3) { }; } + test longName { + try std.testing.expectEqualStrings("Sunday", DayOfWeek.Sun.longName()); + try std.testing.expectEqualStrings("Wednesday", DayOfWeek.Wed.longName()); + } + /// Returns the weekday number, Sunday = 0 through Saturday = 6. pub fn weekdayNumber(self: DayOfWeek) u3 { return @intFromEnum(self); } + test weekdayNumber { + try std.testing.expectEqual(@as(u3, 0), DayOfWeek.Sun.weekdayNumber()); + try std.testing.expectEqual(@as(u3, 6), DayOfWeek.Sat.weekdayNumber()); + } + /// Returns the ISO 8601 weekday number, Monday = 1 through Sunday = 7. pub fn isoWeekdayNumber(self: DayOfWeek) u3 { return if (self == .Sun) 7 else @intFromEnum(self); } + test isoWeekdayNumber { + // ISO 8601 starts its week on Monday, so Sunday moves from the + // front of the week to the back of it. + try std.testing.expectEqual(@as(u3, 1), DayOfWeek.Mon.isoWeekdayNumber()); + try std.testing.expectEqual(@as(u3, 6), DayOfWeek.Sat.isoWeekdayNumber()); + try std.testing.expectEqual(@as(u3, 7), DayOfWeek.Sun.isoWeekdayNumber()); + } + /// Returns the day of the week that falls `days` days after 1970-01-01 /// (which was a Thursday); negative values count backward. pub fn fromDaysSinceStartOfEra(days: Date.DaysType) DayOfWeek { @@ -156,6 +239,16 @@ pub const DayOfWeek = enum(u3) { return @enumFromInt(result); } + test fromDaysSinceStartOfEra { + // The epoch itself was a Thursday. + try std.testing.expectEqual(DayOfWeek.Thu, fromDaysSinceStartOfEra(0)); + try std.testing.expectEqual(DayOfWeek.Fri, fromDaysSinceStartOfEra(1)); + try std.testing.expectEqual(DayOfWeek.Thu, fromDaysSinceStartOfEra(7)); + + // Negative counts run backwards into the days before it. + try std.testing.expectEqual(DayOfWeek.Wed, fromDaysSinceStartOfEra(-1)); + } + /// The type the name maps below are built from. Comparison ignores /// case, so the maps only have to carry lower-case keys. pub const MapType = std.StaticStringMapWithEql(DayOfWeek, std.ascii.eqlIgnoreCase); @@ -266,6 +359,14 @@ pub fn weekdayDifference(start: DayOfWeek, end: DayOfWeek) u3 { return if (d >= 0) @intCast(d) else @intCast(d + 7); } +test weekdayDifference { + try std.testing.expectEqual(@as(u3, 2), weekdayDifference(.Sun, .Tue)); + try std.testing.expectEqual(@as(u3, 0), weekdayDifference(.Wed, .Wed)); + + // Counting is always forwards, so going back a day is six days on. + try std.testing.expectEqual(@as(u3, 6), weekdayDifference(.Tue, .Mon)); +} + test "weekdayDifference" { const difference = [7][7]u3{ [_]u3{ 0, 1, 2, 3, 4, 5, 6 }, diff --git a/src/formatsequence.zig b/src/formatsequence.zig index 6857dd9..acc5fe1 100644 --- a/src/formatsequence.zig +++ b/src/formatsequence.zig @@ -118,7 +118,7 @@ pub const FormatTag = enum { return @as(u30, @divTrunc(value, factor)); } - test "cnv" { + test convertFractionalSeconds { const cases = [_]struct { tag: FormatTag, expected: u30, value: u30 }{ .{ .tag = .S, .expected = 1, .value = 123456789 }, .{ .tag = .SS, .expected = 12, .value = 123456789 }, @@ -156,6 +156,12 @@ pub const FormatTag = enum { }; } + test init { + var it: Tokenizer = .init("YYYY"); + try std.testing.expectEqual(FormatTag.YYYY, it.next().?.tag); + try std.testing.expectEqual(@as(?Token, null), it.next()); + } + /// Returns the next token, or null when the format string is /// exhausted. pub fn next(self: *Tokenizer) ?Token { @@ -182,5 +188,16 @@ pub const FormatTag = enum { .char = self.format_string[self.index], }; } + + test next { + // The longest sequence that matches wins, so "MM" is one tag + // and not two of `M`, while the dash matches nothing and comes + // back as a literal. + var it: Tokenizer = .init("MM-D"); + try std.testing.expectEqual(FormatTag.MM, it.next().?.tag); + try std.testing.expectEqual(@as(u8, '-'), it.next().?.char); + try std.testing.expectEqual(FormatTag.D, it.next().?.tag); + try std.testing.expectEqual(@as(?Token, null), it.next()); + } }; }; diff --git a/src/hour.zig b/src/hour.zig index f391b1d..f9d9dcc 100644 --- a/src/hour.zig +++ b/src/hour.zig @@ -21,3 +21,16 @@ pub fn writeTwelveHour(hour: Hour, case: enum { lower, upper }, writer: anytype) .upper => try writer.writeAll("PM"), } } + +test writeTwelveHour { + var buf: [2]u8 = undefined; + + var lower = std.Io.Writer.fixed(&buf); + try writeTwelveHour(9, .lower, &lower); + try std.testing.expectEqualStrings("am", lower.buffered()); + + // Noon is already past the meridian, and so is every hour after it. + var upper = std.Io.Writer.fixed(&buf); + try writeTwelveHour(12, .upper, &upper); + try std.testing.expectEqualStrings("PM", upper.buffered()); +} diff --git a/src/iso8601.zig b/src/iso8601.zig index a212e04..fdd8c34 100644 --- a/src/iso8601.zig +++ b/src/iso8601.zig @@ -226,6 +226,28 @@ fn ordinalDate(cursor: *Cursor, year: Year, precision: *Precision) ParseError!Da return .{ .year = year, .month = month, .day = @intCast(remaining) }; } +test ordinalDate { + // Day 75 of 2024, which is a leap year, so the count reaches March 15 + // rather than the 16th. + var precision: Precision = .year; + var cursor: Cursor = .{ .text = "075" }; + try std.testing.expectEqual( + Date{ .year = 2024, .month = .Mar, .day = 15 }, + try ordinalDate(&cursor, 2024, &precision), + ); + try std.testing.expectEqual(Precision.day, precision); + + // 366 is a day in a leap year and not in an ordinary one. + var last: Cursor = .{ .text = "366" }; + try std.testing.expectEqual( + Date{ .year = 2024, .month = .Dec, .day = 31 }, + try ordinalDate(&last, 2024, &precision), + ); + + var overrun: Cursor = .{ .text = "366" }; + try std.testing.expectError(error.OutOfRange, ordinalDate(&overrun, 2025, &precision)); +} + /// Reads the `Www[-D]` of a week date. `year` is the ISO week-numbering /// year, which near New Year is not always the calendar year of the date /// it produces: 2027-W01-1 is 2027-01-04, while 2026-W53-5 is 2027-01-01. @@ -260,6 +282,36 @@ fn weekDate(cursor: *Cursor, year: Year, extended: bool, precision: *Precision) (@as(Date.DaysType, weekday) - 1)); } +test weekDate { + var precision: Precision = .year; + + // Week 11 of 2024, day 5, is Friday 15 March. + var cursor: Cursor = .{ .text = "11-5" }; + try std.testing.expectEqual( + Date{ .year = 2024, .month = .Mar, .day = 15 }, + try weekDate(&cursor, 2024, true, &precision), + ); + try std.testing.expectEqual(Precision.day, precision); + + // The week-numbering year is not always the calendar year of the date + // it produces: the first week of 2027 starts in the January that + // follows 2026's 53rd week. + var spanning: Cursor = .{ .text = "53-5" }; + try std.testing.expectEqual( + Date{ .year = 2027, .month = .Jan, .day = 1 }, + try weekDate(&spanning, 2026, true, &precision), + ); + + // Naming no day leaves the week as the precision, and the date on the + // Monday the week starts with. + var reduced: Cursor = .{ .text = "11" }; + try std.testing.expectEqual( + Date{ .year = 2024, .month = .Mar, .day = 11 }, + try weekDate(&reduced, 2024, true, &precision), + ); + try std.testing.expectEqual(Precision.week, precision); +} + /// The number of ISO weeks in `year`. A year has 53 when it starts on a /// Thursday, or when it is a leap year starting on a Wednesday, and 52 /// otherwise. @@ -273,6 +325,18 @@ pub fn isoWeeksInYear(year: Year) u8 { return 52; } +test isoWeeksInYear { + // 2026 begins on a Thursday, so it has a 53rd week. + try std.testing.expectEqual(@as(u8, 53), isoWeeksInYear(2026)); + + // 2020 is a leap year beginning on a Wednesday, the other way to get + // one, since the extra day pushes a Thursday into the final week. + try std.testing.expectEqual(@as(u8, 53), isoWeeksInYear(2020)); + + try std.testing.expectEqual(@as(u8, 52), isoWeeksInYear(2024)); + try std.testing.expectEqual(@as(u8, 52), isoWeeksInYear(2025)); +} + const Time = struct { hour: Hour = 0, minute: Minute = 0, @@ -375,6 +439,17 @@ fn agree(extended: *?bool, is_extended: bool) ParseError!void { if (known != is_extended) return error.MixedFormats; } +test agree { + // The first component to say which form it is in settles it. + var extended: ?bool = null; + try agree(&extended, true); + try std.testing.expectEqual(@as(?bool, true), extended); + + // Saying the same thing again is fine; contradicting it is not. + try agree(&extended, true); + try std.testing.expectError(error.MixedFormats, agree(&extended, false)); +} + /// Reads a zone, if one is there. Either spelling of the offset is taken /// whatever form the rest of the representation used; see `parse`. fn parseZone(cursor: *Cursor) ParseError!?i32 { @@ -404,6 +479,27 @@ fn parseZone(cursor: *Cursor) ParseError!?i32 { @as(i32, @intCast(minutes)) * std.time.s_per_min); } +test parseZone { + // Zulu is UTC. + var zulu: Cursor = .{ .text = "Z" }; + try std.testing.expectEqual(@as(?i32, 0), try parseZone(&zulu)); + + // Both spellings of an offset are accepted whatever form the rest of + // the representation was written in. + var extended: Cursor = .{ .text = "-05:00" }; + try std.testing.expectEqual(@as(?i32, -5 * std.time.s_per_hour), try parseZone(&extended)); + + var basic: Cursor = .{ .text = "+0545" }; + try std.testing.expectEqual( + @as(?i32, 5 * std.time.s_per_hour + 45 * std.time.s_per_min), + try parseZone(&basic), + ); + + // Null means the input named no zone, which is not the same as UTC. + var absent: Cursor = .{ .text = "" }; + try std.testing.expectEqual(@as(?i32, null), try parseZone(&absent)); +} + /// Turns a parsed month number into a `Month`, rejecting 0 and anything /// past 12. fn monthFrom(value: u32) ParseError!Month { @@ -411,6 +507,14 @@ fn monthFrom(value: u32) ParseError!Month { return std.enums.fromInt(Month, value) orelse unreachable; } +test monthFrom { + try std.testing.expectEqual(Month.Jan, try monthFrom(1)); + try std.testing.expectEqual(Month.Dec, try monthFrom(12)); + + try std.testing.expectError(error.OutOfRange, monthFrom(0)); + try std.testing.expectError(error.OutOfRange, monthFrom(13)); +} + /// Turns a parsed day number into a `Day`, checking it against the length /// of the month it falls in, which is why the year is needed as well. fn dayFrom(value: u32, month: Month, year: Year) ParseError!Day { @@ -418,6 +522,16 @@ fn dayFrom(value: u32, month: Month, year: Year) ParseError!Day { return @intCast(value); } +test dayFrom { + try std.testing.expectEqual(@as(Day, 31), try dayFrom(31, .Jan, 2024)); + + // The month and year are needed because the limit moves with them. + try std.testing.expectEqual(@as(Day, 29), try dayFrom(29, .Feb, 2024)); + try std.testing.expectError(error.OutOfRange, dayFrom(29, .Feb, 2025)); + try std.testing.expectError(error.OutOfRange, dayFrom(31, .Apr, 2024)); + try std.testing.expectError(error.OutOfRange, dayFrom(0, .Jan, 2024)); +} + /// A position in the input, with the small operations the grammar is /// written in terms of. /// @@ -436,11 +550,27 @@ const Cursor = struct { return self.index >= self.text.len; } + test done { + var cursor: Cursor = .{ .text = "5" }; + try std.testing.expect(!cursor.done()); + + cursor.index = 1; + try std.testing.expect(cursor.done()); + } + /// The character at the cursor. The caller must have checked `done`. fn peek(self: Cursor) u8 { return self.text[self.index]; } + test peek { + var cursor: Cursor = .{ .text = "2024" }; + try std.testing.expectEqual(@as(u8, '2'), cursor.peek()); + + // Peeking does not consume, so the answer does not change. + try std.testing.expectEqual(@as(u8, '2'), cursor.peek()); + } + /// Consumes `char` if it is next, and reports whether it was. fn eat(self: *Cursor, char: u8) bool { if (self.done() or self.peek() != char) return false; @@ -448,6 +578,17 @@ const Cursor = struct { return true; } + test eat { + var cursor: Cursor = .{ .text = "-03" }; + try std.testing.expect(cursor.eat('-')); + try std.testing.expectEqual(@as(usize, 1), cursor.index); + + // A refusal leaves the position alone, which is what lets the + // caller try something else. + try std.testing.expect(!cursor.eat('-')); + try std.testing.expectEqual(@as(usize, 1), cursor.index); + } + /// Consumes the next character if it is any of `chars`, and reports /// whether it was. fn eatAny(self: *Cursor, chars: []const u8) bool { @@ -457,6 +598,16 @@ const Cursor = struct { return true; } + test eatAny { + // The date and time may be joined by either case of T, or by a + // space, so the separator is matched against a set. + var cursor: Cursor = .{ .text = "t14" }; + try std.testing.expect(cursor.eatAny("Tt ")); + try std.testing.expectEqual(@as(usize, 1), cursor.index); + + try std.testing.expect(!cursor.eatAny("Tt ")); + } + /// The length of the run of digits at the cursor. fn digitsAhead(self: Cursor) usize { var count: usize = 0; @@ -465,6 +616,14 @@ const Cursor = struct { return count; } + test digitsAhead { + // How many digits follow is what tells `2024-075` from `2024-07`, + // so the run is measured before any of it is consumed. + try std.testing.expectEqual(@as(usize, 3), (Cursor{ .text = "075" }).digitsAhead()); + try std.testing.expectEqual(@as(usize, 2), (Cursor{ .text = "07-05" }).digitsAhead()); + try std.testing.expectEqual(@as(usize, 0), (Cursor{ .text = "W11" }).digitsAhead()); + } + /// Reads exactly `count` digits. fn digits(self: *Cursor, count: usize) ParseError!u32 { if (self.index + count > self.text.len) return error.ParseError; @@ -478,6 +637,21 @@ const Cursor = struct { return value; } + test digits { + var cursor: Cursor = .{ .text = "2024-03" }; + try std.testing.expectEqual(@as(u32, 2024), try cursor.digits(4)); + try std.testing.expect(cursor.eat('-')); + try std.testing.expectEqual(@as(u32, 3), try cursor.digits(2)); + + // Exactly `count` digits are required, so running out or hitting + // a non-digit is an error rather than a short read. + var short: Cursor = .{ .text = "20" }; + try std.testing.expectError(error.ParseError, short.digits(4)); + + var letters: Cursor = .{ .text = "20xx" }; + try std.testing.expectError(error.ParseError, letters.digits(4)); + } + /// Reads a decimal fraction, if one is there, and returns it scaled /// to `unit` nanoseconds, so ".5" of a minute is 30 seconds' worth. /// @@ -504,10 +678,65 @@ const Cursor = struct { return @intCast(numerator * unit / denominator); } + + test fraction { + // The fraction is of whatever component it follows, so the same + // digits mean different amounts against different units. + var half_minute: Cursor = .{ .text = ".5" }; + try std.testing.expectEqual(@as(?u64, std.time.ns_per_min / 2), try half_minute.fraction(std.time.ns_per_min)); + + // ISO 8601 allows a comma as well, and prefers it. + var comma: Cursor = .{ .text = ",25" }; + try std.testing.expectEqual(@as(?u64, std.time.ns_per_s / 4), try comma.fraction(std.time.ns_per_s)); + + // No fraction there at all is not an error; there just isn't one. + var none: Cursor = .{ .text = "Z" }; + try std.testing.expectEqual(@as(?u64, null), try none.fraction(std.time.ns_per_s)); + + // A separator with no digits after it is malformed. + var empty: Cursor = .{ .text = "." }; + try std.testing.expectError(error.BadFraction, empty.fraction(std.time.ns_per_s)); + } }; const testing = std.testing; +test parse { + // A full timestamp: date, time, and zone. + const full = try parse("2024-03-15T14:30:00Z"); + try testing.expectEqual(@as(Year, 2024), full.value.year); + try testing.expectEqual(Month.Mar, full.value.month); + try testing.expectEqual(@as(Day, 15), full.value.day); + try testing.expectEqual(@as(Hour, 14), full.value.hour); + try testing.expect(full.has_offset); + try testing.expectEqual(Precision.second, full.precision); + + // The basic form, written without separators, means the same thing. + const basic = try parse("20240315T143000Z"); + try testing.expectEqual(full.value, basic.value); + + // A representation may stop early, and `precision` says where. What + // was not written is defaulted, so this is midnight on the first. + const reduced = try parse("2024-03"); + try testing.expectEqual(Precision.month, reduced.precision); + try testing.expectEqual(@as(Day, 1), reduced.value.day); + try testing.expectEqual(@as(Hour, 0), reduced.value.hour); + + // A local time says nothing about its offset, which `has_offset` + // reports and a zero `offset` cannot. + const local = try parse("2024-03-15T14:30:00"); + try testing.expect(!local.has_offset); + + // Only the representation is consumed; the rest is the caller's. + // Note that a space is one of the separators a time may follow the + // date with, so trailing text has to start past a complete one. + const trailing = try parse("2024-03-15T14:30:00Z and then some"); + try testing.expectEqualStrings("2024-03-15T14:30:00Z", trailing.str); + + // The date and the time must agree about which form they are in. + try testing.expectError(error.MixedFormats, parse("2024-03-15T143000")); +} + /// Asserts that `input` parses whole, to the given value, offset flag and /// precision. fn expectParse( @@ -525,6 +754,74 @@ fn expectParse( try testing.expectEqualStrings(input, result.str); } +test parseDate { + // The three forms are told apart by what follows the year: a two + // digit month, a three digit ordinal day, or a W. + var extended: ?bool = null; + var precision: Precision = .year; + + var calendar: Cursor = .{ .text = "2024-03-15" }; + try testing.expectEqual( + Date{ .year = 2024, .month = .Mar, .day = 15 }, + try parseDate(&calendar, &extended, &precision), + ); + try testing.expectEqual(@as(?bool, true), extended); + + extended = null; + var ordinal: Cursor = .{ .text = "2024-075" }; + try testing.expectEqual( + Date{ .year = 2024, .month = .Mar, .day = 15 }, + try parseDate(&ordinal, &extended, &precision), + ); + + extended = null; + var week: Cursor = .{ .text = "2024-W11-5" }; + try testing.expectEqual( + Date{ .year = 2024, .month = .Mar, .day = 15 }, + try parseDate(&week, &extended, &precision), + ); + + // A bare year is too short to say which form it is in, so `extended` + // is left for a later component to settle, and nothing below the year + // was named, so `precision` is left where the caller set it. + extended = null; + precision = .year; + var year_only: Cursor = .{ .text = "2024" }; + try testing.expectEqual( + Date{ .year = 2024, .month = .Jan, .day = 1 }, + try parseDate(&year_only, &extended, &precision), + ); + try testing.expectEqual(@as(?bool, null), extended); + try testing.expectEqual(Precision.year, precision); +} + +test parseTime { + var extended: ?bool = null; + var precision: Precision = .year; + + var cursor: Cursor = .{ .text = "14:30:05" }; + const time = try parseTime(&cursor, &extended, &precision); + try testing.expectEqual(@as(Hour, 14), time.hour); + try testing.expectEqual(@as(Minute, 30), time.minute); + try testing.expectEqual(@as(Second, 5), time.second); + try testing.expectEqual(Precision.second, precision); + + // A fraction may sit on whichever component is the last one written, + // so half past an hour can be spelled either way. + extended = null; + var fractional: Cursor = .{ .text = "14.5" }; + const half = try parseTime(&fractional, &extended, &precision); + try testing.expectEqual(@as(Hour, 14), half.hour); + try testing.expectEqual(@as(Minute, 30), half.minute); + + // 24:00 is the end of a day rather than the start of one, which the + // caller resolves by moving to the following date. + extended = null; + var end: Cursor = .{ .text = "24:00" }; + const midnight = try parseTime(&end, &extended, &precision); + try testing.expect(midnight.end_of_day); +} + test "calendar dates in both forms" { const march15: DateTime = .{ .year = 2024, .month = .Mar, .day = 15, .weekday = .Fri }; diff --git a/src/leap.zig b/src/leap.zig index 5f4cf52..e9b0b62 100644 --- a/src/leap.zig +++ b/src/leap.zig @@ -31,7 +31,7 @@ pub fn is(year: Year) bool { // return @rem(year, 4) == 0 and (@rem(year, 100) != 0 or @rem(year, 400) == 0); } -test "isLeap" { +test is { const testing = @import("std").testing; try testing.expectEqual(false, is(2005)); try testing.expectEqual(true, is(2096)); diff --git a/src/month.zig b/src/month.zig index e9e4ead..6503b5c 100644 --- a/src/month.zig +++ b/src/month.zig @@ -34,13 +34,18 @@ pub const Month = enum(u4) { pub fn as(self: Month, comptime T: type) T { const info = @typeInfo(T); if (info != .int) @compileError("can't convert to anything but an int"); - switch (info.bits.signedness) { + switch (info.int.signedness) { .signed => if (info.int.bits < 5) @compileError("must have at least 5 bits"), .unsigned => if (info.int.bits < 4) @compileError("must have at least 4 bits"), } return @intCast(@intFromEnum(self)); } + test as { + try std.testing.expectEqual(@as(u4, 1), Month.Jan.as(u4)); + try std.testing.expectEqual(@as(i32, 12), Month.Dec.as(i32)); + } + /// What `parseInt` and the name parsers can fail with. pub const ParseError = error{ TooShort, @@ -65,6 +70,18 @@ pub const Month = enum(u4) { return std.enums.fromInt(Month, @as(u4, @intCast(month))) orelse unreachable; } + test parseInt { + try std.testing.expectEqual(Month.Mar, try parseInt("3")); + // A leading zero is accepted, since dates are written with one. + try std.testing.expectEqual(Month.Mar, try parseInt("03")); + try std.testing.expectEqual(Month.Dec, try parseInt("12")); + + try std.testing.expectError(error.Overflow, parseInt("13")); + try std.testing.expectError(error.Underflow, parseInt("0")); + try std.testing.expectError(error.TooShort, parseInt("")); + try std.testing.expectError(error.IllegalCharacter, parseInt("1x")); + } + /// Returns the calendar month number, January = 1 through December = 12. pub fn monthNumber(self: Month) u4 { return switch (self) { @@ -83,6 +100,11 @@ pub const Month = enum(u4) { }; } + test monthNumber { + try std.testing.expectEqual(@as(u4, 1), Month.Jan.monthNumber()); + try std.testing.expectEqual(@as(u4, 12), Month.Dec.monthNumber()); + } + /// Returns the month after this one, wrapping from December to January. pub fn next(self: Month) Month { return switch (self) { @@ -101,6 +123,12 @@ pub const Month = enum(u4) { }; } + test next { + try std.testing.expectEqual(Month.Feb, Month.Jan.next()); + // December wraps round to January. + try std.testing.expectEqual(Month.Jan, Month.Dec.next()); + } + /// Returns the month before this one, wrapping from January to December. pub fn prev(self: Month) Month { return switch (self) { @@ -119,6 +147,12 @@ pub const Month = enum(u4) { }; } + test prev { + try std.testing.expectEqual(Month.Nov, Month.Dec.prev()); + // January wraps back to December. + try std.testing.expectEqual(Month.Dec, Month.Jan.prev()); + } + /// Returns the number of the last day of this month (28-31) in `year`, /// accounting for leap years. pub fn lastDay(self: Month, year: Year) Day { @@ -138,6 +172,15 @@ pub const Month = enum(u4) { }; } + test lastDay { + try std.testing.expectEqual(@as(Day, 31), Month.Jan.lastDay(2024)); + try std.testing.expectEqual(@as(Day, 30), Month.Apr.lastDay(2024)); + + // Only February depends on the year. + try std.testing.expectEqual(@as(Day, 29), Month.Feb.lastDay(2024)); + try std.testing.expectEqual(@as(Day, 28), Month.Feb.lastDay(2025)); + } + /// Returns the quarter of the year (1-4) containing this month. pub fn quarter(self: Month) u3 { return switch (self) { @@ -156,6 +199,12 @@ pub const Month = enum(u4) { }; } + test quarter { + try std.testing.expectEqual(@as(u3, 1), Month.Mar.quarter()); + try std.testing.expectEqual(@as(u3, 2), Month.Apr.quarter()); + try std.testing.expectEqual(@as(u3, 4), Month.Dec.quarter()); + } + /// Returns the three-letter English name ("Jan" ... "Dec"). pub fn shortName(self: Month) []const u8 { return switch (self) { @@ -174,6 +223,11 @@ pub const Month = enum(u4) { }; } + test shortName { + try std.testing.expectEqualStrings("Jan", Month.Jan.shortName()); + try std.testing.expectEqualStrings("Sep", Month.Sep.shortName()); + } + /// Returns the full English name ("January" ... "December"). pub fn longName(self: Month) []const u8 { return switch (self) { @@ -192,6 +246,12 @@ pub const Month = enum(u4) { }; } + test longName { + try std.testing.expectEqualStrings("January", Month.Jan.longName()); + // May is the one name that is the same at both lengths. + try std.testing.expectEqualStrings("May", Month.May.longName()); + } + /// Returns the number of days in `year` that pass before the first of /// this month, accounting for leap years. pub fn daysBefore(self: Month, year: Year) u9 { @@ -211,6 +271,17 @@ pub const Month = enum(u4) { }; } + test daysBefore { + // Nothing passes before January, and January's 31 days before + // February whatever the year. + try std.testing.expectEqual(@as(u9, 0), Month.Jan.daysBefore(2024)); + try std.testing.expectEqual(@as(u9, 31), Month.Feb.daysBefore(2024)); + + // From March on, a leap year has put one more day behind it. + try std.testing.expectEqual(@as(u9, 60), Month.Mar.daysBefore(2024)); + try std.testing.expectEqual(@as(u9, 59), Month.Mar.daysBefore(2025)); + } + /// Walks the months in order. The cursor is nulled once `next` wraps /// back around to January, which is what ends the iteration; there is /// no separate count to keep. @@ -221,6 +292,10 @@ pub const Month = enum(u4) { pub const init: Iterator = .{ .index = .Jan }; /// Returns the next month, or null once December has been returned. + /// + /// This has no doctest of its own: a doctest is named by a bare + /// identifier, and `next` here would be ambiguous with `Month.next` + /// in the enclosing scope. See the one on `Month.iterator`. pub fn next(self: *Iterator) ?Month { defer { if (self.index) |i| { @@ -240,6 +315,20 @@ pub const Month = enum(u4) { return .init; } + test iterator { + var count: usize = 0; + var last: ?Month = null; + + var it = iterator(); + while (it.next()) |month| { + count += 1; + last = month; + } + + try std.testing.expectEqual(@as(usize, 12), count); + try std.testing.expectEqual(Month.Dec, last.?); + } + /// The three-letter month names, "jan" through "dec". Comparison /// ignores case, so only lower-case keys are carried. pub const short_map = std.StaticStringMapWithEql(Month, std.ascii.eqlIgnoreCase).initComptime( diff --git a/src/ordinal.zig b/src/ordinal.zig index 9b9ab52..bcd8dc0 100644 --- a/src/ordinal.zig +++ b/src/ordinal.zig @@ -17,6 +17,15 @@ fn exact(a: []const u8, b: []const u8) bool { return std.mem.eql(u8, a, b); } +test exact { + // The maps are keyed on exact bytes rather than folded case, because + // the superscript suffixes have no case to fold and the ASCII ones + // only ever appear lower case in a formatted date. + try std.testing.expect(exact("st", "st")); + try std.testing.expect(!exact("st", "ST")); + try std.testing.expect(!exact("st", "s")); +} + /// Returns a namespace whose `map` recognizes the English ordinal suffixes /// ("st", "nd", "rd", "th") in the given style: plain ASCII for `.normal`, /// Unicode superscript letters for `.superscript`. @@ -44,3 +53,17 @@ pub fn Ordinal(comptime style: enum { normal, superscript }) type { }; }; } + +test Ordinal { + const plain = Ordinal(.normal).map; + // Only membership matters: a hit says the two bytes were a suffix. + try std.testing.expect(plain.get("st") != null); + try std.testing.expect(plain.get("nd") != null); + try std.testing.expect(plain.get("xx") == null); + + // The superscript style spells the same four suffixes in Unicode + // superscript letters, so the ASCII ones are not in it. + const super = Ordinal(.superscript).map; + try std.testing.expect(super.get("ˢᵗ") != null); + try std.testing.expect(super.get("st") == null); +} diff --git a/src/posixtz.zig b/src/posixtz.zig index 64cee45..3a9f3f8 100644 --- a/src/posixtz.zig +++ b/src/posixtz.zig @@ -92,6 +92,31 @@ pub const Rule = union(enum) { }, } } + + test dayOfMonth { + // The United States rules: the second Sunday of March and the + // first Sunday of November. + const march: Rule = .{ .month_week_day = .{ .month = .Mar, .week = 2, .weekday = .Sun } }; + try std.testing.expectEqual(Month.Mar, march.dayOfMonth(2024).month); + try std.testing.expectEqual(@as(Day, 10), march.dayOfMonth(2024).day); + + // Week 5 means the last such weekday, however many there are. + const last: Rule = .{ .month_week_day = .{ .month = .Mar, .week = 5, .weekday = .Sun } }; + try std.testing.expectEqual(@as(Day, 31), last.dayOfMonth(2024).day); + + // `Jn` never counts February 29, so J60 is March 1 in any year. + const julian: Rule = .{ .julian_no_leap = 60 }; + try std.testing.expectEqual(Month.Mar, julian.dayOfMonth(2024).month); + try std.testing.expectEqual(@as(Day, 1), julian.dayOfMonth(2024).day); + try std.testing.expectEqual(Month.Mar, julian.dayOfMonth(2025).month); + + // The zero-based form does count it, so the same ordinal lands a + // day earlier in a leap year than it does in an ordinary one. + const zero_based: Rule = .{ .julian = 59 }; + try std.testing.expectEqual(Month.Feb, zero_based.dayOfMonth(2024).month); + try std.testing.expectEqual(@as(Day, 29), zero_based.dayOfMonth(2024).day); + try std.testing.expectEqual(Month.Mar, zero_based.dayOfMonth(2025).month); + } }; /// A switch into or out of daylight saving time. @@ -109,6 +134,18 @@ pub const Transition = struct { const midnight = @as(i64, date.toDaysSinceStartOfEra()) * std.time.s_per_day; return midnight + self.time - offset_before; } + + test timestamp { + // The second Sunday of March 2024 is the 10th, and the switch + // defaults to 02:00 local time. The offset in effect just before + // it is standard time, which is what turns that into UTC. + const transition: Transition = .{ + .rule = .{ .month_week_day = .{ .month = .Mar, .week = 2, .weekday = .Sun } }, + }; + + const at = transition.timestamp(2024, -6 * std.time.s_per_hour); + try std.testing.expectEqual(@as(i64, 1710057600), at); + } }; /// The daylight saving half of a rule: what the clock reads then, what it @@ -209,6 +246,30 @@ pub const Posix = struct { }; } + test spanAt { + const rule = try parse("CST6CDT,M3.2.0,M11.1.0"); + + // Midsummer 2024 falls inside daylight saving time, and the span runs + // from the March switch to the November one. + const summer = rule.spanAt(1720000000); + try testing.expect(summer.local_type.is_dst); + try testing.expectEqualStrings("CDT", summer.local_type.designation); + try testing.expectEqual(@as(i64, 1710057600), summer.start); + try testing.expectEqual(@as(i64, 1730617200), summer.end); + + // Midwinter is standard time, and its span is bounded by the switches + // in the years either side, which is why three years are computed. + const winter = rule.spanAt(1704067200); + try testing.expect(!winter.local_type.is_dst); + try testing.expectEqualStrings("CST", winter.local_type.designation); + + // A zone that never switches has one span covering all of time. + const fixed = try parse("<-03>3"); + const always = fixed.spanAt(0); + try testing.expectEqual(@as(i64, std.math.minInt(i64)), always.start); + try testing.expectEqual(@as(i64, std.math.maxInt(i64)), always.end); + } + /// Returns the local time type in effect at `timestamp`. pub fn typeAt(self: Posix, timestamp: i64) Type { const dst = self.dst orelse return .{ @@ -244,6 +305,18 @@ pub const Posix = struct { .designation = self.std_designation, }; } + + test typeAt { + const rule = try parse("CST6CDT,M3.2.0,M11.1.0"); + + const summer = rule.typeAt(1720000000); + try testing.expect(summer.is_dst); + try testing.expectEqual(@as(i32, -5 * std.time.s_per_hour), summer.offset); + + const winter = rule.typeAt(1704067200); + try testing.expect(!winter.is_dst); + try testing.expectEqual(@as(i32, -6 * std.time.s_per_hour), winter.offset); + } }; /// Parses a POSIX TZ string. The returned value borrows the designations @@ -304,17 +377,40 @@ const Cursor = struct { return self.index >= self.text.len; } + test done { + var cursor: Cursor = .{ .text = "5" }; + try std.testing.expect(!cursor.done()); + + cursor.index = 1; + try std.testing.expect(cursor.done()); + } + /// The character at the cursor. The caller must have checked `done`. fn peek(self: Cursor) u8 { return self.text[self.index]; } + test peek { + const cursor: Cursor = .{ .text = "<-03>3" }; + try std.testing.expectEqual(@as(u8, '<'), cursor.peek()); + } + /// Consumes `char`, which the grammar requires to be next. fn expect(self: *Cursor, char: u8) ParseError!void { if (self.done() or self.peek() != char) return error.BadRule; self.index += 1; } + test expect { + // The dots of an `Mm.w.d` rule are required, so a missing one is + // a malformed rule rather than the end of the field. + var cursor: Cursor = .{ .text = ".2.0" }; + try cursor.expect('.'); + try std.testing.expectEqual(@as(usize, 1), cursor.index); + + try std.testing.expectError(error.BadRule, cursor.expect('.')); + } + /// Reads a zone abbreviation, either three or more letters or any run /// of letters, digits and signs inside angle brackets. fn designation(self: *Cursor) ParseError![]const u8 { @@ -343,6 +439,25 @@ const Cursor = struct { return name; } + test designation { + // The bare form is a run of three or more letters. + var plain: Cursor = .{ .text = "CST6CDT" }; + try std.testing.expectEqualStrings("CST", try plain.designation()); + + // The bracketed form is what lets a name hold digits and signs, + // which is how the numeric zone abbreviations are written. + var bracketed: Cursor = .{ .text = "<-03>3" }; + try std.testing.expectEqualStrings("-03", try bracketed.designation()); + // The closing bracket is consumed too, leaving the offset next. + try std.testing.expectEqualStrings("3", bracketed.text[bracketed.index..]); + + var too_short: Cursor = .{ .text = "ES5" }; + try std.testing.expectError(error.BadDesignation, too_short.designation()); + + var unclosed: Cursor = .{ .text = "3"); + try testing.expectEqualStrings("-03", fixed.std_designation); + try testing.expectEqual(@as(?Dst, null), fixed.dst); + + // Naming a daylight saving time without saying when it applies is + // something POSIX allows but this cannot evaluate. + try testing.expectError(error.MissingRules, parse("EST5EDT")); +} + test "parse a rule with no daylight saving time" { const rule = try parse("IST-5:30"); try testing.expectEqualStrings("IST", rule.std_designation); diff --git a/src/print.zig b/src/print.zig index b4a2690..19d2446 100644 --- a/src/print.zig +++ b/src/print.zig @@ -65,6 +65,24 @@ pub fn ordinal(writer: anytype, num: anytype, superscript: bool) !void { ); } +test ordinal { + var buf: [8]u8 = undefined; + + var first = std.Io.Writer.fixed(&buf); + try ordinal(&first, @as(u16, 1), false); + try std.testing.expectEqualStrings("1st", first.buffered()); + + // The teens are the exception: 11 through 13 take "th" even though + // their last digit says otherwise. + var teen = std.Io.Writer.fixed(&buf); + try ordinal(&teen, @as(u16, 11), false); + try std.testing.expectEqualStrings("11th", teen.buffered()); + + var super = std.Io.Writer.fixed(&buf); + try ordinal(&super, @as(u16, 2), true); + try std.testing.expectEqualStrings("2ⁿᵈ", super.buffered()); +} + test "print ordinal normal" { const cases = [_]struct { number: u16, result: []const u8 }{ .{ @@ -207,7 +225,7 @@ pub fn offset(writer: anytype, seconds: i32, separator: enum { none, colon }) !v try writer.print("{d:0>2}", .{magnitude % std.time.s_per_hour / std.time.s_per_min}); } -test "offset" { +test offset { const cases = [_]struct { seconds: i32, colon: []const u8, none: []const u8 }{ .{ .seconds = 0, .colon = "+00:00", .none = "+0000" }, .{ .seconds = -5 * std.time.s_per_hour, .colon = "-05:00", .none = "-0500" }, diff --git a/src/read.zig b/src/read.zig index 2b43abc..e2f2f6d 100644 --- a/src/read.zig +++ b/src/read.zig @@ -50,7 +50,7 @@ pub fn digits(text: []const u8) u32 { return value; } -test "digits" { +test digits { try std.testing.expectEqual(@as(u32, 0), digits("")); try std.testing.expectEqual(@as(u32, 7), digits("7")); try std.testing.expectEqual(@as(u32, 7), digits("07")); @@ -70,7 +70,16 @@ pub fn nanosecond(text: []const u8, length: usize) !Nanosecond { try std.math.powi(Nanosecond, 10, 9 - @as(Nanosecond, @intCast(length))); } -test "int" { +test nanosecond { + // The length is the number of digits the field was written with, so + // the same digits mean different amounts at different lengths. + try std.testing.expectEqual(@as(Nanosecond, 500000000), try nanosecond("5", 1)); + try std.testing.expectEqual(@as(Nanosecond, 120000000), try nanosecond("12", 2)); + try std.testing.expectEqual(@as(Nanosecond, 123456789), try nanosecond("123456789", 9)); + try std.testing.expectError(error.TooShort, nanosecond("1", 2)); +} + +test int { // A digit run that reaches the end of the input is returned in full // even when it is shorter than maxlen. try std.testing.expectEqualStrings("5", int("5", 2)); diff --git a/src/rfc822.zig b/src/rfc822.zig index dfad7e1..33391dd 100644 --- a/src/rfc822.zig +++ b/src/rfc822.zig @@ -164,16 +164,37 @@ const Cursor = struct { return self.text[self.index..]; } + test rest { + var cursor: Cursor = .{ .text = "06 Nov 1994" }; + try std.testing.expectEqualStrings("06 Nov 1994", cursor.rest()); + + cursor.index = 3; + try std.testing.expectEqualStrings("Nov 1994", cursor.rest()); + } + /// Whether the input is exhausted. fn done(self: Cursor) bool { return self.index >= self.text.len; } + test done { + var cursor: Cursor = .{ .text = "Z" }; + try std.testing.expect(!cursor.done()); + + cursor.index = 1; + try std.testing.expect(cursor.done()); + } + /// The character at the cursor. The caller must have checked `done`. fn peek(self: Cursor) u8 { return self.text[self.index]; } + test peek { + const cursor: Cursor = .{ .text = "GMT" }; + try std.testing.expectEqual(@as(u8, 'G'), cursor.peek()); + } + /// Consumes `char` if it is next, and reports whether it was. fn eat(self: *Cursor, char: u8) bool { if (self.done() or self.peek() != char) return false; @@ -181,16 +202,47 @@ const Cursor = struct { return true; } + test eat { + // The comma after the day name is optional, so it is tried + // rather than required, and a refusal costs the caller nothing. + var cursor: Cursor = .{ .text = ", 06 Nov" }; + try std.testing.expect(cursor.eat(',')); + try std.testing.expectEqual(@as(usize, 1), cursor.index); + + try std.testing.expect(!cursor.eat(',')); + try std.testing.expectEqual(@as(usize, 1), cursor.index); + } + /// Consumes `char`, which must be next. fn literal(self: *Cursor, char: u8) ParseError!void { if (!self.eat(char)) return error.ParseError; } + test literal { + // The colon between the hour and the minute is not optional. + var cursor: Cursor = .{ .text = ":49" }; + try cursor.literal(':'); + try std.testing.expectEqual(@as(usize, 1), cursor.index); + + try std.testing.expectError(error.ParseError, cursor.literal(':')); + } + /// Consumes any run of spaces and tabs. fn skipSpace(self: *Cursor) void { while (!self.done() and (self.peek() == ' ' or self.peek() == '\t')) self.index += 1; } + test skipSpace { + // RFC 822 allows runs of spaces and tabs between components. + var cursor: Cursor = .{ .text = " \tNov" }; + cursor.skipSpace(); + try std.testing.expectEqualStrings("Nov", cursor.rest()); + + // Finding none is not a failure here. + cursor.skipSpace(); + try std.testing.expectEqualStrings("Nov", cursor.rest()); + } + /// Consumes a run of spaces and tabs, requiring at least one. fn skipRequiredSpace(self: *Cursor) ParseError!void { const before = self.index; @@ -198,6 +250,15 @@ const Cursor = struct { if (self.index == before) return error.ParseError; } + test skipRequiredSpace { + var cursor: Cursor = .{ .text = " Nov" }; + try cursor.skipRequiredSpace(); + try std.testing.expectEqualStrings("Nov", cursor.rest()); + + // Where the grammar needs a separator, having none is an error. + try std.testing.expectError(error.ParseError, cursor.skipRequiredSpace()); + } + /// Consumes between `min_len` and `max_len` ASCII digits and returns /// their value along with how many were read. `max_len` must be at /// most 4 so that the value always fits in a `u16`. @@ -219,6 +280,27 @@ const Cursor = struct { return .{ .value = value, .len = len }; } + test digits { + // The length is reported as well as the value, because it is what + // tells a two digit year from a four digit one. + var cursor: Cursor = .{ .text = "1994" }; + const four = try cursor.digits(1, 4); + try std.testing.expectEqual(@as(u16, 1994), four.value); + try std.testing.expectEqual(@as(usize, 4), four.len); + + var short: Cursor = .{ .text = "82 " }; + const two = try short.digits(1, 4); + try std.testing.expectEqual(@as(u16, 82), two.value); + try std.testing.expectEqual(@as(usize, 2), two.len); + + // Reading stops at `max_len` even when more digits follow. + var capped: Cursor = .{ .text = "123456" }; + try std.testing.expectEqual(@as(u16, 1234), (try capped.digits(1, 4)).value); + + var none: Cursor = .{ .text = "Nov" }; + try std.testing.expectError(error.ParseError, none.digits(1, 4)); + } + /// Parses a zone and returns it as seconds east of UTC. Both the /// numeric `("+" / "-") 4DIGIT` form and the named forms are accepted. /// A name is taken to be the whole run of letters that follows, so @@ -254,6 +336,22 @@ const Cursor = struct { self.index += len; return offset; } + + test zone { + var numeric: Cursor = .{ .text = "-0600" }; + try std.testing.expectEqual(@as(i32, -6 * std.time.s_per_hour), try numeric.zone()); + + var named: Cursor = .{ .text = "GMT" }; + try std.testing.expectEqual(@as(i32, 0), try named.zone()); + + // The whole run of letters is taken, so this is Mountain Standard + // Time and not the military zone `M` with `ST` left over. + var three: Cursor = .{ .text = "MST" }; + try std.testing.expectEqual(@as(i32, -7 * std.time.s_per_hour), try three.zone()); + + var military: Cursor = .{ .text = "Z" }; + try std.testing.expectEqual(@as(i32, 0), try military.zone()); + } }; /// The named zones of RFC 822 section 5.1, as seconds east of UTC, plus @@ -293,6 +391,48 @@ fn militaryZone(letter: u8) ?i32 { return hours * std.time.s_per_hour; } +test militaryZone { + // RFC 822 gives these letters the opposite sign to the military + // standard they came from, and that is what is implemented. + try std.testing.expectEqual(@as(?i32, 0), militaryZone('Z')); + try std.testing.expectEqual(@as(?i32, -1 * std.time.s_per_hour), militaryZone('A')); + try std.testing.expectEqual(@as(?i32, -12 * std.time.s_per_hour), militaryZone('M')); + try std.testing.expectEqual(@as(?i32, 1 * std.time.s_per_hour), militaryZone('N')); + + // Matching ignores case, and `J` is deliberately unassigned. + try std.testing.expectEqual(@as(?i32, -1 * std.time.s_per_hour), militaryZone('a')); + try std.testing.expectEqual(@as(?i32, null), militaryZone('J')); + try std.testing.expectEqual(@as(?i32, null), militaryZone('0')); +} + +test parse { + const result = try parse("Sun, 06 Nov 1994 08:49:37 GMT"); + try std.testing.expectEqual(@as(Year, 1994), result.value.year); + try std.testing.expectEqual(Month.Nov, result.value.month); + try std.testing.expectEqual(@as(Day, 6), result.value.day); + try std.testing.expectEqual(@as(Hour, 8), result.value.hour); + try std.testing.expectEqual(DayOfWeek.Sun, result.value.weekday); + try std.testing.expectEqual(@as(i32, 0), result.value.offset); + + // The day name, its comma and the seconds are all optional, and a two + // digit year is the obsolete RFC 822 form windowed into this century. + const terse = try parse("20 Jun 82 12:34 -0500"); + try std.testing.expectEqual(@as(Year, 1982), terse.value.year); + try std.testing.expectEqual(@as(Second, 0), terse.value.second); + try std.testing.expectEqual(@as(i32, -5 * std.time.s_per_hour), terse.value.offset); + + // Only the date is consumed, so a header with more after it can carry + // on from where this stopped. + try std.testing.expectEqualStrings( + "Sun, 06 Nov 1994 08:49:37 GMT", + (try parse("Sun, 06 Nov 1994 08:49:37 GMT (comment)")).str, + ); + + // A day name that disagrees with the date is rejected rather than + // believed. + try std.testing.expectError(error.ParseError, parse("Mon, 06 Nov 1994 08:49:37 GMT")); +} + test "parse" { const cases = [_]struct { value: []const u8, expected: DateTime }{ // RFC 822 section 5 and RFC 2822 appendix A.1.1. diff --git a/src/si.zig b/src/si.zig index a94043f..1fca097 100644 --- a/src/si.zig +++ b/src/si.zig @@ -48,6 +48,11 @@ pub const Prefix = enum(i8) { return @intFromEnum(self); } + test exponent { + try std.testing.expectEqual(@as(i8, 3), Prefix.kilo.exponent()); + try std.testing.expectEqual(@as(i8, -9), Prefix.nano.exponent()); + } + /// Returns the SI symbol for this prefix (e.g. "k" for kilo, "µ" for /// micro). Asserts that this is one of the named SI prefixes. pub fn symbol(self: Prefix) []const u8 { @@ -79,6 +84,11 @@ pub const Prefix = enum(i8) { _ => unreachable, }; } + + test symbol { + try std.testing.expectEqualStrings("k", Prefix.kilo.symbol()); + try std.testing.expectEqualStrings("µ", Prefix.micro.symbol()); + } }; /// Converts `value` from units of prefix `from` to units of prefix `to`. @@ -99,12 +109,7 @@ pub fn convert(from: Prefix, to: Prefix, value: i128) struct { result: i128, rem return .{ .result = value, .remainder = 0 }; } -test "symbol" { - try std.testing.expectEqualStrings("k", Prefix.kilo.symbol()); - try std.testing.expectEqualStrings("µ", Prefix.micro.symbol()); -} - -test "convert-1" { +test convert { const result = convert(.milli, .micro, 1); try std.testing.expectEqual(@as(i128, 1000), result.result); try std.testing.expectEqual(@as(i128, 0), result.remainder); diff --git a/src/tzdb.zig b/src/tzdb.zig index 4ab569d..3353590 100644 --- a/src/tzdb.zig +++ b/src/tzdb.zig @@ -32,6 +32,23 @@ pub fn validateName(name: []const u8) InvalidNameError!void { }; } +test validateName { + // Ordinary IANA names, including the `Etc/GMT+5` family and the + // legacy `US/Central` spellings, all pass. + try validateName("UTC"); + try validateName("America/Chicago"); + try validateName("Etc/GMT+5"); + try validateName("US/Central"); + + // A name arriving from `TZ` must not be able to walk out of the zone + // directory or name an absolute path, since it becomes one. + try std.testing.expectError(error.InvalidZoneName, validateName("../../etc/passwd")); + try std.testing.expectError(error.InvalidZoneName, validateName("/etc/passwd")); + try std.testing.expectError(error.InvalidZoneName, validateName(".hidden")); + try std.testing.expectError(error.InvalidZoneName, validateName("")); + try std.testing.expectError(error.InvalidZoneName, validateName("America/Chicago\x00")); +} + /// The operating system's copy of the IANA database. /// /// Which directory holds that copy, and which zone the user wants, are @@ -170,6 +187,26 @@ pub const system = struct { return .{ .name = body }; } + test resolveTz { + // Unset means the machine's own zone; set but empty means UTC. + try std.testing.expectEqual(Tz.local, resolveTz(null)); + try std.testing.expectEqual(Tz.utc, resolveTz("")); + + // A leading colon is the tzcode convention for "implementation + // defined", and is dropped before the rest is classified. + try std.testing.expectEqualStrings("America/Chicago", resolveTz("America/Chicago").name); + try std.testing.expectEqualStrings("America/Chicago", resolveTz(":America/Chicago").name); + + // An absolute path bypasses TZDIR entirely. + try std.testing.expectEqualStrings("/etc/localtime", resolveTz("/etc/localtime").path); + + // A rule names no file, so there is nothing to look for. Note + // that `Etc/GMT+5` is a zone name and not a rule, which is what + // makes this more than a look at the first character. + try std.testing.expectEqualStrings("CST6CDT,M3.2.0,M11.1.0", resolveTz("CST6CDT,M3.2.0,M11.1.0").rule); + try std.testing.expectEqualStrings("Etc/GMT+5", resolveTz("Etc/GMT+5").name); + } + /// A TZif file for a single zone is a few kilobytes at most; the /// largest in the 2026c release is well under 32 KiB. const size_limit: std.Io.Limit = .limited(1 << 20); @@ -206,6 +243,22 @@ pub const system = struct { return try gpa.dupe(u8, found); } + test version { + // Read from the first line of `tzdata.zi`, which not every + // system ships, so null is an ordinary answer rather than an + // error. The caller owns the string when there is one. + for (search_directories) |directory| { + const found = (try version(testing.io, testing.allocator, directory)) orelse continue; + defer testing.allocator.free(found); + + // A release is a year and a letter, such as "2026c". + try testing.expect(found.len >= 5); + try testing.expect(std.ascii.isDigit(found[0])); + return; + } + return error.SkipZigTest; + } + /// What `load` can fail with: a name that does not validate, anything /// that goes wrong reading the file, anything wrong with its contents, /// or a failed allocation. @@ -245,6 +298,26 @@ pub const system = struct { return TimeZone.fromOwnedBytes(owned_name, bytes); } + test load { + for (search_directories) |directory| { + var zone = load(testing.io, testing.allocator, directory, "America/Chicago") catch continue; + defer zone.deinit(testing.allocator); + + try testing.expectEqualStrings("America/Chicago", zone.name); + try testing.expectEqual(@as(i32, -6 * std.time.s_per_hour), zone.offsetAt(1705320000)); + + // The name is validated before it is joined onto the + // directory, so a value taken straight from `TZ` cannot walk + // out of the tree. + try testing.expectError( + error.InvalidZoneName, + load(testing.io, testing.allocator, directory, "../../etc/passwd"), + ); + return; + } + return error.SkipZigTest; + } + /// Loads a zone from a TZif file directly, rather than by name. /// /// With `path` null this reads `/etc/localtime`, which is the @@ -270,6 +343,18 @@ pub const system = struct { return TimeZone.fromOwnedBytes(owned_name, bytes); } + + test loadLocal { + // Passing null reads the machine's own zone from + // `/etc/localtime`, which is a path rather than a name and so + // needs no TZDIR. + var zone = loadLocal(testing.io, testing.allocator, null) catch return error.SkipZigTest; + defer zone.deinit(testing.allocator); + + // The zone it names is not knowable here, but it is a real one. + try testing.expectEqualStrings("localtime", zone.name); + _ = zone.offsetAt(0); + } }; /// The copy of the database compiled into this binary. @@ -295,11 +380,33 @@ pub const embedded = struct { return buffer[0..wanted]; } + test names { + // The buffer bounds how many are written, so a caller can ask for + // however many it has room for; `count` says how many there are. + var buffer: [8][]const u8 = undefined; + const found = names(&buffer); + + try std.testing.expectEqual(@min(buffer.len, count()), found.len); + + // They come back sorted, which is what makes `load` a binary + // search rather than a scan. + for (found, 0..) |name, i| { + if (i == 0) continue; + try std.testing.expect(std.mem.lessThan(u8, found[i - 1], name)); + } + } + /// The number of embedded zones. pub fn count() usize { return generated.entries.len; } + test count { + // Zero unless the build asked for the data with `-Dembed-tzdata`, + // which is what `available` reports. + try std.testing.expectEqual(available, count() > 0); + } + /// Looks up a zone by name. Needs no allocator, because the data is /// already in the binary and the zone borrows it. Returns null if the /// build has no embedded data or does not include this zone. @@ -311,9 +418,33 @@ pub const embedded = struct { ); } + test load { + // Null when this build embedded no data, which is the default. + if (!available) { + try std.testing.expectEqual(@as(?TimeZone, null), try load("America/Chicago")); + return error.SkipZigTest; + } + + // The zone borrows the blob that is already in the binary, so no + // allocator is involved and there is nothing to free. + const zone = (try load("America/Chicago")).?; + try std.testing.expectEqualStrings("America/Chicago", zone.name); + try std.testing.expectEqual(@as(i32, -6 * std.time.s_per_hour), zone.offsetAt(1705320000)); + + try std.testing.expectEqual(@as(?TimeZone, null), try load("Nowhere/Nothing")); + } + /// Looks `name` up in the index. The generated entries are sorted by /// name, so this is a binary search over them. fn find(name: []const u8) ?generated.Entry { + // With no embedded data `entries` is comptime-empty, and the + // search below will not compile against it: indexing a slice + // whose length is known to be zero is an error however + // unreachable the index is. Returning early at comptime keeps the + // rest from being analyzed, which is what lets a caller name + // `embedded.load` in a build that did not ask for the data. + if (comptime generated.entries.len == 0) return null; + var low: usize = 0; var high: usize = generated.entries.len; while (low < high) { @@ -326,6 +457,18 @@ pub const embedded = struct { } return null; } + + test find { + if (!available) return error.SkipZigTest; + + // The entries are sorted by name, so every one of them is + // findable and nothing else is. + var buffer: [4][]const u8 = undefined; + for (names(&buffer)) |name| { + try std.testing.expect(find(name) != null); + } + try std.testing.expectEqual(@as(?generated.Entry, null), find("Nowhere/Nothing")); + } }; const testing = std.testing; diff --git a/src/tzif.zig b/src/tzif.zig index 9899ff3..b5f531e 100644 --- a/src/tzif.zig +++ b/src/tzif.zig @@ -70,6 +70,26 @@ const Counts = struct { @as(u64, self.isstdcnt) + @as(u64, self.isutcnt); } + + test blockLength { + // Two transitions, two types, "CST\0CDT\0", no leap seconds and + // no indicators, at the 4-byte time width of a version 1 block: + // 2*(4+1) + 2*6 + 8 = 30. + const counts: Counts = .{ + .version = .v2, + .isutcnt = 0, + .isstdcnt = 0, + .leapcnt = 0, + .timecnt = 2, + .typecnt = 2, + .charcnt = 8, + }; + try testing.expectEqual(@as(u64, 30), counts.blockLength(4)); + + // The same counts at the 8-byte width of the second block, where + // each transition costs four bytes more: 2*(8+1) + 12 + 8 = 38. + try testing.expectEqual(@as(u64, 38), counts.blockLength(8)); + } }; /// A parsed TZif file, as slices into the bytes it was parsed from. @@ -101,6 +121,14 @@ pub const Tzif = struct { return self.transition_times.len / self.time_size; } + test transitionCount { + const bytes = try buildFile(&.{ 1710057600, 1730617200 }, &.{ 1, 0 }, "CST6CDT,M3.2.0,M11.1.0"); + defer testing.allocator.free(bytes); + const file = try parse(bytes); + + try testing.expectEqual(@as(usize, 2), file.transitionCount()); + } + /// Returns the `index`th transition as a Unix timestamp in seconds. pub fn transitionAt(self: Tzif, index: usize) i64 { const at = index * self.time_size; @@ -111,11 +139,31 @@ pub const Tzif = struct { }; } + test transitionAt { + const bytes = try buildFile(&.{ 1710057600, 1730617200 }, &.{ 1, 0 }, "CST6CDT,M3.2.0,M11.1.0"); + defer testing.allocator.free(bytes); + const file = try parse(bytes); + + // Decoded from the file's own big-endian bytes on each call, + // which is why nothing here needs an allocator. + try testing.expectEqual(@as(i64, 1710057600), file.transitionAt(0)); + try testing.expectEqual(@as(i64, 1730617200), file.transitionAt(1)); + } + /// The number of local time types in the file. Always at least one. pub fn typeCount(self: Tzif) usize { return self.type_records.len / type_record_len; } + test typeCount { + const bytes = try buildFile(&.{ 1710057600, 1730617200 }, &.{ 1, 0 }, "CST6CDT,M3.2.0,M11.1.0"); + defer testing.allocator.free(bytes); + const file = try parse(bytes); + + // The file is built with a standard type and a daylight one. + try testing.expectEqual(@as(usize, 2), file.typeCount()); + } + /// Returns the `index`th local time type. pub fn typeAt(self: Tzif, index: usize) Type { const record = self.type_records[index * type_record_len ..][0..type_record_len]; @@ -129,6 +177,21 @@ pub const Tzif = struct { }; } + test typeAt { + const bytes = try buildFile(&.{ 1710057600, 1730617200 }, &.{ 1, 0 }, "CST6CDT,M3.2.0,M11.1.0"); + defer testing.allocator.free(bytes); + const file = try parse(bytes); + + const standard = file.typeAt(0); + try testing.expectEqualStrings("CST", standard.designation); + try testing.expectEqual(@as(i32, -6 * std.time.s_per_hour), standard.offset); + try testing.expect(!standard.is_dst); + + const daylight = file.typeAt(1); + try testing.expectEqualStrings("CDT", daylight.designation); + try testing.expect(daylight.is_dst); + } + /// Returns the type that applies before the first transition. RFC 8536 /// specifies the first type that is not a daylight saving time, falling /// back to the first type of all. @@ -140,6 +203,16 @@ pub const Tzif = struct { return self.typeAt(0); } + test defaultType { + const bytes = try buildFile(&.{ 1710057600, 1730617200 }, &.{ 1, 0 }, "CST6CDT,M3.2.0,M11.1.0"); + defer testing.allocator.free(bytes); + const file = try parse(bytes); + + // The first type that is not a daylight saving one, which here + // is the standard type rather than the one at index 0 by luck. + try testing.expectEqualStrings("CST", file.defaultType().designation); + } + /// A stretch of time over which one local time type applies, and that /// type. The bounds let a caller tell whether some other instant is /// still governed by the same type without searching again. @@ -179,6 +252,27 @@ pub const Tzif = struct { }; } + test spanAtTimestamp { + const bytes = try buildFile(&.{ 1710057600, 1730617200 }, &.{ 1, 0 }, "CST6CDT,M3.2.0,M11.1.0"); + defer testing.allocator.free(bytes); + const file = try parse(bytes); + + // Between the two transitions, bounded by both of them. + const summer = file.spanAtTimestamp(1720000000).?; + try testing.expectEqualStrings("CDT", summer.local_type.designation); + try testing.expectEqual(@as(i64, 1710057600), summer.start); + try testing.expectEqual(@as(i64, 1730617200), summer.end); + + // Before the first transition there is no lower bound. + const before = file.spanAtTimestamp(0).?; + try testing.expectEqualStrings("CST", before.local_type.designation); + try testing.expectEqual(@as(i64, std.math.minInt(i64)), before.start); + + // At or after the last transition the file has nothing more to + // say and the footer takes over. + try testing.expectEqual(@as(?Span, null), file.spanAtTimestamp(1730617200)); + } + /// Returns the local time type in effect at `timestamp`, or null under /// the same condition as `spanAtTimestamp`. /// @@ -201,6 +295,18 @@ pub const Tzif = struct { return self.typeAt(self.transition_types[low]); } + test typeAtTimestamp { + const bytes = try buildFile(&.{ 1710057600, 1730617200 }, &.{ 1, 0 }, "CST6CDT,M3.2.0,M11.1.0"); + defer testing.allocator.free(bytes); + const file = try parse(bytes); + + try testing.expectEqualStrings("CST", file.typeAtTimestamp(0).?.designation); + try testing.expectEqualStrings("CDT", file.typeAtTimestamp(1710057600).?.designation); + + // Null once past the last stored transition; see `posixtz`. + try testing.expectEqual(@as(?Type, null), file.typeAtTimestamp(1730617200)); + } + /// Returns the type in effect at or after the last transition, which is /// what the footer's rules must agree with at the moment they take over. pub fn lastType(self: Tzif) Type { @@ -208,6 +314,16 @@ pub const Tzif = struct { if (count == 0) return self.defaultType(); return self.typeAt(self.transition_types[count - 1]); } + + test lastType { + const bytes = try buildFile(&.{ 1710057600, 1730617200 }, &.{ 1, 0 }, "CST6CDT,M3.2.0,M11.1.0"); + defer testing.allocator.free(bytes); + const file = try parse(bytes); + + // The November transition returns the zone to standard time, so + // that is what the footer's rules have to agree with. + try testing.expectEqualStrings("CST", file.lastType().designation); + } }; /// Parses the TZif file in `bytes`. The returned value borrows `bytes`, @@ -271,6 +387,29 @@ fn parseHeader(bytes: []const u8) ParseError!Counts { return counts; } +test parseHeader { + const bytes = try buildFile(&.{1710057600}, &.{1}, "CST6CDT,M3.2.0,M11.1.0"); + defer testing.allocator.free(bytes); + + // This reads the first header. In a version 2 file that describes the + // placeholder 32-bit block, which carries the types and designations + // but no transitions; `parse` steps over it to reach the real one. + const counts = try parseHeader(bytes); + try testing.expectEqual(Version.v2, counts.version); + try testing.expectEqual(@as(u32, 0), counts.timecnt); + try testing.expectEqual(@as(u32, 2), counts.typecnt); + + // The magic is checked before anything is read out of the header. + try testing.expectError(error.BadMagic, parseHeader("XZif" ++ ("\x00" ** 40))); + try testing.expectError(error.Truncated, parseHeader("TZif")); + + // RFC 8536 requires at least one local time type and one designation. + var no_types = try testing.allocator.dupe(u8, bytes[0..header_len]); + defer testing.allocator.free(no_types); + std.mem.writeInt(u32, no_types[36..40], 0, .big); + try testing.expectError(error.BadHeader, parseHeader(no_types)); +} + /// Carves the data block at the start of `bytes` into its fields. fn parseBlock(bytes: []const u8, counts: Counts, time_size: u8) ParseError!Tzif { var rest = bytes; @@ -317,6 +456,25 @@ fn take(rest: *[]const u8, len: u64) ParseError![]const u8 { return rest.*[0..n]; } +test take { + // Each call hands back the next `len` bytes and advances `rest`, so + // the block's fields can be sliced off one after another. + var rest: []const u8 = "CST\x00CDT\x00"; + try testing.expectEqualStrings("CST", try take(&rest, 3)); + try testing.expectEqualStrings("\x00", try take(&rest, 1)); + try testing.expectEqualStrings("CDT\x00", try take(&rest, 4)); + try testing.expectEqual(@as(usize, 0), rest.len); + + // Asking for more than is there is what makes a short file an error + // rather than an out-of-bounds read. + var short: []const u8 = "CS"; + try testing.expectError(error.Truncated, take(&short, 3)); + + // A length too large to be a slice at all is caught the same way. + var any: []const u8 = "CST"; + try testing.expectError(error.Truncated, take(&any, std.math.maxInt(u64))); +} + const testing = std.testing; /// Appends `value` to `list` as `T` in big-endian order. @@ -408,6 +566,47 @@ fn buildFile(transitions: []const i64, indices: []const u8, footer: ?[]const u8) return list.toOwnedSlice(testing.allocator); } +test parse { + const bytes = try buildFile(&.{ 1710057600, 1730617200 }, &.{ 1, 0 }, "CST6CDT,M3.2.0,M11.1.0"); + defer testing.allocator.free(bytes); + + const file = try parse(bytes); + try testing.expectEqual(Version.v2, file.version); + + // The 32-bit block is stepped over, so the transitions come from the + // 64-bit one and the footer is there to govern times past them. + try testing.expectEqual(@as(u8, 8), file.time_size); + try testing.expectEqual(@as(usize, 2), file.transitionCount()); + try testing.expectEqualStrings("CST6CDT,M3.2.0,M11.1.0", file.footer); + + // The result borrows `bytes` rather than copying, so it must not + // outlive them, and no allocator was needed to build it. + try testing.expectEqualStrings("CDT", file.typeAtTimestamp(1720000000).?.designation); + + try testing.expectError(error.BadMagic, parse("XZif" ++ ("\x00" ** 40))); +} + +test parseBlock { + // The block is everything after a header, and the header's counts are + // what say how long each of its arrays is. A version 1 file is one + // header and one block, so this is what `parse` does for that case. + const bytes = try buildFile(&.{1710057600}, &.{1}, null); + defer testing.allocator.free(bytes); + + const counts = try parseHeader(bytes); + const file = try parseBlock(bytes[header_len..], counts, 4); + + try testing.expectEqual(@as(usize, 1), file.transitionCount()); + try testing.expectEqual(@as(i64, 1710057600), file.transitionAt(0)); + try testing.expectEqual(@as(usize, 2), file.typeCount()); + + // Cutting the block short is caught rather than read past. + try testing.expectError( + error.Truncated, + parseBlock(bytes[header_len .. header_len + 2], counts, 4), + ); +} + test "parse a version 1 file" { const bytes = try buildFile(&.{ 1710057600, 1730617200 }, &.{ 1, 0 }, null); defer testing.allocator.free(bytes);