// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Step 1 of the algorithm, UTS #10 section 7.1: put the input into //! Normalization Form D. //! //! This is here rather than borrowed because `uucode` is the data layer and //! not a normalizer. It exposes `canonical_combining_class`, //! `decomposition_type` and `decomposition_mapping` -- the raw //! `UnicodeData.txt` fields, which is exactly what NFD runs *on* -- and has //! no normalization API at all. Three things have to happen on top of them: //! the decomposition has to recurse, Hangul has to be handled arithmetically //! because it is not in the table, and the result has to be reordered by //! combining class. const std = @import("std"); const Allocator = std.mem.Allocator; const uucode = @import("uucode"); /// Conjoining jamo, from section 3.12 of the standard. Hangul syllables are /// not listed in `UnicodeData.txt`; their decomposition is arithmetic, and a /// table lookup will not find it. pub const hangul = struct { pub const s_base = 0xAC00; pub const l_base = 0x1100; pub const v_base = 0x1161; pub const t_base = 0x11A7; pub const l_count = 19; pub const v_count = 21; pub const t_count = 28; pub const n_count = v_count * t_count; // 588 pub const s_count = l_count * n_count; // 11172 pub fn isSyllable(cp: u21) bool { return cp >= s_base and cp < s_base + s_count; } test isSyllable { try std.testing.expect(isSyllable(0xD55C)); // 한 // A jamo is not a syllable: it is what a syllable decomposes to. try std.testing.expect(!isSyllable(0x1112)); try std.testing.expect(!isSyllable('a')); } }; /// The most code points one code point can decompose to. /// /// Four, measured over Unicode 18.0.0, and the witness is U+1F82 GREEK SMALL /// LETTER ALPHA WITH PSILI AND VARIA AND YPOGEGRAMMENI, which goes to /// U+03B1 U+0313 U+0300 U+0345 through three levels of mapping. Hangul /// reaches three. So the per-code-point step needs no allocation. pub const max_expansion = 4; /// Below this, a code point is its own NFD and cannot reorder: it has no /// canonical decomposition and a combining class of zero. /// /// So a code point below it decomposes to itself, and `append` can put it /// straight into the output instead of asking. That is worth doing because /// the cost `zig build bench` measures in step 1 is per code point and almost /// independent of the script -- it *is* the property lookups rather than any /// decomposing -- and it is 22% off a string of ASCII and 15% off Latin text /// in NFC, where most of the letters are ASCII even when the accented ones /// are not. /// /// The reordering pass still runs. Skipping it when nothing had a combining /// class was measured too, and it is not worth it: answering that question /// costs a lookup for every code point, which is dearer than the pass it /// avoids -- 5% dearer on Han and Hangul, which reorder nothing either way -- /// and it added nothing to the ASCII case, where the whole of the win is the /// decomposition lookups this skips. /// /// U+00C0 LATIN CAPITAL LETTER A WITH GRAVE is the first canonical /// decomposition there is, and U+0300 COMBINING GRAVE ACCENT the first /// non-zero combining class, so the bound is the lower of the two. The test /// below asserts both against the data rather than trusting this comment, /// since a future Unicode could in principle assign something lower. pub const inert_below: u21 = 0xC0; /// The canonical combining class of a code point, UAX #15's `ccc`. Zero for /// a starter. pub fn combiningClass(cp: u21) u8 { return uucode.get(.canonical_combining_class, cp); } test combiningClass { try std.testing.expectEqual(@as(u8, 0), combiningClass('a')); try std.testing.expectEqual(@as(u8, 230), combiningClass(0x0301)); // acute, above try std.testing.expectEqual(@as(u8, 202), combiningClass(0x0327)); // cedilla, attached below } pub fn isStarter(cp: u21) bool { return combiningClass(cp) == 0; } test isStarter { try std.testing.expect(isStarter('e')); try std.testing.expect(!isStarter(0x0301)); } /// The full canonical decomposition of one code point, written into `buf`. /// /// Canonical only: a compatibility mapping is left alone, which is what /// separates NFD from NFKD and is why `decomposition_type` is consulted /// rather than just taking whatever mapping is there. The result is *not* /// canonically ordered -- that is the caller's job once it has the whole /// string, because a reordering can cross the boundary between one code /// point's decomposition and the next one's. pub fn decompose(cp: u21, buf: *[max_expansion]u21) []const u21 { var len: usize = 0; decomposeInto(cp, buf, &len); return buf[0..len]; } test decompose { var buf: [max_expansion]u21 = undefined; // U+00E9 LATIN SMALL LETTER E WITH ACUTE. try std.testing.expectEqualSlices(u21, &.{ 'e', 0x0301 }, decompose(0x00E9, &buf)); // Hangul, arithmetically: 한 is ㅎ, ㅏ and ㄴ. try std.testing.expectEqualSlices(u21, &.{ 0x1112, 0x1161, 0x11AB }, decompose(0xD55C, &buf)); // U+FB01 LATIN SMALL LIGATURE FI has only a compatibility mapping. try std.testing.expectEqualSlices(u21, &.{0xFB01}, decompose(0xFB01, &buf)); } fn decomposeInto(cp: u21, buf: *[max_expansion]u21, len: *usize) void { if (hangul.isSyllable(cp)) { const index = cp - hangul.s_base; const t = index % hangul.t_count; buf[len.*] = @intCast(hangul.l_base + index / hangul.n_count); buf[len.* + 1] = @intCast(hangul.v_base + (index % hangul.n_count) / hangul.t_count); len.* += 2; // A syllable with no trailing consonant is two jamo, not three. if (t != 0) { buf[len.*] = @intCast(hangul.t_base + t); len.* += 1; } return; } if (uucode.get(.decomposition_type, cp) != .canonical) { buf[len.*] = cp; len.* += 1; return; } // uucode stores a mapping either in the row or in a pool it hands back a // slice of; the buffer is only for the "maps to itself" case, which is // one code point. var mapping_buf: [1]u21 = undefined; const mapping = uucode.get(.decomposition_mapping, cp).with(&mapping_buf, cp); for (mapping) |component| decomposeInto(component, buf, len); } /// Reorder in place, UAX #15's Canonical Ordering Algorithm: within each /// maximal run of non-starters, sort by combining class, stably. /// /// Insertion sort because the runs are short -- two or three in almost all /// real text -- and because it is the stable one. Stability is not a nicety /// here: two marks with the same combining class are *not* canonically /// equivalent when swapped, so reordering them would change the string. pub fn canonicalOrder(cps: []u21) void { if (cps.len < 2) return; var i: usize = 1; while (i < cps.len) : (i += 1) { const ccc = combiningClass(cps[i]); if (ccc == 0) continue; var j = i; while (j > 0) : (j -= 1) { const prev = combiningClass(cps[j - 1]); if (prev == 0 or prev <= ccc) break; std.mem.swap(u21, &cps[j - 1], &cps[j]); } } } test canonicalOrder { // An acute (230) then a cedilla (202): the cedilla goes first. var cps = [_]u21{ 'c', 0x0301, 0x0327 }; canonicalOrder(&cps); try std.testing.expectEqualSlices(u21, &.{ 'c', 0x0327, 0x0301 }, &cps); } /// The one uucode table this needs, fetched once. /// /// `uucode.get` walks the stage tables per *field*, and the four fields this /// build asks for share one table -- so asking for a code point's /// decomposition type and then its combining class walks the same three /// stages twice. `getAll` returns the row, and step 1 needs two of its /// fields for almost every code point: whether it decomposes, and what it /// weighs at the reordering pass. /// /// The table's name is a string because that is uucode's API. If a future /// field configuration split these two fields across tables, the field reads /// below would stop compiling rather than quietly read the wrong row. fn row(cp: u21) @TypeOf(uucode.getAll("0", 0)) { return uucode.getAll("0", cp); } /// Put the code point just appended into canonical order, moving it back over /// any mark of a higher combining class. /// /// This is `canonicalOrder` done one code point at a time, and it is the same /// insertion sort with the same stability -- appending in order and inserting /// each new non-starter where it belongs sorts every run of non-starters by /// class. What it buys is the pass it replaces: a separate `canonicalOrder` /// looks the combining class up for every code point in the string, where /// this looks one up only for a code point that *has* a class to compare, /// which in most text is none of them. fn orderLast(span: []u21, ccc: u8) void { if (ccc == 0 or span.len < 2) return; var j = span.len - 1; while (j > 0) : (j -= 1) { const previous = combiningClass(span[j - 1]); if (previous == 0 or previous <= ccc) break; std.mem.swap(u21, &span[j - 1], &span[j]); } } /// S1.1: append the NFD of `input` to `out`. /// /// `out` is appended to rather than replaced so that a caller reusing a /// buffer can clear it with `clearRetainingCapacity` and keep the /// allocation. pub fn append(out: *std.ArrayList(u21), gpa: Allocator, input: []const u21) Allocator.Error!void { const start = out.items.len; try out.ensureUnusedCapacity(gpa, input.len); for (input) |cp| try appendOne(out, gpa, cp, start); } test append { const gpa = std.testing.allocator; var out: std.ArrayList(u21) = .empty; defer out.deinit(gpa); // ç followed by an acute: decomposed, then the cedilla and the acute put // in order. try append(&out, gpa, &.{ 0x00E7, 0x0301 }); try std.testing.expectEqualSlices(u21, &.{ 'c', 0x0327, 0x0301 }, out.items); } /// The same, for UTF-8 input. pub fn appendUtf8(out: *std.ArrayList(u21), gpa: Allocator, input: []const u8) error{ OutOfMemory, InvalidUtf8 }!void { const start = out.items.len; try out.ensureUnusedCapacity(gpa, input.len); // Validated up front rather than per code point, because // `Utf8Iterator` panics on ill-formed input instead of reporting it -- // it takes the length from the lead byte and slices with it -- and // because it means the decoding below cannot fail. _ = std.unicode.Utf8View.init(input) catch return error.InvalidUtf8; var i: usize = 0; while (i < input.len) { // A run of ASCII bytes is a run of inert code points: one byte // apiece, no decomposition, no combining class, nothing to reorder. // So it is a widening copy with one capacity check for the whole run // rather than a check apiece -- which is worth 7% on a string of // ASCII, and is also what makes the copy *sound*: the reserve above // is one slot per input code point, and a code point that decomposes // takes more than one. const run = i; while (i < input.len and input[i] < 0x80) i += 1; if (i != run) { try out.ensureUnusedCapacity(gpa, i - run); for (input[run..i]) |byte| out.appendAssumeCapacity(byte); continue; } const len = std.unicode.utf8ByteSequenceLength(input[i]) catch unreachable; const cp = std.unicode.utf8Decode(input[i..][0..len]) catch unreachable; i += len; try appendOne(out, gpa, cp, start); } } test appendUtf8 { const gpa = std.testing.allocator; var out: std.ArrayList(u21) = .empty; defer out.deinit(gpa); try appendUtf8(&out, gpa, "caf\u{00E9}"); try std.testing.expectEqualSlices(u21, &.{ 'c', 'a', 'f', 'e', 0x0301 }, out.items); try std.testing.expectError(error.InvalidUtf8, appendUtf8(&out, gpa, "\xc3")); } /// S1.1 again, recording where each code point of the NFD came from: for every /// code point appended to `out`, the index in `input` of the code point that /// decomposed to it is appended to `origins`. /// /// For search, which has to report a match as a range of the caller's text /// rather than of its NFD. The two arrays move together through the canonical /// reordering, so a mark that sorts back past another keeps its own origin. /// A separate function rather than a flag on `append`, because that one is /// the hot path of every sort key and this one is not. pub fn appendTracked( out: *std.ArrayList(u21), origins: *std.ArrayList(u32), gpa: Allocator, input: []const u21, ) Allocator.Error!void { const start = out.items.len; try out.ensureUnusedCapacity(gpa, input.len); try origins.ensureUnusedCapacity(gpa, input.len); for (input, 0..) |cp, k| { var buf: [max_expansion]u21 = undefined; for (decompose(cp, &buf)) |d| { try out.append(gpa, d); try origins.append(gpa, @intCast(k)); const ccc = combiningClass(d); if (ccc == 0) continue; var j = out.items.len - 1; while (j > start) : (j -= 1) { const previous = combiningClass(out.items[j - 1]); if (previous == 0 or previous <= ccc) break; std.mem.swap(u21, &out.items[j - 1], &out.items[j]); std.mem.swap(u32, &origins.items[j - 1], &origins.items[j]); } } } } test appendTracked { const gpa = std.testing.allocator; var out: std.ArrayList(u21) = .empty; defer out.deinit(gpa); var origins: std.ArrayList(u32) = .empty; defer origins.deinit(gpa); // ç, then an acute: the cedilla came from the first code point and the // acute from the second, whichever order they end up in. try appendTracked(&out, &origins, gpa, &.{ 0x00E7, 0x0301 }); try std.testing.expectEqualSlices(u21, &.{ 'c', 0x0327, 0x0301 }, out.items); try std.testing.expectEqualSlices(u32, &.{ 0, 0, 1 }, origins.items); } /// One code point of step 1: decompose it, append what it decomposes to, and /// put each of those into canonical order. /// /// `start` is where this string began in `out`, because a mark can have to /// move back past code points an earlier call appended -- a reordering can /// cross the boundary between one code point's decomposition and the next /// one's, which is why the reordering used to be a pass of its own. fn appendOne( out: *std.ArrayList(u21), gpa: Allocator, cp: u21, start: usize, ) Allocator.Error!void { // Below `inert_below` a code point decomposes to itself and has no // combining class, so it needs no lookup and cannot reorder. if (cp < inert_below) { try out.append(gpa, cp); return; } // Hangul is arithmetic and its jamo are all starters, so it needs no // lookup either. if (hangul.isSyllable(cp)) { var buf: [max_expansion]u21 = undefined; try out.appendSlice(gpa, decompose(cp, &buf)); return; } const r = row(cp); if (r.decomposition_type != .canonical) { try out.append(gpa, cp); orderLast(out.items[start..], r.canonical_combining_class); return; } var buf: [max_expansion]u21 = undefined; for (decompose(cp, &buf)) |part| { try out.append(gpa, part); orderLast(out.items[start..], combiningClass(part)); } } const testing = std.testing; fn expectNfd(expected: []const u21, input: []const u21) !void { var out: std.ArrayList(u21) = .empty; defer out.deinit(testing.allocator); try append(&out, testing.allocator, input); try testing.expectEqualSlices(u21, expected, out.items); } test "decomposition recurses" { // U+1E14 -> U+0112 U+0300 -> U+0045 U+0304 U+0300. Two levels, and a // single-step mapping would stop at U+0112. try expectNfd(&.{ 0x0045, 0x0304, 0x0300 }, &.{0x1E14}); // The deepest and widest in the data: three levels, four code points. try expectNfd(&.{ 0x03B1, 0x0313, 0x0300, 0x0345 }, &.{0x1F82}); // A singleton, and then a singleton onto a pair: U+212B -> U+00C5 -> // U+0041 U+030A. try expectNfd(&.{ 0x03A9, 0x0345 }, &.{ 0x2126, 0x0345 }); try expectNfd(&.{ 0x0041, 0x030A }, &.{0x212B}); } test "compatibility mappings are left alone" { // U+1FBF GREEK PSILI is 0020 0313. NFD must not touch it; NFKD // would. try expectNfd(&.{0x1FBF}, &.{0x1FBF}); // U+FB01 LATIN SMALL LIGATURE FI is too. try expectNfd(&.{0xFB01}, &.{0xFB01}); } test "hangul decomposes arithmetically" { // U+AC00, the first syllable: no trailing consonant, so two jamo. try expectNfd(&.{ 0x1100, 0x1161 }, &.{0xAC00}); // U+AC01 adds the first trailing consonant. try expectNfd(&.{ 0x1100, 0x1161, 0x11A8 }, &.{0xAC01}); // U+D7A3, the last. try expectNfd(&.{ 0x1112, 0x1175, 0x11C2 }, &.{0xD7A3}); // Jamo themselves are starters and decompose to nothing. try expectNfd(&.{ 0x1100, 0x1161 }, &.{ 0x1100, 0x1161 }); } test "canonical ordering is by combining class" { // U+1E0B U+0323: d-with-dot-above followed by a dot below. The dot below // has combining class 220 and the dot above 230, so NFD puts the below // first even though the string wrote it second. try expectNfd(&.{ 0x0064, 0x0323, 0x0307 }, &.{ 0x1E0B, 0x0323 }); // A starter ends a run: the marks after the second `a` do not migrate // past it. try expectNfd( &.{ 0x0061, 0x0323, 0x0307, 0x0061, 0x0323, 0x0307 }, &.{ 0x0061, 0x0307, 0x0323, 0x0061, 0x0307, 0x0323 }, ); } test "ordering is stable within a combining class" { // Two marks of class 230. Swapping them would be a different string, so // the sort must leave them as they are. try expectNfd(&.{ 0x0061, 0x0301, 0x0307 }, &.{ 0x0061, 0x0301, 0x0307 }); try expectNfd(&.{ 0x0061, 0x0307, 0x0301 }, &.{ 0x0061, 0x0307, 0x0301 }); } test "utf8 input agrees with code point input" { var from_utf8: std.ArrayList(u21) = .empty; defer from_utf8.deinit(testing.allocator); try appendUtf8(&from_utf8, testing.allocator, "Märtens"); var from_cps: std.ArrayList(u21) = .empty; defer from_cps.deinit(testing.allocator); try append(&from_cps, testing.allocator, &.{ 'M', 0x00E4, 'r', 't', 'e', 'n', 's' }); try testing.expectEqualSlices(u21, from_cps.items, from_utf8.items); // And the decomposition actually happened. try testing.expectEqualSlices(u21, &.{ 'M', 'a', 0x0308, 'r', 't', 'e', 'n', 's' }, from_utf8.items); } test "invalid utf8 is refused" { var out: std.ArrayList(u21) = .empty; defer out.deinit(testing.allocator); try testing.expectError(error.InvalidUtf8, appendUtf8(&out, testing.allocator, "\xff\xfe")); } test "nothing below inert_below decomposes or reorders" { // `inert_below` is a claim about the data and this is the claim: no code // point under it has a canonical decomposition or a non-zero combining // class, so the fast path in `append` can skip both lookups. A future // Unicode that assigned either lower would fail here rather than sort // wrongly. var cp: u21 = 0; while (cp < inert_below) : (cp += 1) { try testing.expectEqual(@as(u8, 0), combiningClass(cp)); var buf: [max_expansion]u21 = undefined; try testing.expectEqualSlices(u21, &.{cp}, decompose(cp, &buf)); } // And it is not conservative by more than it needs to be: the two // witnesses are the first of each. var witness: [max_expansion]u21 = undefined; try testing.expect(decompose(inert_below, &witness).len > 1); try testing.expectEqual(@as(u8, 230), combiningClass(0x0300)); } test "ordering one code point at a time is the pass it replaced" { // `appendOne` inserts each code point into canonical order as it goes, // where a straight reading of UAX #15 decomposes the whole string and // then sorts each run of non-starters. The two must agree on every // input, so this checks them against each other over the awkward shapes: // marks out of order, marks that have to cross a decomposition boundary, // equal classes that must not swap, and long runs. const cases = [_][]const u21{ &.{ 'a', 0x0301, 0x0328 }, // 230 then 202: reorders &.{ 'a', 0x0328, 0x0301 }, // 202 then 230: already ordered &.{ 0x01ED, 0x0304 }, // composed, decomposes to o + 328, then 304 &.{ 0x1E14, 0x0328 }, // two levels of decomposition, then a mark &.{ 0x0344, 0x0300 }, // 344 decomposes to two marks itself &.{ 'a', 0x0316, 0x0301, 0x0315, 0x0308, 0x0327 }, // UAX #15's own example &.{ 'a', 0x05B0, 0x05B0 }, // equal classes: stability matters &.{ 0x1F82, 0x0345, 0x0300 }, // the deepest decomposition plus marks &.{ 0xAC00, 0x0301 }, // Hangul, which decomposes arithmetically &.{ 0x3060, 0x0301 }, // kana with a voiced mark }; for (cases) |input| { var incremental: std.ArrayList(u21) = .empty; defer incremental.deinit(testing.allocator); try append(&incremental, testing.allocator, input); // The same thing the other way: decompose everything, then sort. var whole: std.ArrayList(u21) = .empty; defer whole.deinit(testing.allocator); for (input) |cp| { var buf: [max_expansion]u21 = undefined; try whole.appendSlice(testing.allocator, decompose(cp, &buf)); } canonicalOrder(whole.items); try testing.expectEqualSlices(u21, whole.items, incremental.items); } } test "every assigned code point decomposes the same way either route" { // The cases above are the shapes worth naming; this is the sweep. Every // code point on its own, and every code point followed by a mark of a // lower combining class -- which is the pair that reorders. var cp: u21 = 0; while (cp < 0x110000) : (cp += 1) { if (cp >= 0xD800 and cp <= 0xDFFF) continue; for ([_][]const u21{ &.{cp}, &.{ cp, 0x0328 }, &.{ cp, 0x0315, 0x0300 } }) |input| { var incremental: std.ArrayList(u21) = .empty; defer incremental.deinit(testing.allocator); try append(&incremental, testing.allocator, input); var whole: std.ArrayList(u21) = .empty; defer whole.deinit(testing.allocator); for (input) |part| { var buf: [max_expansion]u21 = undefined; try whole.appendSlice(testing.allocator, decompose(part, &buf)); } canonicalOrder(whole.items); if (!std.mem.eql(u21, whole.items, incremental.items)) { std.debug.print("U+{X:0>4}: pass gives {any}, incremental gives {any}\n", .{ cp, whole.items, incremental.items, }); return error.TestUnexpectedResult; } } } } test "an expanding decomposition does not exhaust the reserve" { // `append` reserves room for `input.len` code points and then appends at // least one per input code point -- three for a Hangul syllable. So the // reserve is not a bound on the output, and an inert code point after an // expansion must not assume the capacity is still there. var n: usize = 1; while (n <= 200) : (n += 1) { var input: std.ArrayList(u21) = .empty; defer input.deinit(testing.allocator); for (0..n) |_| try input.append(testing.allocator, 0xAC1B); // 3 jamo try input.append(testing.allocator, 'a'); var out: std.ArrayList(u21) = .empty; defer out.deinit(testing.allocator); try append(&out, testing.allocator, input.items); try testing.expectEqual(3 * n + 1, out.items.len); try testing.expectEqual(@as(u21, 'a'), out.items[out.items.len - 1]); } } test "the tracked route is the same NFD, with each code point's origin" { const gpa = testing.allocator; // A Hangul syllable, a two-level decomposition, and a mark that has to // sort back past another: U+0063 U+030A U+0327 is c, ring above (230), // cedilla (202), and the cedilla moves in front of the ring. const input = [_]u21{ 0xAC1B, 0x1E14, 0x0063, 0x030A, 0x0327, 'z' }; var plain: std.ArrayList(u21) = .empty; defer plain.deinit(gpa); try append(&plain, gpa, &input); var tracked: std.ArrayList(u21) = .empty; defer tracked.deinit(gpa); var origins: std.ArrayList(u32) = .empty; defer origins.deinit(gpa); try appendTracked(&tracked, &origins, gpa, &input); try testing.expectEqualSlices(u21, plain.items, tracked.items); try testing.expectEqualSlices( u32, &.{ 0, 0, 0, 1, 1, 1, 2, 4, 3, 5 }, origins.items, ); try testing.expectEqual(@as(u21, 0x0327), tracked.items[7]); } test "every assigned code point decomposes the same way tracked" { const gpa = testing.allocator; var plain: std.ArrayList(u21) = .empty; defer plain.deinit(gpa); var tracked: std.ArrayList(u21) = .empty; defer tracked.deinit(gpa); var origins: std.ArrayList(u32) = .empty; defer origins.deinit(gpa); var cp: u21 = 0; while (cp <= 0x10FFFF) : (cp += 1) { // Only a code point that decomposes or has a combining class can come // out differently; the rest are copied either way. var buf: [max_expansion]u21 = undefined; const parts = decompose(cp, &buf); if (combiningClass(cp) == 0 and parts.len == 1 and parts[0] == cp) continue; // Each code point after a mark of a higher class, so that a // reordering across the boundary is exercised too. const input = [_]u21{ 0x0063, 0x0301, cp }; plain.clearRetainingCapacity(); tracked.clearRetainingCapacity(); origins.clearRetainingCapacity(); try append(&plain, gpa, &input); try appendTracked(&tracked, &origins, gpa, &input); try testing.expectEqualSlices(u21, plain.items, tracked.items); try testing.expectEqual(tracked.items.len, origins.items.len); } }