// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The four steps of UTS #10 section 7, put together. const std = @import("std"); const Allocator = std.mem.Allocator; const data = @import("data"); const Element = data.Element; const nfd = @import("nfd.zig"); const elements = @import("elements.zig"); const key = @import("key.zig"); const table = @import("table.zig"); const Options = key.Options; const Table = table.Table; pub const Error = error{ OutOfMemory, InvalidUtf8 }; /// A collation: a table, plus the parametric settings applied to it. /// /// Holds no allocation and is cheap to copy, because the table is comptime /// data and the settings are three fields. Sharing one between threads is /// fine; the scratch that building a key needs lives in `Builder`. pub const Collator = struct { /// The collation element table, optionally with a tailoring layered over /// it -- `table.ducet.tailored(&collate.locales.sv)`, say. A tailored /// table is still a table, so there is only the one field. table: Table = table.ducet, options: Options = .{}, /// Build a sort key for UTF-8 text. The caller owns the result. /// /// Sorting a list means building a key for each string and then /// comparing the keys, which is the entire point of the sort key: *n* /// key constructions and `n log n` byte comparisons, rather than `n log /// n` collations. For that case hoist a `Builder` and use it, so that the /// scratch is allocated once rather than per string. pub fn sortKeyAlloc(c: Collator, gpa: Allocator, text: []const u8) Error![]u8 { // The scratch comes off the stack for a string of ordinary length // and only reaches `gpa` for something long; the key itself is the // caller's and so is always `gpa`'s. What this saves is three // allocations and three frees per call, for buffers whose whole life // is this function. var fallback = std.heap.stackFallback(scratch_size, gpa); const scratch = fallback.get(); var builder: Builder = .empty; defer builder.deinit(scratch); var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); builder.writeSortKeyUtf8(scratch, &out.writer, c, text) catch |err| switch (err) { error.InvalidUtf8 => return error.InvalidUtf8, error.OutOfMemory, error.WriteFailed => return error.OutOfMemory, }; return out.toOwnedSlice(); } /// The same, for text already decoded to code points. /// /// This is the entry point that accepts anything a `u21` can hold, /// including a surrogate, which is weighted as an unassigned code point /// by section 10.1.1's second approach. The UTF-8 entry points refuse /// ill-formed input instead, because a UTF-8 slice holding a surrogate /// is a bug in the caller rather than an ordering question. pub fn sortKeyAllocCodePoints(c: Collator, gpa: Allocator, text: []const u21) Allocator.Error![]u8 { var fallback = std.heap.stackFallback(scratch_size, gpa); const scratch = fallback.get(); var builder: Builder = .empty; defer builder.deinit(scratch); var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); builder.writeSortKey(scratch, &out.writer, c, text) catch |err| switch (err) { error.OutOfMemory, error.WriteFailed => return error.OutOfMemory, }; return out.toOwnedSlice(); } /// Compare two strings. Weighs both and throws the weights away, so for /// more than a couple of comparisons over the same strings, build the /// keys once instead. /// /// No whole key is written: the levels are compared one at a time and the /// answer is taken from the first that decides, which is section 9.7's /// incremental comparison. Almost every pair of different strings is /// settled by the primary level, and writing the key is between a quarter /// and two fifths of building one, so this is faster than writing two /// keys and comparing them -- 15% on ASCII and 24% on Vietnamese. /// /// Nothing is allocated for strings of ordinary length -- the two keys /// and the scratch all come off the stack, and `gpa` is reached only for /// something long. That matters because this is the convenient entry /// point and therefore the one that ends up inside a sort comparator, /// where an allocation apiece is most of the cost: the first version of /// this allocated five times per comparison, which measured 604 ns a pair /// against an arena and 30 *microseconds* against a checking allocator. pub fn order(c: Collator, gpa: Allocator, a: []const u8, b: []const u8) Error!std.math.Order { var fallback = std.heap.stackFallback(2 * scratch_size + 2 * key_size, gpa); const scratch = fallback.get(); // Both strings are weighed, which steps 1 and 2 have to do either // way, and then the *levels* are compared one at a time and the // comparison stops at the first that decides -- section 9.7's // incremental comparison, as far as this representation can take it. // Most pairs differ at the first level, and writing the other two for // both strings is a third of what a key costs. var first: Builder = .empty; defer first.deinit(scratch); var second: Builder = .empty; defer second.deinit(scratch); for ([_][]const u8{ a, b }, [_]*Builder{ &first, &second }) |text, builder| { builder.weighUtf8(scratch, c, text) catch |err| switch (err) { error.InvalidUtf8 => return error.InvalidUtf8, error.OutOfMemory => return error.OutOfMemory, }; } var buf_a: std.Io.Writer.Allocating = .init(scratch); defer buf_a.deinit(); var buf_b: std.Io.Writer.Allocating = .init(scratch); defer buf_b.deinit(); const levels = c.options.strength.levels(); for (0..levels) |level| { buf_a.clearRetainingCapacity(); buf_b.clearRetainingCapacity(); for ( [_]*Builder{ &first, &second }, [_]*std.Io.Writer.Allocating{ &buf_a, &buf_b }, ) |builder, out| { key.writeLevel( &out.writer, c.options, c.table.tailoring, builder.weighted.items, level, ) catch return error.OutOfMemory; } const answer = orderKeys(buf_a.written(), buf_b.written()); if (answer != .eq) return answer; } // What the loop cannot reach: the case level of a collation that // stops at the secondary level, and the identical level. Both are // written by `key.write` after its own loop, and both are rare enough // that the whole of the remainder goes through one comparison. buf_a.clearRetainingCapacity(); buf_b.clearRetainingCapacity(); for ( [_]*Builder{ &first, &second }, [_]*std.Io.Writer.Allocating{ &buf_a, &buf_b }, ) |builder, out| { if (c.options.case_level and levels == 2) { out.writer.writeAll(&.{ 0, 0 }) catch return error.OutOfMemory; key.writeCaseLevelPublic(&out.writer, c.options, builder.weighted.items) catch return error.OutOfMemory; } key.writeIdenticalLevel(&out.writer, c.options, builder.text.items) catch return error.OutOfMemory; } return orderKeys(buf_a.written(), buf_b.written()); } }; /// How much stack the entry points above keep for a `Builder`'s three /// buffers: the NFD of the string, its collation elements, and those elements /// after variable weighting. /// /// Enough for a string of about forty code points, which is more than a name /// or a word and less than a line. Past it the allocator is reached, which is /// the same thing that would have happened for every string before. const scratch_size = 1024; /// And how much for one sort key, which is six bytes a code point at /// tertiary strength and nine at identical. const key_size = 512; /// Step 4: compare two sort keys. A plain binary comparison -- the levels are /// already in the bytes. pub fn orderKeys(a: []const u8, b: []const u8) std.math.Order { return key.order(a, b); } /// Reusable scratch for building many keys, which is the case this library /// exists to serve: one key per node of a node-set, per sort level. /// /// One per thread. Nothing here is shared, and nothing here is a `Collator`, /// so the same builder can serve several collations. pub const Builder = struct { /// The NFD of the string being worked on. Mutable, because S2.1.3 says /// to remove a code point from the input when a discontiguous match /// consumes it. text: std.ArrayList(u21), elements: std.ArrayList(Element), weighted: std.ArrayList(key.Weighted), pub const empty: Builder = .{ .text = .empty, .elements = .empty, .weighted = .empty }; pub fn deinit(b: *Builder, gpa: Allocator) void { b.text.deinit(gpa); b.elements.deinit(gpa); b.weighted.deinit(gpa); b.* = undefined; } /// Steps 1 to 3, writing the key to `w`. /// /// The levels of a sort key cannot be streamed independently -- every /// primary weight in the string precedes the first secondary weight -- /// so the element array is buffered here whatever the caller does with /// the bytes. pub fn writeSortKey( b: *Builder, gpa: Allocator, w: *std.Io.Writer, c: Collator, text: []const u21, ) error{ OutOfMemory, WriteFailed }!void { try b.prepare(gpa, c, text); try key.write(w, c.options, c.table.tailoring, b.weighted.items, b.text.items); } /// The same, for UTF-8 text. pub fn writeSortKeyUtf8( b: *Builder, gpa: Allocator, w: *std.Io.Writer, c: Collator, text: []const u8, ) error{ OutOfMemory, InvalidUtf8, WriteFailed }!void { b.reset(); try nfd.appendUtf8(&b.text, gpa, text); try b.finish(gpa, c); try key.write(w, c.options, c.table.tailoring, b.weighted.items, b.text.items); } pub fn sortKeyAllocCodePoints( b: *Builder, gpa: Allocator, c: Collator, text: []const u21, ) Allocator.Error![]u8 { var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); b.writeSortKey(gpa, &out.writer, c, text) catch |err| switch (err) { error.OutOfMemory, error.WriteFailed => return error.OutOfMemory, }; return out.toOwnedSlice(); } pub fn sortKeyAlloc(b: *Builder, gpa: Allocator, c: Collator, text: []const u8) Error![]u8 { var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); b.writeSortKeyUtf8(gpa, &out.writer, c, text) catch |err| switch (err) { error.InvalidUtf8 => return error.InvalidUtf8, error.OutOfMemory, error.WriteFailed => return error.OutOfMemory, }; return out.toOwnedSlice(); } /// Steps 1 and 2 only, leaving the weighted elements in the builder for /// something else to write or compare. `Collator.order` uses it to weigh /// both strings before comparing them a level at a time. pub fn weighUtf8( b: *Builder, gpa: Allocator, c: Collator, text: []const u8, ) error{ OutOfMemory, InvalidUtf8 }!void { b.reset(); try nfd.appendUtf8(&b.text, gpa, text); try b.finish(gpa, c); } /// The collation elements for a string, for a caller that wants to look /// at them rather than at a key. Valid until the next call. pub fn collationElements( b: *Builder, gpa: Allocator, c: Collator, text: []const u21, ) Allocator.Error![]const Element { try b.prepare(gpa, c, text); return b.elements.items; } fn reset(b: *Builder) void { b.text.clearRetainingCapacity(); b.elements.clearRetainingCapacity(); b.weighted.clearRetainingCapacity(); } fn prepare(b: *Builder, gpa: Allocator, c: Collator, text: []const u21) Allocator.Error!void { b.reset(); try nfd.append(&b.text, gpa, text); try b.finish(gpa, c); } fn finish(b: *Builder, gpa: Allocator, c: Collator) Allocator.Error!void { try elements.append(&b.elements, gpa, c.table, b.text.items); try key.weigh(&b.weighted, gpa, c.table, c.options.alternate, b.elements.items); } }; const testing = std.testing; test "the case from the issue: Maertens, Moeller, Mueller" { // `xsl:sort` comparing by code point puts Mueller before Märtens, // because `u` is U+0075 and `ä` is U+00E4. The root collation gives ä, ö // and ü the same primary weights as a, o and u, so it gets this right // with no tailoring at all -- which is the whole argument for doing this // rather than reaching for a locale. const c: Collator = .{}; const names = [_][]const u8{ "Märtens", "Möller", "Mueller" }; var i: usize = 1; while (i < names.len) : (i += 1) { try testing.expectEqual( std.math.Order.lt, try c.order(testing.allocator, names[i - 1], names[i]), ); } // And the code point order it replaces really is the other way round. try testing.expect(std.mem.order(u8, "Mueller", "Märtens") == .lt); } /// Whether the default table has entries for the characters a test names. /// /// A build restricted by `-Drepertoire=` need not, and a test about which /// level two characters differ at is then a test about weights that are not /// there -- both of them take section 10.1.3's implicit weights instead, /// which differ at the first level and nowhere else. fn inRepertoire(cps: []const u21) bool { const c: Collator = .{}; for (cps) |cp| { if (!c.table.inRepertoire(cp)) return false; } return true; } test "the levels, one at a time" { if (!inRepertoire(&.{ 'c', 'C', 0x00E1, 'a', 0x0301, 'd', 'b' })) return error.SkipZigTest; const c: Collator = .{}; // Figure 3: "cab" <3 "Cab" <2 "cáb" <1 "dab". try testing.expectEqual(std.math.Order.lt, try c.order(testing.allocator, "cab", "Cab")); try testing.expectEqual(std.math.Order.lt, try c.order(testing.allocator, "Cab", "cáb")); try testing.expectEqual(std.math.Order.lt, try c.order(testing.allocator, "cáb", "dab")); // At primary strength the first three are all the same word. const primary: Collator = .{ .options = .{ .strength = .primary } }; try testing.expectEqual(std.math.Order.eq, try primary.order(testing.allocator, "cab", "Cab")); try testing.expectEqual(std.math.Order.eq, try primary.order(testing.allocator, "cab", "cáb")); try testing.expectEqual(std.math.Order.lt, try primary.order(testing.allocator, "cab", "dab")); // At secondary strength the accent counts and the case does not. const secondary: Collator = .{ .options = .{ .strength = .secondary } }; try testing.expectEqual(std.math.Order.eq, try secondary.order(testing.allocator, "cab", "Cab")); try testing.expectEqual(std.math.Order.lt, try secondary.order(testing.allocator, "cab", "cáb")); } test "canonically equivalent strings collate equal" { const c: Collator = .{}; // Composed and decomposed, which step 1 exists to reconcile. try testing.expectEqual( std.math.Order.eq, try c.order(testing.allocator, "Märtens", "Ma\u{0308}rtens"), ); // Even at identical strength, which compares the NFD itself. const identical: Collator = .{ .options = .{ .strength = .identical } }; try testing.expectEqual( std.math.Order.eq, try identical.order(testing.allocator, "Märtens", "Ma\u{0308}rtens"), ); } test "a prefix sorts before what extends it" { // The note under S3.2: "abc" < "abcX" where X is any character. const c: Collator = .{}; try testing.expectEqual(std.math.Order.lt, try c.order(testing.allocator, "abc", "abcX")); try testing.expectEqual(std.math.Order.lt, try c.order(testing.allocator, "abc", "abc1")); } test "at the default settings a trailing punctuation mark changes nothing" { // Worth a test of its own because it surprises people. The UCA default // for `alternate` is `shifted` and the UCA default for `strength` is // tertiary -- section 8.1 states both -- and `shifted` puts what it took // from a variable collation element on the *fourth* level, which // tertiary strength does not look at. So at the defaults punctuation is // ignored outright, and the prefix property above does not extend to it. // // LDML defaults `alternate` to `non_ignorable` for exactly this reason. // Either is a legitimate reading of the specification; this library // takes the UCA's, and a caller who wants punctuation to count says so. // // It needs the exclamation mark to *be* variable, which is a fact about // the table: outside section 9.3.3's repertoire it takes an implicit // weight instead, and an implicit weight is not in the variable band. if (!inRepertoire(&.{ 'a', 'b', 'c', '!' })) return error.SkipZigTest; const c: Collator = .{}; try testing.expectEqual(std.math.Order.eq, try c.order(testing.allocator, "abc", "abc!")); const quaternary: Collator = .{ .options = .{ .strength = .quaternary } }; try testing.expectEqual(std.math.Order.lt, try quaternary.order(testing.allocator, "abc", "abc!")); // With `non_ignorable` it counts at the first level -- though still // after "abc", because a prefix sorts before what extends it whatever // the extension weighs. const plain: Collator = .{ .options = .{ .alternate = .non_ignorable } }; try testing.expectEqual(std.math.Order.lt, try plain.order(testing.allocator, "abc", "abc!")); try testing.expectEqual(std.math.Order.lt, try plain.order(testing.allocator, "abc!", "abcX")); } test "table 12, the specification's own variable weighting example" { // Needs the characters the table is about, which a build restricted by // `-Drepertoire=` need not have: U+2010 HYPHEN is in General Punctuation. if (!inRepertoire(&.{ ' ', '-', 0x2010, 'd', 'e', 'a', 't', 'h', 'D' })) { return error.SkipZigTest; } // Section 4.1 tabulates what each `Alternate` does to ten strings that // differ by a space, a U+002D HYPHEN-MINUS, a U+2010 HYPHEN or nothing, // and by case. These are two of its columns, verbatim. // // `blanked` is not among them: it leaves four of the ten equal at every // level it looks at, so their order in the table is the sort's stability // rather than the collation's answer. `shift_trimmed` is the one section // 4 calls "otherwise not recommended". const columns = [_]struct { options: Options, order: []const []const u8, }{ .{ // Every variable element keeps its own low primary weight, so // all six punctuated forms sort ahead of "death". .options = .{ .alternate = .non_ignorable }, .order = &.{ "de luge", "de Luge", "de-luge", "de-Luge", "de\u{2010}luge", "de\u{2010}Luge", "death", "deluge", "deLuge", "demark", }, }, .{ // The variable elements weigh nothing until the fourth level, so // the six punctuated forms collapse onto "deluge" and are then // separated by case first and by which mark it was second. .options = .{ .alternate = .shifted, .strength = .quaternary }, .order = &.{ "death", "de luge", "de-luge", "de\u{2010}luge", "deluge", "de Luge", "de-Luge", "de\u{2010}Luge", "deLuge", "demark", }, }, }; var builder: Builder = .empty; defer builder.deinit(testing.allocator); for (columns) |column| { const c: Collator = .{ .options = column.options }; var i: usize = 1; while (i < column.order.len) : (i += 1) { const previous = try builder.sortKeyAlloc(testing.allocator, c, column.order[i - 1]); defer testing.allocator.free(previous); const current = try builder.sortKeyAlloc(testing.allocator, c, column.order[i]); defer testing.allocator.free(current); if (orderKeys(previous, current) != .lt) { std.debug.print("{t}: \"{s}\" did not sort before \"{s}\"\n", .{ column.options.alternate, column.order[i - 1], column.order[i], }); return error.TestUnexpectedResult; } } } } test "blanked makes punctuation vanish entirely" { // The hyphen has to be variable, which it is only if the table has it. if (!inRepertoire(&.{ '-', 'b', 'l', 'a', 'c', 'k', 'i', 'r', 'd' })) { return error.SkipZigTest; } const c: Collator = .{ .options = .{ .alternate = .blanked } }; try testing.expectEqual( std.math.Order.eq, try c.order(testing.allocator, "black-bird", "blackbird"), ); } test "a builder gives the same answer as the one-shot path" { const c: Collator = .{}; var builder: Builder = .empty; defer builder.deinit(testing.allocator); for ([_][]const u8{ "Märtens", "Möller", "Mueller", "", "a", "!!!", "한국" }) |s| { const one_shot = try c.sortKeyAlloc(testing.allocator, s); defer testing.allocator.free(one_shot); const reused = try builder.sortKeyAlloc(testing.allocator, c, s); defer testing.allocator.free(reused); try testing.expectEqualSlices(u8, one_shot, reused); } } test "the empty string sorts before everything" { const c: Collator = .{}; const empty_key = try c.sortKeyAlloc(testing.allocator, ""); defer testing.allocator.free(empty_key); const a_key = try c.sortKeyAlloc(testing.allocator, "a"); defer testing.allocator.free(a_key); try testing.expectEqual(std.math.Order.lt, orderKeys(empty_key, a_key)); } test "ill-formed utf8 is refused, and code points are not" { const c: Collator = .{}; try testing.expectError(error.InvalidUtf8, c.sortKeyAlloc(testing.allocator, "\xc3")); // The same surrogate reached through the code point entry point is // weighted rather than refused. const surrogate = try c.sortKeyAllocCodePoints(testing.allocator, &.{0xD800}); defer testing.allocator.free(surrogate); try testing.expect(surrogate.len > 0); } test "a CLDR tailoring reorders what the root collation got wrong for a language" { // Only when the build asked for it: `-Dlocales=tr`. A locale that was not // compiled in is a missing declaration rather than a null, which is the // point of generating declarations instead of a lookup by string. const locales = @import("locales"); if (!@hasDecl(locales, "tr")) return error.SkipZigTest; const turkish: Collator = .{ .table = table.ducet.tailored(&locales.tr), .options = .{ .alternate = .non_ignorable }, }; const root_collation: Collator = .{ .options = .{ .alternate = .non_ignorable } }; var builder: Builder = .empty; defer builder.deinit(testing.allocator); // Turkish treats ı and i as separate letters, ç as a letter after c, and // ş, ö, ü, ğ likewise. The root collation makes every one of those a // secondary or tertiary difference from its base letter instead. const expected = [_][]const u8{ "cam", "çam", "dam", "gam", "ğam", "ham", "ıam", "iam", "jam" }; var i: usize = 1; while (i < expected.len) : (i += 1) { const previous = try builder.sortKeyAlloc(testing.allocator, turkish, expected[i - 1]); defer testing.allocator.free(previous); const current = try builder.sortKeyAlloc(testing.allocator, turkish, expected[i]); defer testing.allocator.free(current); if (orderKeys(previous, current) != .lt) { std.debug.print("tr: \"{s}\" did not sort before \"{s}\"\n", .{ expected[i - 1], expected[i], }); return error.TestUnexpectedResult; } } // And the tailoring is doing something: the root collation puts ç with c // rather than after it, so "çam" lands before "dam" either way but // *equal* to "cam" at primary strength, which Turkish will not have. const primary_root: Collator = .{ .options = .{ .strength = .primary } }; try testing.expectEqual( std.math.Order.eq, try primary_root.order(testing.allocator, "cam", "çam"), ); const primary_turkish: Collator = .{ .table = table.ducet.tailored(&locales.tr), .options = .{ .strength = .primary }, }; try testing.expectEqual( std.math.Order.lt, try primary_turkish.order(testing.allocator, "cam", "çam"), ); // The root collation is unchanged by any of this, which is what makes a // tailoring a delta rather than a different library. try testing.expectEqual( std.math.Order.lt, try root_collation.order(testing.allocator, "cam", "dam"), ); } test "the Swedish tailoring puts three letters after z" { const locales = @import("locales"); if (!@hasDecl(locales, "sv")) return error.SkipZigTest; const swedish: Collator = .{ .table = table.ducet.tailored(&locales.sv), .options = .{ .alternate = .non_ignorable }, }; var builder: Builder = .empty; defer builder.deinit(testing.allocator); // å, ä and ö are letters of their own at the end of the Swedish // alphabet, not variants of a and o. Swedish gets there by a route worth // exercising: the rule is `&[before 1]ǀ<å<<<Å<ä...`, which anchors on the // primary weight *below* U+01C0 LATIN LETTER DENTAL CLICK rather than on // z, so it tests `[before 1]` as well as the ordering. const expected = [_][]const u8{ "yta", "zebra", "åker", "även", "öl" }; var i: usize = 1; while (i < expected.len) : (i += 1) { const previous = try builder.sortKeyAlloc(testing.allocator, swedish, expected[i - 1]); defer testing.allocator.free(previous); const current = try builder.sortKeyAlloc(testing.allocator, swedish, expected[i]); defer testing.allocator.free(current); if (orderKeys(previous, current) != .lt) { std.debug.print("sv: \"{s}\" did not sort before \"{s}\"\n", .{ expected[i - 1], expected[i], }); return error.TestUnexpectedResult; } } // The root collation does the opposite, which is the whole point: å is a // secondary variant of a there, so it sorts among the a-words. const root_collation: Collator = .{ .options = .{ .alternate = .non_ignorable } }; try testing.expectEqual( std.math.Order.lt, try root_collation.order(testing.allocator, "åker", "zebra"), ); } test "a language tag finds the most specific tailoring built in" { const locales = @import("locales"); if (!@hasDecl(locales, "sv")) return error.SkipZigTest; // Exact, and by CLDR's own spelling. try testing.expectEqual(&locales.sv, locales.byName("sv").?); try testing.expectEqual(@as(?*const data.Tailoring, null), locales.byName("sv-FI")); // A tag matches the whole thing first, then with subtags dropped. try testing.expectEqual(&locales.sv, locales.match("sv").?); try testing.expectEqual(&locales.sv, locales.match("sv-FI").?); try testing.expectEqual(&locales.sv, locales.match("sv-FI-u-co-standard").?); // Either separator, and case insensitively: a language tag's case // carries no meaning. try testing.expectEqual(&locales.sv, locales.match("SV").?); try testing.expectEqual(&locales.sv, locales.match("sv_FI").?); // A region-specific file is preferred over its base when both are built. if (@hasDecl(locales, "de_AT")) { try testing.expectEqual(&locales.de_AT, locales.match("de-AT").?); try testing.expectEqual(&locales.de_AT, locales.match("de-at-1996").?); // `de` itself has no standard collation in CLDR: its file carries // `phonebook`, `search` and `eor` and no `standard`, because the root // collation is already German's answer. Which of two things that // means depends on whether `de` was asked for. Unbuilt, the match // fails and null means "use the root". Built, it is a tailoring that // tailors nothing -- the same answer by a different route, and not a // sign that the rules went missing. if (@hasDecl(locales, "de")) { try testing.expectEqual(&locales.de, locales.match("de").?); try testing.expectEqual(@as(usize, 0), locales.de.overrides.len); try testing.expectEqual(@as(usize, 0), locales.de.contractions.len); } else { try testing.expectEqual(@as(?*const data.Tailoring, null), locales.match("de")); } } // Nothing at all for a language nobody asked for, and nothing for // nonsense. try testing.expectEqual(@as(?*const data.Tailoring, null), locales.match("zxx")); try testing.expectEqual(@as(?*const data.Tailoring, null), locales.match("")); try testing.expectEqual(@as(?*const data.Tailoring, null), locales.match("-")); } test "a reordering moves a whole script" { const locales = @import("locales"); if (!@hasDecl(locales, "ru")) return error.SkipZigTest; // Russian's entire standard tailoring is `[reorder Cyrl]`: it changes no // individual character, only where Cyrillic sits relative to everything // else. So this is the one test where the reordering is the whole of // what is being checked. const russian: Collator = .{ .table = table.ducet.tailored(&locales.ru), .options = .{ .alternate = .non_ignorable }, }; const root_collation: Collator = .{ .options = .{ .alternate = .non_ignorable } }; // Cyrillic before Latin under the tailoring, after it in the root. try testing.expectEqual( std.math.Order.lt, try russian.order(testing.allocator, "\u{0430}", "a"), ); try testing.expectEqual( std.math.Order.gt, try root_collation.order(testing.allocator, "\u{0430}", "a"), ); // And Greek, which Cyrillic was moved past, keeps its place relative to // Latin -- the groups either side of the one that moved shift together, // they do not interleave. try testing.expectEqual( std.math.Order.gt, try russian.order(testing.allocator, "\u{03B1}", "a"), ); try testing.expectEqual( std.math.Order.gt, try root_collation.order(testing.allocator, "\u{03B1}", "a"), ); // The core groups are not named by the rule, so step 1 of the // interpretation leaves them at the front: punctuation and digits still // sort below every letter, Cyrillic included. try testing.expectEqual( std.math.Order.lt, try russian.order(testing.allocator, "-", "\u{0430}"), ); try testing.expectEqual( std.math.Order.lt, try russian.order(testing.allocator, "5", "\u{0430}"), ); // The tailoring really is nothing but a reorder: no code point overrides // and no contractions, which is what makes the corpus for it in // `tools/oracle_dump.zig` need script samples to test anything at all. try testing.expectEqual(@as(usize, 0), locales.ru.overrides.len); try testing.expectEqual(@as(usize, 0), locales.ru.contractions.len); try testing.expect(locales.ru.reorder.len != 0); } test "sorting a list is what this is for" { const c: Collator = .{}; var builder: Builder = .empty; defer builder.deinit(testing.allocator); const names = [_][]const u8{ "Mueller", "Märtens", "Möller", "Maier" }; var keys: [names.len][]u8 = undefined; for (names, 0..) |name, i| keys[i] = try builder.sortKeyAlloc(testing.allocator, c, name); defer for (keys) |k| testing.allocator.free(k); var index = [_]usize{ 0, 1, 2, 3 }; const Context = struct { keys: []const []const u8, fn lessThan(ctx: @This(), a: usize, b: usize) bool { return orderKeys(ctx.keys[a], ctx.keys[b]) == .lt; } }; std.mem.sort(usize, &index, Context{ .keys = &keys }, Context.lessThan); var sorted: [names.len][]const u8 = undefined; for (index, 0..) |from, to| sorted[to] = names[from]; try testing.expectEqualSlices([]const u8, &.{ "Maier", "Märtens", "Möller", "Mueller" }, &sorted); } test "Arabic puts the tashkil in the empty secondary-ignorable space" { const locales = @import("locales"); if (!@hasDecl(locales, "ar")) return error.SkipZigTest; // The two rules that made Arabic the last locale to be refused, and both // of them are about the shape of the weight space rather than about a // letter. const arabic: Collator = .{ .table = table.cldr_root.tailored(&locales.ar), .options = .{ .alternate = .non_ignorable }, }; const secondary: Collator = .{ .table = arabic.table, .options = .{ .strength = .secondary, .alternate = .non_ignorable }, }; const primary: Collator = .{ .table = arabic.table, .options = .{ .strength = .primary, .alternate = .non_ignorable }, }; // The rules are about code points that are awkward to write as text, so // the comparison goes through the code point entry point. const compare = struct { fn f(c: Collator, a: []const u21, b: []const u21) !std.math.Order { const first = try c.sortKeyAllocCodePoints(testing.allocator, a); defer testing.allocator.free(first); const second = try c.sortKeyAllocCodePoints(testing.allocator, b); defer testing.allocator.free(second); return orderKeys(first, second); } }.f; // `&[last secondary ignorable]<<<\u064B<<<\u08F0<<<...`, forty-three of // them: the tashkil, which Arabic makes tertiary differences. Forty-three // is what needed a sixth bit of tertiary weight -- five bits reach 31 -- // and the position needed reading rather than tabulating: a secondary // ignorable has a zero primary and a zero secondary, the CLDR root has // nothing in that space, so the last of them is the completely ignorable // element and the chain counts up from zero. const tashkil = [_]u21{ 0x064B, 0x08F0, 0x08E7, 0x064C, 0x08F1, 0x08E8, 0x064D, 0x08F2, 0x08E9, 0x064E, 0x08E4, 0x08F4, 0x08F5, 0x064F, 0x08E5, 0x08FE, 0x0650, 0x08E6, 0x08F6, 0x0651, 0x0652, 0x0653, 0x06DF, 0x06E1, 0x065F, 0x0656, 0x0657, 0x0658, 0x08FF, 0x0659, 0x065A, 0x065B, 0x065C, 0x065D, 0x065E, 0x08F7, 0x08F8, 0x08FD, 0x08FB, 0x08FC, 0x08F9, 0x08FA, 0x0670, }; try testing.expectEqual(43, tashkil.len); for (tashkil, 0..) |mark, i| { // A tertiary difference is invisible at secondary strength: beh with // the mark and beh alone are equal until the third level. try testing.expectEqual( std.math.Order.eq, try compare(secondary, &.{ 0x0628, mark }, &.{0x0628}), ); try testing.expectEqual( std.math.Order.gt, try compare(arabic, &.{ 0x0628, mark }, &.{0x0628}), ); // And the chain is in rule order. if (i == 0) continue; try testing.expectEqual( std.math.Order.lt, try compare(arabic, &.{ 0x0628, tashkil[i - 1] }, &.{ 0x0628, mark }), ); } // And `&[before 2]<<<<`, the rule that has // to move the anchor twice: farsi yeh and then alef maksura go below yeh // at the secondary level, in that order, and yeh ends up above them both. // All three keep yeh's primary weight, so they are equal at primary // strength -- a secondary insertion that promoted itself to a primary // difference would pass an ordering test and still be wrong. for ([_]u21{ 0x06CC, 0x0649 }) |yeh| { try testing.expectEqual( std.math.Order.eq, try compare(primary, &.{yeh}, &.{0x064A}), ); try testing.expectEqual( std.math.Order.lt, try compare(secondary, &.{yeh}, &.{0x064A}), ); } try testing.expectEqual( std.math.Order.lt, try compare(secondary, &.{0x06CC}, &.{0x0649}), ); } test "a tertiary relation on a mark keeps the mark" { const locales = @import("locales"); if (!@hasDecl(locales, "yi")) return error.SkipZigTest; // `&<05E4><05BF><<<<05E3>`: Yiddish makes final pe a tertiary variant of // pe with a rafe. The anchor is two elements -- pe's and the rafe's, // which has no primary weight of its own -- and the relation is about the // second of them, so final pe weighs as pe *and* a rafe whose tertiary // weight is one greater. // // Dropping the rafe and bumping pe's tertiary instead orders the same way // at tertiary strength and not at secondary, where the mark is the whole // of the difference between final pe and bare pe. ICU keeps the mark; // this is the assertion that says so without ICU. const yiddish: Collator = .{ .table = table.cldr_root.tailored(&locales.yi), .options = .{ .alternate = .non_ignorable }, }; const secondary: Collator = .{ .table = yiddish.table, .options = .{ .strength = .secondary, .alternate = .non_ignorable }, }; const primary: Collator = .{ .table = yiddish.table, .options = .{ .strength = .primary, .alternate = .non_ignorable }, }; const compare = struct { fn f(c: Collator, a: []const u21, b: []const u21) !std.math.Order { const first = try c.sortKeyAllocCodePoints(testing.allocator, a); defer testing.allocator.free(first); const second = try c.sortKeyAllocCodePoints(testing.allocator, b); defer testing.allocator.free(second); return orderKeys(first, second); } }.f; const pe: []const u21 = &.{0x05E4}; const pe_rafe: []const u21 = &.{ 0x05E4, 0x05BF }; const final_pe: []const u21 = &.{0x05E3}; // One letter as far as the first level is concerned, all three of them. try testing.expectEqual(std.math.Order.eq, try compare(primary, pe, pe_rafe)); try testing.expectEqual(std.math.Order.eq, try compare(primary, pe, final_pe)); // The mark is a secondary difference, and final pe carries it. try testing.expectEqual(std.math.Order.lt, try compare(secondary, pe, pe_rafe)); try testing.expectEqual(std.math.Order.lt, try compare(secondary, pe, final_pe)); try testing.expectEqual(std.math.Order.eq, try compare(secondary, pe_rafe, final_pe)); // And the rule itself: final pe is the tertiary variant, so it comes // after the spelling it was anchored on. try testing.expectEqual(std.math.Order.lt, try compare(yiddish, pe_rafe, final_pe)); } test "case bits come from the root elements, not from the case properties" { const locales = @import("locales"); if (!@hasDecl(locales, "hr")) return error.SkipZigTest; // Croatian writes `&D