// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What the Encoding Standard says each encoding does, checked against what //! this library does. //! //! The vectors here come from two places that are not the tables in `src`: //! the standard's own worked examples, and arithmetic done by hand from the //! algorithms. A test whose expected value was read out of the same table the //! code reads proves nothing, which is also why `tools/crosscheck.py` exists //! -- it asks CPython the same questions across every input of every //! encoding, and is the broad check that this file's spot checks sit inside. const std = @import("std"); const charset = @import("charset"); const Encoding = charset.Encoding; const testing = std.testing; fn expectDecode(encoding: Encoding, bytes: []const u8, expected: []const u8) !void { const actual = try charset.decodeAlloc(testing.allocator, encoding, bytes, .{}); defer testing.allocator.free(actual); try testing.expectEqualStrings(expected, actual); } fn expectEncode(encoding: Encoding, utf8: []const u8, expected: []const u8) !void { const actual = try charset.encodeAlloc(testing.allocator, encoding, utf8, .{}); defer testing.allocator.free(actual); try testing.expectEqualSlices(u8, expected, actual); } fn expectRoundTrip(encoding: Encoding, utf8: []const u8) !void { const bytes = try charset.encodeAlloc(testing.allocator, encoding, utf8, .{}); defer testing.allocator.free(bytes); const back = try charset.decodeAlloc(testing.allocator, encoding, bytes, .{}); defer testing.allocator.free(back); try testing.expectEqualStrings(utf8, back); } // -- the single-byte encodings ---------------------------------------------- test "windows-1252 puts the euro where ISO-8859-1 has a control" { try expectDecode(.windows_1252, &.{0x80}, "€"); try expectEncode(.windows_1252, "€", &.{0x80}); } test "windows-1252 fills the five positions Latin-1 leaves empty" { // The index maps every byte in 0x80 to 0x9F, including the five that // Microsoft never assigned, which go to the C1 control of the same // number. A decoder that returned an error here would reject text that // browsers accept. for ([_]u8{ 0x81, 0x8d, 0x8f, 0x90, 0x9d }) |byte| { var expected: [2]u8 = undefined; const len = std.unicode.utf8Encode(byte, &expected) catch unreachable; try expectDecode(.windows_1252, &.{byte}, expected[0..len]); } } test "the Cyrillic single-byte encodings" { try expectEncode(.koi8_r, "Привет", &.{ 0xf0, 0xd2, 0xc9, 0xd7, 0xc5, 0xd4 }); try expectEncode(.windows_1251, "Привет", &.{ 0xcf, 0xf0, 0xe8, 0xe2, 0xe5, 0xf2 }); try expectDecode(.ibm866, &.{ 0x8f, 0xe0, 0xa8, 0xa2, 0xa5, 0xe2 }, "Привет"); } test "KOI8-U differs from KOI8-R in exactly the places Ukrainian needs" { try expectDecode(.koi8_u, &.{0xae}, "ў"); try expectDecode(.koi8_u, &.{0xbe}, "Ў"); // KOI8-R has box drawing there instead. try expectDecode(.koi8_r, &.{0xae}, "╝"); } test "ISO-8859-8-I is ISO-8859-8 with a different name" { const bytes = [_]u8{ 0xf9, 0xec, 0xe5, 0xed }; const one = try charset.decodeAlloc(testing.allocator, .iso_8859_8, &bytes, .{}); defer testing.allocator.free(one); const other = try charset.decodeAlloc(testing.allocator, .iso_8859_8_i, &bytes, .{}); defer testing.allocator.free(other); try testing.expectEqualStrings(one, other); } test "a byte with no mapping is one replacement character" { // 0xA1 through 0xA3 are holes in ISO-8859-6. try expectDecode(.iso_8859_6, &.{ 'a', 0xa1, 'b' }, "a\u{fffd}b"); } // -- Shift_JIS -------------------------------------------------------------- test "Shift_JIS encodes and decodes the obvious thing" { try expectEncode(.shift_jis, "日本語", &.{ 0x93, 0xfa, 0x96, 0x7b, 0x8c, 0xea }); try expectDecode(.shift_jis, &.{ 0x93, 0xfa, 0x96, 0x7b, 0x8c, 0xea }, "日本語"); try expectDecode(.shift_jis, &.{ 0x81, 0x40 }, "\u{3000}"); } test "Shift_JIS keeps halfwidth katakana in one byte" { try expectDecode(.shift_jis, &.{0xb1}, "ア"); try expectEncode(.shift_jis, "ア", &.{0xb1}); } test "Shift_JIS reuses the ASCII positions for the yen sign and the overline" { // Which is why a Windows path written on a Japanese system comes back // with a yen sign where the backslash was. try expectEncode(.shift_jis, "¥", &.{0x5c}); try expectEncode(.shift_jis, "‾", &.{0x7e}); // Only one way round: 0x5C still decodes as a backslash. try expectDecode(.shift_jis, &.{0x5c}, "\\"); } test "Shift_JIS maps the end-user defined characters into the private use area" { // Pointer 8836 is 47 x 188, which is leading byte 0xF0 -- 47 past the // second leading-byte range at 0xC1 -- and trailing byte 0x40. try expectDecode(.shift_jis, &.{ 0xf0, 0x40 }, "\u{e000}"); // And the encoder does not go back: the private use area is decode-only // here, so a round trip through it is not one. try testing.expectError( error.UnmappableCodePoint, charset.encodeAlloc(testing.allocator, .shift_jis, "\u{e000}", .{}), ); } test "Shift_JIS skips the duplicated pointers when encoding" { // U+2170 appears twice in index jis0208. The first pointer is inside the // 8272 to 8835 range the Shift_JIS encoder excludes, so the second one is // what comes out -- and that, not the first, is what other Shift_JIS // implementations understand. try expectEncode(.shift_jis, "ⅰ", &.{ 0xfa, 0x40 }); // Both still decode, because only the encoder does the excluding. try expectDecode(.shift_jis, &.{ 0xfa, 0x40 }, "ⅰ"); try expectDecode(.shift_jis, &.{ 0xee, 0xef }, "ⅰ"); } test "a Shift_JIS lead byte followed by ASCII gives back the ASCII" { // The trailing byte is not consumed by the failed sequence: it goes back // on the queue and is read again from a clean state. 0x20 is below the // trailing range, so the pair means nothing while the space still does. try expectDecode(.shift_jis, &.{ 0x81, 0x20 }, "\u{fffd} "); try expectDecode(.shift_jis, &.{ 0x93, 0x20, 'a' }, "\u{fffd} a"); // 0x81 0x41 is not that case: it is pointer 1, a real character. try expectDecode(.shift_jis, &.{ 0x81, 0x41 }, "\u{3001}"); } test "Shift_JIS passes 0x80 through as U+0080" { try expectDecode(.shift_jis, &.{0x80}, "\u{80}"); try expectEncode(.shift_jis, "\u{80}", &.{0x80}); } // -- EUC-JP ----------------------------------------------------------------- test "EUC-JP encodes and decodes the obvious thing" { try expectEncode(.euc_jp, "日本語", &.{ 0xc6, 0xfc, 0xcb, 0xdc, 0xb8, 0xec }); try expectDecode(.euc_jp, &.{ 0xc6, 0xfc, 0xcb, 0xdc, 0xb8, 0xec }, "日本語"); } test "EUC-JP reaches halfwidth katakana through 0x8E" { try expectDecode(.euc_jp, &.{ 0x8e, 0xb1 }, "ア"); try expectEncode(.euc_jp, "ア", &.{ 0x8e, 0xb1 }); } test "EUC-JP reads JIS X 0212 through 0x8F and will not write it" { // 0x8F introduces a JIS X 0212 pair. The standard gives the encoder no // way to produce one, on the grounds that too little else understands it. const decoded = try charset.decodeAlloc( testing.allocator, .euc_jp, &.{ 0x8f, 0xa2, 0xaf }, .{ .error_mode = .fatal }, ); defer testing.allocator.free(decoded); try testing.expect(decoded.len > 0); try testing.expectError( error.UnmappableCodePoint, charset.encodeAlloc(testing.allocator, .euc_jp, decoded, .{}), ); } // -- ISO-2022-JP ------------------------------------------------------------ test "ISO-2022-JP wraps its output in escape sequences" { try expectEncode(.iso_2022_jp, "日本語", &.{ 0x1b, 0x24, 0x42, 0x46, 0x7c, 0x4b, 0x5c, 0x38, 0x6c, 0x1b, 0x28, 0x42, }); } test "ISO-2022-JP returns to ASCII before the text ends" { try expectEncode(.iso_2022_jp, "あa", &.{ 0x1b, 0x24, 0x42, 0x24, 0x22, 0x1b, 0x28, 0x42, 'a', }); } test "ISO-2022-JP outputs do not concatenate, exactly as the standard warns" { // The standard's own example: encoding U+00A5 gives these seven bytes, // and two of them run together decode as U+00A5 U+FFFD U+00A5, because a // mode change to the mode already in effect with nothing emitted in // between is an error. That rule is what stops a run of escape sequences // being used to hide bytes from something scanning the stream. const once = [_]u8{ 0x1b, 0x28, 0x4a, 0x5c, 0x1b, 0x28, 0x42 }; try expectEncode(.iso_2022_jp, "¥", &once); try expectDecode(.iso_2022_jp, &(once ++ once), "¥\u{fffd}¥"); } test "ISO-2022-JP will not encode the bytes an attacker would want" { // Shift-out, shift-in and escape come back as U+FFFD rather than // themselves, so that the "html" error mode cannot be talked into // spelling one out as a character reference. var buffer: [64]u8 = undefined; var writer = std.Io.Writer.fixed(&buffer); var encoder = try charset.Encoder.init(.iso_2022_jp, .{ .error_mode = .html }); try encoder.encode("a\x1bb", &writer); try encoder.finish(&writer); try testing.expectEqualStrings("a�b", writer.buffered()); } test "ISO-2022-JP folds halfwidth katakana to the fullwidth form" { // There is no halfwidth katakana in JIS X 0208, so the encoder maps it // through index ISO-2022-JP katakana first. The text does not survive a // round trip, and cannot. const bytes = try charset.encodeAlloc(testing.allocator, .iso_2022_jp, "ア", .{}); defer testing.allocator.free(bytes); const back = try charset.decodeAlloc(testing.allocator, .iso_2022_jp, bytes, .{}); defer testing.allocator.free(back); try testing.expectEqualStrings("ア", back); } // -- Big5 ------------------------------------------------------------------- test "Big5 encodes and decodes the obvious thing" { try expectEncode(.big5, "中文", &.{ 0xa4, 0xa4, 0xa4, 0xe5 }); try expectDecode(.big5, &.{ 0xa4, 0xa4, 0xa4, 0xe5 }, "中文"); } test "Big5 is the only decoder that returns two code points for one pointer" { // Pointer 1133 is leading byte 0x81 + 7 and trailing byte 0x40 + 34. // Unicode spells the character with a base and a combining macron, and an // index holds one code point per pointer, so the standard lists these // four pointers in the algorithm instead. try expectDecode(.big5, &.{ 0x88, 0x62 }, "\u{00ca}\u{0304}"); try expectDecode(.big5, &.{ 0x88, 0x64 }, "\u{00ca}\u{030c}"); try expectDecode(.big5, &.{ 0x88, 0xa3 }, "\u{00ea}\u{0304}"); try expectDecode(.big5, &.{ 0x88, 0xa5 }, "\u{00ea}\u{030c}"); } test "Big5 takes the last pointer for the six code points that ask for it" { // Everything else with more than one pointer takes the first. try expectEncode(.big5, "十", &.{ 0xa4, 0x51 }); try expectEncode(.big5, "卅", &.{ 0xa4, 0xca }); try expectEncode(.big5, "═", &.{ 0xf9, 0xf9 }); try expectEncode(.big5, "╞", &.{ 0xf9, 0xe9 }); try expectEncode(.big5, "╡", &.{ 0xf9, 0xeb }); try expectEncode(.big5, "╪", &.{ 0xf9, 0xea }); } test "Big5 decodes the Hong Kong extensions but will not write them" { // Everything below pointer 5024 is an extension. The decoder reads them; // the encoder is told to skip them so that its output stays inside what a // plain Big5 consumer understands. const decoded = try charset.decodeAlloc( testing.allocator, .big5, &.{ 0x87, 0x7a }, .{ .error_mode = .fatal }, ); defer testing.allocator.free(decoded); try testing.expectEqualStrings("\u{3875}", decoded); try testing.expectError( error.UnmappableCodePoint, charset.encodeAlloc(testing.allocator, .big5, decoded, .{}), ); } test "Big5 reaches beyond the basic multilingual plane" { try expectDecode(.big5, &.{ 0x87, 0x7b }, "\u{21d53}"); } // -- EUC-KR ----------------------------------------------------------------- test "EUC-KR encodes and decodes the obvious thing" { try expectEncode(.euc_kr, "한국어", &.{ 0xc7, 0xd1, 0xb1, 0xb9, 0xbe, 0xee }); try expectDecode(.euc_kr, &.{ 0xc7, 0xd1, 0xb1, 0xb9, 0xbe, 0xee }, "한국어"); } test "EUC-KR covers the Hangul Syllables block in its entirety" { var code_point: u21 = 0xac00; while (code_point <= 0xd7a3) : (code_point += 1) { var utf8: [4]u8 = undefined; const len = std.unicode.utf8Encode(code_point, &utf8) catch unreachable; try expectRoundTrip(.euc_kr, utf8[0..len]); } } // -- GBK and gb18030 -------------------------------------------------------- test "GBK and gb18030 agree about the two-byte forms" { try expectEncode(.gbk, "中文", &.{ 0xd6, 0xd0, 0xce, 0xc4 }); try expectEncode(.gb18030, "中文", &.{ 0xd6, 0xd0, 0xce, 0xc4 }); try expectDecode(.gbk, &.{ 0xd6, 0xd0, 0xce, 0xc4 }, "中文"); } test "GBK writes the euro as one byte and gb18030 does not" { try expectEncode(.gbk, "€", &.{0x80}); try expectEncode(.gb18030, "€", &.{ 0xa2, 0xe3 }); // Both decode 0x80 as the euro, because the decoder is shared. try expectDecode(.gbk, &.{0x80}, "€"); try expectDecode(.gb18030, &.{0x80}, "€"); } test "gb18030 reaches the rest of Unicode with four bytes, and GBK refuses to" { try expectEncode(.gb18030, "\u{10000}", &.{ 0x90, 0x30, 0x81, 0x30 }); try expectDecode(.gb18030, &.{ 0x90, 0x30, 0x81, 0x30 }, "\u{10000}"); try testing.expectError( error.UnmappableCodePoint, charset.encodeAlloc(testing.allocator, .gbk, "\u{10000}", .{}), ); } test "the one code point the GB18030-2005 revision moved" { // Pointer 7457 is called out in the algorithm rather than given a range // of its own: 7457 is 5 x 1260 + 115 x 10 + 7, so the four digits are // 0, 5, 115 and 7. try expectEncode(.gb18030, "\u{e7c7}", &.{ 0x81, 0x35, 0xf4, 0x37 }); try expectDecode(.gb18030, &.{ 0x81, 0x35, 0xf4, 0x37 }, "\u{e7c7}"); } test "gb18030 has one code point it cannot write at all" { // The index sends 0xA3 0xA0 to U+3000 rather than to U+E5E5, to match // deployed content, which leaves U+E5E5 with nowhere to go. try expectDecode(.gb18030, &.{ 0xa3, 0xa0 }, "\u{3000}"); try testing.expectError( error.UnmappableCodePoint, charset.encodeAlloc(testing.allocator, .gb18030, "\u{e5e5}", .{}), ); } test "the gb18030 encoder's side table does not round trip, and is not meant to" { // These eighteen keep the answers GB18030-2005 gave, so that content // encoded before the 2022 revision still decodes the same way. The index // has since moved them, so encoding one and decoding the result gives // something else. try expectEncode(.gb18030, "\u{e78d}", &.{ 0xa6, 0xd9 }); try expectDecode(.gb18030, &.{ 0xa6, 0xd9 }, "\u{fe10}"); } // -- UTF-16 and the odd ones out -------------------------------------------- test "UTF-16 in both byte orders, including a surrogate pair" { try expectDecode(.utf16le, &.{ 'a', 0x00, 0x3c, 0xd8, 0x00, 0xdf }, "a\u{1f300}"); try expectDecode(.utf16be, &.{ 0x00, 'a', 0xd8, 0x3c, 0xdf, 0x00 }, "a\u{1f300}"); } test "an unpaired surrogate is an error and the code unit after it is not lost" { // The leading surrogate fails on its own, and the code unit that was not // its partner goes back on the queue to be read again. try expectDecode(.utf16le, &.{ 0x3c, 0xd8, 'a', 0x00 }, "\u{fffd}a"); try expectDecode(.utf16le, &.{ 0x00, 0xdc }, "\u{fffd}"); // A leading surrogate at the very end has nothing following it. try expectDecode(.utf16le, &.{ 0x3c, 0xd8 }, "\u{fffd}"); // An odd number of bytes ends mid code unit. try expectDecode(.utf16le, &.{'a'}, "\u{fffd}"); } test "neither UTF-16 has an encoder" { try testing.expectError(error.NoEncoder, charset.Encoder.init(.utf16le, .{})); try testing.expectError(error.NoEncoder, charset.Encoder.init(.utf16be, .{})); // Which is what outputEncoding is for. try expectEncode(Encoding.utf16le.outputEncoding(), "hi", "hi"); } test "replacement decodes anything at all as a single replacement character" { try expectDecode(.replacement, "", ""); try expectDecode(.replacement, "hello", "\u{fffd}"); try expectDecode(.replacement, &.{ 0x00, 0xff, 0x41 }, "\u{fffd}"); try testing.expectError(error.NoEncoder, charset.Encoder.init(.replacement, .{})); } test "x-user-defined round trips every byte there is" { var byte: usize = 0; while (byte < 0x100) : (byte += 1) { const input = [_]u8{@intCast(byte)}; const utf8 = try charset.decodeAlloc(testing.allocator, .x_user_defined, &input, .{ .error_mode = .fatal, }); defer testing.allocator.free(utf8); const back = try charset.encodeAlloc(testing.allocator, .x_user_defined, utf8, .{}); defer testing.allocator.free(back); try testing.expectEqualSlices(u8, &input, back); } try expectDecode(.x_user_defined, &.{0x80}, "\u{f780}"); } // -- UTF-8 ------------------------------------------------------------------ test "UTF-8 follows the Unicode best practice for U+FFFD" { // One replacement character for the maximal subpart, not one per byte. try expectDecode(.utf8, &.{ 0xe1, 0x80, 0xe2, 0xf0, 0x91, 0x92, 0xf1, 0xbf, 'a' }, "\u{fffd}\u{fffd}\u{fffd}\u{fffd}a"); // An overlong sequence fails at the byte that makes it overlong, which // then gets another chance on its own. try expectDecode(.utf8, &.{ 0xe0, 0x80, 0x41 }, "\u{fffd}\u{fffd}A"); // A surrogate written as three bytes is not a scalar value. try expectDecode(.utf8, &.{ 0xed, 0xa0, 0x80 }, "\u{fffd}\u{fffd}\u{fffd}"); // Truncated at the end of the input. try expectDecode(.utf8, &.{ 'a', 0xf0, 0x9f }, "a\u{fffd}"); } test "UTF-8 is the identity on valid input" { const text = "aé中\u{1f300}\u{0}"; try expectDecode(.utf8, text, text); try expectEncode(.utf8, text, text); } // -- EBCDIC ----------------------------------------------------------------- fn expectDecodeEbcdic(code_page: charset.Ebcdic, bytes: []const u8, expected: []const u8) !void { const actual = try charset.decodeEbcdicAlloc(testing.allocator, code_page, bytes, .{}); defer testing.allocator.free(actual); try testing.expectEqualStrings(expected, actual); } fn expectEncodeEbcdic(code_page: charset.Ebcdic, utf8: []const u8, expected: []const u8) !void { const actual = try charset.encodeEbcdicAlloc(testing.allocator, code_page, utf8, .{}); defer testing.allocator.free(actual); try testing.expectEqualSlices(u8, expected, actual); } test "EBCDIC shares nothing with ASCII" { // The letters sit in three runs with gaps between them, a hole punched by // the card codes the encoding grew out of, which is why code that // arranges bytes by arithmetic rather than by table gets this wrong. try expectEncodeEbcdic(.cp037, "HELLO", &.{ 0xc8, 0xc5, 0xd3, 0xd3, 0xd6 }); try expectDecodeEbcdic(.cp037, &.{ 0xc8, 0xc5, 0xd3, 0xd3, 0xd6 }, "HELLO"); try expectEncodeEbcdic(.cp037, "abc", &.{ 0x81, 0x82, 0x83 }); try expectEncodeEbcdic(.cp037, "0123456789", &.{ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, }); try expectEncodeEbcdic(.cp037, " ", &.{0x40}); // I and J are adjacent letters and are nowhere near adjacent here. try expectEncodeEbcdic(.cp037, "IJ", &.{ 0xc9, 0xd1 }); } test "the code pages differ where their languages do" { // CP037 is US and Canada, CP500 international; the two disagree about // where the square brackets and a handful of punctuation live. try expectEncodeEbcdic(.cp037, "[", &.{0xba}); try expectEncodeEbcdic(.cp500, "[", &.{0x4a}); // And the national pages put their own alphabets over the top. try expectEncodeEbcdic(.cp875, "αβγ", &.{ 0x8a, 0x8b, 0x8c }); try expectEncodeEbcdic(.cp1026, "ğĞ", &.{ 0xd0, 0x5a }); } test "every EBCDIC byte decodes, since every position is assigned" { for (std.enums.values(charset.Ebcdic)) |code_page| { var byte: usize = 0; while (byte < 0x100) : (byte += 1) { const decoded = try charset.decodeEbcdicAlloc( testing.allocator, code_page, &.{@intCast(byte)}, .{ .error_mode = .fatal }, ); defer testing.allocator.free(decoded); try testing.expect(decoded.len > 0); } } } test "EBCDIC round trips except where a page spells unassigned as SUBSTITUTE" { for (std.enums.values(charset.Ebcdic)) |code_page| { var byte: usize = 0; while (byte < 0x100) : (byte += 1) { const input = [_]u8{@intCast(byte)}; const utf8 = try charset.decodeEbcdicAlloc(testing.allocator, code_page, &input, .{}); defer testing.allocator.free(utf8); const back = try charset.encodeEbcdicAlloc(testing.allocator, code_page, utf8, .{}); defer testing.allocator.free(back); // CP875 gives six unassigned positions the same U+001A as the // real SUBSTITUTE at 0x3F, so those six come back as 0x3F. Every // other byte of every page is its own again. if (back[0] != byte) { try testing.expectEqualStrings("\u{1a}", utf8); try testing.expectEqual(@as(u8, 0x3f), back[0]); } } } } test "U+001A encodes to the position every EBCDIC page keeps SUBSTITUTE in" { // Microsoft's CP875 table spells six unassigned positions SUBSTITUTE // alongside the real one; 0x3F is the one the other three pages have and // the only one that means it. for (std.enums.values(charset.Ebcdic)) |code_page| { try expectEncodeEbcdic(code_page, "\u{1a}", &.{0x3f}); } } test "EBCDIC is not reachable by a label, and that is deliberate" { // The Encoding Standard's set is closed, and `fromLabel` refusing // everything outside it is what stops a header choosing an encoding the // standard never blessed. EBCDIC is reached by naming a code page. for ([_][]const u8{ "cp037", "ibm037", "ebcdic", "ebcdic-cp-us", "cp500", "ibm500" }) |label| { try testing.expect(Encoding.fromLabel(label) == null); } } test "EBCDIC decoding survives the input arriving in two pieces" { const bytes = [_]u8{ 0xc8, 0xc5, 0xd3, 0xd3, 0xd6, 0x40, 0xa6, 0x96, 0x99, 0x93, 0x84 }; const whole = try charset.decodeEbcdicAlloc(testing.allocator, .cp037, &bytes, .{}); defer testing.allocator.free(whole); for (0..bytes.len + 1) |seam| { var allocating: std.Io.Writer.Allocating = .init(testing.allocator); defer allocating.deinit(); var decoder: charset.Decoder = .initEbcdic(.cp037, .{}); try decoder.decode(bytes[0..seam], &allocating.writer); try decoder.decode(bytes[seam..], &allocating.writer); try decoder.finish(&allocating.writer); try testing.expectEqualStrings(whole, allocating.written()); } } test "an EBCDIC encoder reports what it cannot write" { var buffer: [64]u8 = undefined; var writer = std.Io.Writer.fixed(&buffer); var encoder: charset.Encoder = .initEbcdic(.cp037, .{}); try testing.expectError(error.UnmappableCodePoint, encoder.encode("中", &writer)); try testing.expectEqual(@as(u21, 0x4e2d), encoder.unmappable); // And the html error mode works the same as it does for the standard's // encodings, except that the reference is itself written in EBCDIC: the // standard names the bytes 0x26 0x23 ... 0x3B because every encoding it // defines spells ASCII as ASCII, which EBCDIC does not. const bytes = try charset.encodeEbcdicAlloc(testing.allocator, .cp037, "中", .{ .error_mode = .html, }); defer testing.allocator.free(bytes); const back = try charset.decodeEbcdicAlloc(testing.allocator, .cp037, bytes, .{}); defer testing.allocator.free(back); try testing.expectEqualStrings("中", back); try testing.expectEqualSlices( u8, &.{ 0x50, 0x7b, 0xf2, 0xf0, 0xf0, 0xf1, 0xf3, 0x5e }, bytes, ); } // -- Korean outside the standard --------------------------------------------- fn expectDecodeKorean(korean: charset.Korean, bytes: []const u8, expected: []const u8) !void { const actual = try charset.decodeKoreanAlloc(testing.allocator, korean, bytes, .{}); defer testing.allocator.free(actual); try testing.expectEqualStrings(expected, actual); } fn expectEncodeKorean(korean: charset.Korean, utf8: []const u8, expected: []const u8) !void { const actual = try charset.encodeKoreanAlloc(testing.allocator, korean, utf8, .{}); defer testing.allocator.free(actual); try testing.expectEqualSlices(u8, expected, actual); } test "Johab spells a syllable out letter by letter" { // 한 is ㅎ, ㅏ, ㄴ: fields 20, 3 and 5 under a leading one bit, // 1 10100 00011 00101. 글 is ㄱ, ㅡ, ㄹ: 1 00010 11011 01001. try expectEncodeKorean(.johab, "한글", &.{ 0xd0, 0x65, 0x8b, 0x69 }); try expectDecodeKorean(.johab, &.{ 0xd0, 0x65, 0x8b, 0x69 }, "한글"); // A letter on its own is the other two fields filled. ㄳ cannot begin a // syllable, so it is a final: 1 00001 00010 00100. try expectEncodeKorean(.johab, "ㄳ", &.{ 0x84, 0x44 }); // ㄱ can, so it is an initial, and the final ㄱ nothing writes is an // error rather than a second spelling -- after which its second byte, // being ASCII, is read again as itself. try expectEncodeKorean(.johab, "ㄱ", &.{ 0x88, 0x41 }); try expectDecodeKorean(.johab, &.{ 0x84, 0x42 }, "\u{fffd}B"); } test "Johab moves KS X 1001's symbols and Hanja by arithmetic" { // KS X 1001 row 1 column 1, the ideographic space, is the first position // of the region; the euro sign the 1998 revision added at row 2 column 70 // lands in the second half of leading byte 0xD9. try expectEncodeKorean(.johab, "\u{3000}€", &.{ 0xd9, 0x31, 0xd9, 0xe6 }); // 伽, the first Hanja, is row 42 column 1, and 0xE0 is where Hanja start. try expectEncodeKorean(.johab, "伽", &.{ 0xe0, 0x31 }); // 0xD8 is the user-defined area: one error for the pair. try expectDecodeKorean(.johab, &.{ 0xd8, 0x91, 'a' }, "\u{fffd}a"); // And 0x5C is the backslash, not KS X 1003's won sign. try expectDecodeKorean(.johab, "\\", "\\"); } test "Wansung is KS X 1001, with eight bytes for a syllable it lacks" { try expectEncodeKorean(.wansung, "한글", &.{ 0xc7, 0xd1, 0xb1, 0xdb }); try expectDecodeKorean(.wansung, &.{ 0xc7, 0xd1, 0xb1, 0xdb }, "한글"); // 똠 is not among KS X 1001's 2,350 syllables. Code page 949 -- the // standard's EUC-KR -- gave it a pair of its own and Johab never needed // to; Wansung spells it out as the filler, then ㄸ, ㅗ, ㅁ from row 4. try expectEncode(.euc_kr, "똠", &.{ 0x8c, 0x63 }); try expectEncodeKorean(.johab, "똠", &.{ 0x99, 0xb1 }); try expectEncodeKorean(.wansung, "똠", &.{ 0xa4, 0xd4, 0xa4, 0xa8, 0xa4, 0xc7, 0xa4, 0xb1 }); try expectDecodeKorean(.wansung, &.{ 0xa4, 0xd4, 0xa4, 0xa8, 0xa4, 0xc7, 0xa4, 0xb1 }, "똠"); // No final is the filler again: 꺠 is ㄲ, ㅒ and nothing, and is also not // one of the 2,350. try expectEncodeKorean(.wansung, "꺠", &.{ 0xa4, 0xd4, 0xa4, 0xa2, 0xa4, 0xc2, 0xa4, 0xd4 }); // A syllable that has a code is written with it, but spelled out it // decodes all the same. try expectDecodeKorean(.wansung, &.{ 0xa4, 0xd4, 0xa4, 0xa1, 0xa4, 0xbf, 0xa4, 0xd4 }, "가"); // A code page 949 pair is an error, and its ASCII second byte is read // again on its own. try expectDecodeKorean(.wansung, &.{ 0x8c, 0x63 }, "\u{fffd}c"); } test "the filler not followed by a syllable is only the filler" { // On its own, at the end of the text. try expectDecodeKorean(.wansung, &.{ 0xa4, 0xd4 }, "\u{3164}"); // Followed by something else entirely, which is read as itself. try expectDecodeKorean(.wansung, &.{ 0xa4, 0xd4, 'a', 0xc7, 0xd1 }, "\u{3164}a한"); // Broken off after the vowel: what came after the filler is ㄱ and ㅏ. try expectDecodeKorean(.wansung, &.{ 0xa4, 0xd4, 0xa4, 0xa1, 0xa4, 0xbf }, "\u{3164}ㄱㅏ"); // ㄳ cannot begin a syllable, so the sequence ends there, and the pairs // after the filler stay in step rather than being read across. try expectDecodeKorean(.wansung, &.{ 0xa4, 0xd4, 0xa4, 0xa3, 0xa4, 0xbf, 0xa4, 0xd4 }, "\u{3164}ㄳㅏ\u{3164}"); // Nor can ㄸ end one. try expectDecodeKorean(.wansung, &.{ 0xa4, 0xd4, 0xa4, 0xa1, 0xa4, 0xbf, 0xa4, 0xa8 }, "\u{3164}ㄱㅏㄸ"); // A filler that turns out to begin the real syllable. try expectDecodeKorean( .wansung, &.{ 0xa4, 0xd4, 0xa4, 0xd4, 0xa4, 0xa8, 0xa4, 0xc7, 0xa4, 0xb1 }, "\u{3164}똠", ); // A filler that is only a filler is a character, not an error, so a // fatal decoder has nothing to object to. const utf8 = try charset.decodeKoreanAlloc(testing.allocator, .wansung, &.{ 0xa4, 0xd4, 0xa4, 0xa1 }, .{ .error_mode = .fatal, }); defer testing.allocator.free(utf8); try testing.expectEqualStrings("\u{3164}ㄱ", utf8); } test "the Korean encodings are not reachable by a label, and that is deliberate" { for ([_][]const u8{ "johab", "cp1361", "x-johab", "wansung" }) |label| { try testing.expectEqual(@as(?Encoding, null), Encoding.fromLabel(label)); } // `euc-kr` names the standard's own encoding, which is code page 949. try testing.expectEqual(@as(?Encoding, .euc_kr), Encoding.fromLabel("euc-kr")); } test "Korean decoding survives the input arriving in two pieces" { const cases = [_]struct { charset.Korean, []const u8 }{ .{ .wansung, &.{ 'a', 0xc7, 0xd1, 0x8c, 0x63, 0xb1 } }, .{ .wansung, &.{ 0xa4, 0xd4, 0xa4, 0xa8, 0xa4, 0xc7, 0xa4, 0xb1, 'a' } }, .{ .wansung, &.{ 0xa4, 0xd4, 0xa4, 0xd4, 0xa4, 0xa8, 0xa4, 0xc7, 0xa4 } }, .{ .johab, &.{ 'a', 0xd0, 0x65, 0x84, 0x42, 0xd9, 0x31, 0xd8 } }, }; for (cases) |case| { const whole = try charset.decodeKoreanAlloc(testing.allocator, case[0], case[1], .{}); defer testing.allocator.free(whole); for (0..case[1].len + 1) |seam| { var allocating: std.Io.Writer.Allocating = .init(testing.allocator); defer allocating.deinit(); var decoder: charset.Decoder = .initKorean(case[0], .{}); try decoder.decode(case[1][0..seam], &allocating.writer); try decoder.decode(case[1][seam..], &allocating.writer); try decoder.finish(&allocating.writer); testing.expectEqualStrings(whole, allocating.written()) catch |err| { std.debug.print("{s} seam at {d}\n", .{ case[0].name(), seam }); return err; }; } } } test "the Korean encodings round trip their own alphabets, ASCII included" { const text = "키스의 고유조건은 입술끼리 만나야 하고 特別한 技術은 필요치 않다. 똠방각하 ASCII 0123 \\"; for (std.enums.values(charset.Korean)) |korean| { const bytes = try charset.encodeKoreanAlloc(testing.allocator, korean, text, .{}); defer testing.allocator.free(bytes); const back = try charset.decodeKoreanAlloc(testing.allocator, korean, bytes, .{}); defer testing.allocator.free(back); try testing.expectEqualStrings(text, back); } } // -- error modes ------------------------------------------------------------ test "a fatal decoder stops where a replacing one carries on" { // 0xFF is not a lead byte, not a trailing byte and not halfwidth // katakana, so it is nothing at all. (0x80 would not do: Shift_JIS passes // that through as U+0080.) try expectDecode(.shift_jis, &.{ 'a', 0xff, 'b' }, "a\u{fffd}b"); try testing.expectError( error.InvalidByteSequence, charset.decodeAlloc(testing.allocator, .shift_jis, &.{ 'a', 0xff, 'b' }, .{ .error_mode = .fatal, }), ); } test "the html error mode spells an unencodable character out as a reference" { const bytes = try charset.encodeAlloc(testing.allocator, .windows_1252, "a中b", .{ .error_mode = .html, }); defer testing.allocator.free(bytes); try testing.expectEqualStrings("a中b", bytes); } test "a fatal encoder says which scalar value it could not write" { var buffer: [64]u8 = undefined; var writer = std.Io.Writer.fixed(&buffer); var encoder = try charset.Encoder.init(.windows_1252, .{}); try testing.expectError(error.UnmappableCodePoint, encoder.encode("a中", &writer)); try testing.expectEqual(@as(u21, 0x4e2d), encoder.unmappable); } test "invalid UTF-8 on the way in becomes a replacement character" { // The standard's encoders are defined over scalar values and have nothing // to say about malformed input, so it is dealt with before they see it -- // the same thing that happens to a lone surrogate in a JavaScript string. // windows-1252 then has no way to write U+FFFD, which is the encoder's // ordinary unmappable path rather than a second kind of failure. const bytes = try charset.encodeAlloc(testing.allocator, .windows_1252, &.{ 'a', 0xff, 'b' }, .{ .error_mode = .html, }); defer testing.allocator.free(bytes); try testing.expectEqualStrings("a�b", bytes); // An encoding that can write it, writes it. try expectEncode(.utf8, &.{ 'a', 0xff, 'b' }, "a\u{fffd}b"); } // -- byte order marks ------------------------------------------------------- test "a byte order mark chooses the encoding and is not part of the result" { const utf8 = try charset.decodeBomAlloc( testing.allocator, .windows_1252, "\xef\xbb\xbfhi", .{}, ); defer testing.allocator.free(utf8); try testing.expectEqualStrings("hi", utf8); const utf16 = try charset.decodeBomAlloc( testing.allocator, .windows_1252, "\xff\xfeh\x00i\x00", .{}, ); defer testing.allocator.free(utf16); try testing.expectEqualStrings("hi", utf16); } test "without a mark the fallback is used, mark bytes and all" { const utf8 = try charset.decodeBomAlloc(testing.allocator, .windows_1252, "hi", .{}); defer testing.allocator.free(utf8); try testing.expectEqualStrings("hi", utf8); // decodeAlloc does not sniff, so the mark decodes as three characters. const unsniffed = try charset.decodeAlloc(testing.allocator, .windows_1252, "\xef\xbb\xbf", .{}); defer testing.allocator.free(unsniffed); try testing.expectEqualStrings("", unsniffed); } // -- streaming -------------------------------------------------------------- /// Decoding a byte string in one go and decoding it in two pieces must give /// the same answer, wherever the seam falls. This is the property that a /// decoder holding its state wrongly fails, and it fails it for exactly the /// inputs that are hard to think of by hand -- a lead byte at the end of a /// chunk, an escape sequence cut in half, half a surrogate pair. fn expectSplitInvariant(encoding: Encoding, bytes: []const u8) !void { const whole = try charset.decodeAlloc(testing.allocator, encoding, bytes, .{}); defer testing.allocator.free(whole); for (0..bytes.len + 1) |seam| { var allocating: std.Io.Writer.Allocating = .init(testing.allocator); defer allocating.deinit(); var decoder: charset.Decoder = .init(encoding, .{}); try decoder.decode(bytes[0..seam], &allocating.writer); try decoder.decode(bytes[seam..], &allocating.writer); try decoder.finish(&allocating.writer); testing.expectEqualStrings(whole, allocating.written()) catch |err| { std.debug.print("seam at {d} of {d}\n", .{ seam, bytes.len }); return err; }; } } test "decoding survives the input arriving in two pieces" { const cases = [_]struct { Encoding, []const u8 }{ .{ .utf8, "aé中\u{1f300}b" }, .{ .utf8, &.{ 'a', 0xf0, 0x9f, 0x8c, 'b' } }, .{ .windows_1252, &.{ 'a', 0x80, 0x81, 'b' } }, .{ .shift_jis, &.{ 'a', 0x93, 0xfa, 0xb1, 0x81, 0x41, 'b' } }, .{ .shift_jis, &.{ 0x93, 0xfa, 0x93 } }, .{ .euc_jp, &.{ 'a', 0xc6, 0xfc, 0x8e, 0xb1, 0x8f, 0xa2, 0xaf, 'b' } }, .{ .euc_kr, &.{ 'a', 0xc7, 0xd1, 0xb1, 0xb9, 'b' } }, .{ .big5, &.{ 'a', 0xa4, 0xa4, 0x88, 0x62, 'b' } }, .{ .gbk, &.{ 'a', 0xd6, 0xd0, 0x80, 'b' } }, .{ .gb18030, &.{ 'a', 0x81, 0x35, 0xf4, 0x37, 0xd6, 0xd0, 'b' } }, .{ .gb18030, &.{ 0x81, 0x35, 0xf4, 'X' } }, .{ .utf16le, &.{ 'a', 0x00, 0x3c, 0xd8, 0x00, 0xdf, 0x3c, 0xd8, 'b', 0x00 } }, .{ .utf16be, &.{ 0x00, 'a', 0xd8, 0x3c, 0xdf, 0x00 } }, .{ .iso_2022_jp, &.{ 'a', 0x1b, 0x24, 0x42, 0x46, 0x7c, 0x1b, 0x28, 0x42, 'b' } }, .{ .iso_2022_jp, &.{ 0x1b, 0x28, 0x49, 0x21, 0x1b, 0x28, 0x4a, 0x5c } }, .{ .iso_2022_jp, &.{ 0x1b, 0x24, 0x42, 0x46 } }, .{ .iso_2022_jp, &.{ 0x1b, 'X', 'y' } }, .{ .replacement, "anything at all" }, .{ .x_user_defined, &.{ 'a', 0x80, 0xff } }, }; for (cases) |case| try expectSplitInvariant(case[0], case[1]); } test "encoding survives the input arriving in two pieces" { const text = "aé中\u{1f300}ア¥b"; for ([_]Encoding{ .utf8, .shift_jis, .euc_jp, .gb18030, .big5, .euc_kr, .iso_2022_jp }) |encoding| { const whole = try charset.encodeAlloc(testing.allocator, encoding, text, .{ .error_mode = .html, }); defer testing.allocator.free(whole); for (0..text.len + 1) |seam| { var allocating: std.Io.Writer.Allocating = .init(testing.allocator); defer allocating.deinit(); var encoder = try charset.Encoder.init(encoding, .{ .error_mode = .html }); try encoder.encode(text[0..seam], &allocating.writer); try encoder.encode(text[seam..], &allocating.writer); try encoder.finish(&allocating.writer); testing.expectEqualStrings(whole, allocating.written()) catch |err| { std.debug.print("{s} seam at {d}\n", .{ encoding.name(), seam }); return err; }; } } } test "a decoder can be reused for a second text" { var allocating: std.Io.Writer.Allocating = .init(testing.allocator); defer allocating.deinit(); // ISO-2022-JP is the one that would notice: the second text has to start // in ASCII mode rather than in whatever mode the first one ended in. var decoder: charset.Decoder = .init(.iso_2022_jp, .{}); try decoder.decode(&.{ 0x1b, 0x24, 0x42, 0x46, 0x7c }, &allocating.writer); try decoder.finish(&allocating.writer); const first = allocating.written().len; try decoder.decode("ab", &allocating.writer); try decoder.finish(&allocating.writer); try testing.expectEqualStrings("ab", allocating.written()[first..]); } // -- round trips ------------------------------------------------------------ test "every encoding that has an encoder round trips its own alphabet" { const samples = [_]struct { Encoding, []const u8 }{ .{ .utf8, "aé中\u{1f300}" }, .{ .windows_1252, "naïve café — €5" }, .{ .iso_8859_2, "Příliš žluťoučký kůň" }, .{ .koi8_r, "Съешь ещё этих мягких булок" }, .{ .windows_1251, "Съешь ещё этих мягких булок" }, .{ .ibm866, "Съешь ещё этих мягких булок" }, .{ .iso_8859_7, "Ξεσκεπάζω την ψυχοφθόρα βδελυγμία" }, .{ .windows_874, "เป็นมนุษย์สุดประเสริฐ" }, .{ .shift_jis, "いろはにほへとちりぬるを" }, .{ .euc_jp, "いろはにほへとちりぬるを" }, .{ .iso_2022_jp, "いろはにほへとちりぬるを" }, .{ .euc_kr, "키스의 고유조건은 입술끼리 만나야" }, .{ .gbk, "天地玄黃,宇宙洪荒" }, .{ .gb18030, "天地玄黃,宇宙洪荒" }, .{ .big5, "天地玄黃,宇宙洪荒" }, }; for (samples) |sample| { expectRoundTrip(sample[0], sample[1]) catch |err| { std.debug.print("{s}: {s}\n", .{ sample[0].name(), sample[1] }); return err; }; } } test "ASCII survives every encoding that has an encoder" { // Every encoding here is ASCII compatible below 0x80, which is the one // thing a caller may safely assume without looking anything up. const ascii = "The quick brown fox jumps over the lazy dog 0123456789"; for (std.enums.values(Encoding)) |encoding| { if (!encoding.canEncode()) continue; try expectEncode(encoding, ascii, ascii); try expectDecode(encoding, ascii, ascii); } } test { // glibc's charsets, which have a file of their own. _ = @import("glibc.zig"); }