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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Dumps what this library does with every input of a given shape, so that//! something else can be asked the same questions.//!//! The tables here are generated from the index files, so a test written//! against those tables proves only that the generator and the codecs agree.//! What is worth knowing is whether the codecs agree with an implementation//! that was written from the same standards by somebody else, and Python's//! `codecs` module is one: `tools/crosscheck.py` drives this and diffs the//! two, encoding by encoding.//!//! Errors are fatal here rather than replaced, so that a disagreement about//! whether something is an error shows up as one instead of being smoothed//! into a U+FFFD that both sides happen to produce.//!//! ```//! zig build crosscheck -- windows-1252 decode1//! zig build crosscheck -- shift_jis decode2//! zig build crosscheck -- big5 encode//! zig build crosscheck -- glibc:CP932 decode2//! zig build crosscheck -- glibc members//! ```//!//! A `glibc:` target is one of glibc's charsets, named as glibc names it, and//! goes through `convertGlibcAlloc` to and from UTF-8, which is exactly what//! a caller wanting glibc's answers uses. `tools/crosscheck_glibc.py` is the//! driver that asks glibc the same questions.
const std = @import("std");
const charset = @import("charset");
/// What is being dumped: one of the standard's encodings, or one of the/// EBCDIC code pages or Korean encodings, which are reached by different/// functions.const Target = union(enum) { standard: charset.Encoding, ebcdic: charset.Ebcdic, korean: charset.Korean, glibc: charset.Glibc,};
/// Printed instead of a dump when an encoding has no encoder. The driver/// looks for exactly this.pub const decode_only_marker = "# decode-only";
const Mode = enum { /// Every one-byte input. decode1, /// Every two-byte input. decode2, /// Every scalar value. encode, /// Wansung only: every eight-byte sequence of the filler and three row 4 /// positions, which is how KS X 1001 spells a syllable it has no code /// for. syllables, /// Inputs read from standard input, one to a line, in hexadecimal. decodehex, /// glibc only: UTF-8 read from standard input, one text to a line in /// hexadecimal, and encoded as a whole. encodehex,};
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
var args = init.minimal.args.iterate(); _ = args.next(); const label = args.next() orelse fatal("usage: crosscheck <label> <decode1|decode2|encode>", .{}); const mode_name = args.next() orelse fatal("usage: crosscheck <label> <decode1|decode2|encode>", .{});
var buffer: [64 * 1024]u8 = undefined; var stdout = std.Io.File.stdout().writer(init.io, &buffer); const w = &stdout.interface;
// The charsets glibc is checked against, by glibc's name for each, so // that the driver needs no list of its own to keep in step. if (std.mem.eql(u8, label, "glibc") and std.mem.eql(u8, mode_name, "members")) { for (std.enums.values(charset.Glibc)) |member| try w.print("{s}\n", .{member.name()}); try w.flush(); return; }
// EBCDIC and the Korean encodings have no labels -- that is the point of // them being separate types -- so they are named here by the enum member, // which is also what a caller writes in code. const target: Target = if (std.mem.startsWith(u8, label, "glibc:")) switch (charset.Glibc.lookup(label["glibc:".len..])) { .supported => |member| .{ .glibc = member }, else => fatal("not a glibc charset this library has: {s}", .{label}), } else if (std.meta.stringToEnum(charset.Ebcdic, label)) |code_page| .{ .ebcdic = code_page } else if (std.meta.stringToEnum(charset.Korean, label)) |korean| .{ .korean = korean } else if (charset.Encoding.fromLabel(label)) |encoding| .{ .standard = encoding } else fatal("not a label, an EBCDIC code page or a Korean encoding: {s}", .{label}); const mode = std.meta.stringToEnum(Mode, mode_name) orelse fatal("not a mode: {s}", .{mode_name});
switch (mode) { .decodehex => { var input_buffer: [64 * 1024]u8 = undefined; var stdin = std.Io.File.stdin().reader(init.io, &input_buffer); const r = &stdin.interface; var bytes: [256]u8 = undefined; while (r.takeDelimiterInclusive('\n')) |line| { const hex = std.mem.trimEnd(u8, line, "\n"); const input = std.fmt.hexToBytes(&bytes, hex) catch fatal("not hexadecimal: {s}", .{hex}); try w.print("{s}\t", .{hex}); try decodeOne(gpa, target, input, w); } else |err| switch (err) { error.EndOfStream => {}, else => |other| return other, } }, .encodehex => { if (target != .glibc) fatal("encodehex is for glibc charsets only", .{}); var input_buffer: [64 * 1024]u8 = undefined; var stdin = std.Io.File.stdin().reader(init.io, &input_buffer); const r = &stdin.interface; var bytes: [256]u8 = undefined; while (r.takeDelimiterInclusive('\n')) |line| { const hex = std.mem.trimEnd(u8, line, "\n"); const input = std.fmt.hexToBytes(&bytes, hex) catch fatal("not hexadecimal: {s}", .{hex}); try w.print("{s}\t", .{hex}); try encodeText(gpa, target.glibc, input, w); } else |err| switch (err) { error.EndOfStream => {}, else => |other| return other, } }, .syllables => { if (target != .korean or target.korean != .wansung) fatal("syllables is for wansung only", .{}); var initial: usize = 0xa1; while (initial <= 0xfe) : (initial += 1) { var vowel: usize = 0xa1; while (vowel <= 0xfe) : (vowel += 1) { var final: usize = 0xa1; while (final <= 0xfe) : (final += 1) { const bytes = [8]u8{ 0xa4, 0xd4, 0xa4, @intCast(initial), 0xa4, @intCast(vowel), 0xa4, @intCast(final) }; try w.print("{x}\t", .{&bytes}); try decodeOne(gpa, target, &bytes, w); } } } }, .decode1 => { var byte: usize = 0; while (byte < 0x100) : (byte += 1) { try w.print("{x:0>2}\t", .{byte}); try decodeOne(gpa, target, &.{@intCast(byte)}, w); } }, .decode2 => { var first: usize = 0; while (first < 0x100) : (first += 1) { var second: usize = 0; while (second < 0x100) : (second += 1) { try w.print("{x:0>2}{x:0>2}\t", .{ first, second }); try decodeOne(gpa, target, &.{ @intCast(first), @intCast(second) }, w); } } }, .encode => { // The standard makes three of its encodings decode-only, and // `canEncode` is the library's own answer about which: asking one // of them to encode is `error.NoEncoder`, not a failure to // report. Say so and stop, so that a driver comparing every // encoding in turn does not lose the whole run to an encoding // that was never going to have an encoder. if (target == .standard and !target.standard.canEncode()) { try w.print("{s}\n", .{decode_only_marker}); try w.flush(); return; }
var code_point: u21 = 0; while (code_point <= 0x10ffff) : (code_point += 1) { if (code_point >= 0xd800 and code_point <= 0xdfff) continue; try w.print("{x}\t", .{code_point}); try encodeOne(gpa, target, code_point, w); } }, } try w.flush();}
fn decodeOne( gpa: std.mem.Allocator, target: Target, bytes: []const u8, w: *std.Io.Writer,) !void { const decoded = switch (target) { .standard => |encoding| charset.decodeAlloc(gpa, encoding, bytes, .{ .error_mode = .fatal }), .ebcdic => |code_page| charset.decodeEbcdicAlloc(gpa, code_page, bytes, .{ .error_mode = .fatal }), .korean => |korean| charset.decodeKoreanAlloc(gpa, korean, bytes, .{ .error_mode = .fatal }), .glibc => |member| charset.convertGlibcAlloc(gpa, member, .utf_8, bytes), }; const utf8 = decoded catch |err| switch (err) { error.InvalidByteSequence => return w.writeAll("ERR\n"), // UTF-8 that glibc reads and this library will not: the driver // writes the same for a value glibc gives above U+10FFFF. error.OutsideUnicode => return w.writeAll("OUTSIDE\n"), else => |other| return other, }; defer gpa.free(utf8);
var view = std.unicode.Utf8View.initUnchecked(utf8).iterator(); var first = true; while (view.nextCodepoint()) |code_point| { if (!first) try w.writeAll(","); first = false; try w.print("{x}", .{code_point}); } if (first) try w.writeAll("-"); try w.writeAll("\n");}
fn encodeOne( gpa: std.mem.Allocator, target: Target, code_point: u21, w: *std.Io.Writer,) !void { var utf8: [4]u8 = undefined; const len = std.unicode.utf8Encode(code_point, &utf8) catch unreachable;
const encoded = switch (target) { .standard => |encoding| charset.encodeAlloc(gpa, encoding, utf8[0..len], .{ .error_mode = .fatal }), .ebcdic => |code_page| charset.encodeEbcdicAlloc(gpa, code_page, utf8[0..len], .{ .error_mode = .fatal }), .korean => |korean| charset.encodeKoreanAlloc(gpa, korean, utf8[0..len], .{ .error_mode = .fatal }), .glibc => |member| charset.convertGlibcAlloc(gpa, .utf_8, member, utf8[0..len]), }; const bytes = encoded catch |err| switch (err) { error.UnmappableCodePoint => return w.writeAll("ERR\n"), error.InvalidByteSequence, error.OutsideUnicode => unreachable, else => |other| return other, }; defer gpa.free(bytes);
for (bytes) |byte| try w.print("{x:0>2}", .{byte}); if (bytes.len == 0) try w.writeAll("-"); try w.writeAll("\n");}
fn encodeText( gpa: std.mem.Allocator, member: charset.Glibc, utf8: []const u8, w: *std.Io.Writer,) !void { const bytes = charset.convertGlibcAlloc(gpa, .utf_8, member, utf8) catch |err| switch (err) { error.UnmappableCodePoint, error.InvalidByteSequence => return w.writeAll("ERR\n"), error.OutsideUnicode => return w.writeAll("OUTSIDE\n"), else => |other| return other, }; defer gpa.free(bytes); for (bytes) |byte| try w.print("{x:0>2}", .{byte}); if (bytes.len == 0) try w.writeAll("-"); try w.writeAll("\n");}
fn fatal(comptime format: []const u8, args: anytype) noreturn { std.debug.print(format ++ "\n", args); std.process.exit(1);}