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.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// 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]<yeh><<<farsi yeh><<<alef maksura>`, 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<dž<<<Dž<<<DŽ` and maps the three single code points // U+01C6, U+01C5 and U+01C4 onto those spellings. All three are general // category Lt or Lu, so reading the Unicode case properties calls DŽ and // Dž both uppercase; section 5.1 of the LDML collation specification says // to read the *root* collation elements instead, and those say DŽ is two // uppercase elements and Dž is an uppercase and a lowercase one -- which // makes it mixed. // // `[caseFirst upper]` is where the difference shows: uppercase first, // then mixed, then lowercase. ICU agrees, in nine comparisons of // Croatian's 5,253. const upper_first: Collator = .{ .table = table.cldr_root.tailored(&locales.hr), .options = .{ .alternate = .non_ignorable, .case_first = .upper_first }, }; const lower_first: Collator = .{ .table = upper_first.table, .options = .{ .alternate = .non_ignorable, .case_first = .lower_first }, };
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 dz_upper: []const u21 = &.{0x01C4}; // DŽ const dz_mixed: []const u21 = &.{0x01C5}; // Dž const dz_lower: []const u21 = &.{0x01C6}; // dž
try testing.expectEqual(std.math.Order.lt, try compare(upper_first, dz_upper, dz_mixed)); try testing.expectEqual(std.math.Order.lt, try compare(upper_first, dz_mixed, dz_lower)); try testing.expectEqual(std.math.Order.gt, try compare(lower_first, dz_upper, dz_mixed)); try testing.expectEqual(std.math.Order.gt, try compare(lower_first, dz_mixed, dz_lower));}
test "an uncased element in the middle makes a spelling mixed" { const locales = @import("locales"); if (!@hasDecl(locales, "br")) return error.SkipZigTest;
// Breton's `c'h` is a letter, and its uppercase spelling is C'H -- with // an apostrophe in the middle, which is a primary root collation element // with no case at all. Section 5.1 combines the root elements of the // whole spelling, so "all of them uppercase" is false for C'H: it is // *mixed*, exactly like C'h, and the two differ only at the tertiary // level. Reading the case properties instead would have called C'H // uppercase and put it first, which is what ICU disagreed with in eight // of Breton's 741 comparisons. const upper_first: Collator = .{ .table = table.cldr_root.tailored(&locales.br), .options = .{ .alternate = .non_ignorable, .case_first = .upper_first }, }; const lower_first: Collator = .{ .table = upper_first.table, .options = .{ .alternate = .non_ignorable, .case_first = .lower_first }, };
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 lower: []const u21 = &.{ 'c', 0x02BC, 'h' }; const title: []const u21 = &.{ 'C', 0x02BC, 'h' }; const caps: []const u21 = &.{ 'C', 0x02BC, 'H' };
// The two spellings with a capital in them are both mixed, so nothing // reorders them and the rules decide: C'h before C'H whichever way // `caseFirst` points. try testing.expectEqual(std.math.Order.lt, try compare(upper_first, title, caps)); try testing.expectEqual(std.math.Order.lt, try compare(lower_first, title, caps));
// And mixed sits between uppercase and lowercase, so the all-lowercase // spelling moves and those two do not. try testing.expectEqual(std.math.Order.gt, try compare(upper_first, lower, title)); try testing.expectEqual(std.math.Order.lt, try compare(lower_first, lower, title));}
test "section 10.1.6's Hangul shapes, in the order CLDR's root puts them" { // The trailing weights problem of section 10.1.4, pinned. Syllables are // decomposed to jamo as S1.1 requires, so a syllable written as `L V` is // two weights and `L V T` is three, and whatever follows the syllable // lands where the `T` would have been. // // Section 10.1.6's four tailored methods all turn on giving `T` a weight // above every other script, so that `L1V1T1` outranks `L1V1Xa` for any // following character. CLDR's root does not: its trailing consonants stop // at 0x48A4 and Hiragana begins at 0x48D6, with Han derived above // 0xFB40. So `가一` outranks `각`, where Korean dictionary order compares // syllable by syllable and would have it the other way round. // // This is CLDR's answer rather than this library's: ICU orders these // identically, which the oracle checks on every run -- these shapes are // in its root corpus. The test is here so that a change to any of it // fails loudly, since `DESIGN.md` states this order. if (table.cldr_root.stage1.len == 0) return error.SkipZigTest; // And the jamo have to be in the table, which a build restricted by // `-Drepertoire=` need not have -- without them every shape below takes // implicit weights and the order is code point order, which is a // statement about section 10.1.3 rather than about Hangul. if (!table.cldr_root.hasEntries(&.{ 0x1100, 0x1102, 0x1161, 0x1165, 0x11A8, 0x4E00, 'a' })) { return error.SkipZigTest; } const c: Collator = .{ .table = table.cldr_root };
const ll_v = [_]u21{ 0x1100, 0x1102, 0x1161 }; // L1 L2 V1, Old Korean const ga = [_]u21{ 0x1100, 0x1161 }; // 가, as L1 V1 const ga_a = [_]u21{ 0x1100, 0x1161, 'a' }; // a script below Hangul const ga_ga = [_]u21{ 0x1100, 0x1161, 0x1100, 0x1161 }; const l_vv = [_]u21{ 0x1100, 0x1161, 0x1165 }; // L1 V1 V2, Old Korean const gag = [_]u21{ 0x1100, 0x1161, 0x11A8 }; // 각, as L1 V1 T1 const gag_a = [_]u21{ 0x1100, 0x1161, 0x11A8, 'a' }; const gag_han = [_]u21{ 0x1100, 0x1161, 0x11A8, 0x4E00 }; const ga_han = [_]u21{ 0x1100, 0x1161, 0x4E00 }; // a script above Hangul
const ascending = [_][]const u21{ &ll_v, &ga, &ga_a, &ga_ga, &l_vv, &gag, &gag_a, &gag_han, &ga_han, }; for (ascending[0 .. ascending.len - 1], ascending[1..]) |lower, higher| { const a = try c.sortKeyAllocCodePoints(testing.allocator, lower); defer testing.allocator.free(a); const b = try c.sortKeyAllocCodePoints(testing.allocator, higher); defer testing.allocator.free(b); try testing.expectEqual(std.math.Order.lt, orderKeys(a, b)); }
// And the precomposed syllables weigh exactly what their decompositions // do, which is what makes the anomaly a property of the weights rather // than of how the text happened to be written. for ([_]struct { u21, []const u21 }{ .{ 0xAC00, &ga }, .{ 0xAC01, &gag }, }) |pair| { const composed = try c.sortKeyAllocCodePoints(testing.allocator, &.{pair[0]}); defer testing.allocator.free(composed); const decomposed = try c.sortKeyAllocCodePoints(testing.allocator, pair[1]); defer testing.allocator.free(decomposed); try testing.expectEqualSlices(u8, decomposed, composed); }}