Something went wrong. Try again.
Dates, times and timezones for Zig 0.17: IANA tzdata, ISO 8601, RFC 822, strftime, CLDR, Go, .NET and git date formats
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Fuzz targets for everything here that reads input it did not write.//!//! Each target is a property written once and driven twice. `zig build//! test` runs it over a list of seeds, which is what keeps a case that//! once failed from coming back. `zig build --fuzz` hands the same//! property to the fuzzer, which goes looking for new ones.//!//! The properties are deliberately weak about what a parser should//! *accept*, because that is what the moment.js oracles are for and a//! fuzzer has no opinion about it. What they check is that nothing//! crashes on input nobody chose, and that whatever does come back holds//! together: a date that says it parsed is a real date, a zone that says//! it loaded can be asked about any instant, and anything with an inverse//! survives the round trip.//!//! Any input reaching a parser here is untrusted by construction. A//! panic, an unreachable, or an index out of bounds is a bug even when//! the input is nonsense, which is the whole point of pointing a fuzzer//! at it.
const std = @import("std");const build_options = @import("build_options");
const Date = @import("Date.zig");const Duration = @import("Duration.zig");const DateTime = @import("DateTime.zig");const DayOfWeek = @import("dayofweek.zig").DayOfWeek;const Instant = @import("Instant.zig");const Interval = @import("interval.zig").Interval;const Month = @import("month.zig").Month;const TimeZone = @import("TimeZone.zig");const Year = @import("year.zig").Year;const cldr = @import("cldr.zig");const dotnet = @import("dotnet.zig");const golayout = @import("golayout.zig");const iso8601 = @import("iso8601.zig");const locale = @import("locale.zig");const posixtz = @import("posixtz.zig");const powershell = @import("powershell.zig");const rfc822 = @import("rfc822.zig");const rfc5322 = @import("rfc5322.zig");const strftime = @import("strftime.zig");const tzif = @import("tzif.zig");const tzdb = @import("tzdb.zig");
/// The longest input any target reads. Long enough for a real date, a/// POSIX rule, or a small TZif file, and short enough that the fuzzer/// spends its time on shapes rather than on length.const max_input = 256;
/// Runs `property` over each of `seeds`, which is what a normal test run/// does with a fuzz target.fn overSeeds(comptime property: fn ([]const u8) anyerror!void, seeds: []const []const u8) !void { for (seeds) |seed| try property(seed);}
/// Hands `property` to the fuzzer, which is what `zig build --fuzz` does.////// Note that `zig build --fuzz` does not work on Zig 0.16.0: its own test/// runner fails to compile in fuzz mode, on any project, at/// `compiler/test_runner.zig:566`. These targets are here for when that/// is fixed; `overMutations` is what actually explores today.fn overFuzzer(comptime property: fn ([]const u8) anyerror!void) !void { const driver = struct { fn one(_: void, smith: *std.testing.Smith) anyerror!void { var buffer: [max_input]u8 = undefined; const len = smith.slice(&buffer); try property(buffer[0..len]); } }; try std.testing.fuzz({}, driver.one, .{});}
/// Runs `property` over inputs built by mutating `seeds`, which is the/// part that actually goes looking for something.////// Random bytes on their own rarely reach far into a date parser, because/// almost nothing is a date. Starting from inputs that are nearly right/// and breaking them a little at a time gets past the first check and/// into the arithmetic behind it, which is where the interesting failures/// were: every bug this file found was an overflow reached through a/// value that had already parsed.////// The seed comes from the test runner, so `zig build test --seed=N`/// replays a failure exactly.fn overMutations(comptime property: fn ([]const u8) anyerror!void, seeds: []const []const u8) !void { var prng: std.Random.DefaultPrng = .init(std.testing.random_seed); const random = prng.random();
var buffer: [max_input]u8 = undefined; for (0..build_options.fuzz_iterations) |_| { const input = mutate(random, seeds, &buffer); property(input) catch |err| { std.debug.print( "fuzz: seed {d} produced {any}\n on input: {s}\n as bytes: {x}\n", .{ std.testing.random_seed, err, input, input }, ); return err; }; }}
/// Builds one input by taking a seed and damaging it.fn mutate(random: std.Random, seeds: []const []const u8, buffer: []u8) []const u8 { const base = seeds[random.uintLessThan(usize, seeds.len)]; var len = @min(base.len, buffer.len); @memcpy(buffer[0..len], base[0..len]);
// Between one and four changes, so an input stays recognisable often // enough to get deep and is wrecked often enough to test the shallow // paths too. const rounds = random.uintLessThan(usize, 4) + 1; for (0..rounds) |_| { switch (random.uintLessThan(u8, 6)) { // Flip a byte to anything at all. 0 => if (len > 0) { buffer[random.uintLessThan(usize, len)] = random.int(u8); }, // Flip a byte to something a date might hold, which reaches // further in than a random byte does. 1 => if (len > 0) { const alphabet = "0123456789:-+TZW.,/ abcdefMTWSJ<>"; buffer[random.uintLessThan(usize, len)] = alphabet[random.uintLessThan(usize, alphabet.len)]; }, // Cut it short. 2 => if (len > 0) { len = random.uintLessThan(usize, len); }, // Grow it with a byte. 3 => if (len < buffer.len) { buffer[len] = random.int(u8); len += 1; }, // Splice another seed onto the end. 4 => { const other = seeds[random.uintLessThan(usize, seeds.len)]; const take = @min(other.len, buffer.len - len); @memcpy(buffer[len..][0..take], other[0..take]); len += take; }, // Repeat a stretch of it, which is how a length field or a // count gets somewhere unreasonable. else => if (len > 0 and len < buffer.len) { const take = @min(random.uintLessThan(usize, len) + 1, buffer.len - len); @memcpy(buffer[len..][0..take], buffer[0..take]); len += take; }, } }
return buffer[0..len];}
/// Runs `property` over values drawn from a generator seeded by the test/// runner, for the targets whose input is a value rather than text.////// These are the properties `std.testing.fuzz` would drive through a/// `Smith` if `zig build --fuzz` worked. Outside that mode `std.testing.fuzz`/// hands a target a single empty input, and a `Smith` reading from nothing/// answers every range with its minimum, so a target driven only that way/// checks one value and looks like it checked millions. This draws the/// values itself. `zig build test --seed=N` replays a failure exactly, and/// the property prints the value it failed on.fn overRandom(comptime property: fn (std.Random) anyerror!void) !void { var prng: std.Random.DefaultPrng = .init(std.testing.random_seed); const random = prng.random(); for (0..build_options.fuzz_iterations) |i| { property(random) catch |err| { std.debug.print("fuzz: seed {d} produced {any} on draw {d}\n", .{ std.testing.random_seed, err, i }); return err; }; }}
/// A year anywhere a `Year` reaches, most often near the present, sometimes/// far from it, and sometimes at one of its two ends, which is where the/// arithmetic has overflowed before.fn randomYear(random: std.Random) Year { return switch (random.uintLessThan(u8, 8)) { 0 => std.math.minInt(Year) + random.intRangeAtMost(Year, 0, 400), 1 => std.math.maxInt(Year) - random.intRangeAtMost(Year, 0, 400), 2, 3 => random.int(Year), else => random.intRangeAtMost(Year, -10000, 10000), };}
/// Any date a `Date` can hold, drawn as `randomYear` draws its year.fn randomDate(random: std.Random) Date { const year = randomYear(random); const month: Month = @enumFromInt(random.intRangeAtMost(u4, 1, 12)); return .{ .year = year, .month = month, .day = random.intRangeAtMost(u6, 1, month.lastDay(year)) };}
/// Any well formed `DateTime`, at any offset the parsers can produce.fn randomDateTime(random: std.Random) DateTime { const date = randomDate(random); var value: DateTime = .{ .year = date.year, .month = date.month, .day = date.day, .hour = random.intRangeAtMost(u5, 0, 23), .minute = random.intRangeAtMost(u6, 0, 59), .second = random.intRangeAtMost(u6, 0, 59), .nanosecond = random.intRangeAtMost(u30, 0, std.time.ns_per_s - 1), .offset = random.intRangeAtMost(i32, -(24 * std.time.s_per_hour - 1), 24 * std.time.s_per_hour - 1), }; value.updateDayOfWeek(); return value;}
/// An integer of type `T` that is zero, small, middling or anywhere at all,/// either sign, since each size reaches a different part of the arithmetic.fn randomAmount(comptime T: type, random: std.Random, small: T, middling: T) T { return switch (random.uintLessThan(u8, 5)) { 0 => 0, 1 => random.intRangeAtMost(T, -small, small), 2, 3 => random.intRangeAtMost(T, -middling, middling), else => random.int(T), };}
fn randomDuration(random: std.Random) Duration { return .{ .months = randomAmount(i64, random, 24, 12 * 100_000), .days = randomAmount(i64, random, 60, 366 * 100_000), .nanoseconds = randomAmount(i128, random, 2 * Duration.nanoseconds_per_day, 366 * 100_000 * Duration.nanoseconds_per_day), };}
/// Asserts that `datetime` is a date that could exist, which every parser/// here promises about anything it returns.fn isWellFormed(datetime: DateTime) !void { try std.testing.expect(datetime.asDate().isRegular()); try std.testing.expectEqual(datetime.asDate().dayOfWeek(), datetime.weekday); try std.testing.expect(datetime.hour < 24); try std.testing.expect(datetime.minute < 60); // Up to 61, not 60: `Second` holds the C89 "double leap second", and // `strftime.parse` reads `%S` up to 61 because glibc's `strptime` does // (checked against glibc 2.42, which refuses 62). try std.testing.expect(datetime.second <= 61); try std.testing.expect(datetime.nanosecond < std.time.ns_per_s);
// An offset has to be one the syntaxes admit, which is wider than any // zone has ever used: RFC 3339 writes the hour as `00-23` and both // parsers here follow it, so `+20:24` is a well formed offset even // though no such zone exists. Asserting the real range instead -- // -12:00 to +14:00 -- says the parsers are wrong when they are not. try std.testing.expect(datetime.offset > -24 * std.time.s_per_hour); try std.testing.expect(datetime.offset < 24 * std.time.s_per_hour);}
// ISO 8601 -------------------------------------------------------------
/// Whatever `iso8601.parse` accepts has to be a real date, and what it/// says it consumed has to be a prefix of what it was given.fn iso8601Property(text: []const u8) !void { const result = iso8601.parse(text) catch return;
try isWellFormed(result.value); try std.testing.expect(result.str.len <= text.len); try std.testing.expectEqualStrings(result.str, text[0..result.str.len]);
// A reduced representation cannot claim more precision than it wrote. if (result.precision == .year) { try std.testing.expectEqual(Month.Jan, result.value.month); try std.testing.expectEqual(@as(u6, 1), result.value.day); } if (!result.has_offset) try std.testing.expectEqual(@as(i32, 0), result.value.offset);}
const iso8601_seeds = [_][]const u8{ "", "2024-03-15", "20240315", "2024-03", "2024", "2024-075", "2024075", "2024-W11-5", "2024W115", "2024-W11", "2024-03-15T14:30:00Z", "2024-03-15T14:30:00.5+05:30", "2024-03-15T24:00", "2024-02-30", "2024-13-01", "2024-00-01", "2024-W54-1", "2024-W00-1", "2024-000", "2024-367", "0000-01-01", "9999-12-31", "2024-03-15T14:30:60", "-------", "TTTTTT", "2024-03-15T", "2024-W", "..", ",,", "2024-03-15T.5",};
test "iso8601.parse over the seeds" { try overSeeds(iso8601Property, &iso8601_seeds);}
test "fuzz iso8601.parse" { try overFuzzer(iso8601Property);}
test "mutate iso8601.parse" { try overMutations(iso8601Property, &iso8601_seeds);}
// ISO 8601 durations ---------------------------------------------------
/// Whatever `iso8601.parseDuration` accepts, `Duration.format` writes in a/// form that reads back as the same value: canonical, so not always the/// same text, but always the same duration, whatever its fields' signs.fn iso8601DurationProperty(text: []const u8) !void { const result = iso8601.parseDuration(text) catch return;
try std.testing.expect(result.str.len <= text.len); try std.testing.expectEqualStrings(result.str, text[0..result.str.len]);
var buffer: [max_input]u8 = undefined; var writer = std.Io.Writer.fixed(&buffer); try result.value.format(&writer); const again = iso8601.parseDuration(writer.buffered()) catch |err| { std.debug.print("wrote \"{s}\", which does not read back\n", .{writer.buffered()}); return err; }; try std.testing.expectEqualStrings(writer.buffered(), again.str); try std.testing.expect(again.value.eql(result.value));}
const iso8601_duration_seeds = [_][]const u8{ "", "P3Y6M4DT12H30M5S", "PT0.5S", "-P1D", "P2W", "P1.5D", "P1M-1D", "P3Y15M3DT-10M", "P-1Y-2M3D", "P1DT-1H-30M-0.5S", "-P1Y-2M", "P9223372036854775807D", "PT-9999999999999999999H", "P--1D",};
test "iso8601.parseDuration over the seeds" { try overSeeds(iso8601DurationProperty, &iso8601_duration_seeds);}
test "fuzz iso8601.parseDuration" { try overFuzzer(iso8601DurationProperty);}
test "mutate iso8601.parseDuration" { try overMutations(iso8601DurationProperty, &iso8601_duration_seeds);}
// ISO 8601 intervals ---------------------------------------------------
/// Whatever `iso8601.parseInterval` accepts has well formed endpoints that/// run forwards, can be resolved without a panic, and survives being/// written out and read back.fn iso8601IntervalProperty(text: []const u8) !void { const result = iso8601.parseInterval(text) catch return;
try std.testing.expect(result.str.len <= text.len); try std.testing.expectEqualStrings(result.str, text[0..result.str.len]);
// The parser promises that both of these are safe to call, which is // the point of its range check. const interval = result.value; const start = interval.start(); const end = interval.end(); try isWellFormed(start); try isWellFormed(end); try std.testing.expect(interval.length() >= 0);
// Written out, it reads back as the same interval, in the same form. // Only while the years stay within the four digits ISO 8601 allows, // which a duration or an end of 24:00 can carry them past. if (start.year < 0 or start.year > 9999 or end.year < 0 or end.year > 9999) return; var buffer: [max_input * 2]u8 = undefined; var writer = std.Io.Writer.fixed(&buffer); try interval.format(&writer); const again = iso8601.parseInterval(writer.buffered()) catch |err| { std.debug.print("wrote \"{s}\", which does not read back\n", .{writer.buffered()}); return err; }; try std.testing.expectEqualStrings(writer.buffered(), again.str); try std.testing.expectEqual(std.meta.activeTag(interval), std.meta.activeTag(again.value)); try std.testing.expectEqual(start.toInstant(), again.value.start().toInstant()); try std.testing.expectEqual(end.toInstant(), again.value.end().toInstant()); if (interval.duration()) |d| try std.testing.expect(d.eql(again.value.duration().?));}
const iso8601_interval_seeds = [_][]const u8{ "", "2007-03-01T13:00:00Z/2008-05-11T15:30:00Z", "2007-03-01T13:00:00Z/P1Y2M10DT2H30M", "P1Y2M10DT2H30M/2008-05-11T15:30:00Z", "2024-03--2024-04", "2007-12-14T13:30-06:00/15:30", "2008-02-15/03-14", "2008-02-15T09:00/16T17:00", "20071214T1330/1530", "2024-03-15T09:00/24:00", "9999-12-31T23:00/24:00", "9999-12-31/P1D", "P1M/0000-01-31", "2024-03-15/PT1.5S", "2024-W11-5/W12-1", "2024-075/080", "2024-03-15/P9999999999Y", "//", "----",};
test "iso8601.parseInterval over the seeds" { try overSeeds(iso8601IntervalProperty, &iso8601_interval_seeds);}
test "fuzz iso8601.parseInterval" { try overFuzzer(iso8601IntervalProperty);}
test "mutate iso8601.parseInterval" { try overMutations(iso8601IntervalProperty, &iso8601_interval_seeds);}
// ISO 8601 recurring intervals -----------------------------------------
/// Whatever `iso8601.parseRecurringInterval` accepts walks as a series/// without a panic: each occurrence is well formed, meets the one before it/// end to end, and the walk stops at its count or at an `OutOfRange` at the/// edge of the calendar. And it reads back as itself once written out.fn iso8601RecurringProperty(text: []const u8) !void { const result = iso8601.parseRecurringInterval(text) catch return;
try std.testing.expect(result.str.len <= text.len); try std.testing.expectEqualStrings(result.str, text[0..result.str.len]); const series = result.value; try std.testing.expect(series.count != 0);
var it = series.iterator(); var previous: ?Interval = null; var seen: u64 = 0; while (seen < 64) : (seen += 1) { const occurrence = (it.next() catch |err| switch (err) { error.OutOfRange => break, }) orelse break; try isWellFormed(occurrence.start()); try isWellFormed(occurrence.end()); try std.testing.expect(occurrence.length() >= 0); if (previous) |p| { // Consecutive: the series has no gaps and no overlaps. if (series.isForwards()) { try std.testing.expectEqual(p.end().toInstant(), occurrence.start().toInstant()); } else { try std.testing.expectEqual(p.start().toInstant(), occurrence.end().toInstant()); } } previous = occurrence; } if (series.count) |count| { if (count <= 64) try std.testing.expect(seen <= count); }
const first = series.interval; const start = first.start(); const end = first.end(); if (start.year < 0 or start.year > 9999 or end.year < 0 or end.year > 9999) return; var buffer: [max_input * 2]u8 = undefined; var writer = std.Io.Writer.fixed(&buffer); try series.format(&writer); const again = iso8601.parseRecurringInterval(writer.buffered()) catch |err| { std.debug.print("wrote \"{s}\", which does not read back\n", .{writer.buffered()}); return err; }; try std.testing.expectEqualStrings(writer.buffered(), again.str); try std.testing.expectEqual(series.count, again.value.count); try std.testing.expectEqual(start.toInstant(), again.value.interval.start().toInstant()); try std.testing.expectEqual(end.toInstant(), again.value.interval.end().toInstant());}
const iso8601_recurring_seeds = [_][]const u8{ "", "R12/1985-04-12T23:20:50Z/1985-06-25T10:30:00Z", "R12/1985-04-12T23:20:50Z/P1Y2M15DT12H30M", "R/P1Y2M15DT12H/1985-04-12T23:20:50Z", "R5/2024-01-31/P1M", "R/2024-03-15T09:00Z/17:00", "R2/2024-03--2024-04", "R/9999-12-30/P1D", "R/P1D/0000-01-02", "R3/2024-03-15/PT0S", "R0/2024-03-15/P1D", "R-1/2024-03-15/P1D", "R18446744073709551615/2024-03-15/P1D", "R12/20150929T140000Z/P1H30M0S/F2W", "RRRR",};
test "iso8601.parseRecurringInterval over the seeds" { try overSeeds(iso8601RecurringProperty, &iso8601_recurring_seeds);}
test "fuzz iso8601.parseRecurringInterval" { try overFuzzer(iso8601RecurringProperty);}
test "mutate iso8601.parseRecurringInterval" { try overMutations(iso8601RecurringProperty, &iso8601_recurring_seeds);}
// RFC 822 --------------------------------------------------------------
fn rfc822Property(text: []const u8) !void { const result = rfc822.parse(text) catch return;
try isWellFormed(result.value); try std.testing.expect(result.str.len <= text.len); try std.testing.expectEqualStrings(result.str, text[0..result.str.len]);}
const rfc822_seeds = [_][]const u8{ "", "Sun, 06 Nov 1994 08:49:37 GMT", "20 Jun 82 12:34 -0500", "Fri, 21 Nov 1997 09:55:06 -0600", "Mon, 06 Nov 1994 08:49:37 GMT", "06 Nov 1994 08:49:37 Z", "32 Nov 1994 08:49:37 GMT", "06 Xxx 1994 08:49:37 GMT", "06 Nov 1994 25:49:37 GMT", "06 Nov 1994 08:49:37 +9999", "Sun,,,06 Nov 1994 08:49:37 GMT", "\t\t\t", "Sun", "06 Nov", "06 Nov 1994", "06 Nov 1994 08:49",};
test "rfc822.parse over the seeds" { try overSeeds(rfc822Property, &rfc822_seeds);}
test "fuzz rfc822.parse" { try overFuzzer(rfc822Property);}
test "mutate rfc822.parse" { try overMutations(rfc822Property, &rfc822_seeds);}
// RFC 5322 -------------------------------------------------------------
fn rfc5322Property(text: []const u8) !void { const result = rfc5322.parse(text) catch return;
try isWellFormed(result.value); try std.testing.expect(result.str.len <= text.len); try std.testing.expectEqualStrings(result.str, text[0..result.str.len]);
// Only "-0000" claims an unknown offset, and it is UTC either way. if (result.unknown_offset) try std.testing.expectEqual(@as(i32, 0), result.value.offset);}
const rfc5322_seeds = [_][]const u8{ "", "Fri, 21 Nov 1997 09:55:06 -0600", "21 Nov 1997 09:55 +0000", "Thu, 13 (the thirteenth) Feb 1969 23:32:54 -0330 (Newfoundland)", "Fri,\r\n 21 Nov\r\n\t1997 09:55:06 -0600", "Fri, 21 Nov 1997 09:55:06 -0000", "Mon, 21 Nov 1997 09:55:06 -0600", "20 Jun 82 12:34 EST", "21 Nov 1997 09:55:06 +9999", "21 Nov 1997 12345678901 09:55:06 +0000", "Fri, 21 Nov 1997 09:55:06 -0600 (never closed", "((((((((((", "21 Nov 1997 09:55:06 -0600 (a (nested \\) one)", "\r\n\r\n\r\n", "Fri,", "21 Nov",};
test "rfc5322.parse over the seeds" { try overSeeds(rfc5322Property, &rfc5322_seeds);}
test "fuzz rfc5322.parse" { try overFuzzer(rfc5322Property);}
test "mutate rfc5322.parse" { try overMutations(rfc5322Property, &rfc5322_seeds);}
// Format strings -------------------------------------------------------
/// Both parsing modes have to survive anything, and both have to keep/// their promises about what they consumed.fn formatStringProperty(text: []const u8) !void { inline for (.{ DateTime.Mode.lenient, DateTime.Mode.strict }) |mode| { // A format string with most of the shapes in it, so one input // exercises names, numbers, an offset and a literal at once. if (DateTime.parseWith("ddd, DD MMM YYYY HH:mm:ss ZZ", text, .{ .mode = mode })) |result| { try isWellFormed(result.value); try std.testing.expect(result.skipped <= result.str.len); try std.testing.expect(result.str.len <= text.len);
// Strict takes all of it or none of it. if (mode == .strict) { try std.testing.expectEqual(text.len, result.str.len); try std.testing.expectEqual(@as(usize, 0), result.skipped); } } else |_| {} }}
const format_string_seeds = [_][]const u8{ "", "Fri, 15 Mar 2024 14:30:05 +0000", "Fri, 15 Mar 2024 14:30:05 -0500", "Mon, 15 Mar 2024 14:30:05 +0000", "Xxx, 15 Mar 2024 14:30:05 +0000", "Fri, 32 Mar 2024 14:30:05 +0000", "Fri, 15 Xxx 2024 14:30:05 +0000", "Fri, 15 Mar 2024 24:00:00 +0000", "Fri, 15 Mar 2024 14:30:05", "Friday, 15 March 2024 14:30:05 +0000", ",,,,,,,,", "0000000000000000",};
test "DateTime.parseWith over the seeds" { try overSeeds(formatStringProperty, &format_string_seeds);}
test "fuzz DateTime.parseWith" { try overFuzzer(formatStringProperty);}
test "mutate DateTime.parseWith" { try overMutations(formatStringProperty, &format_string_seeds);}
// strftime -------------------------------------------------------------
/// A strftime format string is comptime, so the untrusted surface is the/// text handed to the parser. Everything it can reach is in one format/// string here: names, numbers at several widths, a day of the year, an/// ISO week date, a meridiem, an offset and a zone abbreviation, which is/// also the assembly in `State.finish` -- the arithmetic that turns a/// week number or a day of the year into a date, and the place a value/// that had already parsed can still overflow.fn strftimeProperty(text: []const u8) !void { inline for (.{ "%Y-%m-%dT%H:%M:%S%z", "%a, %d %b %Y %H:%M:%S %Z", "%G-W%V-%u", "%C%y-%j %I:%M %p", "%s", }) |format_string| { if (strftime.parse(format_string, text)) |result| { try isWellFormed(result.value); try std.testing.expect(result.str.len <= text.len); try std.testing.expectEqualStrings(result.str, text[0..result.str.len]); } else |_| {} }}
const strftime_seeds = [_][]const u8{ "", "2024-03-15T14:30:05-0500", "Fri, 15 Mar 2024 14:30:05 CDT", "2024-W11-5", "2024-075 02:30 PM", "1710513005", "-2208988800", "9999-99-99T99:99:99+9999", "0000-W53-7", "0000-366 12:00 AM", "99999999999999999999", "2024-03-15T14:30:05Z", " ",};
test "strftime.parse over the seeds" { try overSeeds(strftimeProperty, &strftime_seeds);}
test "fuzz strftime.parse" { try overFuzzer(strftimeProperty);}
test "mutate strftime.parse" { try overMutations(strftimeProperty, &strftime_seeds);}
// .NET and PowerShell --------------------------------------------------
/// A .NET format string is comptime, so the untrusted surface is the text./// The formats here reach every reader the parser has between them: both/// of .NET's own fast paths, names long and short, one and two digit/// numbers, a two digit year, a meridiem both whole and by its first/// letter, the era, all three offsets, `Z` and `GMT`, and an optional/// fraction behind an optional dot -- and `State.finish`, where a value/// that had already parsed can still be refused.fn dotnetProperty(text: []const u8) !void { inline for (.{ "o", "r", "u", "dddd, MMMM d, yyyy h:mm:ss.FFFFFFF tt K", "ddd dd MMM yy H:m:s.fff t zz gg", "yyyyyy-M-dTHH:mm:ss.FFz Z", "yyyyMMddTHHmmssffff GMT", }) |format_string| { if (dotnet.parse(format_string, text)) |result| { try isWellFormed(result.value); } else |_| {} }}
const dotnet_seeds = [_][]const u8{ "", "2024-03-15T14:30:05.1234567-05:00", "2024-03-15T14:30:05.1234567+5:45", "Fri, 15 Mar 2024 19:30:05 GMT", "2024-03-15 19:30:05Z", "Friday, March 15, 2024 2:30:05.12 PM -05:00", "Fri 15 Mar 24 14:30:5.123 P -05 A.D.", "002024-3-15T14:30:05.1-5 Z", "20240315T1430051234 GMT", "9999-12-31T23:59:59.9999999+14:00", "0000-00-00T99:99:99.9999999+99:99", "Sunday, February 30, 2024 13:61:61 PM Z", "999999-99-99T99:99:99.99+99 gmt",};
test "dotnet.parse over the seeds" { try overSeeds(dotnetProperty, &dotnet_seeds);}
test "fuzz dotnet.parse" { try overFuzzer(dotnetProperty);}
test "mutate dotnet.parse" { try overMutations(dotnetProperty, &dotnet_seeds);}
/// The same for a `-UFormat` string, where the parser's own work is in/// `UState.finish`: a date settled from `%s`, from a year and a month,/// from `%j`, or from an ISO week, and every other field checked against/// it.fn uformatProperty(text: []const u8) !void { inline for (.{ "%c %Z", "%F %T %Z (%j, %U, %u, %w, %V, %G, %g, %C)", "%G-W%V-%u %r", "%Y %j %l:%M:%S %p", "%s %Z", "%D %e %k", }) |format_string| { if (powershell.parseUFormat(format_string, text)) |result| { try isWellFormed(result.value); } else |_| {} }}
const uformat_seeds = [_][]const u8{ "", "Fri 15 Mar 2024 14:30:05 -05", "2024-03-15 14:30:05 -05 (075, 10, 5, 5, 11, 2024, 24, 20)", "2020-W53-5 09:00:00 PM", "2024 075 2:30:05 PM", "1710513005 -05", "-62135596800 +14", "999999999999999 +00", "03/15/24 15 14", "0000-W99-9 13:99:99 XM", "9999 366 12:59:59 AM",};
test "powershell.parseUFormat over the seeds" { try overSeeds(uformatProperty, &uformat_seeds);}
test "fuzz powershell.parseUFormat" { try overFuzzer(uformatProperty);}
test "mutate powershell.parseUFormat" { try overMutations(uformatProperty, &uformat_seeds);}
/// Writing has no untrusted text, but it has the whole range of `Year`,/// which .NET never had to think about: an ISO week year past either end,/// a count of seconds since the epoch in the tens of quadrillions for/// `%s`, and `g` before year 1. None of it may crash. Where a value is one/// .NET could hold, what is written has to read back as it was.fn dotnetFormatProperty(random: std.Random) !void { var value = randomDateTime(random);
var buffer: [512]u8 = undefined; inline for (.{ "o", "r", "U", "F", "dddd, MMMM d, yyyy h:mm:ss.FFFFFFF tt K", "yyyyy yy gg z" }) |format_string| { var writer = std.Io.Writer.fixed(&buffer); dotnet.format(value, format_string, &writer) catch |err| switch (err) { error.YearOutsideEra => try std.testing.expect(value.year < 1), else => return err, }; } inline for (.{ "%c %Z %s", "%G %g %V %u %C %j %U %e %k %l" }) |format_string| { var writer = std.Io.Writer.fixed(&buffer); try powershell.uformat(value, format_string, &writer); }
// Brought within what .NET holds -- years 1 to 9999, a tick of a // hundred nanoseconds, whole minutes of offset within fourteen hours -- // and then written and read back. if (value.year < 1 or value.year > 9999) return; value.nanosecond -= value.nanosecond % 100; value.offset = @divTrunc(std.math.clamp(value.offset, -14 * std.time.s_per_hour, 14 * std.time.s_per_hour), 60) * 60;
const round_trip = "yyyy-MM-ddTHH:mm:ss.fffffffzzz"; var writer = std.Io.Writer.fixed(&buffer); try dotnet.format(value, round_trip, &writer); const back = try dotnet.parse(round_trip, writer.buffered()); try std.testing.expect(back.has_offset); try std.testing.expectEqual(value, back.value);
// `%Z` says only the hour, so the offset is brought to a whole one. value.offset = @divTrunc(value.offset, std.time.s_per_hour) * std.time.s_per_hour; value.nanosecond = 0; const uformat = "%F %T %Z"; var uwriter = std.Io.Writer.fixed(&buffer); try powershell.uformat(value, uformat, &uwriter); const uback = try powershell.parseUFormat(uformat, uwriter.buffered()); try std.testing.expectEqual(value, uback.value);}
test "random values through dotnet.format and powershell.uformat" { try overRandom(dotnetFormatProperty);}
// Locales --------------------------------------------------------------
/// Cuts fuzzer bytes into the runs a locale is made of.////// Where a run starts and how long it is both come out of the input, so/// that the fuzzer decides the shape of a locale as well as its contents:/// empty names, names that are prefixes of one another, and names that/// are not valid UTF-8 all arrive without being asked for.const Carver = struct { text: []const u8, at: usize = 0,
/// Returns the next run, of at most `max` bytes. fn next(self: *Carver, max: usize) []const u8 { if (self.text.len == 0) return "";
// One byte says how long the run is, and the run follows it. const header = self.at % self.text.len; const wanted = self.text[header] % (max + 1); const from = (header + 1) % self.text.len; const len = @min(wanted, self.text.len - from); self.at = from + len; return self.text[from..][0..len]; }};
test Carver { // One byte of length, then that many bytes, then the next length. var carver: Carver = .{ .text = "\x03abc\x02ef" }; try std.testing.expectEqualStrings("abc", carver.next(8)); try std.testing.expectEqualStrings("ef", carver.next(8));
// A run is never longer than asked for, and an empty input yields // nothing however often it is asked. var short: Carver = .{ .text = "\xffabcdef" }; try std.testing.expect(short.next(2).len <= 2);
var empty: Carver = .{ .text = "" }; try std.testing.expectEqualStrings("", empty.next(8)); try std.testing.expectEqualStrings("", empty.next(8));}
/// A `Locale` carved out of fuzzer bytes.////// Everything a locale holds is a string this library did not write, and/// ten of them are format strings: the `L` family stands for another/// format string rather than for a value, and the locale supplies it. So/// those reach the tokenizer at run time, where before a locale every/// format string was comptime and a bad one was a compile error. That is/// the new untrusted surface, and this is what points the fuzzer at it.////// The arrays live here so that the `Locale` can borrow them; a `Locale`/// built by `asLocale` must not outlive the `FuzzLocale` it came from.const FuzzLocale = struct { months: [12][]const u8 = undefined, months_short: [12][]const u8 = undefined, weekdays: [7][]const u8 = undefined, weekdays_short: [7][]const u8 = undefined, weekdays_min: [7][]const u8 = undefined, long: locale.LongDateFormat = undefined,
fn init(text: []const u8) FuzzLocale { var carver: Carver = .{ .text = text }; var built: FuzzLocale = .{};
for (&built.months) |*name| name.* = carver.next(16); for (&built.months_short) |*name| name.* = carver.next(8); for (&built.weekdays) |*name| name.* = carver.next(16); for (&built.weekdays_short) |*name| name.* = carver.next(8); for (&built.weekdays_min) |*name| name.* = carver.next(4);
built.long = .{ .LT = carver.next(24), .LTS = carver.next(24), .L = carver.next(24), .LL = carver.next(24), .LLL = carver.next(32), .LLLL = carver.next(32), // Left to be derived half the time, so that both ways through // `LongDateFormat.get` are reached. .l = if (text.len > 0 and text[0] & 1 == 0) carver.next(24) else null, .llll = if (text.len > 1 and text[1] & 1 == 0) carver.next(32) else null, };
return built; }
fn asLocale(self: *const FuzzLocale, text: []const u8) locale.Locale { return .{ .tag = "fuzz", .months = &self.months, .months_short = &self.months_short, .weekdays = &self.weekdays, .weekdays_short = &self.weekdays_short, .weekdays_min = &self.weekdays_min, .long_date_format = self.long, .week = .{ // Any rule at all, including the ones whose first week // opens in the December before. .starts_on = @enumFromInt(if (text.len > 2) text[2] % 7 else 0), .january_day_in_first_week = if (text.len > 3) @as(i8, @bitCast(text[3])) else 1, }, .months_decline = .{ .day_then_month = text.len > 4 and text[4] & 1 == 1, .month_then_ordinal = text.len > 4 and text[4] & 2 == 2, }, }; }};
/// The sequences a locale can reach, including every localized one, since/// those are the ones whose expansion the locale controls.const locale_formats = [_][]const u8{ "L", "LL", "LLL", "LLLL", "l", "ll", "lll", "llll", "LT", "LTS", "A a", "Do Mo wo DDDo do Wo", "dddd D MMMM YYYY", "ddd MMM dd", "e d E w ww gg gggg", "[x] LLLL [y] L",};
/// Writing a date in a locale nobody sanitized has to be safe, whatever/// the locale says a sequence stands for.fn localeFormatProperty(text: []const u8) !void { var built: FuzzLocale = .init(text); const in = built.asLocale(text);
const dates = [_]DateTime{ .{ .year = 2024, .month = .Mar, .day = 5, .hour = 13, .minute = 7, .weekday = .Tue }, .{ .year = 1900, .month = .Jan, .day = 1, .hour = 0, .minute = 0, .weekday = .Mon }, .{ .year = 2024, .month = .Dec, .day = 31, .hour = 23, .minute = 59, .weekday = .Tue }, };
var buffer: [4096]u8 = undefined; for (dates) |value| { inline for (locale_formats) |fmt| { var writer = std.Io.Writer.fixed(&buffer); // A locale can name an expansion longer than any buffer, so // running out of room is an answer rather than a failure. value.formatWith(fmt, in, &writer) catch {}; } }}
/// And reading one back. Whatever a locale lets through still has to be a/// real date, which is the promise `parseWith` makes to every caller and/// which a locale is in no position to change.fn localeParseProperty(text: []const u8) !void { var built: FuzzLocale = .init(text); const in = built.asLocale(text);
inline for (.{ DateTime.Mode.lenient, DateTime.Mode.strict }) |mode| { inline for (.{ "LLLL", "L", "llll", "dddd D MMMM YYYY", "Do MMM A" }) |fmt| { if (DateTime.parseWith(fmt, text, .{ .locale = in, .mode = mode })) |result| { try isWellFormed(result.value); try std.testing.expect(result.skipped <= result.str.len); try std.testing.expect(result.str.len <= text.len); } else |_| {} } }}
/// The same against the locales that ship, which have real names rather/// than carved ones: what this looks for is an input that gets a real/// table to misbehave.fn localeTableProperty(text: []const u8) !void { const shipped: []const locale.Locale = if (locale.embedded) locale.all else &.{locale.en};
// One of them per input rather than all of them, chosen by the input. // Walking a hundred and thirty-seven tables for every input spends // the run on the same answers over and over; letting the fuzzer pick // gets through far more inputs, and it reaches every locale soon // enough over a run of any length. const in = shipped[(if (text.len > 0) text[text.len - 1] else 0) % shipped.len];
inline for (.{ DateTime.Mode.lenient, DateTime.Mode.strict }) |mode| { if (DateTime.parseWith("dddd D MMMM YYYY", text, .{ .locale = in, .mode = mode })) |result| { try isWellFormed(result.value); } else |_| {} }
// And the name lookups on their own, which is where a name that is a // prefix of another one has to lose to the longer one. if (in.matchMonth(text, .MMMM)) |found| { try std.testing.expect(found.len <= text.len); try std.testing.expect(found.len > 0); } if (in.matchWeekday(text, .dddd)) |found| { try std.testing.expect(found.len <= text.len); try std.testing.expect(found.len > 0); } if (in.matchMeridiem(text)) |found| { try std.testing.expect(found.len <= text.len); }
_ = locale.byName(text);}
const locale_seeds = [_][]const u8{ "", // A locale's worth of plausible runs: names, then the `L` family. "\x03Jan\x03Feb\x03Mar\x03Apr\x03May\x03Jun\x03Jul\x03Aug\x03Sep\x03Oct\x03Nov\x03Dec", // Format strings where a locale expects them, including ones that // name a localized sequence and so would expand for ever if nothing // stopped them. "\x0aMM/DD/YYYY\x0aD MMMM YYYY\x04LLLL\x01L", "\x04LLLL\x04LLLL\x04LLLL\x04LLLL\x04LLLL\x04LLLL", // Empty names throughout, which match everywhere and consume nothing. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", // Bracketed and escaped text in an expansion, which the tokenizer // treats specially and which a locale can now leave unbalanced. "\x06[abc]\x02\\\\\x05[a[b]\x03[ab", // Real dates, for the parsing half. "Tuesday 5 March 2024", "mardi 5 mars 2024", "\u{432}\u{442}\u{43e}\u{440}\u{43d}\u{438}\u{43a} 5 \u{43c}\u{430}\u{440}\u{442}\u{430} 2024", "5th Mar PM", "\xff\xff\xff\xff\xff\xff\xff\xff",};
test "DateTime.formatWith over the locale seeds" { try overSeeds(localeFormatProperty, &locale_seeds);}
test "fuzz DateTime.formatWith with a locale" { try overFuzzer(localeFormatProperty);}
test "mutate DateTime.formatWith with a locale" { try overMutations(localeFormatProperty, &locale_seeds);}
test "DateTime.parseWith over the locale seeds" { try overSeeds(localeParseProperty, &locale_seeds);}
test "fuzz DateTime.parseWith with a locale" { try overFuzzer(localeParseProperty);}
test "mutate DateTime.parseWith with a locale" { try overMutations(localeParseProperty, &locale_seeds);}
test "the shipped locales over the locale seeds" { try overSeeds(localeTableProperty, &locale_seeds);}
test "fuzz the shipped locales" { try overFuzzer(localeTableProperty);}
test "mutate the shipped locales" { try overMutations(localeTableProperty, &locale_seeds);}
/// A locale that ships has to be able to read back what it wrote, for any/// date and in any language.////// The properties above are weak on purpose: they ask that nothing falls/// over, because a locale carved out of fuzzer bytes has no business/// round tripping. This is the strong one, and it is only possible/// because the shipped tables are real: a name written in a language has/// to be a name readable in that language, whatever the date and whatever/// the alphabet. An asymmetry between the two sides -- a name that is a/// prefix of another and wins when it should lose, a form written that is/// not among the forms matched -- shows up here and nowhere else.////// The date comes out of the input rather than out of a list, so this/// explores the calendar as well as the languages.fn localeRoundTripProperty(text: []const u8) !void { if (text.len < 6) return;
const shipped: []const locale.Locale = if (locale.embedded) locale.all else &.{locale.en}; const in = shipped[text[0] % shipped.len];
// moment's pseudo-locale wraps its names in tildes, which are not // letters in any alphabet and which moment's own name pattern does // not accept either. It is for making untranslated text obvious on // screen, not for reading back. if (std.mem.eql(u8, in.tag, "x-pseudo")) return;
// Any day of a wide span, kept inside what a four digit year can // write since the format string below cannot express anything wider. const span = 3_000_000; const days: Date.DaysType = @mod(std.mem.readInt(i32, text[1..5], .little), span) - span / 3; const date = Date.fromDaysSinceStartOfEra(days); if (!date.isRegular() or date.year < 1 or date.year > 9999) return;
const value: DateTime = .{ .year = date.year, .month = date.month, .day = date.day, .weekday = date.dayOfWeek(), };
// Separated by a character no language uses in a name, so that what // is being tested is the names rather than where one ends. var buffer: [256]u8 = undefined; var writer = std.Io.Writer.fixed(&buffer); try value.formatWith("dddd|D|MMMM|YYYY", in, &writer); const written = writer.buffered();
const parsed = DateTime.parseWith("dddd|D|MMMM|YYYY", written, .{ .locale = in, .mode = .strict, }) catch |err| { std.debug.print("fuzz: {s} wrote {s} and could not read it: {}\n", .{ in.tag, written, err }); return err; };
try std.testing.expectEqual(value.year, parsed.value.year); try std.testing.expectEqual(value.month, parsed.value.month); try std.testing.expectEqual(value.day, parsed.value.day); try std.testing.expectEqual(value.weekday, parsed.value.weekday);}
const locale_round_trip_seeds = [_][]const u8{ // A locale index and four bytes of day number, which is what the // property reads; the rest are what mutating these produces. "\x00\x00\x00\x00\x00\x00", "\x01\x40\x4c\x00\x00\x00", "\x2a\xff\xff\xff\x7f\x00", "\x55\x00\x00\x00\x80\x00", "\x7f\x9c\x1f\x00\x00\x00",};
test "the shipped locales round trip over the seeds" { try overSeeds(localeRoundTripProperty, &locale_round_trip_seeds);}
test "fuzz the shipped locales round trip" { try overFuzzer(localeRoundTripProperty);}
test "mutate the shipped locales round trip" { try overMutations(localeRoundTripProperty, &locale_round_trip_seeds);}
// CLDR patterns --------------------------------------------------------
/// A CLDR pattern is text this library did not write, and unlike a/// moment.js format string it does not have to be comptime: `cldr`'s/// runtime entry point exists because the locale's own patterns arrive as/// data, and a caller may just as well hand it a pattern out of a/// configuration file. So the tokenizer, the quoting, and every field/// writer are reachable from arbitrary bytes, which is what this points/// the fuzzer at.////// The property is only that nothing crashes and that a refusal is one of/// the three documented errors. What a pattern *should* write is what/// `zig build oracle-cldr` is for, and a fuzzer has no opinion about it.fn cldrPatternProperty(text: []const u8) !void { const dates = [_]DateTime{ .{ .year = 2024, .month = .Mar, .day = 5, .hour = 13, .minute = 7, .weekday = .Tue, .offset = -21036 }, .{ .year = 1, .month = .Jan, .day = 1, .weekday = .Mon }, .{ .year = -4000, .month = .Dec, .day = 31, .hour = 23, .minute = 59, .second = 59, .weekday = .Tue }, };
// One shipped locale per input, chosen by the input, for the same // reason the moment locale target does it: walking every table for // every input spends the run on the same answers over and over. const shipped: []const cldr.Locale = if (cldr.embedded) cldr.all else &.{cldr.en}; const in = shipped[(if (text.len > 0) text[text.len - 1] else 0) % shipped.len];
var buffer: [4096]u8 = undefined; for (dates) |value| { var writer = std.Io.Writer.fixed(&buffer); // A pattern can ask for more than any buffer holds -- `yyyy` // repeated is a legal pattern -- so running out of room is an // answer rather than a failure. cldr.formatRuntime(value, text, in, &writer) catch |err| switch (err) { error.WriteFailed => {}, error.UnterminatedQuote, error.UnknownField, error.InvalidFieldWidth => {}, };
// And the locale's own patterns, which are the ones a caller // reaches without writing a pattern at all. for ([_]cldr.Length{ .full, .long, .medium, .short }) |length| { var styled = std.Io.Writer.fixed(&buffer); cldr.formatDateTime(value, length, length, in, &styled) catch {}; } }}
const cldr_pattern_seeds = [_][]const u8{ "", "yyyy-MM-dd'T'HH:mm:ssXXX", "EEEE, MMMM d, y 'at' h:mm:ss a zzzz", "GGGGG QQQQQ LLLLL cccccc bbbbb BBBBB", // Quoting, which is the part of the tokenizer with state in it. "'", "''", "'unterminated", "'don''t' HH", "''", // Counts at and past the edge of what each field means. "MMMMMM", "OO", "VVV", "jjj", "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy", "SSSSSSSSSSSSSSSSSSSS", "AAAAAAAAAAAAAAAAAAAA", // Letters that name nothing, which are reserved rather than text. "PPPP", "hello world", "\xff\xff\xff\xff",};
test "cldr.formatRuntime over the seeds" { try overSeeds(cldrPatternProperty, &cldr_pattern_seeds);}
test "fuzz cldr.formatRuntime" { try overFuzzer(cldrPatternProperty);}
test "mutate cldr.formatRuntime" { try overMutations(cldrPatternProperty, &cldr_pattern_seeds);}
// Week rules -----------------------------------------------------------
/// A week rule is two numbers a locale hands over, and both of them reach/// the calendar arithmetic.////// The day the week starts on is one of seven, but the day that anchors/// week one is signed and can name a day of the December before -- eight/// of moment's locales use one that does. So the arithmetic has to hold/// for an anchor nobody would write as well as for the four ISO 8601/// uses.fn weekRuleProperty(text: []const u8) !void { if (text.len < 6) return;
const year: Year = @bitCast(std.mem.readInt(u32, text[0..4], .little)); const starts_on: DayOfWeek = @enumFromInt(text[4] % 7); const anchor: i8 = @bitCast(text[5]);
const weeks = Date.weeksInYear(year, starts_on, anchor); try std.testing.expect(weeks >= 1);
// Every week the rule admits names a real date, and that date is back // in the week it came from. var week: u16 = 1; while (week <= @as(u16, @intCast(@min(weeks, 60)))) : (week += 1) { const date = Date.fromWeek(year, week, starts_on, starts_on, anchor); if (!date.isRegular()) continue;
const found = date.weekOfYear(starts_on, anchor); try std.testing.expect(found.week >= 1); }}
const week_rule_seeds = [_][]const u8{ // 2024, Monday, the fourth: ISO 8601. "\xe8\x07\x00\x00\x01\x04", // 2024, Sunday, the first: what moment's `en` uses. "\xe8\x07\x00\x00\x00\x01", // 2024, Sunday, five days before it: what a `doy` of 12 comes to. "\xe8\x07\x00\x00\x00\xfb", // The ends of the calendar, where the arithmetic saturates. "\x00\x00\x00\x80\x01\x04", "\xff\xff\xff\x7f\x01\x04", "\x00\x00\x00\x00\x00\x00",};
test "the week rules over the seeds" { try overSeeds(weekRuleProperty, &week_rule_seeds);}
test "fuzz the week rules" { try overFuzzer(weekRuleProperty);}
test "mutate the week rules" { try overMutations(weekRuleProperty, &week_rule_seeds);}
// POSIX TZ rules -------------------------------------------------------
/// A rule that parses has to answer for any instant without falling over,/// including the ends of the range.fn posixtzProperty(text: []const u8) !void { const rule = posixtz.parse(text) catch return;
// Inside the calendar the answers have to hold together. for ([_]i64{ 0, 1710513005, -2208988800, std.math.minInt(i32), std.math.maxInt(i32), // A margin off each end, because placing a span needs the years // either side and the outermost year has none. See `Posix.spanAt`. Date.min_seconds + 2 * 366 * std.time.s_per_day, Date.max_seconds - 2 * 366 * std.time.s_per_day, }) |at| { const local_type = rule.typeAt(at); try std.testing.expect(local_type.designation.len > 0);
// A span has to contain the instant it was asked about, which is // the whole reason a caller can trust its bounds. const span = rule.spanAt(at); try std.testing.expect(span.start <= at); try std.testing.expect(span.end > at); try std.testing.expectEqual(local_type.offset, span.local_type.offset);
// The bounds have to be switches rather than arbitrary instants: // the span holds all the way to its end, and something else // begins there. This is what the agreement above stopped being // able to check once `typeAt` started deferring to `spanAt`. if (span.start > std.math.minInt(i64) and span.start < Date.max_seconds) { try std.testing.expectEqual(span.local_type.offset, rule.typeAt(span.start).offset); } if (span.end < Date.max_seconds and span.end > Date.min_seconds) { const next = rule.spanAt(span.end); try std.testing.expect(next.start >= span.end); } }
// Outside it there is no year to evaluate the rule against, so the // only promise is that asking is safe. See `Posix.spanAt`. for ([_]i64{ std.math.minInt(i64), std.math.maxInt(i64), Date.min_seconds, Date.max_seconds, Date.min_seconds - 1, Date.max_seconds + 1, std.math.minInt(i64) / 4, std.math.maxInt(i64) / 4, }) |at| { _ = rule.typeAt(at); _ = rule.spanAt(at); }}
const posixtz_seeds = [_][]const u8{ "", "CST6CDT,M3.2.0,M11.1.0", "IST-5:30", "<-03>3", "EST5EDT", "EST5EDT,M3.2.0/2,M11.1.0/2", "CST6CDT,J60,J300", "CST6CDT,59,300", "CST6CDT,M3.5.0,M11.1.0", "AAA0BBB,M1.1.0/167,M1.1.0/-167", "AAA24BBB25,M1.1.0,M2.1.0", "<>0", "<ABC", "M3.2.0", "AAA0BBB,M13.1.0,M1.1.0", "AAA0BBB,M1.6.0,M1.1.0", "AAA0BBB,M1.1.7,M1.1.0", "AAA0BBB,J0,J366", // Ends at its own separator, which used to read past the end. "CST6CDT,M3.2.0/", "CST6CDT,M3.2.0/2,M11.1.0/", "CST6CDT,M3.2.0/2,M11.1.0/-",};
test "posixtz.parse over the seeds" { try overSeeds(posixtzProperty, &posixtz_seeds);}
test "fuzz posixtz.parse" { try overFuzzer(posixtzProperty);}
test "mutate posixtz.parse" { try overMutations(posixtzProperty, &posixtz_seeds);}
// TZif files -----------------------------------------------------------
/// The one that reads a binary format rather than text, and the one most/// worth pointing a fuzzer at: everything it returns is a slice into/// bytes it was handed, sized by counts the same bytes claimed.fn tzifProperty(bytes: []const u8) !void { const file = tzif.parse(bytes) catch return;
// Every index the counts admit has to be readable. var index: usize = 0; while (index < file.transitionCount()) : (index += 1) _ = file.transitionAt(index);
index = 0; while (index < file.typeCount()) : (index += 1) { const local_type = file.typeAt(index); // A designation is a slice into the file's own bytes and has to // stay inside them. try std.testing.expect(@intFromPtr(local_type.designation.ptr) >= @intFromPtr(bytes.ptr)); try std.testing.expect( @intFromPtr(local_type.designation.ptr) + local_type.designation.len <= @intFromPtr(bytes.ptr) + bytes.len, ); }
_ = file.defaultType(); _ = file.lastType();
for ([_]i64{ 0, 1710513005, -2208988800, std.math.minInt(i64), std.math.maxInt(i64) }) |at| { if (file.spanAtTimestamp(at)) |span| { try std.testing.expect(span.start <= at); try std.testing.expect(span.end > at); } _ = file.typeAtTimestamp(at); }
// Transitions are supposed to be sorted, which is what makes the // binary search in `spanAtTimestamp` mean anything. if (file.transitionCount() > 1) { index = 1; while (index < file.transitionCount()) : (index += 1) { if (file.transitionAt(index - 1) > file.transitionAt(index)) break; } }}
const tzif_seeds = [_][]const u8{ "", "TZif", "TZif2", "TZif" ++ ("\x00" ** 40), "TZif" ++ ("\xff" ** 40), "TZif2" ++ ("\x00" ** 39), "XZif" ++ ("\x00" ** 40), "TZif" ++ ("\x00" ** 15) ++ ("\xff" ** 25),};
test "tzif.parse over the seeds" { try overSeeds(tzifProperty, &tzif_seeds);}
test "fuzz tzif.parse" { try overFuzzer(tzifProperty);}
test "mutate tzif.parse" { try overMutations(tzifProperty, &tzif_seeds);}
// Zone names -----------------------------------------------------------
/// A name that validates is about to be joined onto a directory, so it/// must not be able to reach outside one.fn zoneNameProperty(text: []const u8) !void { tzdb.validateName(text) catch return;
try std.testing.expect(text.len > 0); try std.testing.expect(text[0] != '/'); try std.testing.expect(text[0] != '.'); try std.testing.expect(std.mem.indexOf(u8, text, "..") == null); for (text) |char| try std.testing.expect(std.ascii.isPrint(char));}
const zone_name_seeds = [_][]const u8{ "", "UTC", "America/Chicago", "Etc/GMT+5", "US/Central", "../../etc/passwd", "/etc/passwd", ".hidden", "a/../b", "a//b", "America/Chicago\x00", "\x00", "..", ".", "a" ** 257,};
test "tzdb.validateName over the seeds" { try overSeeds(zoneNameProperty, &zone_name_seeds);}
test "fuzz tzdb.validateName" { try overFuzzer(zoneNameProperty);}
test "mutate tzdb.validateName" { try overMutations(zoneNameProperty, &zone_name_seeds);}
// Go layouts -----------------------------------------------------------
/// A Go layout is comptime, so the untrusted surface is the text. The/// layouts here between them reach every kind of chunk the parser has:/// names long and short, padded and unpadded numbers, a two digit year, a/// meridiem, the three spellings of an offset, a zone name, and fractions/// both fixed and trimmed.fn golayoutProperty(text: []const u8) !void { inline for (.{ golayout.layout.rfc3339_nano, golayout.layout.rfc1123z, golayout.layout.rfc850, golayout.layout.unix_date, golayout.layout.default, golayout.layout.stamp_micro, golayout.layout.kitchen, "2006-002 15:04:05.000 Z0700", }) |layout_string| { if (golayout.parse(layout_string, text)) |value| { // Go reads an offset of up to `+24:60:60`, past the day that // `isWellFormed` holds the other parsers to, so the offset is // held to Go's limit here and everything else to the usual one. var clock = value; clock.offset = 0; try isWellFormed(clock); const go_limit = 24 * std.time.s_per_hour + 60 * std.time.s_per_min + 60; try std.testing.expect(@abs(value.offset) <= go_limit); } else |_| {} }}
const golayout_seeds = [_][]const u8{ "", "2024-03-15T14:30:05.123456789-05:00", "2024-03-15T14:30:05Z", "Fri, 15 Mar 2024 14:30:05 -0500", "Friday, 15-Mar-24 14:30:05 CDT", "Fri Mar 15 14:30:05 CDT 2024", "03/15 02:30:05PM '24 -0500", "Mar 15 14:30:05.123456", "2:30PM", "2024-075 14:30:05.123 Z", "2024-366 14:30:05.123 +0530", "9999-12-31T23:59:59.999999999+23:59", "Mar 32 25:61:61.000000", "13/32 13:60:60AM '99 +9999",};
test "golayout.parse over the seeds" { try overSeeds(golayoutProperty, &golayout_seeds);}
test "fuzz golayout.parse" { try overFuzzer(golayoutProperty);}
test "mutate golayout.parse" { try overMutations(golayoutProperty, &golayout_seeds);}
// Calendar arithmetic --------------------------------------------------
/// `DateTime.addChecked` either answers with the date and time the/// calendar says, or refuses with `OutOfRange` exactly when that answer is/// outside the years a `Year` can hold -- never panics, never refuses/// something that fits, and never answers something that does not.////// The expected answer is worked out here in `i256`, where no duration a/// `Duration` can hold overflows anything, following XML Schema's order as/// `add` does: the sub-day part and its carry, the months with the day/// clamped, then the days. Two further checks do not share that working:/// a purely sub-day duration moves the instant by exactly that much, and/// a purely whole-day one moves the day number by exactly that many.fn arithmeticProperty(random: std.Random) !void { const start = randomDateTime(random); const duration = randomDuration(random); const arithmetic: Duration.Arithmetic = if (random.boolean()) .xml_schema else .composite; checkArithmetic(start, duration, arithmetic) catch |err| { std.debug.print("addChecked ({s}): {any}\n plus {any}\n", .{ @tagName(arithmetic), start, duration }); return err; };}
fn checkArithmetic(start: DateTime, duration: Duration, arithmetic: Duration.Arithmetic) !void { const got = start.addCheckedWith(duration, arithmetic);
const ns_per_day: i256 = Duration.nanoseconds_per_day; const time_of_day: i256 = @as(i256, start.hour) * Duration.nanoseconds_per_hour + @as(i256, start.minute) * Duration.nanoseconds_per_minute + @as(i256, start.second) * Duration.nanoseconds_per_second + start.nanosecond; const total = time_of_day + duration.nanoseconds; const carry = @divFloor(total, ns_per_day); const rest = total - carry * ns_per_day;
const month_index = @as(i256, start.year) * 12 + (@intFromEnum(start.month) - 1) + duration.months; const year_wide = @divFloor(month_index, 12); const year_fits = year_wide >= std.math.minInt(Year) and year_wide <= std.math.maxInt(Year);
const expected: ?Date = blk: { if (!year_fits) break :blk null; const year: Year = @intCast(year_wide); const month: Month = @enumFromInt(@as(u4, @intCast(@mod(month_index, 12) + 1))); const moved = @as(i256, duration.days) + carry; // XML Schema clamps the day to its month and then counts; ISO // 8601-2's composite method does the same unless the day itself was // moved, in which case its full value counts from the first of the // month and the excess runs into the next. const days = if (arithmetic == .composite and moved != 0) @as(i256, (Date{ .year = year, .month = month, .day = 1 }).toDaysSinceStartOfEra()) + (start.day - 1) + moved else @as(i256, (Date{ .year = year, .month = month, .day = @min(start.day, month.lastDay(year)) }).toDaysSinceStartOfEra()) + moved; if (days < Date.min_days or days > Date.max_days) break :blk null; break :blk Date.fromDaysSinceStartOfEra(@intCast(days)); };
const value = got catch |err| { try std.testing.expectEqual(error.OutOfRange, err); // Refused, so the calendar's answer must really be out of range. try std.testing.expectEqual(@as(?Date, null), expected); return; }; // Answered, so it must be the calendar's answer. try std.testing.expect(expected != null); try isWellFormed(value); try std.testing.expectEqual(expected.?, value.asDate()); try std.testing.expectEqual(@as(i256, value.hour), @divFloor(rest, Duration.nanoseconds_per_hour)); try std.testing.expectEqual(@as(i256, value.minute), @mod(@divFloor(rest, Duration.nanoseconds_per_minute), 60)); try std.testing.expectEqual(@as(i256, value.second), @mod(@divFloor(rest, Duration.nanoseconds_per_second), 60)); try std.testing.expectEqual(@as(i256, value.nanosecond), @mod(rest, Duration.nanoseconds_per_second)); try std.testing.expectEqual(start.offset, value.offset);
if (duration.months == 0 and duration.days == 0) { // Only the clock moved, at a fixed offset: the instant moved by // exactly the duration. try std.testing.expectEqual( @as(i256, start.toInstant().timestamp) + duration.nanoseconds, @as(i256, value.toInstant().timestamp), ); } if (duration.months == 0 and duration.nanoseconds == 0) { // Only whole days: the day number moved by exactly that many, and // the time of day did not move at all. try std.testing.expectEqual( @as(i256, start.asDate().toDaysSinceStartOfEra()) + duration.days, @as(i256, value.asDate().toDaysSinceStartOfEra()), ); try std.testing.expectEqual(start.hour, value.hour); try std.testing.expectEqual(start.nanosecond, value.nanosecond); }}
test "random DateTime.addChecked" { try overRandom(arithmeticProperty);}
// The two edges, by name, since a random draw reaches them only by luck:// a day before the last one fits and a day after it does not, and the same// at the other end.test "DateTime.addChecked at the ends of the calendar" { const last: DateTime = .{ .year = std.math.maxInt(Year), .month = .Dec, .day = 31, .hour = 23, .weekday = (Date{ .year = std.math.maxInt(Year), .month = .Dec, .day = 31 }).dayOfWeek() }; inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(last, .{ .nanoseconds = Duration.nanoseconds_per_hour - 1 }, a); inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(last, .{ .nanoseconds = Duration.nanoseconds_per_hour }, a); inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(last, .{ .days = -1 }, a); inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(last, .{ .months = 1 }, a); const first: DateTime = .{ .year = std.math.minInt(Year), .month = .Jan, .day = 1, .weekday = (Date{ .year = std.math.minInt(Year), .month = .Jan, .day = 1 }).dayOfWeek() }; inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(first, .{ .nanoseconds = -1 }, a); inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(first, .{ .days = 1 }, a); inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(first, .{ .months = -1 }, a); inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(first, .{ .months = std.math.minInt(i64), .days = std.math.minInt(i64), .nanoseconds = std.math.minInt(i128) }, a); inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(first, .{ .months = std.math.maxInt(i64), .days = std.math.maxInt(i64), .nanoseconds = std.math.maxInt(i128) }, a);}
// Round trips ----------------------------------------------------------
// Anything with an inverse has to survive it, for any date at all rather// than the handful a test would think to write down.test "fuzz the calendar round trips" { const driver = struct { fn one(_: void, smith: *std.testing.Smith) anyerror!void { const year = smith.valueRangeAtMost(Year, -10000, 10000); const month: Month = @enumFromInt(smith.valueRangeAtMost(u4, 1, 12)); const date: Date = .{ .year = year, .month = month, .day = smith.valueRangeAtMost(u6, 1, month.lastDay(year)), };
// A date is its day number and back again. try std.testing.expectEqual(date, Date.fromDaysSinceStartOfEra(date.toDaysSinceStartOfEra()));
// And its day of the year and back again. const day_of_year = @as(i32, date.month.daysBefore(date.year)) + date.day; try std.testing.expectEqual(date, Date.fromDayOfYear(date.year, day_of_year));
// And its week and weekday and back again, under either rule. const iso = date.isoWeek(); try std.testing.expectEqual(date, Date.fromWeek(iso.year, iso.week, date.dayOfWeek(), .Mon, 4)); try std.testing.expect(iso.week >= 1 and iso.week <= 53);
const english = date.localeWeek(); try std.testing.expectEqual(date, Date.fromWeek(english.year, english.week, date.dayOfWeek(), .Sun, 1)); try std.testing.expect(english.week >= 1 and english.week <= 54); } }; try std.testing.fuzz({}, driver.one, .{});}
/// The calendar round trips again, over every year a `Year` holds, drawn/// by `overRandom` so that they run on more than the one date a `Smith`/// with nothing to read produces.fn calendarProperty(random: std.Random) !void { const date = randomDate(random); checkCalendar(date) catch |err| { std.debug.print("calendar: {any}\n", .{date}); return err; };}
fn checkCalendar(date: Date) !void { try std.testing.expectEqual(date, Date.fromDaysSinceStartOfEra(date.toDaysSinceStartOfEra()));
const day_of_year = @as(i32, date.month.daysBefore(date.year)) + date.day; try std.testing.expectEqual(date, Date.fromDayOfYear(date.year, day_of_year));
const iso = date.isoWeek(); try std.testing.expect(iso.week >= 1 and iso.week <= 53); try std.testing.expectEqual(date, Date.fromWeek(iso.year, iso.week, date.dayOfWeek(), .Mon, 4));
const english = date.localeWeek(); try std.testing.expect(english.week >= 1 and english.week <= 54); try std.testing.expectEqual(date, Date.fromWeek(english.year, english.week, date.dayOfWeek(), .Sun, 1));}
test "random calendar round trips" { try overRandom(calendarProperty);}
// Formatting and parsing are inverses for any instant, which is the// property the moment oracles cannot check because they compare text// rather than values.test "fuzz format and parse round trip" { const driver = struct { fn one(_: void, smith: *std.testing.Smith) anyerror!void { // Kept inside the range a four digit year can write, since // the format string cannot express anything wider. const at = smith.valueRangeAtMost(i64, -62135596800, 253402300799); const offset_minutes = smith.valueRangeAtMost(i32, -12 * 60, 14 * 60); const seconds = offset_minutes * 60;
const shifted: Instant = .{ .timestamp = @as(i128, at + seconds) * std.time.ns_per_s, }; var value = shifted.asDateTime(); value.offset = seconds;
var buffer: [64]u8 = undefined; var writer = std.Io.Writer.fixed(&buffer); try value.format("YYYY-MM-DDTHH:mm:ssZ", &writer);
const parsed = try DateTime.parseStrict("YYYY-MM-DDTHH:mm:ssZ", writer.buffered()); try std.testing.expectEqual(value.year, parsed.value.year); try std.testing.expectEqual(value.month, parsed.value.month); try std.testing.expectEqual(value.day, parsed.value.day); try std.testing.expectEqual(value.hour, parsed.value.hour); try std.testing.expectEqual(value.minute, parsed.value.minute); try std.testing.expectEqual(value.second, parsed.value.second); try std.testing.expectEqual(value.offset, parsed.value.offset); try std.testing.expectEqual(value.weekday, parsed.value.weekday); } }; try std.testing.fuzz({}, driver.one, .{});}