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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438// 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 without fuzzing. `zig build fuzz --fuzz` hands them to//! Zig's fuzzer, and `tools/fuzz.zig` is a loop of our own 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, Korean encodings and glibc's charsets, which are separate types/// because the standard's set is closed.const Charset = union(enum) { standard: Encoding, ebcdic: charset.Ebcdic, korean: charset.Korean, glibc: charset.Glibc,
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), .korean => |korean| charset.decodeKoreanAlloc(backing, korean, bytes, options), .glibc => |member| charset.decodeGlibcAlloc(backing, member, 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), .korean => |korean| charset.encodeKoreanAlloc(backing, korean, utf8, options), .glibc => |member| charset.encodeGlibcAlloc(backing, member, 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), .korean => |korean| .initKorean(korean, options), .glibc => |member| .initGlibc(member, options), }; }
fn name(self: Charset) []const u8 { return switch (self) { .standard => |encoding| encoding.name(), .ebcdic => |code_page| code_page.name(), .korean => |korean| korean.name(), .glibc => |member| member.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 }}; for (std.enums.values(charset.Korean)) |korean| list = list ++ .{Charset{ .korean = korean }}; // Last, so that adding one moves no seed that names an earlier charset. for (std.enums.values(charset.Glibc)) |member| list = list ++ .{Charset{ .glibc = member }}; break :blk list;};
/// The ones with an encoder: everything but `replacement` and the two UTF-16/// variants, EBCDIC and the Korean encodings included.const encodable_charsets = blk: { var list: []const Charset = &.{}; for (all_charsets) |cs| { const ok = switch (cs) { .standard => |encoding| encoding.canEncode(), .ebcdic, .korean, .glibc => 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, // Both Korean encodings are ASCII below 0x80. .korean => { for (bytes) |byte| if (byte >= 0x80) return; return error.RejectedPlainAscii; }, // So are all of glibc's except its EBCDIC pages, of which // IBM875 leaves some positions unassigned, the ones that are // not byte oriented, and ISO-2022-JP, which can end part way // through an escape sequence or a character. .glibc => |member| switch (member) { .ibm037, .ibm500, .ibm875, .ibm1026 => return, .utf_16, .utf_16le, .utf_16be, .utf_32, .utf_32le, .utf_32be => return, .iso_10646_ucs2, .unicode, .unicodelittle, .unicodebig => return, .iso_10646_ucs4, .ucs_4le => return, .iso_2022_jp => return, else => { for (bytes) |byte| if (byte >= 0x80) return; return error.RejectedPlainAscii; }, }, .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./// Whether UTF-8 holds one of the combining diacritical marks or the Hebrew/// points, which is every mark CP1255 and CP1258 have.fn hasCombiningMark(utf8: []const u8) bool { var view = std.unicode.Utf8View.initUnchecked(utf8).iterator(); while (view.nextCodepoint()) |c| { if ((c >= 0x0300 and c <= 0x036f) or (c >= 0x0591 and c <= 0x05c7)) return true; } return false;}
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);
// glibc's ISO-2022-JP writes U+001B as a bare ESC, as glibc does, so a // text holding one can spell out an escape sequence that reads back as // something else. The property cannot hold for it, and matching glibc // matters more. if (std.meta.eql(cs, Charset{ .glibc = .iso_2022_jp }) and std.mem.findScalar(u8, text, 0x1b) != null) return; // glibc's CP1255 and CP1258 write a combining mark as it comes, and read // it back composed with the letter before it, which they then write as // one byte if they have one. A text with a mark in it can come back // shorter for the same reason. if ((std.meta.eql(cs, Charset{ .glibc = .cp1255 }) or std.meta.eql(cs, Charset{ .glibc = .cp1258 })) and hasCombiningMark(text)) return;
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 }), // Wansung: 가, the Hangul filler on its own, a pair only code page 949 // has, and a leading byte with nothing after it. input(&.{ 44, 0 }, &.{ 0xb0, 0xa1, 0xa4, 0xd4, 0x81, 0x41, 0xa1 }), // Wansung's eight-byte syllables: a filler that only turns out to be one // when a second follows it, 똠 spelled out, and one broken off part way. input(&.{ 44, 1 }, &.{ 0xa4, 0xd4, 0xa4, 0xd4, 0xa4, 0xa8, 0xa4, 0xc7, 0xa4, 0xb1, 0xa4, 0xd4, 0xa4, 0xa1, 0xa4, }), // Johab: 한, ㄳ (which is only ever a final), the ideographic space from // the symbol region, and a user-defined leading byte left hanging. input(&.{ 45, 1 }, &.{ 0xd0, 0x65, 0x84, 0x44, 0xd9, 0x31, 0xd8 }), // glibc's EUC-KR: a C1 control, the postal code mark, and the four // characters that would be one syllable in Wansung. input(&.{ glibc_euc_kr, 0 }, &.{ 0x85, 0xa2, 0xe8, 0xa4, 0xd4, 0xa4, 0xa1, 0xa4, 0xbf, 0xa4, 0xa1 }), // glibc's code page 932: an end-user defined character, 0x80, and a // leading byte left hanging. input(&.{ glibc_cp932, 1 }, &.{ 0xf0, 0x40, 0x80, 0x81 }), // glibc's UTF-16: a big-endian mark, a surrogate pair, a second mark, // and a leading surrogate left hanging. input(&.{ glibc_utf_16, 1 }, &.{ 0xfe, 0xff, 0xd8, 0x3d, 0xde, 0x00, 0xfe, 0xff, 0xd8, 0x3d }), // glibc's UTF-32: a little-endian mark split from what follows, a value // above U+10FFFF, and three bytes of a unit. input(&.{ glibc_utf_32, 3 }, &.{ 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x41, 0x00, 0x00 }), // glibc's ISO-2022-JP: Roman, a kanji with a line break before its // second, an escape sequence that is not one and so is ESC, and an // escape sequence cut short. input(&.{ glibc_iso_2022_jp, 1 }, "\x1b(J\\~\x1b$B0!\n0!\x1b(I\x1b("), // glibc's CP1255: ש with dagesh and shin dot, which compose into one // character, then a letter held back when the text ends. input(&.{ glibc_cp1255, 0 }, &.{ 0xf9, 0xd1, 0xcc, 0xe1 }), // glibc's CP1258: O, an acute and a tilde, which make Ó and a tilde // rather than Ṍ, then an unassigned byte after a held letter. input(&.{ glibc_cp1258, 1 }, &.{ 0x4f, 0xec, 0xde, 0x41, 0x81 }), // glibc's EUC-JP: a C1 control, JIS X 0212's first kanji, a JIS X 0208 // cell from code page 932's row 13, and 0x8F with one byte after it. input(&.{ glibc_euc_jp, 0 }, &.{ 0x85, 0x8f, 0xb0, 0xa1, 0xad, 0xa1, 0x8f, 0xb0 }), // glibc's SJIS: the yen sign at 0x5C, a halfwidth katakana, 亜, a lead // byte from code page 932's user-defined area, and a lead byte left // hanging. input(&.{ glibc_sjis, 1 }, &.{ 0x5c, 0xb1, 0x88, 0x9f, 0xf0, 0x40, 0x81 }), // glibc's GBK: the euro sign at 0x80, 啊, a user-defined cell, GB // 18030's euro sign, and a lead byte left hanging. input(&.{ glibc_gbk, 1 }, &.{ 0x80, 0xb0, 0xa1, 0xaa, 0xa1, 0xa2, 0xe3, 0x81 }), // glibc's GB2312: its own middle dot, 啊, a cell only GBK has, and a lead // byte left hanging. input(&.{ glibc_euc_cn, 1 }, &.{ 0xa1, 0xa4, 0xb0, 0xa1, 0xa2, 0xa1, 0xb0 }), // glibc's Big5: 0x80, a private use cell, the dark shade, a control // picture the standard has, and a lead byte left hanging. input(&.{ glibc_big5, 1 }, &.{ 0x80, 0xc6, 0xa1, 0xf9, 0xfe, 0xa3, 0xc0, 0xa4 }), // glibc's GB18030: 0xA3A0, a four-byte private use code point, and four // bytes cut short. input(&.{ glibc_gb18030, 1 }, &.{ 0xa3, 0xa0, 0x82, 0x35, 0x90, 0x37, 0x81, 0x30, 0x81 }),};
/// Where glibc's charsets start in `all_charsets`.const glibc_first = all_charsets.len - std.enums.values(charset.Glibc).len;const glibc_euc_kr = glibc_first + @backingInt(charset.Glibc.euc_kr);const glibc_cp932 = glibc_first + @backingInt(charset.Glibc.cp932);const glibc_utf_16 = glibc_first + @backingInt(charset.Glibc.utf_16);const glibc_utf_32 = glibc_first + @backingInt(charset.Glibc.utf_32);const glibc_iso_2022_jp = glibc_first + @backingInt(charset.Glibc.iso_2022_jp);const glibc_cp1255 = glibc_first + @backingInt(charset.Glibc.cp1255);const glibc_cp1258 = glibc_first + @backingInt(charset.Glibc.cp1258);const glibc_euc_jp = glibc_first + @backingInt(charset.Glibc.euc_jp);const glibc_sjis = glibc_first + @backingInt(charset.Glibc.sjis);const glibc_gbk = glibc_first + @backingInt(charset.Glibc.gbk);const glibc_euc_cn = glibc_first + @backingInt(charset.Glibc.euc_cn);const glibc_big5 = glibc_first + @backingInt(charset.Glibc.big5);const glibc_gb18030 = glibc_first + @backingInt(charset.Glibc.gb18030);
test "the Korean seeds choose the encodings they say they do" { // A seed names its charset by position in `all_charsets`, so adding to // the list ahead of these would quietly point them at something else. try std.testing.expectEqual(Charset{ .korean = .wansung }, all_charsets[44]); try std.testing.expectEqual(Charset{ .korean = .johab }, all_charsets[45]);}
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 });}