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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! glibc's UTF-16, UTF-32, UCS-2 and UCS-4, in all their byte orders.//!//! The charsets come in four forms and three byte orders, and glibc's eleven//! of them are combinations of the two://!//! - **UTF-16** pairs surrogates for anything above U+FFFF, and fails on a//! surrogate that is not part of a pair.//! - **UCS-2** has no pairs. Every surrogate is an error, and so is any//! scalar value above U+FFFF on the way in, except the tag characters,//! which glibc writes nothing for, as it does in its legacy charsets.//! - **UTF-32** is a scalar value in four bytes, and anything above U+10FFFF//! or a surrogate is an error.//! - **UCS-4** is four bytes as well, but glibc reads any value up to//! 0x7FFFFFFF, surrogates and values above U+10FFFF included. This library//! cannot represent those, so the decoder fails on them and//! `convertGlibcAlloc` tells that failure apart as `error.OutsideUnicode`//! wherever glibc's conversion could have succeeded: into UTF-8 or UCS-4,//! or into UCS-4 alone for a surrogate.//!//! The byte order is little-endian, big-endian, or **marked**. A marked//! charset -- glibc's `UTF-16`, `UTF-32` and `UNICODE` -- writes a byte order//! mark before the first character and then the machine's own byte order.//! Reading one, a mark as the very first unit, in either order, says which//! order the rest is in and is not part of the text; without one the text is//! in the machine's order. Only the first unit is looked at: a second mark is//! the character U+FEFF. The charsets with a fixed byte order never treat a//! mark as anything but that character.//!//! glibc's plain `UCS-2` is in the machine's byte order too, which is why//! this file asks the target what that is rather than assuming: on a//! big-endian machine glibc's answers differ, and so do these.//!//! None of this is the WHATWG's UTF-16, which is in `utf16.zig` and has no//! encoder at all.
const std = @import("std");const builtin = @import("builtin");
const codec = @import("../codec.zig");
const Bytes = codec.Bytes;const ByteQueue = codec.ByteQueue;const Decoded = codec.Decoded;const Encoded = codec.Encoded;const Glibc = @import("../glibc.zig").Glibc;
pub const Form = enum { utf16, ucs2, utf32, ucs4,
fn width(self: Form) u3 { return switch (self) { .utf16, .ucs2 => 2, .utf32, .ucs4 => 4, }; }};
pub const Order = enum { little, big, /// A byte order mark first, then the machine's order. marked,};
pub const Variant = struct { form: Form, order: Order,};
const native: Order = switch (builtin.cpu.arch.endian()) { .little => .little, .big => .big,};
/// Which form and byte order a glibc charset is, if it is one of these.pub fn variant(charset: Glibc) ?Variant { return switch (charset) { .utf_16 => .{ .form = .utf16, .order = .marked }, .utf_16le => .{ .form = .utf16, .order = .little }, .utf_16be => .{ .form = .utf16, .order = .big }, .utf_32 => .{ .form = .utf32, .order = .marked }, .utf_32le => .{ .form = .utf32, .order = .little }, .utf_32be => .{ .form = .utf32, .order = .big }, .iso_10646_ucs2 => .{ .form = .ucs2, .order = native }, .unicode => .{ .form = .ucs2, .order = .marked }, .unicodelittle => .{ .form = .ucs2, .order = .little }, .unicodebig => .{ .form = .ucs2, .order = .big }, .iso_10646_ucs4 => .{ .form = .ucs4, .order = .big }, .ucs_4le => .{ .form = .ucs4, .order = .little }, else => null, };}
/// Whether `bytes` is entirely made of UCS-4 values glibc reads -- up to/// 0x7FFFFFFF, in whole units -- in the given byte order. A UCS-4 text that/// this library's decoder refused and this accepts has a value in it that is/// not a Unicode scalar value.pub fn isGlibcUcs4(bytes: []const u8, order: Order) bool { if (bytes.len % 4 != 0) return false; var i: usize = 0; while (i < bytes.len) : (i += 4) { const value = std.mem.readInt(u32, bytes[i..][0..4], if (order == .big) .big else .little); if (value > 0x7fffffff) return false; } return true;}
/// Whether the UCS-4 in `bytes` holds a surrogate. glibc reads one, but/// writes it only as UCS-4: converting it to anything else, UTF-8 included,/// fails.pub fn hasUcs4Surrogate(bytes: []const u8, order: Order) bool { var i: usize = 0; while (i + 4 <= bytes.len) : (i += 4) { const value = std.mem.readInt(u32, bytes[i..][0..4], if (order == .big) .big else .little); if (value >= 0xd800 and value <= 0xdfff) return true; } return false;}
pub const Decoder = struct { form: Form, big_endian: bool, /// Whether the next unit is the first of a marked text, and so may be a /// byte order mark. looking_for_mark: bool, unit: [4]u8 = undefined, unit_len: u3 = 0, leading_surrogate: ?u16 = null,
pub fn init(v: Variant) Decoder { return .{ .form = v.form, .big_endian = (if (v.order == .marked) native else v.order) == .big, .looking_for_mark = v.order == .marked, }; }
pub fn handle(self: *Decoder, queue: *ByteQueue, byte: ?u8) Decoded { const width = self.form.width(); const b = byte orelse { if (self.unit_len == 0 and self.leading_surrogate == null) return .finished; // Part of a unit, or a leading surrogate with nothing after it. self.unit_len = 0; self.leading_surrogate = null; return .failure; };
self.unit[self.unit_len] = b; self.unit_len += 1; if (self.unit_len < width) return .cont; self.unit_len = 0; const bytes = self.unit[0..width]; const value: u32 = if (width == 2) std.mem.readInt(u16, bytes[0..2], self.endian()) else std.mem.readInt(u32, bytes[0..4], self.endian());
if (self.looking_for_mark) { self.looking_for_mark = false; if (value == 0xfeff) return .cont; if (value == @as(u32, if (width == 2) 0xfffe else 0xfffe0000)) { self.big_endian = !self.big_endian; return .cont; } }
switch (self.form) { .utf16 => { if (self.leading_surrogate) |leading| { self.leading_surrogate = null; if (isTrailingSurrogate(value)) { return .{ .code_point = 0x10000 + (@as(u21, leading - 0xd800) << 10) + @as(u21, @intCast(value - 0xdc00)) }; } // The pair is the error, and this unit gets another // chance on its own. queue.restore(bytes); return .failure; } if (isLeadingSurrogate(value)) { self.leading_surrogate = @intCast(value); return .cont; } if (isTrailingSurrogate(value)) return .failure; return .{ .code_point = @intCast(value) }; }, .ucs2 => { if (isLeadingSurrogate(value) or isTrailingSurrogate(value)) return .failure; return .{ .code_point = @intCast(value) }; }, .utf32, .ucs4 => { if (value > 0x10ffff or isLeadingSurrogate(value) or isTrailingSurrogate(value)) return .failure; return .{ .code_point = @intCast(value) }; }, } }
fn endian(self: *const Decoder) std.builtin.Endian { return if (self.big_endian) .big else .little; }};
pub const Encoder = struct { form: Form, big_endian: bool, /// Whether a byte order mark is still to be written, before the first /// character. mark_pending: bool,
pub fn init(v: Variant) Encoder { return .{ .form = v.form, .big_endian = (if (v.order == .marked) native else v.order) == .big, .mark_pending = v.order == .marked, }; }
pub fn handle(self: *Encoder, code_point: ?u21) Encoded { const c = code_point orelse return .finished; // Decide whether this character can be written before writing the // mark, so that the mark is still to come for whatever is written // instead of it -- a character reference, in the `html` mode. const dropped = self.form == .ucs2 and c > 0xffff; if (dropped and !(c >= 0xe0000 and c <= 0xe007f)) return .{ .failure = c };
var bytes: Bytes = .{}; if (self.mark_pending) { self.mark_pending = false; self.put(&bytes, 0xfeff); } // A tag character in UCS-2 is written as nothing, but glibc still // writes the mark ahead of it when it is the first. if (dropped) return if (bytes.len == 0) .cont else .{ .bytes = bytes };
if (self.form == .utf16 and c > 0xffff) { const offset = c - 0x10000; self.put(&bytes, 0xd800 + (offset >> 10)); self.put(&bytes, 0xdc00 + (offset & 0x3ff)); } else { self.put(&bytes, c); } return .{ .bytes = bytes }; }
fn put(self: *const Encoder, bytes: *Bytes, value: u21) void { const endian: std.builtin.Endian = if (self.big_endian) .big else .little; const start = bytes.len; switch (self.form.width()) { 2 => std.mem.writeInt(u16, bytes.buffer[start..][0..2], @intCast(value), endian), 4 => std.mem.writeInt(u32, bytes.buffer[start..][0..4], value, endian), else => unreachable, } bytes.len += self.form.width(); }};
fn isLeadingSurrogate(value: u32) bool { return value >= 0xd800 and value <= 0xdbff;}
fn isTrailingSurrogate(value: u32) bool { return value >= 0xdc00 and value <= 0xdfff;}
fn decodeAll(v: Variant, input: []const u8, out: []u21) ?[]u21 { var decoder: Decoder = .init(v); var queue: ByteQueue = .{ .input = input }; var len: usize = 0; while (true) { switch (decoder.handle(&queue, queue.next())) { .finished => return out[0..len], .cont => {}, .code_point => |c| { out[len] = c; len += 1; }, .code_points => unreachable, .failure => return null, } }}
test "a marked UTF-16 text takes its byte order from the mark" { var out: [4]u21 = undefined; const marked: Variant = .{ .form = .utf16, .order = .marked }; try std.testing.expectEqualSlices(u21, &.{'A'}, decodeAll(marked, "\xff\xfeA\x00", &out).?); try std.testing.expectEqualSlices(u21, &.{'A'}, decodeAll(marked, "\xfe\xff\x00A", &out).?); // Only the first unit can be a mark. try std.testing.expectEqualSlices(u21, &.{ 0xfeff, 'A' }, decodeAll(marked, "\xfe\xff\xfe\xff\x00A", &out).?); // A fixed byte order keeps the mark as a character. try std.testing.expectEqualSlices(u21, &.{ 0xfeff, 'A' }, decodeAll(.{ .form = .utf16, .order = .little }, "\xff\xfeA\x00", &out).?);}
test "unpaired surrogates and odd bytes fail" { var out: [4]u21 = undefined; const le: Variant = .{ .form = .utf16, .order = .little }; try std.testing.expectEqualSlices(u21, &.{0x1f600}, decodeAll(le, "\x3d\xd8\x00\xde", &out).?); try std.testing.expectEqual(null, decodeAll(le, "\x3d\xd8A\x00", &out)); try std.testing.expectEqual(null, decodeAll(le, "\x00\xde", &out)); try std.testing.expectEqual(null, decodeAll(le, "A\x00B", &out)); try std.testing.expectEqual(null, decodeAll(.{ .form = .ucs2, .order = .little }, "\x3d\xd8\x00\xde", &out));}
test "a marked encoder writes the mark once, in the machine's order" { var encoder: Encoder = .init(.{ .form = .utf16, .order = .marked }); const first = encoder.handle('A'); const second = encoder.handle('B'); const mark: []const u8 = if (native == .little) "\xff\xfeA\x00" else "\xfe\xff\x00A"; try std.testing.expectEqualSlices(u8, mark, first.bytes.slice()); try std.testing.expectEqual(2, second.bytes.len);}
test "UCS-2 drops a tag character but still writes the mark" { var encoder: Encoder = .init(.{ .form = .ucs2, .order = .marked }); try std.testing.expectEqual(@as(Encoded, .{ .failure = 0x1f600 }), encoder.handle(0x1f600)); try std.testing.expectEqual(2, encoder.handle(0xe0041).bytes.len); try std.testing.expectEqual(@as(Encoded, .cont), encoder.handle(0xe0041));}
test "UCS-4 values glibc reads" { try std.testing.expect(isGlibcUcs4("\x00\x11\x00\x00\x7f\xff\xff\xff", .big)); try std.testing.expect(!isGlibcUcs4("\x80\x00\x00\x00", .big)); try std.testing.expect(!isGlibcUcs4("\x00\x00\x00", .big)); try std.testing.expect(isGlibcUcs4("\x00\xd8\x00\x00", .little)); try std.testing.expect(hasUcs4Surrogate("\x41\x00\x00\x00\xff\xdf\x00\x00", .little)); try std.testing.expect(!hasUcs4Surrogate("\x00\x00\xd7\xff\x00\x00\xe0\x00", .big));}