// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! Reading the corpus off the token stream. //! //! The corpus is written as arrays rather than objects, so the standard parser //! cannot be pointed at it, and its entries are small and very numerous: about //! nineteen per case, two and a half million cases. Parsing each into a //! std.json.Value and converting cost an allocation apiece for no lasting //! benefit. These read the tokens directly instead. const std = @import("std"); /// Reads the next token and insists it is the one expected. For the brackets /// around an entry, which carry no information beyond being there. pub fn expect(source: anytype, comptime token: std.meta.Tag(std.json.Token)) !void { if (try source.next() != token) return error.UnexpectedToken; } /// Reads a number. The corpus writes plain integers, so anything a JSON number /// can be that an integer cannot is an error rather than something to round. pub fn number(source: anytype, comptime T: type) !T { const text: []const u8 = switch (try source.next()) { .number => |t| t, .allocated_number => |t| t, else => return error.UnexpectedToken, }; return std.fmt.parseInt(T, text, 10) catch error.InvalidNumber; } /// Reads a number that may be null, which is how the 65816 recordings write a /// cycle in which nothing was transferred: the machine that made them did not /// enable RAM unless one of the address lines was asserted, so there was no /// byte to write down. pub fn optionalNumber(source: anytype, comptime T: type) !?T { const text: []const u8 = switch (try source.next()) { .number => |t| t, .allocated_number => |t| t, .null => return null, else => return error.UnexpectedToken, }; return std.fmt.parseInt(T, text, 10) catch error.InvalidNumber; } /// Reads a string. pub fn string(source: anytype, comptime T: type) !T { const text: []const u8 = switch (try source.next()) { .string => |t| t, .allocated_string => |t| t, else => return error.UnexpectedToken, }; return std.meta.stringToEnum(T, text) orelse error.UnexpectedToken; } /// Narrows a number out of an already parsed value, for the from-value path. pub fn cast(comptime T: type, value: std.json.Value) !T { return switch (value) { .integer => |i| std.math.cast(T, i) orelse error.UnexpectedToken, else => error.UnexpectedToken, }; }