Something went wrong. Try again.
The Unicode Collation Algorithm (UTS #10) and CLDR locale tailorings in Zig: sort text the way people expect rather than by code point.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A collation element table, UTS #10 section 3.4, and the lookups the//! second step of the algorithm makes into one.
const std = @import("std");const Allocator = std.mem.Allocator;const uucode = @import("uucode");
const data = @import("data");const Element = data.Element;const Entry = data.Entry;const Contraction = data.Contraction;const ImplicitRange = data.ImplicitRange;const Tailoring = data.Tailoring;
/// The generated DUCET. See `tools/gen_ducet.zig`, which writes it out of/// `data/allkeys-*.txt` at build time.pub const ducet: Table = .of(@import("ducet"));
/// The CLDR root collation: the same algorithm over a tailored table.////// CLDR modifies DUCET before anyone's language is considered at all --/// regrouping scripts, narrowing which characters count as variable, and/// adding the sentinels that section 1.6's sort key merging needs. It is what/// ICU orders by, so it is what most other software agrees with.////// Empty unless the library was built with `-Dembed-cldr`, which is off by/// default because the data arrives in a 66 MB archive.pub const cldr_root: Table = .of(@import("cldr"));
pub const Table = struct { /// The Unicode version the table was generated from, for a caller that /// wants to say so in a diagnostic. unicode_version: []const u8,
/// The band of primary weights belonging to variable collation elements. /// Taken from the data rather than written down: see `isVariable`. min_variable_primary: u16, max_variable_primary: u16,
/// Code point >> 8, to a block number in `stage2`, or `no_block`. stage1: []const u16, /// Blocks of 256 entries, as raw bits. /// /// `u64` and not `Entry` because this is the big array -- DUCET fills /// 188 blocks, so 48,128 entries -- and a hexadecimal literal apiece is /// a third of the generated source that a struct literal apiece would /// be. The cast back happens on the way out of `entry`, where it costs /// nothing. stage2: []const u64, /// Where the elements live for every entry that maps to more or fewer /// than one of them, and for every contraction. expansions: []const Element, /// Sorted by `Contraction.lessThan`: grouped by first code point, and /// longest first inside a group. contractions: []const Contraction, /// Where the contractions keep the code points after their first. contraction_points: []const u21, /// Section 10.1.3's Table 16, as ranges. implicit_ranges: []const ImplicitRange,
/// Han in CLDR's order, when the table has it: see `data.HanRange`. Empty /// for the DUCET, whose own order *is* the code-point one. han_order: []const data.HanRange = &.{},
/// A per-locale tailoring layered over this table, consulted before it. /// /// A tailored table is still a table: nothing else in the algorithm has /// to know, which is why this hangs here rather than beside it. tailoring: ?*const Tailoring = null,
/// Section 9.3.3's repertoire: the code point ranges this table has /// entries for, or empty for the whole of Unicode. /// /// A code point outside it is weighed from its own value by section /// 10.1.3, exactly as an unassigned one is, which orders it after every /// character that does have an entry. So a restricted table is a /// different collation from the full one rather than a smaller one, and /// it is conformant over the repertoire it names and not beyond it. This /// is declared so that a caller -- or a conformance run -- can tell which /// comparisons it is entitled to trust. repertoire: []const [2]u21 = &.{},
pub const no_block: u16 = 0xFFFF;
/// Wraps one generated table module. pub fn of(comptime generated: type) Table { return .{ .unicode_version = generated.unicode_version, .min_variable_primary = generated.min_variable_primary, .max_variable_primary = generated.max_variable_primary, .stage1 = &generated.stage1, .stage2 = &generated.stage2, .expansions = &generated.expansions, .contractions = &generated.contractions, .contraction_points = &generated.contraction_points, .implicit_ranges = &generated.implicit_ranges, // Only the CLDR root has one; a table generated without a // `FractionalUCA.txt` declares it empty. .han_order = if (@hasDecl(generated, "han_order")) &generated.han_order else &.{}, // Section 9.3.3: only a table generated with `-Drepertoire=` // declares one, and an empty one means the whole of Unicode. .repertoire = if (@hasDecl(generated, "repertoire")) &generated.repertoire else &.{}, }; }
/// Whether this table has a mapping for every one of these code points. /// /// The question a caller restricted by `-Drepertoire=` wants answered /// about the text it is about to sort: anything without a mapping is /// weighed from its code point by section 10.1.3 and sorts after /// everything that has one, which is correct but is not the order the /// full table would give. pub fn hasEntries(t: Table, cps: []const u21) bool { for (cps) |cp| { if (!t.inRepertoire(cp)) return false; if (t.entry(cp).len == 0) return false; } return true; }
/// Whether a code point is one this table has entries for. Always true /// for an unrestricted table. pub fn inRepertoire(t: Table, cp: u21) bool { if (t.repertoire.len == 0) return true; for (t.repertoire) |r| { if (cp >= r[0] and cp <= r[1]) return true; } return false; }
/// The number of code points one stage-2 block covers. pub const block_len = 256;
/// UTS10-D16, a variable collation element -- punctuation, symbols, and /// whatever else the table gave a low primary weight so that `Alternate` /// could single it out. /// /// A range test rather than a flag stored per element. Well-formedness /// condition WF4 forbids a non-variable collation element from having a /// primary weight that falls between two variable ones, so the variable /// elements occupy one contiguous band of primary weights and membership /// of that band is the whole question. The `*` that marks these entries /// in `allkeys.txt` therefore need not be carried into the generated /// table at all, and asking costs two compares rather than a load. /// /// It is a band and not a single threshold because of the CLDR root /// collation, where U+FFFE sits *below* every variable element at primary /// weight 0x0001 and is not itself variable. That is deliberate on /// CLDR's part -- U+FFFE is the merge separator of section 1.6, given the /// lowest primary weight there is so that it sorts before everything -- /// and a lone threshold would have swept it up. DUCET has nothing below /// its band, so the same test serves both. pub fn isVariable(t: Table, e: Element) bool { return e.primary >= t.min_variable_primary and e.primary <= t.max_variable_primary; }
/// The same table with a tailoring layered over it. pub fn tailored(t: Table, tailoring: *const Tailoring) Table { var out = t; out.tailoring = tailoring; return out; }
/// What the table has for one code point, or `Entry.none` if it has /// nothing -- in which case the weights are derived, by `implicit`. /// /// The tailoring wins where it says anything, which is what makes it a /// tailoring. Where it is silent but adds a contraction starting at this /// code point, the root's entry is returned with the flag set, so that /// step 2 knows to look. pub fn entry(t: Table, cp: u21) Entry { const root_entry = t.rootEntry(cp); const x = t.tailoring orelse return root_entry;
var e = x.entry(cp) orelse root_entry; // Set from *either* list, and after the override rather than as part // of it. A tailoring that replaces what a code point maps to has not // thereby said anything about contractions starting there, and both // lists may have some: CLDR writes its rules in NFD, so a tailoring // for `å` is a contraction on `a` and a combining ring, while `a` // itself may separately have been shifted to make room. Taking the // flag from the override alone loses the contraction, and the // ordering it was there to fix goes with it. e.starts_contraction = root_entry.starts_contraction or x.contractionsFor(cp).len != 0; return e; }
fn rootEntry(t: Table, cp: u21) Entry { const high = cp >> 8; if (high >= t.stage1.len) return .none; const block = t.stage1[high]; if (block == no_block) return .none; return @bitCast(t.stage2[@as(usize, block) * block_len + (cp & 0xFF)]); }
/// The elements an entry maps to. `scratch` holds the answer in the /// common case of a single element, which is stored in the entry itself /// rather than out in `expansions`. pub fn elementsOf(t: Table, e: Entry, scratch: *[1]Element) []const Element { if (e.len == 0) return &.{}; if (e.tailored) { const x = t.tailoring.?; return x.expansions[e.payload..][0..e.len]; } if (e.len == 1) { scratch[0] = @bitCast(e.payload); return scratch[0..1]; } return t.expansions[e.payload..][0..e.len]; }
/// The code points after a contraction's first, from this table's own /// pool. pub fn restOf(t: Table, c: Contraction) []const u21 { return t.contraction_points[c.rest_index..][0..c.rest_len]; }
/// The same for a contraction the tailoring added. /// The code points a contextual mapping is conditional on, from the /// root's pool. Empty for every root contraction there is. pub fn prefixOf(t: Table, c: Contraction) []const u21 { return t.contraction_points[c.prefix_index..][0..c.prefix_len]; }
/// The same, for a mapping the tailoring added. pub fn tailoredPrefixOf(t: Table, c: Contraction) []const u21 { const x = t.tailoring.?; return x.contraction_points[c.prefix_index..][0..c.prefix_len]; }
pub fn tailoredRestOf(t: Table, c: Contraction) []const u21 { return t.tailoring.?.restOf(c); }
/// The elements of a contraction from this table's own list. pub fn elementsOfContraction(t: Table, c: Contraction) []const Element { return t.expansions[c.elements_index..][0..c.elements_len]; }
/// The elements of a contraction from the tailoring's list. pub fn elementsOfTailoredContraction(t: Table, c: Contraction) []const Element { const x = t.tailoring.?; return x.expansions[c.elements_index..][0..c.elements_len]; }
/// The root's contractions beginning with `cp`, unless the tailoring /// suppresses them. pub fn rootContractionsFor(t: Table, cp: u21) []const Contraction { if (t.suppresses(cp)) return &.{}; return t.contractionsFor(cp); }
/// Contractions the tailoring adds that begin with `cp`, longest first. /// These are tried ahead of the root's. pub fn tailoredContractionsFor(t: Table, cp: u21) []const Contraction { const x = t.tailoring orelse return &.{}; return x.contractionsFor(cp); }
/// Whether the tailoring suppresses the root's contractions beginning /// with `cp`: `[suppressContractions …]`, and see `Tailoring.suppressed`. pub fn suppresses(t: Table, cp: u21) bool { const x = t.tailoring orelse return false; var lo: usize = 0; var hi: usize = x.suppressed.len; while (lo < hi) { const mid = lo + (hi - lo) / 2; if (x.suppressed[mid] < cp) lo = mid + 1 else hi = mid; } return lo < x.suppressed.len and x.suppressed[lo] == cp; }
/// Every contraction beginning with `cp`, longest first. Empty unless /// `entry(cp).starts_contraction`, which is the cheap test to make /// first. /// /// The root's own, so a tailoring that suppresses them is asked first: /// `rootContractionsFor` is the one step 2 calls. pub fn contractionsFor(t: Table, cp: u21) []const Contraction { // The list is sorted by first code point, so the group is a // contiguous run; find its start by bisection and walk to its end. var lo: usize = 0; var hi: usize = t.contractions.len; while (lo < hi) { const mid = lo + (hi - lo) / 2; if (t.contractions[mid].first < cp) lo = mid + 1 else hi = mid; } var end = lo; while (end < t.contractions.len and t.contractions[end].first == cp) end += 1; return t.contractions[lo..end]; }
/// Section 10.1.3: the pair of collation elements for a code point the /// table has no mapping for. /// /// [.AAAA.0020.0002][.BBBB.0000.0000] /// /// The second element has a non-zero primary weight and zero weights /// below it, which breaks well-formedness condition WF1 as stated. That /// is deliberate, and is the large-weight-value exception of section 9.2 /// -- DUCET itself writes such pairs out by hand, for instance at U+337F /// SQUARE ERA NAME MEIJI. pub fn implicit(t: Table, cp: u21) [2]Element { const aaaa, const bbbb = t.implicitPrimaries(cp); return .{ .{ .primary = aaaa, .secondary = 0x0020, .tertiary = 0x0002 }, .{ .primary = bbbb, .secondary = 0, .tertiary = 0 }, }; }
fn implicitPrimaries(t: Table, cp: u21) struct { u16, u16 } { // The low half is the same for every row but the siniform ones, and // `data.implicit_tail_bit` is always set so that it can never be // zero -- and so that a tailoring allocating primary weights of its // own knows where to stop. const tail: u16 = @intCast((cp & 0x7FFF) | data.implicit_tail_bit);
// CLDR orders Han by radical and stroke count, so where the table // carries that order the weight is computed from an ideograph's rank // in it rather than from its code point. `data.HanRange` says why. // // The ranks run to 101,996, which is four lead weights' worth -- // `data.implicit_primary_base` to +3 -- and leaves 0xFB80 upwards, // which section // 10.1.3 gives to the Han outside the core blocks, for an ideograph // CLDR has not classified. There should be none; one would be a Han // code point newer than the CLDR release, and it sorts after every // ideograph that is classified rather than among them. if (t.han_order.len != 0) { if (t.hanRank(cp)) |rank| { return .{ @intCast(data.implicit_primary_base + (rank >> 15)), @intCast((rank & 0x7FFF) | data.implicit_tail_bit), }; } for (t.implicit_ranges) |r| { if (cp < r.first or cp > r.last) continue; switch (r.kind) { .core_han, .other_han => return .{ @intCast(0xFB80 + (cp >> 15)), tail, }, .siniform => {}, } } }
for (t.implicit_ranges) |r| { if (cp < r.first or cp > r.last) continue; switch (r.kind) { .siniform => { // "a range of code points, from which unassigned code // points are to be excluded" -- an unassigned code point // inside a Tangut block is weighted as unassigned rather // than as Tangut, so this falls out of the loop rather // than answering. if (uucode.get(.general_category, cp) == .other_not_assigned) break; return .{ r.lead, @intCast((cp - r.base) | 0x8000) }; }, .core_han => return .{ @intCast(0xFB40 + (cp >> 15)), tail }, .other_han => return .{ @intCast(0xFB80 + (cp >> 15)), tail }, } }
// Unassigned, and everything else the table does not mention -- // which includes surrogate code points, taking the second of the two // approaches section 10.1.1 offers for ill-formed input. return .{ @intCast(0xFBC0 + (cp >> 15)), tail }; }
/// Where an ideograph sits in CLDR's order, or null if the table's Han /// order does not mention it. fn hanRank(t: Table, cp: u21) ?u21 { var lo: usize = 0; var hi: usize = t.han_order.len; while (lo < hi) { const mid = lo + (hi - lo) / 2; const r = t.han_order[mid]; if (cp < r.first) { hi = mid; } else if (cp > r.last) { lo = mid + 1; } else { return r.base + (cp - r.first); } } return null; }
/// Append the elements for one code point, whether the table has them or /// they have to be derived. Does not consider contractions: that is /// `elements.append`'s job, which has the rest of the string to look at. pub fn appendElements( t: Table, out: *std.ArrayList(Element), gpa: Allocator, cp: u21, ) Allocator.Error!void { const e = t.entry(cp); if (e.len == 0) { try out.appendSlice(gpa, &t.implicit(cp)); return; } var scratch: [1]Element = undefined; try out.appendSlice(gpa, t.elementsOf(e, &scratch)); }};
const testing = std.testing;
test "stage1 stops at the last block that holds anything" { // The array is emitted only as far as its last useful entry, so the last // entry must be a useful one -- otherwise the generator left something // on the table, which for a restricted build is most of it. // // And a code point past the end has to come out the same as one whose // block is `no_block`: no entry, and section 10.1.3's derived weights. // That is what makes the truncation free, and it is `rootEntry`'s bounds // check rather than anything the generator arranges. for ([_]Table{ ducet, cldr_root }) |t| { if (t.stage1.len == 0) continue; try testing.expect(t.stage1[t.stage1.len - 1] != Table.no_block);
const past: u21 = @intCast(t.stage1.len * Table.block_len); if (past <= 0x10FFFF) { try testing.expectEqual(@as(u8, 0), t.entry(past).len); const derived = t.implicit(past); try testing.expect(derived[0].primary >= data.implicit_primary_base); try testing.expectEqual(@as(u16, 0x0020), derived[0].secondary); } }}
test "a restricted repertoire is closed under canonical decomposition" { // The invariant the whole of section 9.3.3 rests on here, and the one // that was missing at first. A canonically decomposable code point has no // entry in any table -- step 1 has replaced it before anything is looked // up -- so it sorts by whatever its decomposition weighs. If the // decomposition falls outside the repertoire, a character the repertoire // *names* silently gets section 10.1.3's implicit weights and sorts after // the entire table. // // U+0374 GREEK NUMERAL SIGN is the one that found it: it is in Greek and // Coptic and decomposes to U+02B9 MODIFIER LETTER PRIME, which is in // Spacing Modifier Letters. A repertoire of Greek without that block put // `0374 0062` after `0375 0021`, one line out of order in 7,294 and no // other symptom. The generator closes the repertoire over decomposition // now, and this is that claim as a test. for ([_]Table{ ducet, cldr_root }) |t| { if (t.repertoire.len == 0) continue; var decomposed: std.ArrayList(u21) = .empty; defer decomposed.deinit(testing.allocator); for (t.repertoire) |range| { var cp = range[0]; while (cp <= range[1]) : (cp += 1) { decomposed.clearRetainingCapacity(); try @import("nfd.zig").append(&decomposed, testing.allocator, &.{cp}); for (decomposed.items) |part| { if (!t.inRepertoire(part)) { std.debug.print( "U+{X:0>4} is in the repertoire and decomposes to U+{X:0>4}, which is not\n", .{ cp, part }, ); return error.TestUnexpectedResult; } } } } }}
/// Whether the table holds the ASCII characters the specification's examples/// are written with.////// A build restricted by `-Drepertoire=` need not, and a test that reads/// elements straight out of the table for `a` or a hyphen is then a test/// about weights that are not there: they take section 10.1.3's implicit/// weights instead, which differ at the first level and nowhere else, and/// which are never variable.fn haveAsciiExamples() bool { return ducet.hasEntries(&.{ ' ', '!', '-', 'A', 'a', 'b', 'c', 'd', 'z' });}
test "single code points come back with the weights allkeys.txt gives them" { if (!haveAsciiExamples()) return error.SkipZigTest; var scratch: [1]Element = undefined;
// 0041 ; [.23EC.0020.0008] # LATIN CAPITAL LETTER A, in DUCET 17.0.0. // The weights in the specification's own examples are from an older // release -- section 12.1 says as much -- so these come from // `data/allkeys-17.0.0.txt`. const a = ducet.elementsOf(ducet.entry('A'), &scratch); try testing.expectEqual(@as(usize, 1), a.len); try testing.expectEqual(@as(u16, 0x23EC), a[0].primary); try testing.expectEqual(@as(u16, 0x0020), a[0].secondary); try testing.expectEqual(@as(u16, 0x0008), a[0].tertiary);
// Lowercase shares the primary and secondary and differs at the third // level, which is what makes case a tertiary difference. // 0061 ; [.23EC.0020.0002] # LATIN SMALL LETTER A const lower = ducet.elementsOf(ducet.entry('a'), &scratch); try testing.expectEqual(a[0].primary, lower[0].primary); try testing.expectEqual(a[0].secondary, lower[0].secondary); try testing.expectEqual(@as(u16, 0x0002), lower[0].tertiary);}
test "space is variable and A is not" { if (!haveAsciiExamples()) return error.SkipZigTest; var scratch: [1]Element = undefined; // 0020 ; [*0209.0020.0002] # SPACE const space = ducet.elementsOf(ducet.entry(' '), &scratch); try testing.expectEqual(@as(u16, 0x0209), space[0].primary); try testing.expect(ducet.isVariable(space[0]));
const a = ducet.elementsOf(ducet.entry('A'), &scratch); try testing.expect(!ducet.isVariable(a[0]));}
test "canonically decomposable code points are not in the table" { // Step 1 has already replaced them, so an entry for one would be dead // weight. U+00C4 is A + combining diaeresis after NFD. try testing.expectEqual(@as(u8, 0), ducet.entry(0x00C4).len); try testing.expectEqual(@as(u8, 0), ducet.entry(0x1E14).len); // A compatibility decomposition is *not* removed by NFD, so it stays -- // unless section 9.3.3's repertoire does not reach it, which is a // statement about the build rather than about the algorithm. if (ducet.inRepertoire(0xFB01)) try testing.expect(ducet.entry(0xFB01).len > 0);}
test "expansions are reachable" { var scratch: [1]Element = undefined; // FDFA ARABIC LIGATURE SALLALLAHOU ALAYHE WASALLAM, the longest // expansion in the table at eighteen collation elements -- and a code // point a restricted build need not carry at all. if (!ducet.inRepertoire(0xFDFA)) return error.SkipZigTest; const e = ducet.entry(0xFDFA); try testing.expectEqual(@as(u8, 18), e.len); try testing.expectEqual(@as(usize, 18), ducet.elementsOf(e, &scratch).len);}
test "CLDR orders Han by radical and stroke, the DUCET by code point" { if (cldr_root.stage1.len == 0) return error.SkipZigTest;
// The DUCET's order is section 10.1.3's, computed from the code point, so // the two ideographs the CLDR order disagrees about are in code-point // order here. try testing.expect(ducet.implicit(0x9FEF)[0].primary <= ducet.implicit(0x9FFE)[0].primary); try testing.expect(order(ducet.implicit(0x9FEF), ducet.implicit(0x9FFE)) == .lt);
// CLDR ranks U+9FFE under an early radical and U+9FEF under a late one, // so it puts them the other way round. ICU agrees with CLDR: asking it // about the untailored root gives `und 9fef 9ffe ours=lt icu=gt`, which // is where this came from. try testing.expect(order(cldr_root.implicit(0x9FFE), cldr_root.implicit(0x9FEF)) == .lt);
// Radical 1 is 一, and its first ideograph is U+4E00, so that much is the // same in both orders. try testing.expectEqual(@as(u16, 0xFB40), cldr_root.implicit(0x4E00)[0].primary); try testing.expectEqual(@as(u16, 0x8000), cldr_root.implicit(0x4E00)[1].primary); try testing.expect(order(cldr_root.implicit(0x4E00), cldr_root.implicit(0x4E01)) == .lt);
// And a radical the table writes out by hand, which a build restricted by // `-Drepertoire=` need not carry: U+2EA5 is in CJK Radicals Supplement. if (!cldr_root.hasEntries(&.{0x2EA5})) return;
// U+2EA5 CJK RADICAL PAW // TWO is `[.FB40.0020.0004][.F22B.0000.0000]` in `allkeys_CLDR.txt`, // which says "sort like U+722B with a tertiary difference" in the // code-point encoding -- is re-encoded to say it about the *rank* of // U+722B, or the radical and its ideograph would part company. var scratch: [1]Element = undefined; const radical = cldr_root.elementsOf(cldr_root.entry(0x2EA5), &scratch); const ideograph = cldr_root.implicit(0x722B); try testing.expectEqual(ideograph[0].primary, radical[0].primary); try testing.expectEqual(ideograph[1].primary, radical[1].primary); try testing.expectEqual(@as(u16, 0x0004), radical[0].tertiary);}
/// Which of two element pairs sorts first, by primary weight then by the/// trailing weight: enough for the implicit-weight tests above.fn order(a: [2]Element, b: [2]Element) std.math.Order { if (a[0].primary != b[0].primary) { return if (a[0].primary < b[0].primary) .lt else .gt; } if (a[1].primary != b[1].primary) { return if (a[1].primary < b[1].primary) .lt else .gt; } return .eq;}
test "implicit weights match the worked example in section 10.1.3" { // "using Table 16 to weight the CJK Unified ideograph U+4E00, for UCA // one calculates a pair of collation elements as follows: // [.FB40.0020.0002][.CE00.0000.0000]" try testing.expectEqual(@as(u8, 0), ducet.entry(0x4E00).len); const w = ducet.implicit(0x4E00); try testing.expectEqual(@as(u16, 0xFB40), w[0].primary); try testing.expectEqual(@as(u16, 0x0020), w[0].secondary); try testing.expectEqual(@as(u16, 0x0002), w[0].tertiary); try testing.expectEqual(@as(u16, 0xCE00), w[1].primary); try testing.expectEqual(@as(u16, 0), w[1].secondary); try testing.expectEqual(@as(u16, 0), w[1].tertiary);}
test "implicit weights by kind" { // Tangut: AAAA 0xFB00, BBBB (CP - 0x17000) | 0x8000. const tangut = ducet.implicit(0x17000); try testing.expectEqual(@as(u16, 0xFB00), tangut[0].primary); try testing.expectEqual(@as(u16, 0x8000), tangut[1].primary);
// Tangut Supplement shares the lead *and* the base with Tangut proper, // which is why a range cannot take its base to be its own first code // point. const supplement = ducet.implicit(0x18D00); try testing.expectEqual(@as(u16, 0xFB00), supplement[0].primary); try testing.expectEqual(@as(u16, @intCast((0x18D00 - 0x17000) | 0x8000)), supplement[1].primary);
// An ideograph outside the core blocks: 0xFB80 rather than 0xFB40. const ext_a = ducet.implicit(0x3400); try testing.expectEqual(@as(u16, 0xFB80), ext_a[0].primary);
// A code point that is not assigned at all. const unassigned = ducet.implicit(0x0378); try testing.expectEqual(@as(u16, 0xFBC0), unassigned[0].primary);
// A surrogate is weighted as though it were unassigned, which is the // second approach in section 10.1.1 and is what lets the conformance // suite run without filtering out the lines that contain one. 0xD800 is // in the second plane's worth of the unassigned range, hence 0xFBC1 // rather than 0xFBC0: Table 16 says 0xFBC0 + (CP >> 15). const surrogate = ducet.implicit(0xD800); try testing.expectEqual(@as(u16, 0xFBC1), surrogate[0].primary);}
test "unassigned code points inside a siniform range fall through" { // `@implicitweights 18D00..18D7F; FB00` covers Tangut Ideograph // Supplement, but only 18D00..18D1E is assigned. 0x18D1F is inside the // range and unassigned, so section 10.1.3 excludes it and it takes the // unassigned weights instead of Tangut's. try testing.expectEqual(.other_not_assigned, uucode.get(.general_category, 0x18D1F)); try testing.expectEqual(@as(u16, 0xFB00), ducet.implicit(0x18D00)[0].primary); try testing.expectEqual(@as(u16, 0xFBC3), ducet.implicit(0x18D1F)[0].primary);}
test "contractions are grouped by their first code point" { // A restricted table may have no contractions at all -- the whole of // Basic Latin has none -- and then there is nothing here to group. if (ducet.contractions.len == 0) return error.SkipZigTest;
// Only 77 code points start a contraction, and a code point that does // not must not pay for a search. try testing.expect(!ducet.entry('a').starts_contraction); try testing.expectEqual(@as(usize, 0), ducet.contractionsFor('a').len);
// Every contraction in the list is reachable from its starter, and the // starter says so. var checked: usize = 0; for (ducet.contractions) |c| { try testing.expect(ducet.entry(c.first).starts_contraction); const group = ducet.contractionsFor(c.first); try testing.expect(group.len > 0); // Longest first, so that S2.1 finds the longest match first. var previous: u8 = 255; for (group) |g| { try testing.expect(g.rest_len <= previous); previous = g.rest_len; } checked += 1; } try testing.expect(checked > 0);}
test "the table was generated from the data files in data/" { try testing.expectEqualStrings("17.0.0", ducet.unicode_version); try testing.expectEqual(@as(u16, 0x0201), ducet.min_variable_primary); try testing.expectEqual(@as(u16, 0x2190), ducet.max_variable_primary);}
test "the CLDR root collation, when it was built in" { if (cldr_root.stage1.len == 0) return error.SkipZigTest;
try testing.expectEqualStrings("17.0.0", cldr_root.unicode_version);
// CLDR's variable band is far narrower than DUCET's: 0x0201..0x04E0 // against 0x0201..0x2190. Symbols are variable in DUCET and are not in // CLDR, which is one of the orderings the two disagree about. try testing.expectEqual(@as(u16, 0x0201), cldr_root.min_variable_primary); try testing.expect(cldr_root.max_variable_primary < ducet.max_variable_primary);
// The band survives a `-Drepertoire=` restriction, which is deliberate -- // it is a range of weights rather than a set of code points, and the // entries that survive keep the weights they had. The *entries* below do // not survive it, so they are read only when they are there. if (!cldr_root.hasEntries(&.{ ' ', 0xFFFE })) return;
var scratch: [1]Element = undefined; const space = cldr_root.elementsOf(cldr_root.entry(' '), &scratch); try testing.expect(cldr_root.isVariable(space[0]));
// U+FFFE, the merge separator of section 1.6: the lowest primary weight // in the table, and deliberately not variable. This is the entry a lone // variable-weight threshold would have misread, and the reason // `isVariable` tests a band. const merge = cldr_root.elementsOf(cldr_root.entry(0xFFFE), &scratch); try testing.expectEqual(@as(u16, 0x0001), merge[0].primary); try testing.expect(!cldr_root.isVariable(merge[0])); try testing.expect(merge[0].primary < cldr_root.min_variable_primary);}