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.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582// 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 buffer: [scratch_size]u8 = undefined; var fallback: std.heap.BufferFirstAllocator = .init(&buffer, gpa); const scratch = fallback.allocator(); 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(); }
test sortKeyAlloc { const gpa = std.testing.allocator; const c: Collator = .{}; const names = [_][]const u8{ "Mueller", "Märtens", "Möller" };
var keys: [names.len][]u8 = undefined; for (names, &keys) |name, *k| k.* = try c.sortKeyAlloc(gpa, name); defer for (keys) |k| gpa.free(k);
// Märtens, Möller, Mueller -- where code point order puts Mueller first. try std.testing.expectEqual(std.math.Order.lt, orderKeys(keys[1], keys[2])); try std.testing.expectEqual(std.math.Order.lt, orderKeys(keys[2], keys[0])); }
/// 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 buffer: [scratch_size]u8 = undefined; var fallback: std.heap.BufferFirstAllocator = .init(&buffer, gpa); const scratch = fallback.allocator(); 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(); }
test sortKeyAllocCodePoints { const gpa = std.testing.allocator; const c: Collator = .{}; const decoded = try c.sortKeyAllocCodePoints(gpa, &.{ 'c', 'a', 'f', 0x00E9 }); defer gpa.free(decoded); const utf8 = try c.sortKeyAlloc(gpa, "caf\u{00E9}"); defer gpa.free(utf8); try std.testing.expectEqualSlices(u8, utf8, decoded); }
/// Build a match key for UTF-8 text. The caller owns the result. /// /// A match key is for finding rather than sorting: two strings have equal /// match keys when they are equal under this collation, and a string /// that a `Searcher` finds inside another has its match key inside the /// other's, record-aligned, which `findMatchKey` looks for. So keys can /// be stored, indexed and searched as bytes, and only the candidates they /// turn up need a `Searcher`. Its binary order means nothing, and it /// holds only the levels the strength compares. /// /// Equal keys always mean equal strings. The converse holds for both /// root collations and can fail under a tailoring: a collation compares /// each level's weights as a sequence of their own, so two strings whose /// elements hold the same weights split differently are equal, and a /// tailoring can make that possible where the root tables cannot. Arabic /// does, for a hamza and a tashkil in either order. A key sees the /// elements, and calls those two different. /// /// Two more things a key cannot say. It has no grapheme cluster /// boundaries, and it cannot tell where one character's elements end and /// the next one's begin, so a key can be found where the `Searcher` would /// refuse the match -- `a`'s key is inside `æ`'s at primary strength, /// since `æ` expands to an a and an e. And it cannot express asymmetric /// search, or `sharp_s_tertiary`. Each of those needs the `Searcher`. /// /// See `key.writeMatchKey` for the layout. pub fn matchKeyAlloc(c: Collator, gpa: Allocator, text: []const u8) Error![]u8 { var buffer: [scratch_size]u8 = undefined; var fallback: std.heap.BufferFirstAllocator = .init(&buffer, gpa); const scratch = fallback.allocator(); var builder: Builder = .empty; defer builder.deinit(scratch);
var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); builder.writeMatchKeyUtf8(scratch, &out.writer, c, text) catch |err| switch (err) { error.InvalidUtf8 => return error.InvalidUtf8, error.OutOfMemory, error.WriteFailed => return error.OutOfMemory, }; return out.toOwnedSlice(); }
test matchKeyAlloc { const gpa = std.testing.allocator; // Secondary strength: accents count and case does not. const c: Collator = .{ .options = .{ .strength = .secondary } };
const stored = try c.matchKeyAlloc(gpa, "Your R\u{00E9}sum\u{00E9}"); defer gpa.free(stored); const wanted = try c.matchKeyAlloc(gpa, "r\u{00E9}sum\u{00E9}"); defer gpa.free(wanted); const unaccented = try c.matchKeyAlloc(gpa, "resume"); defer gpa.free(unaccented);
try std.testing.expect(c.findMatchKey(stored, wanted) != null); try std.testing.expect(c.findMatchKey(stored, unaccented) == null); }
/// The same, for text already decoded to code points. pub fn matchKeyAllocCodePoints(c: Collator, gpa: Allocator, text: []const u21) Allocator.Error![]u8 { var buffer: [scratch_size]u8 = undefined; var fallback: std.heap.BufferFirstAllocator = .init(&buffer, gpa); const scratch = fallback.allocator(); var builder: Builder = .empty; defer builder.deinit(scratch);
var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); builder.writeMatchKey(scratch, &out.writer, c, text) catch |err| switch (err) { error.OutOfMemory, error.WriteFailed => return error.OutOfMemory, }; return out.toOwnedSlice(); }
test matchKeyAllocCodePoints { const gpa = std.testing.allocator; const c: Collator = .{ .options = .{ .strength = .primary } }; const decoded = try c.matchKeyAllocCodePoints(gpa, &.{ 'C', 'a', 'f', 0x00E9 }); defer gpa.free(decoded); const utf8 = try c.matchKeyAlloc(gpa, "cafe"); defer gpa.free(utf8); // Equal at primary strength, so equal keys. try std.testing.expectEqualSlices(u8, utf8, decoded); }
/// How many bytes one record of this collation's match keys is. Every /// match key it writes is a whole number of them. pub fn matchKeyWidth(c: Collator) usize { return key.matchKeyWidth(c.options, c.table.tailoring != null); }
test matchKeyWidth { const gpa = std.testing.allocator; const c: Collator = .{ .options = .{ .strength = .secondary } }; try std.testing.expectEqual(@as(usize, 4), c.matchKeyWidth());
// One record for each letter of "abc". const k = try c.matchKeyAlloc(gpa, "abc"); defer gpa.free(k); try std.testing.expectEqual(3 * c.matchKeyWidth(), k.len); }
/// Where `pattern_key` first occurs in `target_key`, both match keys from /// this collation, as a byte offset that is a whole number of records /// in -- or null if it does not occur. An empty pattern key, which is /// what a pattern that weighs nothing has, is found at zero. pub fn findMatchKey(c: Collator, target_key: []const u8, pattern_key: []const u8) ?usize { return key.findMatchKey(c.matchKeyWidth(), target_key, pattern_key); }
test findMatchKey { const gpa = std.testing.allocator; const c: Collator = .{ .options = .{ .strength = .primary } }; const target = try c.matchKeyAlloc(gpa, "a Caf\u{00E9}"); defer gpa.free(target); const pattern = try c.matchKeyAlloc(gpa, "cafe"); defer gpa.free(pattern);
// The space is shifted and has no record, so the pattern is found // after one record: the `a`. try std.testing.expectEqual(@as(?usize, c.matchKeyWidth()), c.findMatchKey(target, pattern)); }
/// 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 buffer: [2 * scratch_size + 2 * key_size]u8 = undefined; var fallback: std.heap.BufferFirstAllocator = .init(&buffer, gpa); const scratch = fallback.allocator();
// 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()); }
test order { const gpa = std.testing.allocator; const c: Collator = .{}; try std.testing.expectEqual(std.math.Order.lt, try c.order(gpa, "M\u{00E4}rtens", "Mueller")); // Case is a tertiary difference: lowercase first, by default. try std.testing.expectEqual(std.math.Order.lt, try c.order(gpa, "mueller", "Mueller"));
// At primary strength only the letters count. const primary: Collator = .{ .options = .{ .strength = .primary } }; try std.testing.expectEqual(std.math.Order.eq, try primary.order(gpa, "M\u{00FC}ller", "muller")); }};
/// 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);}
test orderKeys { const gpa = std.testing.allocator; const c: Collator = .{}; const names = [_][]const u8{ "Mueller", "Möller", "Märtens" };
// One key per name, then a plain byte comparison per pair. var keys: [names.len][]u8 = undefined; for (names, &keys) |name, *k| k.* = try c.sortKeyAlloc(gpa, name); defer for (keys) |k| gpa.free(k);
const Pair = struct { name: []const u8, key: []const u8 }; var pairs: [names.len]Pair = undefined; for (names, keys, &pairs) |name, k, *p| p.* = .{ .name = name, .key = k }; std.mem.sort(Pair, &pairs, {}, struct { fn lessThan(_: void, a: Pair, b: Pair) bool { return orderKeys(a.key, b.key) == .lt; } }.lessThan);
for (pairs, [_][]const u8{ "Märtens", "Möller", "Mueller" }) |p, expected| { try std.testing.expectEqualStrings(expected, p.name); }}
/// 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; }
test deinit { const gpa = std.testing.allocator; var builder: Builder = .empty; // Everything the builder grew is freed with it. defer builder.deinit(gpa); const k = try builder.sortKeyAlloc(gpa, .{}, "a fairly long string, to grow the scratch"); gpa.free(k); }
/// 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); }
test writeSortKey { const gpa = std.testing.allocator; var builder: Builder = .empty; defer builder.deinit(gpa);
// The key can go anywhere a writer can: here, a fixed buffer. var buf: [64]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try builder.writeSortKey(gpa, &w, .{ .options = .{ .strength = .primary } }, &.{ 'a', 'b' }); // 0061 ; [.2485.0020.0002] and 0062 ; [.24A4.0020.0002] try std.testing.expectEqualSlices(u8, &.{ 0x24, 0x85, 0x24, 0xA4 }, w.buffered()); }
/// 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); }
test writeSortKeyUtf8 { const gpa = std.testing.allocator; var builder: Builder = .empty; defer builder.deinit(gpa);
var buf: [64]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try builder.writeSortKeyUtf8(gpa, &w, .{ .options = .{ .strength = .primary } }, "ab"); try std.testing.expectEqualSlices(u8, &.{ 0x24, 0x85, 0x24, 0xA4 }, w.buffered());
try std.testing.expectError(error.InvalidUtf8, builder.writeSortKeyUtf8(gpa, &w, .{}, "\xff")); }
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(); }
test sortKeyAllocCodePoints { const gpa = std.testing.allocator; const c: Collator = .{}; var builder: Builder = .empty; defer builder.deinit(gpa);
const one = try builder.sortKeyAllocCodePoints(gpa, c, &.{ 'r', 0x00E9, 's', 'u', 'm', 0x00E9 }); defer gpa.free(one); // The same builder again, for a canonically equivalent spelling. const other = try builder.sortKeyAllocCodePoints(gpa, c, &.{ 'r', 'e', 0x0301, 's', 'u', 'm', 'e', 0x0301 }); defer gpa.free(other); try std.testing.expectEqualSlices(u8, one, other); }
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(); }
test sortKeyAlloc { const gpa = std.testing.allocator; const c: Collator = .{}; // One builder for the whole list, so its scratch is allocated once. var builder: Builder = .empty; defer builder.deinit(gpa);
const names = [_][]const u8{ "Märtens", "Möller", "Mueller" }; var keys: [names.len][]u8 = undefined; for (names, &keys) |name, *k| k.* = try builder.sortKeyAlloc(gpa, c, name); defer for (keys) |k| gpa.free(k);
try std.testing.expectEqual(std.math.Order.lt, orderKeys(keys[0], keys[1])); try std.testing.expectEqual(std.math.Order.lt, orderKeys(keys[1], keys[2])); }
/// Steps 1 and 2, then a match key rather than a sort key, written to /// `w`. See `Collator.matchKeyAlloc`. pub fn writeMatchKey( 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.writeMatchKey(w, c.options, c.table.tailoring != null, b.weighted.items, b.text.items); }
test writeMatchKey { const gpa = std.testing.allocator; var builder: Builder = .empty; defer builder.deinit(gpa);
var buf: [64]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try builder.writeMatchKey(gpa, &w, .{ .options = .{ .strength = .secondary } }, &.{ 'a', 'b' }); // A record per letter, primary then secondary. try std.testing.expectEqualSlices(u8, &.{ 0x24, 0x85, 0x00, 0x20, 0x24, 0xA4, 0x00, 0x20 }, w.buffered()); }
/// The same, for UTF-8 text. pub fn writeMatchKeyUtf8( 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.writeMatchKey(w, c.options, c.table.tailoring != null, b.weighted.items, b.text.items); }
test writeMatchKeyUtf8 { const gpa = std.testing.allocator; var builder: Builder = .empty; defer builder.deinit(gpa);
var buf: [64]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); // At primary strength, case and accents weigh nothing. try builder.writeMatchKeyUtf8(gpa, &w, .{ .options = .{ .strength = .primary } }, "\u{00C1}B"); try std.testing.expectEqualSlices(u8, &.{ 0x24, 0x85, 0x24, 0xA4 }, w.buffered()); }
pub fn matchKeyAllocCodePoints( b: *Builder, gpa: Allocator, c: Collator, text: []const u21, ) Allocator.Error![]u8 { var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); b.writeMatchKey(gpa, &out.writer, c, text) catch |err| switch (err) { error.OutOfMemory, error.WriteFailed => return error.OutOfMemory, }; return out.toOwnedSlice(); }
test matchKeyAllocCodePoints { const gpa = std.testing.allocator; const c: Collator = .{ .options = .{ .strength = .secondary } }; var builder: Builder = .empty; defer builder.deinit(gpa);
const target = try builder.matchKeyAllocCodePoints(gpa, c, &.{ 'x', 'A', 'b', 'y' }); defer gpa.free(target); const pattern = try builder.matchKeyAllocCodePoints(gpa, c, &.{ 'a', 'b' }); defer gpa.free(pattern); try std.testing.expectEqual(@as(?usize, c.matchKeyWidth()), c.findMatchKey(target, pattern)); }
pub fn matchKeyAlloc(b: *Builder, gpa: Allocator, c: Collator, text: []const u8) Error![]u8 { var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); b.writeMatchKeyUtf8(gpa, &out.writer, c, text) catch |err| switch (err) { error.InvalidUtf8 => return error.InvalidUtf8, error.OutOfMemory, error.WriteFailed => return error.OutOfMemory, }; return out.toOwnedSlice(); }
test matchKeyAlloc { const gpa = std.testing.allocator; const c: Collator = .{ .options = .{ .strength = .secondary } }; var builder: Builder = .empty; defer builder.deinit(gpa);
// Equal strings at this strength, equal keys -- so a key can be an // index entry, and a lookup a comparison of bytes. const stored = try builder.matchKeyAlloc(gpa, c, "R\u{00E9}sum\u{00E9}"); defer gpa.free(stored); const query = try builder.matchKeyAlloc(gpa, c, "r\u{00E9}sum\u{00E9}"); defer gpa.free(query); try std.testing.expectEqualSlices(u8, stored, query); }
/// 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); }
test weighUtf8 { const gpa = std.testing.allocator; var builder: Builder = .empty; defer builder.deinit(gpa);
// Shifted, the hyphen keeps its place but weighs nothing until the // fourth level. try builder.weighUtf8(gpa, .{}, "a-b"); try std.testing.expectEqual(@as(usize, 3), builder.weighted.items.len); try std.testing.expectEqual(Element.ignorable, builder.weighted.items[1].element); }
/// 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; }
test collationElements { const gpa = std.testing.allocator; var builder: Builder = .empty; defer builder.deinit(gpa);
// é is e and a combining acute after step 1, and each has an element: // 0065 ; [.24F8.0020.0002] and 0301 ; [.0000.0024.0002]. const elements_of = try builder.collationElements(gpa, .{}, &.{0x00E9}); try std.testing.expectEqualSlices(Element, &.{ .{ .primary = 0x24F8, .secondary = 0x0020, .tertiary = 0x0002 }, .{ .primary = 0, .secondary = 0x0024, .tertiary = 0x0002 }, }, elements_of); }
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 "U+FFFE joins fields that sort one after the other" { // Section 1.6, and section 10.1.5's rules for U+FFFE since UCA 18.0. A // whole-string reversal of the secondary level lets the accent on the // second field outrank the one on the first: "cote" + U+FFFE + "côté" // came after "côte" + U+FFFE + "cote" when the level was reversed end to // end, though "cote" is before "côte" in French order. // // A `-Drepertoire=` table that leaves U+FFFE out weighs it as unassigned, // which is a different collation and not the one this is about. if (!table.ducet.hasEntries(&.{ 'c', 'o', 't', 'e', 'f', 'l', 0x0301, 0x0302, 0x0001, 0xFFFE, 0x1D165 })) return error.SkipZigTest; const french: Collator = .{ .options = .{ .backwards_secondary = true } }; try testing.expectEqual( std.math.Order.lt, try french.order(testing.allocator, "cote\u{FFFE}côté", "côte\u{FFFE}cote"), );
// The conformance suite's witness for the identical level: both // ignorables vanish from the first three levels, and then U+FFFE has to // sort below U+0001. const identical: Collator = .{ .options = .{ .strength = .identical, .alternate = .non_ignorable, } }; try testing.expectEqual( std.math.Order.lt, try identical.order(testing.allocator, "l\u{FFFE}\u{1D165}f", "l\u{0001}\u{FFFE}f"), );}
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. 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 "an expansion weighs as the tailoring has it" { const locales = @import("locales"); if (!@hasDecl(locales, "hu")) return error.SkipZigTest; // Hungarian's `&cs<<<ccs/cs`: ccs is cs with cs again behind it, and cs // is a contraction only Hungarian has. Read from the root the extension // was c and s, and ccs sorted before "cscz"; as cs twice over it sorts // after, because cs follows c. const hungarian: Collator = .{ .table = table.ducet.tailored(&locales.hu), .options = .{ .alternate = .non_ignorable }, }; try testing.expectEqual(std.math.Order.gt, try hungarian.order(testing.allocator, "ccs", "cscz")); try testing.expectEqual(std.math.Order.gt, try hungarian.order(testing.allocator, "ddzs", "dzsdz"));}
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); }}
fn expectMatchKeys(c: Collator, a: []const u8, b: []const u8, equal: bool) !void { const ka = try c.matchKeyAlloc(testing.allocator, a); defer testing.allocator.free(ka); const kb = try c.matchKeyAlloc(testing.allocator, b); defer testing.allocator.free(kb); try testing.expectEqual(equal, std.mem.eql(u8, ka, kb));}
/// Where `pattern`'s match key is in `target`'s, in records.fn findMatchKeyRecord(c: Collator, target: []const u8, pattern: []const u8) !?usize { const t = try c.matchKeyAlloc(testing.allocator, target); defer testing.allocator.free(t); const p = try c.matchKeyAlloc(testing.allocator, pattern); defer testing.allocator.free(p); try testing.expectEqual(@as(usize, 0), t.len % c.matchKeyWidth()); const at = c.findMatchKey(t, p) orelse return null; return at / c.matchKeyWidth();}
test "match keys are equal when the strings match" { if (!inRepertoire(&.{ 'r', 'e', 's', 'u', 'm', 'R', 0x0301, '-' })) return error.SkipZigTest; const tertiary: Collator = .{}; try expectMatchKeys(tertiary, "resume", "resume", true); try expectMatchKeys(tertiary, "resume", "Resume", false); // Shifted punctuation weighs nothing below the fourth level. try expectMatchKeys(tertiary, "resume", "re-sume", true); // Canonically equivalent spellings. try expectMatchKeys(tertiary, "r\u{00E9}sum\u{00E9}", "re\u{0301}sume\u{0301}", true);
const secondary: Collator = .{ .options = .{ .strength = .secondary } }; try expectMatchKeys(secondary, "resume", "Resume", true); try expectMatchKeys(secondary, "resume", "r\u{00E9}sum\u{00E9}", false);
const primary: Collator = .{ .options = .{ .strength = .primary } }; try expectMatchKeys(primary, "resume", "R\u{00C9}SUM\u{00C9}", true);
// At the fourth level the hyphen counts again. const quaternary: Collator = .{ .options = .{ .strength = .quaternary } }; try expectMatchKeys(quaternary, "resume", "re-sume", false);
// And at identical strength only the NFD does, three bytes a code point. const identical: Collator = .{ .options = .{ .strength = .identical } }; try testing.expectEqual(@as(usize, 3), identical.matchKeyWidth()); try expectMatchKeys(identical, "r\u{00E9}sum\u{00E9}", "re\u{0301}sume\u{0301}", true); try expectMatchKeys(identical, "resume", "Resume", false);}
test "a match key is found inside a target's, record-aligned" { if (!inRepertoire(&.{ 'r', 'e', 's', 'u', 'm', 'R', 'a', ' ', 0x0301 })) return error.SkipZigTest; const secondary: Collator = .{ .options = .{ .strength = .secondary } }; // Record one, not two: the space is shifted and has no record. try testing.expectEqual(@as(?usize, 1), try findMatchKeyRecord(secondary, "a Resume", "resume")); try testing.expectEqual(@as(?usize, null), try findMatchKeyRecord(secondary, "a r\u{00E9}sum\u{00E9}", "resume")); // A pattern that weighs nothing is found at the start. try testing.expectEqual(@as(?usize, 0), try findMatchKeyRecord(secondary, "resume", ""));
// Bytes that straddle two records are not a match. try testing.expectEqual(@as(?usize, null), key.findMatchKey(2, &.{ 0, 1, 2, 3 }, &.{ 1, 2 })); try testing.expectEqual(@as(?usize, 2), key.findMatchKey(2, &.{ 0, 1, 1, 2, 1, 2 }, &.{ 1, 2 }));}
test "a match key has the levels its options ask for" { const c: Collator = .{}; try testing.expectEqual(@as(usize, 6), c.matchKeyWidth()); const primary: Collator = .{ .options = .{ .strength = .primary } }; try testing.expectEqual(@as(usize, 2), primary.matchKeyWidth()); // Section 5.1's case level, which honours case at secondary strength. const cased: Collator = .{ .options = .{ .strength = .secondary, .case_level = true } }; try testing.expectEqual(@as(usize, 6), cased.matchKeyWidth()); if (!inRepertoire(&.{ 'r', 'e', 's', 'u', 'm', 'R', 0x0301 })) return error.SkipZigTest; try expectMatchKeys(cased, "resume", "r\u{00E9}sum\u{00E9}", false); try expectMatchKeys(cased, "resume", "Resume", false); const case_only: Collator = .{ .options = .{ .strength = .primary, .case_level = true } }; // At primary strength the case level is not written, as in a sort key. try expectMatchKeys(case_only, "resume", "Resume", true);}
test "a tailoring's match keys" { const locales = @import("locales"); if (!@hasDecl(locales, "da")) return error.SkipZigTest; // Danish `&[before 1]ǀ<…<å<<<Å<<<aa` makes aa a tertiary variant of å. const danish: Collator = .{ .table = table.ducet.tailored(&locales.da), .options = .{ .strength = .secondary }, }; try testing.expectEqual(@as(usize, 6), danish.matchKeyWidth()); try expectMatchKeys(danish, "\u{00E5}", "aa", true); try testing.expectEqual(@as(?usize, 1), try findMatchKeyRecord(danish, "Haarby", "\u{00E5}"));}
test "a tailoring can make strings equal whose match keys differ" { const locales = @import("locales"); if (!@hasDecl(locales, "ar")) return error.SkipZigTest; // Arabic puts its tashkil where they weigh only at the tertiary level, // and dammatan's chain position there is high hamza's tertiary weight. // So a hamza and a dammatan, in either order, read the same weights level // by level and are equal -- but the elements holding those weights are // not, and neither are the match keys. const arabic: Collator = .{ .table = table.ducet.tailored(&locales.ar) }; try testing.expectEqual(.eq, try arabic.order(testing.allocator, "\u{0674}\u{064C}", "\u{064C}\u{0674}")); try expectMatchKeys(arabic, "\u{0674}\u{064C}", "\u{064C}\u{0674}", false);}