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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Charsets as glibc 2.44's iconv defines them.//!//! `Encoding` is what the WHATWG Encoding Standard means by each encoding.//! This is what glibc means, which is often something else: glibc's//! `ISO-8859-1` is Latin-1 where the standard's `iso-8859-1` label is//! windows-1252, glibc's `EUC-KR` is KS X 1001 where the standard's is code//! page 949, and so on. A program that has to give the same answer as//! something built on glibc -- zig-git, which has to show a commit the way git//! does -- needs glibc's meaning, byte for byte.//!//! A member of `Glibc` is a charset this library reproduces *exactly*: the//! same output for every input, and failure on exactly the inputs glibc//! fails on. Anything short of that is not a member, and `lookup` reports//! its names as `.unsupported` rather than giving an answer that is nearly//! right. That is checked rather than hoped for: `tools/crosscheck_glibc.py`//! runs every input of every member through both and fails on any//! difference.//!//! The one known difference is text that is **outside Unicode**: glibc//! decodes UTF-8's old five- and six-byte forms and four-byte values above//! U+10FFFF, and UCS-4 values up to 0x7FFFFFFF, surrogates included, and//! this library cannot represent those. `convertGlibcAlloc` reports them as//! `error.OutsideUnicode` where glibc's conversion could have succeeded,//! separately from bytes that are invalid everywhere. glibc writes a UCS-4//! surrogate only as UCS-4, so into anything else it is a plain error.//!//! A few of glibc's charsets are in the machine's own byte order -- `UCS-2`,//! and what `UTF-16`, `UTF-32` and `UNICODE` write after their byte order//! mark -- and so are these, so the answers match glibc on the same machine.//!//! Names are glibc's, never the standard's labels, and are only ever//! resolved here: `Encoding.fromLabel` does not see them, so the standard's//! closed set stays closed. See `docs/adr/0001-glibc-charsets.md`.
const std = @import("std");
const names = @import("tables/glibc_names.zig");
/// The glibc 2.44 charsets this library reproduces exactly.////// A member is named after glibc's own name for the charset, lowercased with/// the punctuation turned into underscores, and `name` gives glibc's spelling/// back. Every one of glibc's names for a charset resolves to its member: all/// of `UTF-8`, `UTF8`, `utf-8` and `ISO-10646/UTF8/` are `.utf_8`.pub const Glibc = enum { /// UTF-8. Comparing against this is how to ask whether a glibc name /// means UTF-8, whatever it was spelt as. utf_8, /// ASCII, which is what glibc calls `ANSI_X3.4-1968`: every byte above /// 0x7F is an error. ansi_x3_4_1968,
/// UTF-16 with a byte order mark: written as the mark and then the /// machine's own byte order; read in whichever order a leading mark says, /// or the machine's if there is none. utf_16, utf_16le, utf_16be, /// UTF-32 with a byte order mark, which works as `utf_16`'s does. utf_32, utf_32le, utf_32be, /// UCS-2 in the machine's own byte order, which glibc calls /// `ISO-10646/UCS2` and also answers to `UCS-2` and `UCS2`. UTF-16 /// without the pairs: surrogates are errors, and nothing above U+FFFF can /// be written except the tag characters, which are written as nothing. iso_10646_ucs2, /// UCS-2 with a byte order mark, which works as `utf_16`'s does. unicode, /// UCS-2 in little-endian order, which glibc also calls `UCS-2LE`. unicodelittle, /// UCS-2 in big-endian order, which glibc also calls `UCS-2BE`. unicodebig, /// UCS-4 in big-endian order, which glibc calls `ISO-10646/UCS4` and also /// answers to `UCS-4`, `UCS-4BE` and `ISO-10646`. glibc reads values up /// to 0x7FFFFFFF in it, Unicode or not; see `convertGlibcAlloc` for the /// ones this library cannot. iso_10646_ucs4, /// UCS-4 in little-endian order. ucs_4le,
/// ISO-8859-1: Latin-1, with 0x80 to 0x9F the C1 controls. Not /// windows-1252, which is what the standard's `iso-8859-1` label means. iso_8859_1, iso_8859_2, iso_8859_3, iso_8859_4, iso_8859_5, iso_8859_6, iso_8859_7, iso_8859_8, /// ISO-8859-9: Latin-5, which is Latin-1 with six Turkish letters. Not /// windows-1254, which is what the standard's `iso-8859-9` label means. iso_8859_9, iso_8859_10, /// ISO-8859-11: Thai, with 0x80 to 0x9F the C1 controls. iso_8859_11, iso_8859_13, iso_8859_14, iso_8859_15, iso_8859_16, /// TIS-620: ISO-8859-11 without the C1 controls and without the /// no-break space at 0xA0. tis_620, /// Windows code page 874, which glibc calls IBM874 and also answers to /// `CP874` and `WINDOWS-874`. ibm874,
/// The Windows code pages. Unlike the standard's windows-125x, glibc /// leaves the positions Microsoft never assigned unassigned. cp1250, cp1251, cp1252, cp1253, cp1254, /// Hebrew. glibc composes a letter and its points into one character /// where Unicode has one, both ways: see `codecs/glibc_combining.zig`. cp1255, cp1256, cp1257, /// Vietnamese, which composes a letter and its tone mark as CP1255 does. cp1258,
koi8_r, /// KOI8-U as RFC 2319 defines it. koi8_u, /// KOI8-RU, which adds Belarusian to KOI8-U. koi8_ru, macintosh, /// glibc's Macintosh Ukrainian, which is also what it calls /// `MAC-CYRILLIC`. mac_uk, /// Microsoft's Macintosh Cyrillic. cp10007,
ibm037, ibm500, ibm875, ibm1026, ibm866,
/// Code page 949, which glibc calls the Unified Hangul Code and also /// answers to `CP949`. The same as the standard's EUC-KR. uhc, /// EUC-KR as KS X 1001 defines it, with nothing of code page 949's. euc_kr, /// Johab, KS X 1001 Annex 3, code page 1361. johab, /// Code page 932, Microsoft's Shift_JIS, which glibc also calls /// `WINDOWS-31J` and `MS932`. Not glibc's `SJIS`, which is JIS X 0208 /// alone. cp932, /// ISO-2022-JP as RFC 1468 has it: ASCII, JIS X 0201 Roman and JIS X /// 0208, without the halfwidth katakana and code page 932 extensions the /// standard's ISO-2022-JP reads. iso_2022_jp, /// EUC-JP with JIS X 0208 as `iso_2022_jp` has it and JIS X 0212 both /// ways, where the standard's only reads JIS X 0212. euc_jp, /// Shift_JIS as JIS X 0208 has it: JIS X 0201 for the single bytes, so /// 0x5C is the yen sign, and none of code page 932's additions. sjis,
/// GBK without what GB 18030 added to it, and with nothing in the /// Private Use Area: the standard's GBK is gb18030's table whole. gbk, /// GB 2312 in EUC form, which glibc also calls `GB2312`: GBK's table cut /// down to GB 2312's square, with two cells of its own. euc_cn, /// Big5 itself rather than Big5-HKSCS, which is what the standard's is: /// no Hong Kong rows, and the ETEN extensions as the Private Use Area. big5, /// GB18030, which can write every scalar value: the standard's, with /// 0x80 an error and the eighteen code points GB18030-2022 moved kept /// where they were, so that every one reads back as itself. gb18030,
/// glibc's name for this charset, as glibc spells it. pub fn name(self: Glibc) []const u8 { return names.charsets[charset_index[@backingInt(self)]]; }
/// Whether glibc's encoder for this charset silently drops the tag /// characters U+E0000 to U+E007F. All of them do except the ones that /// can write every scalar value -- UTF-8, UTF-16, UTF-32, UCS-4 and /// GB18030 -- and ISO-2022-JP, which fails on them, and matching glibc /// means doing the same. pub fn dropsTagCharacters(self: Glibc) bool { return switch (self) { .utf_8, .utf_16, .utf_16le, .utf_16be, .utf_32, .utf_32le, .utf_32be, .iso_10646_ucs4, .ucs_4le, .iso_2022_jp, .gb18030 => false, else => true, }; }
/// What `lookup` makes of a name. pub const Lookup = union(enum) { /// A charset this library reproduces. supported: Glibc, /// A name glibc accepts but this library does not reproduce: a /// charset that is not a member, a name that turns on `//IGNORE` or /// `//TRANSLIT`, or a name that comes down to nothing, which glibc /// takes to mean the charset of whatever locale the caller is in. unsupported, /// A name glibc would refuse to open. unknown, };
/// Resolve a name the way glibc 2.44's `iconv_open` would. /// /// glibc is forgiving about how a name is written, and this is too, in /// exactly the same ways. Case does not matter. Anything that is not a /// letter, a digit or one of `_ - . , : /` is ignored wherever it is, /// so `utf 8` is `UTF8`. Trailing slashes, commas and white space are /// ignored. And a name with two or more slashes in it ends in suffixes: /// everything after its last slash or comma is a suffix, repeatedly, /// until fewer than two slashes are left. `IGNORE` and `TRANSLIT`, in /// any case, are the suffixes glibc acts on; any other is ignored. /// /// `tests/glibc-name-cases.txt` is several thousand names with glibc's /// verdict on each, and this is tested against all of them. pub fn lookup(name_or_alias: []const u8) Lookup { var rest = name_or_alias; var acted_on = false; while (true) { rest = std.mem.trimEnd(u8, rest, " \t\n\x0b\x0c\r,/"); if (std.mem.countScalar(u8, rest, '/') < 2) break; const cut = std.mem.findLastAny(u8, rest, "/,").?; const suffix = rest[cut + 1 ..]; if (std.ascii.eqlIgnoreCase(suffix, "IGNORE") or std.ascii.eqlIgnoreCase(suffix, "TRANSLIT")) { acted_on = true; } rest = rest[0..cut]; }
// The longest name glibc knows is shorter than this, so a name that // does not fit, once cleaned up, is not one of them. var buffer: [64]u8 = undefined; var len: usize = 0; for (rest) |c| { if (!std.ascii.isAlphanumeric(c) and std.mem.findScalar(u8, "_-.,:/", c) == null) continue; if (len == buffer.len) return .unknown; buffer[len] = std.ascii.toUpper(c); len += 1; } const cleaned = std.mem.trimEnd(u8, buffer[0..len], "/");
if (cleaned.len == 0) return .unsupported; const charset = find(cleaned) orelse return .unknown; if (acted_on) return .unsupported; return if (members[charset]) |member| .{ .supported = member } else .unsupported; }
fn find(cleaned: []const u8) ?u16 { const Context = struct { fn order(key: []const u8, entry: names.Entry) std.math.Order { return std.mem.order(u8, key, entry.name); } }; const i = std.sort.binarySearch(names.Entry, &names.entries, cleaned, Context.order) orelse return null; return names.entries[i].charset; }
/// Which of glibc's charsets each member is, found by name at compile /// time, so that a member whose name glibc does not have will not /// compile. const charset_index = blk: { @setEvalBranchQuota(1_000_000); const tags = std.enums.values(Glibc); var result: [tags.len]u16 = undefined; for (tags, 0..) |tag, i| { const wanted = canonicalName(tag); result[i] = for (names.charsets, 0..) |charset, j| { if (std.mem.eql(u8, charset, wanted)) break j; } else @compileError("glibc has no charset called " ++ wanted); } break :blk result; };
/// The other way round: for each of glibc's charsets, the member it is, /// if it is one. const members = blk: { var result: [names.charsets.len]?Glibc = @splat(null); for (std.enums.values(Glibc), charset_index) |tag, i| result[i] = tag; break :blk result; };
/// glibc's spelling of a member's name, worked out from the member's /// own: upper case, underscores back to hyphens, and the few names whose /// punctuation is not a hyphen spelt out. fn canonicalName(comptime tag: Glibc) []const u8 { return switch (tag) { .ansi_x3_4_1968 => "ANSI_X3.4-1968", .iso_10646_ucs2 => "ISO-10646/UCS2", .iso_10646_ucs4 => "ISO-10646/UCS4", else => comptime blk: { const tag_name = @tagName(tag); var result: [tag_name.len]u8 = undefined; for (tag_name, 0..) |c, i| result[i] = if (c == '_') '-' else std.ascii.toUpper(c); const final = result; break :blk &final; }, }; }};
test "every member has a name glibc knows" { for (std.enums.values(Glibc)) |member| { try std.testing.expectEqual(Glibc.Lookup{ .supported = member }, Glibc.lookup(member.name())); }}
test "every glibc name for UTF-8 is utf_8" { for (names.entries) |entry| { if (!std.mem.eql(u8, names.charsets[entry.charset], "UTF-8")) continue; try std.testing.expectEqual(Glibc.Lookup{ .supported = .utf_8 }, Glibc.lookup(entry.name)); } try std.testing.expectEqual(Glibc.Lookup{ .supported = .utf_8 }, Glibc.lookup("ISO-10646/UTF8/"));}
test "a few names, by hand" { const expect = std.testing.expectEqual; try expect(Glibc.Lookup{ .supported = .iso_8859_1 }, Glibc.lookup("latin1")); try expect(Glibc.Lookup{ .supported = .iso_8859_1 }, Glibc.lookup("ISO_8859-1:1987")); try expect(Glibc.Lookup{ .supported = .utf_8 }, Glibc.lookup("utf 8")); try expect(Glibc.Lookup{ .supported = .utf_8 }, Glibc.lookup("utf-8//bogus")); try expect(Glibc.Lookup{ .supported = .uhc }, Glibc.lookup("cp949")); try expect(Glibc.Lookup{ .supported = .mac_uk }, Glibc.lookup("MAC-CYRILLIC")); try expect(Glibc.Lookup.unsupported, Glibc.lookup("utf-8//IGNORE")); try expect(Glibc.Lookup.unsupported, Glibc.lookup("ASCII//translit")); try expect(Glibc.Lookup{ .supported = .utf_16 }, Glibc.lookup("utf16")); try expect(Glibc.Lookup{ .supported = .iso_10646_ucs2 }, Glibc.lookup("UCS-2")); try expect(Glibc.Lookup{ .supported = .unicodelittle }, Glibc.lookup("ucs-2le")); try expect(Glibc.Lookup{ .supported = .iso_10646_ucs4 }, Glibc.lookup("UCS-4BE")); try expect(Glibc.Lookup.unsupported, Glibc.lookup("WCHAR_T")); try expect(Glibc.Lookup{ .supported = .sjis }, Glibc.lookup("shift_jis")); try expect(Glibc.Lookup{ .supported = .gbk }, Glibc.lookup("cp936")); try expect(Glibc.Lookup{ .supported = .euc_cn }, Glibc.lookup("gb2312")); try expect(Glibc.Lookup{ .supported = .big5 }, Glibc.lookup("cp950")); try expect(Glibc.Lookup{ .supported = .gb18030 }, Glibc.lookup("gb18030")); try expect(Glibc.Lookup{ .supported = .iso_2022_jp }, Glibc.lookup("csISO2022JP")); try expect(Glibc.Lookup.unsupported, Glibc.lookup("ISO-2022-JP-2")); try expect(Glibc.Lookup{ .supported = .cp1255 }, Glibc.lookup("ms-hebr")); try expect(Glibc.Lookup{ .supported = .euc_jp }, Glibc.lookup("ujis")); try expect(Glibc.Lookup{ .supported = .cp1258 }, Glibc.lookup("windows-1258")); try expect(Glibc.Lookup.unsupported, Glibc.lookup("")); try expect(Glibc.Lookup.unknown, Glibc.lookup("latin-1")); try expect(Glibc.Lookup.unknown, Glibc.lookup("8859-1")); try expect(Glibc.Lookup.unknown, Glibc.lookup("foo//IGNORE"));}