// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The four steps of UTS #10 section 7, put together. const std = @import("std"); const Allocator = std.mem.Allocator; const data = @import("data"); const Element = data.Element; const nfd = @import("nfd.zig"); const elements = @import("elements.zig"); const key = @import("key.zig"); const table = @import("table.zig"); const Options = key.Options; const Table = table.Table; pub const Error = error{ OutOfMemory, InvalidUtf8 }; /// A collation: a table, plus the parametric settings applied to it. /// /// Holds no allocation and is cheap to copy, because the table is comptime /// data and the settings are three fields. Sharing one between threads is /// fine; the scratch that building a key needs lives in `Builder`. pub const Collator = struct { /// The collation element table, optionally with a tailoring layered over /// it -- `table.ducet.tailored(&collate.locales.sv)`, say. A tailored /// table is still a table, so there is only the one field. table: Table = table.ducet, options: Options = .{}, /// Build a sort key for UTF-8 text. The caller owns the result. /// /// Sorting a list means building a key for each string and then /// comparing the keys, which is the entire point of the sort key: *n* /// key constructions and `n log n` byte comparisons, rather than `n log /// n` collations. For that case hoist a `Builder` and use it, so that the /// scratch is allocated once rather than per string. pub fn sortKeyAlloc(c: Collator, gpa: Allocator, text: []const u8) Error![]u8 { // The scratch comes off the stack for a string of ordinary length // and only reaches `gpa` for something long; the key itself is the // caller's and so is always `gpa`'s. What this saves is three // allocations and three frees per call, for buffers whose whole life // is this function. var 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<<<<<<`, 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