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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Code pages 1255 and 1258 as glibc 2.44 has them: single-byte tables whose//! combining marks glibc composes with the character before them.//!//! The bytes are the standard's windows-1255 and windows-1258, less the//! positions Microsoft left empty (see `glibc_single_byte.zig`). What glibc//! adds is composition. Reading, a character is held back until the next//! byte shows whether it is followed by a combining mark of the code page,//! and if the two make one Unicode character they are read as that: in//! CP1258 `A` and `CC`, U+0300 COMBINING GRAVE ACCENT, read as À; in CP1255//! ש, dagesh and shin dot read as U+FB2C. Writing does the reverse for a//! character the code page has no byte for, spelling it as a base and the//! marks that make it.//!//! Which pairs compose is a rule over Unicode's canonical decompositions//! rather than a list. A character and a mark compose into the one code//! point whose full canonical decomposition holds the same characters --//! counted, but in any order -- as the character's own and the mark//! together. That is looser than canonical equivalence: in CP1258 Ó and a//! tilde make U+1E4C, whose decomposition has the tilde before the acute. A//! code point whose decomposition is a single other code point, such as//! U+1FEE beside U+0385, is never the result. In CP1255 a second mark goes//! on composing, so the two orders of ש with dagesh and shin dot both make//! U+FB2C. CP1258 does not chain: only a character read from a byte of//! its own takes a mark, so O, a tilde and an acute are Õ and an acute,//! while Ó and a tilde are U+1E4C. Writing, the shortest spelling wins, so Ṍ is Ó and a tilde,//! and between two as short the marks come in decomposition order.//!//! The rule is applied here, at compile time, to the table generated from//! `UnicodeData.txt`. Three characters on top of it are written one way://! CP1258 writes U+0340 and U+0341, the deprecated tone marks, as the grave//! and acute accents, and U+1FEE as ¨ and an acute, which reads back as//! U+0385.
const std = @import("std");
const byte_table = @import("../byte_table.zig");const canonical = @import("../tables/canonical.zig");const codec = @import("../codec.zig");const Glibc = @import("../glibc.zig").Glibc;const glibc_single_byte = @import("glibc_single_byte.zig");
const ByteQueue = codec.ByteQueue;const Decoded = codec.Decoded;const Encoded = codec.Encoded;const unmapped = codec.unmapped;
/// A base and a mark, and what they compose into.const Pair = struct { base: u21, mark: u21, composite: u21 };
/// The bytes a character the code page has no byte of its own for is/// written as.const Spelling = struct { code_point: u21, buffer: [4]u8, len: u8,
fn slice(self: *const Spelling) []const u8 { return self.buffer[0..self.len]; }};
pub const Composer = struct { chaining: Chaining, upper: *const [128]u16, reversed: *const byte_table.Reversed(128), /// Sorted by base, then mark. pairs: []const Pair, /// Sorted by code point. spellings: []const Spelling,
fn compose(self: *const Composer, base: u21, mark: u21) ?u21 { var low: usize = 0; var high: usize = self.pairs.len; while (low < high) { const mid = (low + high) / 2; const pair = self.pairs[mid]; if (pair.base == base and pair.mark == mark) return pair.composite; if (pair.base < base or (pair.base == base and pair.mark < mark)) low = mid + 1 else high = mid; } return null; }
fn spell(self: *const Composer, c: u21) ?*const Spelling { var low: usize = 0; var high: usize = self.spellings.len; while (low < high) { const mid = (low + high) / 2; const spelling = &self.spellings[mid]; if (spelling.code_point == c) return spelling; if (spelling.code_point < c) low = mid + 1 else high = mid; } return null; }};
/// The composer for a charset, or null if it is not one of these.pub fn composer(charset: Glibc) ?*const Composer { return switch (charset) { .cp1255 => &cp1255, .cp1258 => &cp1258, else => null, };}
const cp1255 = build(glibc_single_byte.combiningIndex(.cp1255).?, .chains, &.{});const cp1258 = build(glibc_single_byte.combiningIndex(.cp1258).?, .once, &.{ .{ .code_point = 0x0340, .bytes = &.{0xcc} }, .{ .code_point = 0x0341, .bytes = &.{0xec} }, .{ .code_point = 0x1fee, .bytes = &.{ 0xa8, 0xec } },});
pub const Decoder = struct { composer: *const Composer, /// The last character read, held back in case a mark follows it. held: ?u21 = null, /// Whether that character is itself the result of composing, which in a /// code page that does not chain means no mark can join it. held_composed: bool = false,
pub fn handle(self: *Decoder, queue: *ByteQueue, byte: ?u8) Decoded { const b = byte orelse { const held = self.held orelse return .finished; self.held = null; self.held_composed = false; return .{ .code_point = held }; }; const c: u21 = if (b < 0x80) b else self.composer.upper[b - 0x80]; if (c == unmapped) { // What was held is a character in its own right, so it goes out // first and the bad byte is read again after it. const held = self.held orelse return .failure; self.held = null; self.held_composed = false; queue.restore(&.{b}); return .{ .code_point = held }; } const held = self.held orelse { self.held = c; self.held_composed = false; return .cont; }; const can_compose = self.composer.chaining == .chains or !self.held_composed; if (can_compose) if (self.composer.compose(held, c)) |composite| { self.held = composite; self.held_composed = true; return .cont; }; self.held = c; self.held_composed = false; return .{ .code_point = held }; }};
pub const Encoder = struct { composer: *const Composer,
pub fn handle(self: *Encoder, code_point: ?u21) Encoded { const c = code_point orelse return .finished; if (c < 0x80) return .{ .bytes = .one(@intCast(c)) }; if (self.composer.reversed.byte(c)) |b| return .{ .bytes = .one(b) }; if (self.composer.spell(c)) |spelling| return .{ .bytes = .of(spelling.slice()) }; return .{ .failure = c }; }};
// -- applying the rule, at compile time -------------------------------------
/// A full canonical decomposition. None is longer than four.const Decomposition = struct { len: u8 = 0, items: [8]u21 = undefined,
fn slice(self: *const Decomposition) []const u21 { return self.items[0..self.len]; }
fn append(self: *Decomposition, c: u21) void { self.items[self.len] = c; self.len += 1; }
/// The same characters, in order of code point, so that two can be /// compared as multisets. fn sorted(self: Decomposition) Decomposition { var result = self; std.sort.insertion(u21, result.items[0..result.len], {}, std.sort.asc(u21)); return result; }
fn eql(a: *const Decomposition, b: *const Decomposition) bool { return std.mem.eql(u21, a.slice(), b.slice()); }};
fn mapping(c: u21) ?usize { var low: usize = 0; var high: usize = canonical.composites.len; while (low < high) { const mid = (low + high) / 2; if (canonical.composites[mid] == c) return mid; if (canonical.composites[mid] < c) low = mid + 1 else high = mid; } return null;}
fn decomposeInto(c: u21, out: *Decomposition) void { const i = mapping(c) orelse return out.append(c); decomposeInto(@intCast(canonical.firsts[i]), out); if (canonical.seconds[i] != 0) decomposeInto(@intCast(canonical.seconds[i]), out);}
fn decompose(c: u21) Decomposition { var result: Decomposition = .{}; decomposeInto(c, &result); return result;}
const OneWay = struct { code_point: u21, bytes: []const u8 };
/// A character something might compose into, with its full decomposition/// sorted for comparing.const Candidate = struct { code_point: u21, key: Decomposition };
/// Whether a character that has composed can compose again with a further/// mark. CP1255's can; CP1258 composes only a character read from a byte of/// its own, so that O, a tilde and an acute read as Õ and an acute.const Chaining = enum { chains, once };
fn build(comptime upper: *const [128]u16, comptime chaining: Chaining, comptime one_way: []const OneWay) Composer { @setEvalBranchQuota(20_000_000); return comptime blk: { const reversed = byte_table.reverse(upper.*, 0x80);
// The code page's marks: its characters that end some canonical // decomposition of two. A mark that ends none composes with nothing. var marks: []const u21 = &.{}; for (upper) |c| { if (c == unmapped) continue; for (canonical.seconds) |second| { if (second == c) { marks = marks ++ .{@as(u21, c)}; break; } } }
// What each mark can be part of: every code point with a // decomposition of two whose full decomposition holds the mark. var candidates: [marks.len][]const Candidate = undefined; for (marks, 0..) |mark, m| { candidates[m] = &.{}; for (canonical.composites, canonical.seconds) |composite, second| { if (second == 0) continue; const full = decompose(@intCast(composite)); if (std.mem.findScalar(u21, full.slice(), mark) == null) continue; candidates[m] = candidates[m] ++ .{Candidate{ .code_point = @as(u21, composite), .key = full.sorted() }}; } }
// Every character that can take a mark, starting from the ones the // bytes give and, where composing chains, adding whatever they // compose into. var reached: []const u21 = &.{}; for (0..0x80) |c| reached = reached ++ .{@as(u21, c)}; for (upper) |c| if (c != unmapped) { reached = reached ++ .{@as(u21, c)}; };
var pairs: []const Pair = &.{}; var composed: []const u21 = &.{}; var i: usize = 0; while (i < reached.len) : (i += 1) { const base = reached[i]; const base_full = decompose(base); for (marks, 0..) |mark, m| { var target = base_full; target.append(mark); target = target.sorted(); var found: ?u21 = null; for (candidates[m]) |candidate| { if (!candidate.key.eql(&target)) continue; if (found != null) @compileError("two characters compose from the same base and mark"); found = candidate.code_point; } const composite = found orelse continue; pairs = pairs ++ .{Pair{ .base = base, .mark = mark, .composite = composite }}; if (std.mem.findScalar(u21, composed, composite) == null) composed = composed ++ .{composite}; if (chaining == .chains and std.mem.findScalar(u21, reached, composite) == null) reached = reached ++ .{composite}; } }
// Spellings, for whatever has no byte of its own. Of the pairs that // make a character, the one with the shortest spelling is written, // and between two as short the one whose mark comes last in the // character's decomposition, so that the marks come out in // decomposition order. var spellings: []const Spelling = &.{}; for (composed) |c| { if (reversed.byte(c) != null) continue; const full = decompose(c); var best: ?Spelling = null; var best_position: usize = 0; for (pairs) |pair| { if (pair.composite != c) continue; const base_bytes: []const u8 = if (pair.base < 0x80) &.{@as(u8, pair.base)} else if (reversed.byte(pair.base)) |b| &.{b} else for (spellings) |earlier| { if (earlier.code_point == pair.base) break earlier.slice(); } else @compileError("a base with no spelling"); var spelling: Spelling = .{ .code_point = c, .buffer = undefined, .len = 0 }; for (base_bytes ++ .{reversed.byte(pair.mark).?}) |b| { spelling.buffer[spelling.len] = b; spelling.len += 1; } const position = std.mem.findScalarLast(u21, full.slice(), pair.mark).?; if (best == null or spelling.len < best.?.len or (spelling.len == best.?.len and position > best_position)) { best = spelling; best_position = position; } } spellings = spellings ++ .{best.?}; } for (one_way) |entry| { var spelling: Spelling = .{ .code_point = entry.code_point, .buffer = undefined, .len = entry.bytes.len }; @memcpy(spelling.buffer[0..entry.bytes.len], entry.bytes); spellings = spellings ++ .{spelling}; }
var sorted_pairs = pairs[0..pairs.len].*; std.sort.insertion(Pair, &sorted_pairs, {}, struct { fn lessThan(_: void, a: Pair, b: Pair) bool { return a.base < b.base or (a.base == b.base and a.mark < b.mark); } }.lessThan); var sorted_spellings = spellings[0..spellings.len].*; std.sort.insertion(Spelling, &sorted_spellings, {}, struct { fn lessThan(_: void, a: Spelling, b: Spelling) bool { return a.code_point < b.code_point; } }.lessThan);
const final_pairs = sorted_pairs; const final_spellings = sorted_spellings; const final_reversed = reversed; break :blk .{ .chaining = chaining, .upper = upper, .reversed = &final_reversed, .pairs = &final_pairs, .spellings = &final_spellings, }; };}
test "a base and a mark read as one character" { var queue: ByteQueue = .{ .input = "A\xcc" }; var decoder: Decoder = .{ .composer = &cp1258 }; try std.testing.expectEqual(Decoded.cont, decoder.handle(&queue, queue.next())); try std.testing.expectEqual(Decoded.cont, decoder.handle(&queue, queue.next())); try std.testing.expectEqual(Decoded{ .code_point = 0xc0 }, decoder.handle(&queue, null)); try std.testing.expectEqual(Decoded.finished, decoder.handle(&queue, null));}
test "marks compose in any order, and are written in decomposition order" { // ש, shin dot, dagesh: U+FB2C either way round. try std.testing.expectEqual(@as(?u21, 0xfb2a), cp1255.compose(0x05e9, 0x05c1)); try std.testing.expectEqual(@as(?u21, 0xfb2c), cp1255.compose(0xfb2a, 0x05bc)); try std.testing.expectEqual(@as(?u21, 0xfb2c), cp1255.compose(0xfb49, 0x05c1)); try std.testing.expectEqualSlices(u8, "\xf9\xcc\xd1", cp1255.spell(0xfb2c).?.slice());}
test "composition is by the characters, not their order" { // Ó and a tilde: U+1E4C, which Unicode spells O, tilde, acute. try std.testing.expectEqual(@as(?u21, 0x1e4c), cp1258.compose(0xd3, 0x0303)); // ¨ and an acute make U+0385, never its singleton U+1FEE. try std.testing.expectEqual(@as(?u21, 0x0385), cp1258.compose(0xa8, 0x0301)); try std.testing.expectEqualSlices(u8, "\xa8\xec", cp1258.spell(0x1fee).?.slice()); // Ü with a macron would need a mark CP1258 has not got. try std.testing.expectEqual(@as(?*const Spelling, null), cp1258.spell(0x01d5));}