// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The `std.json` hooks, written once. //! //! Every type here formats to one piece of text and parses back from it, so //! every one of them is a JSON string and the two methods are the same code //! fifteen times over. `std.json` finds them by name -- `jsonStringify` and //! `jsonParse` on the type -- so each type declares a pair of one-line //! methods that call through to these. const std = @import("std"); const Allocator = std.mem.Allocator; /// Writes the value as a JSON string, in the same canonical form `format` /// writes. pub fn stringify(value: anytype, jws: anytype) !void { var buffer: [@TypeOf(value).max_text_len]u8 = undefined; // The buffer is the type's own documented maximum, so the only way this // could fail is if the type disagreed with itself about that. try jws.write(value.bufPrint(&buffer) catch unreachable); } /// Reads a JSON string and parses it with `T.parse`, as strictly as anything /// else here: a JSON document naming `192.168.01.1` is a JSON document with a /// bad address in it. /// /// The specific reason a text was rejected does not survive. `std.json`'s /// error set is closed and `InvalidCharacter` is the only member of it that /// means anything like "this string was not what it should have been", so /// `LeadingZero` and `OctetOutOfRange` and the rest all arrive as that. A /// program that needs to tell a user what was wrong with what they wrote /// should read the field as a string and call `T.parse` itself. /// /// Nothing is retained: the text is parsed into a value here and freed again /// if `std.json` had to allocate it, so these types remain safe to hold after /// the parsed document is gone. pub fn parse(comptime T: type, allocator: Allocator, source: anytype) !T { // Bounded by what the type could possibly need, so a document offering a // megabyte-long "address" is refused before it is assembled. const token = try source.nextAllocMax(allocator, .alloc_if_needed, T.max_text_len); switch (token) { .string => |text| return T.parse(text) catch error.InvalidCharacter, .allocated_string => |text| { defer allocator.free(text); return T.parse(text) catch error.InvalidCharacter; }, else => return error.UnexpectedToken, } }