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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Wansung: KS X 1001 in its EUC form, which the Encoding Standard does not//! define.//!//! This is EUC-KR as RFC 1557 describes it, before Microsoft filled the gaps://! both bytes 0xA1 to 0xFE, ASCII below that, and nothing else. The standard's//! euc-kr index is code page 949, a superset, and its entries with both bytes//! in that range are exactly KS X 1001 -- including the euro sign and the//! registered sign that the 1998 revision added at `A2 E6` and `A2 E7` -- so//! this reads that index and refuses everything outside the square.//!//! A syllable outside KS X 1001's 2,350 is written as eight bytes, the way//! KS X 1001 defines: the Hangul filler `A4 D4`, then the initial//! consonant, the vowel and the final consonant as the jamo of row 4 -- the//! filler again where there is no final. 똠, which has no code of its own, is//! `A4 D4 A4 A8 A4 C7 A4 B1`: filler, ㄸ, ㅗ, ㅁ. A syllable that does have a//! code is written with it, but its eight-byte spelling decodes too.//!//! `A4 D4` not followed by a whole syllable is the filler, U+3164, which is//! what KS X 1001 has at that position, and whatever followed it is decoded//! afresh. A sequence broken off part way therefore costs nothing but itself://! the bytes after the filler are read as what they are rather than being//! knocked out of step with the byte pairs around them.
const std = @import("std");
const codec = @import("../codec.zig");const hangul = @import("hangul.zig");const index = @import("../index.zig");const tables = @import("../tables/euc_kr.zig");
const ByteQueue = codec.ByteQueue;const Decoded = codec.Decoded;const Encoded = codec.Encoded;
const euc_kr_index: index.Index(u16) = .{ .code_points = &tables.encode_code_points, .pointers = &tables.encode_pointers,};
/// A position in KS X 1001, as the two bytes of its EUC form: row and column/// both 0xA1 to 0xFE.pub const Position = struct { row: u8, column: u8 };
fn inSquare(byte: u8) bool { return byte >= 0xa1 and byte <= 0xfe;}
/// The code point at a position in KS X 1001, or null where it has none.pub fn decodePosition(position: Position) ?u21 { if (!inSquare(position.row) or !inSquare(position.column)) return null; const pointer = (@as(u32, position.row - 0x81) * 190) + (position.column - 0x41); return index.codePoint(&tables.decode, pointer);}
/// The position of a code point in KS X 1001, or null where it has none.////// The euc-kr index holds no code point twice, so the pointer it gives is the/// only one, and if that is outside the square the code point is one of the/// Unified Hangul Code's additions rather than KS X 1001's.pub fn encodePosition(code_point: u21) ?Position { const pointer = euc_kr_index.pointer(code_point) orelse return null; const position: Position = .{ .row = @intCast(pointer / 190 + 0x81), .column = @intCast(pointer % 190 + 0x41), }; if (!inSquare(position.row) or !inSquare(position.column)) return null; return position;}
/// Which KS X 1001 to read. The standard's euc-kr index is KS X 1001 as of its/// 1998 revision, which added the euro and registered signs. glibc also has/// the one character the 2002 revision added: U+327E CIRCLED HANGUL IEUNG U,/// the postal code mark, at 0xA2E8.pub const Square = enum { standard, glibc,
const postal_mark: Position = .{ .row = 0xa2, .column = 0xe8 }; const postal_mark_code_point = 0x327e;};
/// `decodePosition`, in the given revision of KS X 1001.pub fn decodePositionIn(square: Square, position: Position) ?u21 { if (square == .glibc and position.row == Square.postal_mark.row and position.column == Square.postal_mark.column) { return Square.postal_mark_code_point; } return decodePosition(position);}
/// `encodePosition`, in the given revision of KS X 1001.pub fn encodePositionIn(square: Square, code_point: u21) ?Position { if (square == .glibc and code_point == Square.postal_mark_code_point) return Square.postal_mark; return encodePosition(code_point);}
/// The opening of an eight-byte syllable, which on its own is the filler.const filler = [2]u8{ 0xa4, 0xd4 };const filler_code_point = 0x3164;
/// The Compatibility Jamo at row 4, column `column`: ㄱ to ㅣ are columns/// 0xA1 to 0xD3, in Unicode's order.fn jamoAt(column: u8) ?u21 { if (column < 0xa1 or column > 0xd3) return null; return 0x3131 + @as(u21, column - 0xa1);}
fn columnOf(jamo: u21) u8 { return @intCast(jamo - 0x3131 + 0xa1);}
/// The six bytes of a syllable that follow the filler, so far.const Syllable = struct { bytes: [6]u8 = undefined, len: u3 = 0,
/// Whether the bytes so far can still begin a syllable: the lead byte of /// row 4 before each letter, and the right kind of letter after it. fn plausible(self: *const Syllable) bool { const i = self.len - 1; const b = self.bytes[i]; if (i % 2 == 0) return b == 0xa4; if (i == 5 and b == filler[1]) return true; const jamo = jamoAt(b) orelse return false; return switch (i) { 1 => hangul.initialOf(jamo) != null, 3 => hangul.vowelOf(jamo) != null, 5 => hangul.finalOf(jamo) != null, else => unreachable, }; }
fn codePoint(self: *const Syllable) u21 { return hangul.compose(.{ .initial = hangul.initialOf(jamoAt(self.bytes[1]).?).?, .vowel = hangul.vowelOf(jamoAt(self.bytes[3]).?).?, .final = if (self.bytes[5] == filler[1]) 0 else hangul.finalOf(jamoAt(self.bytes[5]).?).?, }); }};
pub const Decoder = struct { leading: u8 = 0, /// Set once the filler has been read, while the rest of a syllable may /// still be coming. syllable: ?Syllable = null,
pub fn handle(self: *Decoder, queue: *ByteQueue, byte: ?u8) Decoded { if (self.syllable) |*syllable| { const b = byte orelse return self.notASyllable(queue); syllable.bytes[syllable.len] = b; syllable.len += 1; if (!syllable.plausible()) return self.notASyllable(queue); if (syllable.len < syllable.bytes.len) return .cont; defer self.syllable = null; return .{ .code_point = syllable.codePoint() }; }
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;
if (leading == filler[0] and b == filler[1]) { self.syllable = .{}; return .cont; } if (decodePosition(.{ .row = leading, .column = b })) |c| return .{ .code_point = c }; // As in the standard's EUC-KR: an ASCII byte cannot have been // meant as the second half, so it is read again on its own. if (b < 0x80) queue.restore(&.{b}); return .failure; }
if (b < 0x80) return .{ .code_point = b }; if (inSquare(b)) { self.leading = b; return .cont; } return .failure; }
/// The filler was only the filler: say so, and read what came after it /// again from a clean state. fn notASyllable(self: *Decoder, queue: *ByteQueue) Decoded { const syllable = self.syllable.?; self.syllable = null; queue.restore(syllable.bytes[0..syllable.len]); return .{ .code_point = filler_code_point }; }};
pub const Encoder = struct { pub fn handle(_: *Encoder, code_point: ?u21) Encoded { const c = code_point orelse return .finished; if (c < 0x80) return .{ .bytes = .one(@intCast(c)) };
if (encodePosition(c)) |position| return .{ .bytes = .two(position.row, position.column) }; if (!hangul.isSyllable(c)) return .{ .failure = c };
const letters = hangul.decompose(c); const initial = 0x3100 + @as(u21, hangul.initial_jamo[letters.initial]); const vowel = hangul.first_vowel + @as(u21, letters.vowel); const final = if (letters.final == 0) filler[1] else columnOf(0x3100 + @as(u21, hangul.final_jamo[letters.final - 1])); return .{ .bytes = .of(&.{ filler[0], filler[1], 0xa4, columnOf(initial), 0xa4, columnOf(vowel), 0xa4, final, }) }; }};
test "the square holds KS X 1001 and nothing of the Unified Hangul Code" { // 가 is in both; 갂 is one of the 8,822 that only code page 949 has. try std.testing.expectEqual(Position{ .row = 0xb0, .column = 0xa1 }, encodePosition(0xac00).?); try std.testing.expectEqual(@as(?Position, null), encodePosition(0xac02)); try std.testing.expectEqual(@as(?u21, 0xac00), decodePosition(.{ .row = 0xb0, .column = 0xa1 })); try std.testing.expectEqual(@as(?u21, null), decodePosition(.{ .row = 0x81, .column = 0x41 }));}
test "a syllable without a code of its own is eight bytes" { var encoder: Encoder = .{}; const encoded = encoder.handle('똠'); try std.testing.expectEqualSlices( u8, &.{ 0xa4, 0xd4, 0xa4, 0xa8, 0xa4, 0xc7, 0xa4, 0xb1 }, encoded.bytes.slice(), );}
test "every syllable round trips, whether it has a code or not" { var encoder: Encoder = .{}; var c: u21 = hangul.first_syllable; while (c <= hangul.last_syllable) : (c += 1) { const encoded = encoder.handle(c).bytes; var queue: ByteQueue = .{ .input = encoded.slice() }; var decoder: Decoder = .{}; while (true) { switch (decoder.handle(&queue, queue.next())) { .cont => {}, .code_point => |decoded| { try std.testing.expectEqual(c, decoded); break; }, else => return error.TestUnexpectedResult, } } }}
test "every position in the square round trips" { var count: usize = 0; var row: u8 = 0xa1; while (row <= 0xfe) : (row += 1) { var column: u8 = 0xa1; while (column <= 0xfe) : (column += 1) { const c = decodePosition(.{ .row = row, .column = column }) orelse continue; count += 1; try std.testing.expectEqual(Position{ .row = row, .column = column }, encodePosition(c).?); } } // KS X 1001:1998: 8,224 characters, plus the euro and registered signs. try std.testing.expectEqual(@as(usize, 8226), count);}
test "any arrangement of the bytes a syllable is made of decodes without overflowing the queue" { // A sequence that fails hands up to six bytes back, and those can hold // the start of another that fails in turn. Every string of up to seven of // these bytes is every way that can nest at that length. const alphabet = [_]u8{ 0xa4, 0xd4, 0xa1, 0xbf, 0xb1, 'a' }; var input: [7]u8 = undefined; for (1..input.len + 1) |len| { var n: usize = 0; while (n < std.math.pow(usize, alphabet.len, len)) : (n += 1) { var rest = n; for (input[0..len]) |*b| { b.* = alphabet[rest % alphabet.len]; rest /= alphabet.len; } var queue: ByteQueue = .{ .input = input[0..len] }; var decoder: Decoder = .{}; var steps: usize = 0; while (true) : (steps += 1) { try std.testing.expect(steps < 64); if (decoder.handle(&queue, queue.next()) == .finished) break; } } }}