// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Johab: KS X 1001 Annex 3, Windows code page 1361. Not in the Encoding //! Standard. //! //! Two bytes for everything but ASCII, in two regions that do not overlap. //! //! Hangul, with a leading byte 0x84 to 0xD3, is not looked up but spelled //! out. The sixteen bits are a one, then five bits each for the initial //! consonant, the vowel and the final consonant, and each five-bit field has a //! *fill* value meaning "none". All three filled in is a syllable, and every //! one of the 11,172 has a code. A consonant or vowel standing alone is the //! other two filled with fill, and decodes to the Hangul Compatibility Jamo -- //! which has one code point per letter where Johab has a code per *position*, //! so a consonant that can begin a syllable is written as an initial, and only //! the eleven clusters that cannot (ㄳ, ㄵ, ㄶ, ㄺ to ㅀ, ㅄ) as finals. That //! is the one code per letter Unicode.org's JOHAB.TXT gives, and it is the //! only one accepted here; a final ㄱ, say, is a code nothing writes, and //! decodes as an error rather than as a second spelling of ㄱ. //! //! Everything else in KS X 1001 -- symbols, the old jamo, Hanja -- is moved //! by arithmetic from its row and column into leading bytes 0xD9 to 0xDE and //! 0xE0 to 0xF9, two rows of 94 to each leading byte. The positions come from //! the standard's euc-kr index, as Wansung's do; the rows that hold Hangul //! syllables in KS X 1001 have no place in this region, and the modern jamo //! in row 4 are skipped because they are already in the other one. 0xD8 is //! the user-defined area, and decodes as an error. //! //! 0x5C is the backslash. KS X 1003, the Korean ISO 646, puts the won sign //! there, and JOHAB.TXT follows it while saying in its own notes that the //! backslash "might be a better idea"; Windows and CPython both use it, and //! so does every other encoding in this library. const std = @import("std"); const codec = @import("../codec.zig"); const hangul_letters = @import("hangul.zig"); const wansung = @import("wansung.zig"); const ByteQueue = codec.ByteQueue; const Decoded = codec.Decoded; const Encoded = codec.Encoded; const fill = 0xff; const none = 0xfe; /// The five-bit field of each kind, to the index of that letter in Unicode's /// ordering of initials, vowels and finals -- the ordering the Hangul /// Syllables block is laid out by. The vowels and finals skip values, which /// is the encoding's doing: it kept them where a hardware decoder would find /// them convenient. const initial_index = fields(&.{.{ 2, 0, 19 }}, 1); const vowel_index = fields(&.{ .{ 3, 0, 5 }, .{ 10, 5, 6 }, .{ 18, 11, 6 }, .{ 26, 17, 4 } }, 2); const final_index = fields(&.{ .{ 2, 1, 16 }, .{ 19, 17, 11 } }, 1); fn fields(comptime runs: []const [3]u8, comptime fill_value: u5) [32]u8 { var table: [32]u8 = @splat(none); table[fill_value] = fill; for (runs) |run| { for (0..run[2]) |i| table[run[0] + i] = @intCast(run[1] + i); } return table; } fn field(table: *const [32]u8, comptime fill_value: u5, letter: ?u8) u5 { const wanted = letter orelse return fill_value; return @intCast(std.mem.findScalar(u8, table, wanted).?); } const initial_jamo = hangul_letters.initial_jamo; const final_jamo = hangul_letters.final_jamo; fn hangul(initial: ?u8, vowel: ?u8, final: ?u8) u16 { return 0x8000 | @as(u16, field(&initial_index, 1, initial)) << 10 | @as(u16, field(&vowel_index, 2, vowel)) << 5 | field(&final_index, 1, final); } /// The code for each of U+3131 to U+3163: a consonant as an initial where it /// can be one and as a final where it cannot, a vowel on its own. const jamo_codes = blk: { @setEvalBranchQuota(10_000); var codes: [0x33]u16 = @splat(0); for (final_jamo, 0..) |jamo, final| codes[jamo - 0x31] = hangul(null, null, final + 1); for (initial_jamo, 0..) |jamo, initial| codes[jamo - 0x31] = hangul(initial, null, null); for (0..21) |vowel| codes[0x4f - 0x31 + vowel] = hangul(null, vowel, null); for (codes) |code| std.debug.assert(code != 0); break :blk codes; }; fn decodeHangul(code: u16) ?u21 { const initial = initial_index[(code >> 10) & 0x1f]; const vowel = vowel_index[(code >> 5) & 0x1f]; const final = final_index[code & 0x1f]; if (initial == none or vowel == none or final == none) return null; if (initial != fill and vowel != fill) return hangul_letters.compose(.{ .initial = initial, .vowel = vowel, .final = if (final == fill) 0 else final, }); // A letter on its own: exactly one of the three is not fill. const jamo: u21 = if (initial != fill and final == fill) 0x3100 + @as(u21, initial_jamo[initial]) else if (vowel != fill and final == fill) hangul_letters.first_vowel + @as(u21, vowel) else if (initial == fill and vowel == fill and final != fill) 0x3100 + @as(u21, final_jamo[final - 1]) else return null; // Only the one spelling of each letter, which turns away a final where // an initial would do. return if (jamo_codes[jamo - 0x3131] == code) jamo else null; } fn encodeHangul(code_point: u21) ?u16 { if (hangul_letters.isSyllable(code_point)) { const letters = hangul_letters.decompose(code_point); return hangul(letters.initial, letters.vowel, if (letters.final == 0) null else letters.final); } if (code_point >= 0x3131 and code_point <= 0x3163) return jamo_codes[code_point - 0x3131]; return null; } /// Row 4 of KS X 1001 from column 0x21 to 0x53 is ㄱ to ㅣ, which this /// encoding writes in the Hangul region instead. fn isModernJamo(position: wansung.Position) bool { return position.row == 0xa4 and position.column <= 0xd3; } fn decodeSymbol(square: wansung.Square, leading: u8, trailing: u8) ?u21 { if (!((leading >= 0xd9 and leading <= 0xde) or (leading >= 0xe0 and leading <= 0xf9))) return null; const t2: u8 = if (trailing >= 0x31 and trailing <= 0x7e) trailing - 0x31 else if (trailing >= 0x91 and trailing <= 0xfe) trailing - 0x43 else return null; const pair: u8 = if (leading < 0xe0) 2 * (leading - 0xd9) else @intCast(2 * @as(u16, leading) - 0x197); const position: wansung.Position = .{ .row = pair + @intFromBool(t2 >= 94) + 0xa1, .column = t2 % 94 + 0xa1, }; if (isModernJamo(position)) return null; return wansung.decodePositionIn(square, position); } fn encodeSymbol(square: wansung.Square, code_point: u21) ?u16 { const position = wansung.encodePositionIn(square, code_point) orelse return null; const row: u16 = position.row - 0xa1; // The Hangul syllables of KS X 1001 and the modern jamo are both written // in the Hangul region, and `encodeHangul` will have had them first. std.debug.assert(row < 0x0f or row > 0x27); std.debug.assert(!isModernJamo(position)); const t1: u16 = if (row < 0x29) row + 0x1b2 else row + 0x197; const t2: u16 = (if (t1 & 1 != 0) @as(u16, 94) else 0) + (position.column - 0xa1); return (t1 >> 1) << 8 | (if (t2 < 78) t2 + 0x31 else t2 + 0x43); } /// The Korean ISO 646 puts the won sign where ASCII has the backslash, and /// glibc's Johab follows it, as JOHAB.TXT does. const won_sign = 0x20a9; pub const Decoder = struct { leading: u8 = 0, /// Johab as glibc has it: 0x5C is the won sign, and KS X 1001 includes /// its 2002 revision's postal code mark. glibc: bool = false, pub fn handle(self: *Decoder, queue: *ByteQueue, byte: ?u8) Decoded { const b = byte orelse { if (self.leading == 0) return .finished; self.leading = 0; return .failure; }; if (self.leading != 0) { const leading = self.leading; self.leading = 0; const decoded = if (leading <= 0xd3) decodeHangul(@as(u16, leading) << 8 | b) else decodeSymbol(self.square(), leading, b); if (decoded) |c| return .{ .code_point = c }; if (b < 0x80) queue.restore(&.{b}); return .failure; } if (b == 0x5c and self.glibc) return .{ .code_point = won_sign }; if (b < 0x80) return .{ .code_point = b }; // 0xD8 is the user-defined area. It is taken as a leading byte so // that a pair from it is one error rather than two. if ((b >= 0x84 and b <= 0xd3) or (b >= 0xd8 and b <= 0xde) or (b >= 0xe0 and b <= 0xf9)) { self.leading = b; return .cont; } return .failure; } fn square(self: *const Decoder) wansung.Square { return if (self.glibc) .glibc else .standard; } }; pub const Encoder = struct { /// As for `Decoder.glibc`. glibc: bool = false, pub fn handle(self: *Encoder, code_point: ?u21) Encoded { const c = code_point orelse return .finished; if (self.glibc) { if (c == won_sign) return .{ .bytes = .one(0x5c) }; if (c == 0x5c) return .{ .failure = c }; } if (c < 0x80) return .{ .bytes = .one(@intCast(c)) }; const square: wansung.Square = if (self.glibc) .glibc else .standard; const code = encodeHangul(c) orelse encodeSymbol(square, c) orelse return .{ .failure = c }; return .{ .bytes = .two(@intCast(code >> 8), @truncate(code)) }; } }; test "a syllable is its three letters, bit by bit" { // 한: ㅎ (initial 18, field 20), ㅏ (vowel 0, field 3), ㄴ (final 4, // field 5): 1 10100 00011 00101. try std.testing.expectEqual(@as(?u16, 0b1_10100_00011_00101), encodeHangul('한')); try std.testing.expectEqual(@as(?u21, '한'), decodeHangul(0b1_10100_00011_00101)); // 가, the first syllable: ㄱ, ㅏ, no final. try std.testing.expectEqual(@as(?u16, 0x8861), encodeHangul('가')); } test "every syllable and every modern jamo round trips" { var c: u21 = 0xac00; while (c <= 0xd7a3) : (c += 1) { try std.testing.expectEqual(@as(?u21, c), decodeHangul(encodeHangul(c).?)); } c = 0x3131; while (c <= 0x3163) : (c += 1) { try std.testing.expectEqual(@as(?u21, c), decodeHangul(encodeHangul(c).?)); } } test "a letter has one spelling" { // ㄱ as an initial, and as the final nothing writes. try std.testing.expectEqual(@as(?u21, 0x3131), decodeHangul(0x8841)); try std.testing.expectEqual(@as(?u21, null), decodeHangul(0x8442)); // ㄳ can only be a final. try std.testing.expectEqual(@as(?u21, 0x3133), decodeHangul(0x8444)); // All three fill is nothing at all. try std.testing.expectEqual(@as(?u21, null), decodeHangul(0x8441)); } test "the symbol region is KS X 1001 by arithmetic" { // KS X 1001 0x2121, the ideographic space, is the first position. try std.testing.expectEqual(@as(?u16, 0xd931), encodeSymbol(.standard, 0x3000)); try std.testing.expectEqual(@as(?u21, 0x3000), decodeSymbol(.standard, 0xd9, 0x31)); // The Hangul filler is row 4 too, but past the modern jamo. try std.testing.expectEqual(@as(?u16, 0xdad4), encodeSymbol(.standard, 0x3164)); try std.testing.expectEqual(@as(?u21, null), decodeSymbol(.standard, 0xda, 0xa1)); // 伽, the first Hanja, at KS X 1001 0x4A21. try std.testing.expectEqual(@as(?u16, 0xe031), encodeSymbol(.standard, 0x4f3d)); // The postal code mark is in glibc's KS X 1001 and not the standard's. try std.testing.expectEqual(@as(?u16, null), encodeSymbol(.standard, 0x327e)); try std.testing.expectEqual(@as(?u16, 0xd9e8), encodeSymbol(.glibc, 0x327e)); try std.testing.expectEqual(@as(?u21, 0x327e), decodeSymbol(.glibc, 0xd9, 0xe8)); }