Something went wrong. Try again.
Converting between UTF-8 and legacy character encodings, as the WHATWG Encoding Standard and glibc's iconv define them.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the decoders and encoders must do with input nobody wrote.//!//! Every target here is a property rather than an expected value, because the//! interesting inputs are the ones nobody would think to write down: a lead//! byte at the end of a chunk, an escape sequence cut in half, a trailing//! surrogate with nothing before it. The three properties are that decoding//! cannot crash and cannot produce invalid UTF-8, that where a chunk boundary//! falls does not change the answer, and that a text which has been through//! an encoding once comes out of it unchanged the second time.//!//! These run as ordinary tests too, against the seeds below, so `zig build//! test` exercises them even though this toolchain's fuzzer cannot collect//! coverage. `tools/fuzz.zig` is the loop that drives them with a corpus.
const builtin = @import("builtin");const std = @import("std");
const charset = @import("charset");
const Allocator = std.mem.Allocator;const Encoding = charset.Encoding;const Smith = std.testing.Smith;
/// The allocator the targets use.////// A target reached from both the test runner and the standalone driver/// cannot name `std.testing.allocator`, which does not exist outside a test/// build; the driver points this at an allocator it checks for leaks after/// every input.pub var backing: Allocator = if (builtin.is_test) std.testing.allocator else undefined;
/// The most bytes a target will read. Long inputs find nothing that short/// ones do not: every decoder's state is a byte or two, so a bug in it shows/// up within a handful of characters.pub const max_input = 128;
/// A target, and what `tools/fuzz.zig` has to know to feed it.////// `Smith` reads its answers out of the input byte by byte, and silently/// hands back a zero -- or an empty slice -- when what it reads is out of/// range. A generator that does not know the shape a target asks for/// therefore reports millions of iterations having tested the empty string./// `questions` is how many 32-bit values the target asks for before it asks/// for bytes, and `capacity` is how many bytes it can take.pub const Target = struct { name: []const u8, questions: usize, capacity: usize, run: *const fn (smith: *Smith) anyerror!void,};
pub const targets = [_]Target{ .{ .name = "decode", .questions = 2, .capacity = max_input, .run = decodeIsTotal }, .{ .name = "split", .questions = 2, .capacity = max_input, .run = decodeIgnoresChunkBoundaries }, .{ .name = "idempotent", .questions = 2, .capacity = max_input, .run = encodingTwiceIsEncodingOnce },};
/// Every question is a `u32` and every target reduces it itself, so that a/// generator can write any 32-bit value and have it mean something. Asking/// `Smith` for a narrower range instead would turn most values into its/// lowest one.fn choose(smith: *Smith, count: usize) usize { return smith.value(u32) % count;}
/// Everything this library can read: the standard's encodings and the EBCDIC/// code pages, which are a separate type because the standard's set is/// closed.const Charset = union(enum) { standard: Encoding, ebcdic: charset.Ebcdic,
fn decodeAlloc(self: Charset, bytes: []const u8, options: charset.Decoder.Options) ![]u8 { return switch (self) { .standard => |encoding| charset.decodeAlloc(backing, encoding, bytes, options), .ebcdic => |code_page| charset.decodeEbcdicAlloc(backing, code_page, bytes, options), }; }
fn encodeAlloc(self: Charset, utf8: []const u8, options: charset.Encoder.Options) ![]u8 { return switch (self) { .standard => |encoding| charset.encodeAlloc(backing, encoding, utf8, options), .ebcdic => |code_page| charset.encodeEbcdicAlloc(backing, code_page, utf8, options), }; }
fn decoder(self: Charset, options: charset.Decoder.Options) charset.Decoder { return switch (self) { .standard => |encoding| .init(encoding, options), .ebcdic => |code_page| .initEbcdic(code_page, options), }; }
fn name(self: Charset) []const u8 { return switch (self) { .standard => |encoding| encoding.name(), .ebcdic => |code_page| code_page.name(), }; }};
const all_charsets = blk: { var list: []const Charset = &.{}; for (std.enums.values(Encoding)) |encoding| list = list ++ .{Charset{ .standard = encoding }}; for (std.enums.values(charset.Ebcdic)) |code_page| list = list ++ .{Charset{ .ebcdic = code_page }}; break :blk list;};
/// The ones with an encoder: everything but `replacement` and the two UTF-16/// variants, EBCDIC included.const encodable_charsets = blk: { var list: []const Charset = &.{}; for (all_charsets) |cs| { const ok = switch (cs) { .standard => |encoding| encoding.canEncode(), .ebcdic => true, }; if (ok) list = list ++ .{cs}; } break :blk list;};
fn chooseCharset(smith: *Smith) Charset { return all_charsets[choose(smith, all_charsets.len)];}
fn chooseEncodable(smith: *Smith) Charset { return encodable_charsets[choose(smith, encodable_charsets.len)];}
// -- the properties ---------------------------------------------------------
/// Decoding is total: any bytes at all, in any encoding, produce valid UTF-8/// and no crash. That is what the replacement error mode is for, and a/// decoder that can be made to emit a lone surrogate or half a sequence would/// hand its caller a string that is not a string.fn decodeIsTotal(smith: *Smith) anyerror!void { const cs = chooseCharset(smith); const fatal = choose(smith, 2) == 1;
var buffer: [max_input]u8 = undefined; const bytes = buffer[0..smith.slice(&buffer)];
const utf8 = cs.decodeAlloc(bytes, .{ .error_mode = if (fatal) .fatal else .replacement, }) catch |err| switch (err) { error.InvalidByteSequence => { // The replacement mode has nothing to report, so an error here // can only have come from the other one. std.debug.assert(fatal); // And most of the standard's encodings are ASCII transparent, so // an input with no high byte in it has nothing to fail on. The // exceptions are the three that are not byte oriented at all, and // ISO-2022-JP, which rejects shift-out and shift-in and can end // part way through an escape sequence. EBCDIC is not ASCII // transparent at all, and has no failing byte either: every one // of its 256 positions is assigned. switch (cs) { .ebcdic => return error.EbcdicDecodeFailed, .standard => |encoding| switch (encoding) { .replacement, .utf16le, .utf16be, .iso_2022_jp => return, else => { for (bytes) |byte| if (byte >= 0x80) return; return error.RejectedPlainAscii; }, }, } }, else => |other| return other, }; defer backing.free(utf8);
if (!std.unicode.utf8ValidateSlice(utf8)) return error.DecodedInvalidUtf8;}
/// Where a chunk boundary falls does not change the answer. This is the/// property that a decoder holding its state wrongly fails, and the one that/// is hardest to cover by hand: it takes a multi-byte character, an escape/// sequence or a surrogate pair landing exactly on the seam.fn decodeIgnoresChunkBoundaries(smith: *Smith) anyerror!void { const cs = chooseCharset(smith); const seam_choice = smith.value(u32);
var buffer: [max_input]u8 = undefined; const bytes = buffer[0..smith.slice(&buffer)]; const seam = seam_choice % (bytes.len + 1);
const whole = try cs.decodeAlloc(bytes, .{}); defer backing.free(whole);
var allocating: std.Io.Writer.Allocating = .init(backing); defer allocating.deinit();
var decoder = cs.decoder(.{}); try decoder.decode(bytes[0..seam], &allocating.writer); try decoder.decode(bytes[seam..], &allocating.writer); try decoder.finish(&allocating.writer);
if (!std.mem.eql(u8, whole, allocating.written())) return error.ChunkBoundaryChangedTheAnswer;}
/// Text that has already survived a round trip survives the next one/// unchanged.////// Several encodings are lossy on the way in -- Shift_JIS writes a yen sign/// as a backslash, ISO-2022-JP folds halfwidth katakana to fullwidth, the/// gb18030 encoder keeps eighteen private use characters where the index has/// since moved them -- so the first pass is allowed to change the text. What/// would be a bug is a pair that never settles, because that is a document/// that changes every time it is saved.fn encodingTwiceIsEncodingOnce(smith: *Smith) anyerror!void { const cs = chooseEncodable(smith); const source = chooseCharset(smith);
var buffer: [max_input]u8 = undefined; const bytes = buffer[0..smith.slice(&buffer)];
// Via a decode, so that what reaches the encoder is UTF-8 whatever the // input bytes were. const text = try source.decodeAlloc(bytes, .{}); defer backing.free(text);
const once = try cs.encodeAlloc(text, .{ .error_mode = .html }); defer backing.free(once);
const back = try cs.decodeAlloc(once, .{}); defer backing.free(back);
const twice = try cs.encodeAlloc(back, .{ .error_mode = .html }); defer backing.free(twice);
if (!std.mem.eql(u8, once, twice)) return error.EncodingDidNotSettle;}
// -- running them -----------------------------------------------------------
/// A `Smith` input, in the layout `Smith` reads: each question is a/// little-endian `u64`, and a slice is a little-endian `u32` length followed/// by that many bytes.fn input(comptime questions: []const u32, comptime bytes: []const u8) []const u8 { comptime { var out: []const u8 = &.{}; for (questions) |question| { out = out ++ std.mem.toBytes(@as(u64, question)); } out = out ++ std.mem.toBytes(@as(u32, bytes.len)) ++ bytes; return out; }}
/// Inputs worth keeping: one per shape that took a while to get right.const seeds = [_][]const u8{ input(&.{ 0, 0 }, ""), input(&.{ 1, 0 }, "hello"), input(&.{ 5, 1 }, &.{ 0x81, 0x41, 0x81 }), input(&.{ 30, 0 }, &.{ 0x93, 0xfa, 0x96 }), input(&.{ 34, 3 }, &.{ 0x1b, 0x24, 0x42, 0x46, 0x7c, 0x1b, 0x28 }), input(&.{ 34, 0 }, &.{ 0x1b, 0x28, 0x4a, 0x5c, 0x1b, 0x28, 0x42, 0x1b, 0x28, 0x4a }), input(&.{ 32, 2 }, &.{ 0x8f, 0xa2, 0xaf, 0x8e }), input(&.{ 31, 1 }, &.{ 0x88, 0x62, 0xa4 }), input(&.{ 29, 4 }, &.{ 0x81, 0x35, 0xf4, 0x37, 0x81, 0x30, 0x81 }), input(&.{ 38, 1 }, &.{ 0x3c, 0xd8, 0x00, 0xdf, 0x3c, 0xd8 }), input(&.{ 0, 0 }, &.{ 0xf0, 0x9f, 0x8c, 0x80, 0xf0, 0x9f }), input(&.{ 0, 0 }, &.{ 0xed, 0xa0, 0x80, 0xc0, 0x80 }),};
test "the targets hold for the seeds" { for (targets) |target| { for (seeds) |seed| { var smith: Smith = .{ .in = seed }; target.run(&smith) catch |err| { std.debug.print("{s} failed on a seed\n", .{target.name}); return err; }; } }}
test "fuzz decode" { try std.testing.fuzz({}, struct { fn one(_: void, smith: *Smith) anyerror!void { return decodeIsTotal(smith); } }.one, .{ .corpus = &seeds });}
test "fuzz split" { try std.testing.fuzz({}, struct { fn one(_: void, smith: *Smith) anyerror!void { return decodeIgnoresChunkBoundaries(smith); } }.one, .{ .corpus = &seeds });}
test "fuzz idempotent" { try std.testing.fuzz({}, struct { fn one(_: void, smith: *Smith) anyerror!void { return encodingTwiceIsEncodingOnce(smith); } }.one, .{ .corpus = &seeds });}