// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Steps 3 and 4, UTS #10 sections 7.3 and 7.4: turn an array of collation //! elements into a sort key, and compare two of them. //! //! Step 4 is `std.mem.order`. That is the whole reason step 3 exists: //! ordering *n* strings costs *n* key constructions and `n log n` byte //! comparisons rather than `n log n` collations. //! //! Every weight is a big-endian `u16` and every level is separated by two //! zero bytes, with one compression applied on top: section 9.1.4's //! run-length compression of every level that repeats itself -- the //! secondary, the tertiary, section 5.1's case level, and the fourth, where //! the technique has to be turned upside down because COMMON there is the //! largest weight the level can hold rather than one with room above it. //! `RunLength` below is that, and it takes 45% off a key for a string of //! ASCII and a further 21% to 33% off one built at quaternary strength, //! where that fourth level exists. //! //! The other techniques in section 9.1 are not applied, and the reasons are //! worth writing down because the data settles two of them: //! //! * **9.1.1, dropping the level separators.** Every non-zero tertiary //! weight in the root tables (0x02..0x1E) is below every non-zero //! secondary weight (0x20..0x0127), which is the condition -- but a //! tailoring's tertiary weights are chain positions rather than cases and //! Arabic's tashkil run to 43, above the lowest secondary, so the //! condition holds for the root collations and not for the tailored ones. //! Compression that applies to some collations and not others is worth //! less than it looks. //! * **9.1.2, the levels in eight bits.** The tertiary level fits -- 28 //! distinct non-zero weights, and 255 once `caseFirst` folds the case //! class in. The secondary level cannot: there are 264 distinct non-zero //! secondary weights filling 0x20..0x127 without a gap, and no //! reassignment fits 264 values plus room for synthetic weights into 255. //! Measured against run-length compression, narrowing the tertiary level //! alone was worth another two bytes a key, which is not worth a second //! set of separator-width rules. //! * **9.1.3, comparing as machine words.** The comparison is //! `std.mem.order`, which already goes a word at a time where it can. //! //! Section 9.4's zero-byte avoidance is not needed at all: a key here is a //! Zig slice, not a C string. //! //! A key is therefore only comparable with another key from the same //! collation built by the same version of this library. Nothing promises //! otherwise, and a stored key is not a stable identifier. const std = @import("std"); const Allocator = std.mem.Allocator; const data = @import("data"); const Element = data.Element; const Table = @import("table.zig").Table; /// How many levels a comparison looks at: the `strength` setting of section /// 8.1, declared in `data` so that a `Tailoring` can carry the one its /// locale's rules asked for. pub const Strength = data.Strength; /// What to do with variable collation elements: section 4, and the /// `alternate` setting of section 8.1. /// /// The default here is `shifted`, which is what the UCA specifies. LDML /// defaults to `non_ignorable` instead, and section 8.1 spells out that the /// two disagree; the conformance suite ships a file for each. /// Variable weighting, section 4: what happens to punctuation and other /// "variable" elements. Declared in `data` so that a `Tailoring` can carry /// the one its locale's rules asked for. pub const Alternate = data.Alternate; /// Which case sorts first at the tertiary level: the `caseFirst` setting of /// section 8.1, and what `xsl:sort case-order=` asks for. pub const CaseFirst = data.CaseFirst; pub const Options = struct { strength: Strength = .tertiary, alternate: Alternate = .shifted, /// Section 3.8.1. Some French dictionary traditions order accents from /// the end of the string backwards. UTS10-D46 permits this at any level, /// but says the only practical use is the second, which is why this is a /// bool and not a mask. backwards_secondary: bool = false, case_first: CaseFirst = .off, /// Section 5.1's `caseLevel`: compare case on a level of its own, between /// the secondary and the tertiary, and take it out of the tertiary. /// /// What it is for is comparing case without comparing anything else at /// the tertiary level -- `strength = .secondary` with this on ignores /// accents and honours case, which no single strength can express. /// Church Slavonic's rules ask for it; `cu` is the one CLDR locale that /// does. case_level: bool = false, /// These options with a tailoring's own settings applied. /// /// A locale's rules can ask for settings as well as weights -- Danish /// opens with `[caseFirst upper]` -- and those are the locale's defaults /// rather than the caller's decision, so they are applied on request and /// only where the rules actually said something: /// /// ``` /// const collator: collate.Collator = .{ /// .table = collate.cldr_root.tailored(&collate.locales.da), /// .options = (collate.Options{ .strength = .secondary }) /// .applying(collate.locales.da.settings), /// }; /// ``` /// /// Passing the settings rather than the tailoring keeps this a decision /// the caller writes down, which matters because `xsl:sort` and the like /// have their own opinion about case and it has to be able to win. pub fn applying(o: Options, settings: data.Settings) Options { var out = o; if (settings.strength) |strength| out.strength = strength; if (settings.case_level) |case_level| out.case_level = case_level; if (settings.case_first) |case_first| out.case_first = case_first; if (settings.backwards_secondary) |backwards| out.backwards_secondary = backwards; if (settings.alternate) |alternate| out.alternate = alternate; return out; } }; /// A tertiary weight with the case weight in front of it: the `p.s.t -> /// p.s.ct` row of [UTS #35 part 5][ldml] section 5.1's table of modified /// collation elements, for a collation with `caseFirst` set and no case /// level. /// /// Ordering by case and then by weight is what `caseFirst` means, and it is /// not the same as swapping Table 17's two cased bands over. The bands are /// interleaved with weights in neither of them -- 0x14 is `` and 0x1D /// is its uppercase counterpart, with nine other assignments between them -- /// so swapping 0x1C against 0x1D as a pair leaves ᴴ (0x1D) after ͪ (0x04) /// whichever way round the pair goes, where ICU puts every uppercase form /// before every lowercase one. Danish asks for that with `[caseFirst upper]`, /// and it was 346 of its 6,786 comparisons. /// /// The multiplier is the size of the tertiary field rather than a constant, /// because the case weight has to sit entirely above the tertiary one: with a /// six-bit field and a multiplier of 0x20, case 1 weight 0x21 and case 2 /// weight 0x01 would both come to 0x41 and two different cases would weigh /// the same. /// /// The result is up to eight bits rather than six, which is one reason a sort /// key is built from `u16` weights rather than from the element's own field /// widths. /// /// [ldml]: https://www.unicode.org/reports/tr35/tr35-collation.html fn caseWeight(element: Element, case_first: CaseFirst) u16 { if (case_first == .off) return element.tertiary; const cases = 1 << @bitSizeOf(@FieldType(Element, "tertiary")); return caseWeightOf(element, case_first) * cases + element.tertiary; } /// Section 5.1's case weight `c`: 1, 2 or 3, by `caseFirst`. /// /// "If CaseFirst=UpperFirst, set c = UPPER ? 1 : MIXED ? 2 : 3. Otherwise set /// c = UPPER ? 3 : MIXED ? 2 : 1." Lowercase and uncased are the same value, /// which is why `Element.case` has three values and not four. /// /// A *tertiary* collation element -- one whose primary and secondary weights /// are both zero and whose tertiary weight is not -- takes the constant 3 /// instead, whatever its case bits and whatever `caseFirst` asks for. The /// specification is explicit about why: UCA well-formedness condition 2 wants /// a tertiary element's combined weight above every primary and secondary /// element's, its tertiary weight `T` is already above every such element's /// `t`, and "it must not be affected by caseFirst=upper". Breton, Ewe and /// Vietnamese all noticed when it was. fn caseWeightOf(element: Element, case_first: CaseFirst) u16 { if (element.primary == 0 and element.secondary == 0) return 3; return switch (case_first) { .off, .lower_first => switch (element.case) { .lower => 1, .mixed => 2, .upper => 3, }, .upper_first => switch (element.case) { .upper => 1, .mixed => 2, .lower => 3, }, }; } /// Section 9.1.4's run-length compression of one level. /// /// Sort keys repeat themselves below the first level: 0x0020 is 94.6% of the /// root tables' non-zero secondary weights and 0x0002 is 80.0% of their /// tertiaries -- the non-zero ones being the only ones a key writes -- and a /// string of unaccented lowercase Latin letters has nothing else at either. /// Section 9.1.4 replaces each maximal run of that most common /// weight -- COMMON -- with a single synthetic weight standing for the run's /// length, which takes 45% off an ASCII key. /// /// It works by moving the real weights out of the middle of the `u16` space /// and spending the gap on the synthetic ones. A weight at or below COMMON /// keeps its value, so the low band ends at COMMON; a weight above COMMON /// moves to the top of the space, so the high band begins at `maxbottom`. /// Between them is the gap. /// /// Which end of the gap a run is written in is what makes the order come out /// right, and it depends on the weight that *follows* the run: /// /// * Followed by something below COMMON, or by nothing at all, the run /// becomes `common + length`. A longer run then sorts **higher**, which is /// right: more of a weight that is higher than what follows it. /// * Followed by something above COMMON, it becomes `maxbottom - length`. A /// longer run then sorts **lower**, which is the same statement read the /// other way. /// /// `bound` splits the gap between the two kinds. A run too long for one /// synthetic weight becomes a sequence -- copies of whichever value sits /// against `bound` on its own side, each standing for as much length as a /// single weight can hold, then one weight for the remainder -- which needs a /// run of more than 32,000 identical weights to arise, so there is a test /// that builds one. const RunLength = struct { /// The most common weight at this level, which is also the top of the low /// band, since nothing below COMMON moves. common: u16, /// What is added to a weight above COMMON to lift it into the high band. shift: u16, /// The bottom of the high band: COMMON + 1, lifted. Wider than a weight /// because it need not be one: where COMMON is itself the largest weight /// the level can hold -- the case level under `upper_first`, where a /// lowercase letter takes the uppermost of the three classes -- there is /// nothing above COMMON to lift, this is one past the top of the space, /// and the high branch that would read it cannot be reached. maxbottom: u32, /// The bottom of the low synthetic band, which the first synthetic weight /// sits one above. At the levels where COMMON adjoins the weights below /// it this is COMMON itself; at the fourth level, where COMMON is the /// largest weight the level can hold, the band has to start below it /// instead. low_base: u16, /// Where the low synthetic weights stop and the high ones begin, which is /// the middle of the gap. Both kinds are common enough to want half of /// it: a run followed by nothing is a low one, and that is the whole /// secondary level of every ASCII string, while a run followed by an /// accent is a high one. bound: u16, /// COMMON adjoining the weights below it: everything at or below it keeps /// its value and everything above is lifted to the top of the space, so /// the gap opens immediately above COMMON. fn init(common: u16, max: u16) RunLength { const shift = std.math.maxInt(u16) - max; return .{ .common = common, .shift = shift, .maxbottom = @as(u32, common) + 1 + shift, .low_base = common, .bound = 0x8000, }; } /// COMMON at the very top of the space, which is the fourth level: the /// weight `shifted` gives everything that is not variable is /// `max_quaternary`, and no weight can be above it. Nothing is lifted -- /// the other weights there are variable *primary* weights and stay where /// they are -- and the gap is taken from below COMMON instead, between /// `real_top` and COMMON itself. /// /// There are weights above COMMON all the same, in a tailored collation, /// because the level is written as pairs there and a `<<<<` relation /// gives an element the pair `(max_quaternary, q)` with `q` above zero. /// Those pairs begin with COMMON's own value, so they are above COMMON as /// *pairs* while sharing its first weight -- which is why the synthetic /// weights have to stay below COMMON rather than above it. fn initAtTop(common: u16, real_top: u16) RunLength { // One *above* the highest real weight, not equal to it. A run whose // length is an exact multiple of what one synthetic weight can hold // ends its sequence with `low_base` itself, and that value has to be // one no real weight can take. At the levels where `low_base` is // COMMON the question does not arise -- a weight equal to COMMON is // part of a run by definition and never written as itself. const low_base = real_top + 1; return .{ .common = common, .shift = 0, .maxbottom = common, .low_base = low_base, .bound = low_base + (common - low_base) / 2, }; } /// The levels this is applied to, and what COMMON is at each. /// /// The first level is the one that is not compressed: a primary weight is /// what tells one string from another, and runs of one are rare. fn forLevel(level: usize, case_in_tertiary: bool, case_first: CaseFirst) ?RunLength { const classes = 1 << @bitSizeOf(@FieldType(Element, "tertiary")); return switch (level) { 1 => init(0x0020, std.math.maxInt(@FieldType(Element, "secondary"))), // With `caseFirst` folded in, a tertiary weight is the case class // times the tertiary field's width plus the tertiary weight -- // so COMMON moves to the *uppermost* class under `upper_first`, // which is where an ordinary lowercase letter lands, and the // level is as wide as three classes. 2 => if (case_in_tertiary) init( @as(u16, if (case_first == .upper_first) 3 else 1) * classes + 0x0002, 3 * classes + std.math.maxInt(@FieldType(Element, "tertiary")), ) else init(0x0002, std.math.maxInt(@FieldType(Element, "tertiary"))), 3 => initAtTop(max_quaternary, quaternary_real_top), else => null, }; } /// Section 5.1's case level, whose weights are the three case classes and /// whose COMMON is whichever of them an uncased or lowercase letter gets. fn forCaseLevel(case_first: CaseFirst) RunLength { return init(if (case_first == .upper_first) 3 else 1, 3); } inline fn map(r: RunLength, weight: u16) u16 { return if (weight > r.common) weight + r.shift else weight; } /// One run of COMMON, `length` long, with `next` the weight behind it -- /// null at the end of the level, which counts as below COMMON because a /// level that has ended is below every weight that could continue it. inline fn flush( r: RunLength, w: *std.Io.Writer, length: usize, next: ?u16, ) std.Io.Writer.Error!void { if (length == 0) return; var left = length; if (next == null or next.? < r.common) { // The most one low synthetic weight can hold, which is what each // copy of `bound - 1` stands for. What is left after them is // strictly less than that, so the final weight is below // `bound - 1` and a longer run always sorts above a shorter one. const each = r.bound - 1 - r.low_base; while (left >= each) : (left -= each) try writeWeight(w, r.bound - 1); try writeWeight(w, r.low_base + @as(u16, @intCast(left))); } else { const each: u32 = r.maxbottom - r.bound; while (left >= each) : (left -= each) try writeWeight(w, r.bound); try writeWeight(w, @intCast(r.maxbottom - left)); } } }; /// One level being written with `RunLength` compression: the weights are /// handed over one at a time and the runs are counted as they go. /// /// The three places that write a compressible level -- the secondary level, /// the tertiary level, and section 5.1's case level -- all produce their /// weights differently, and this is what they share. No lookahead is needed /// to decide which end of the gap a run belongs in: the weight that settles /// it is the one that ends the run, which is the weight arriving now. const Runs = struct { rle: RunLength, run: usize = 0, inline fn push(runs: *Runs, w: *std.Io.Writer, weight: u16) std.Io.Writer.Error!void { if (weight == runs.rle.common) { runs.run += 1; return; } try runs.rle.flush(w, runs.run, weight); runs.run = 0; try writeWeight(w, runs.rle.map(weight)); } /// The end of the level, where a run still open is followed by nothing. fn end(runs: *Runs, w: *std.Io.Writer) std.Io.Writer.Error!void { try runs.rle.flush(w, runs.run, null); runs.run = 0; } }; /// The weight `shifted` gives the fourth level of an element that is not /// variable and does not follow one. Section 4 notes any value above every /// variable primary weight would do; 0xFFFF is what the specification's own /// examples use. pub const max_quaternary: u16 = 0xFFFF; /// The highest weight the fourth level can hold that is not `max_quaternary`, /// which is what leaves room for run-length compression's synthetic weights /// between the two. /// /// Everything else on that level is a *variable primary* weight, and those /// occupy one low band of the primary space -- 0x0201..0x04E0 in both root /// tables, since well-formedness condition WF4 keeps them contiguous. A /// `[reorder]` can move primary weights about, so the band is not fixed by /// the table alone; across all 135 tailorings CLDR ships, none moves it at /// all -- the highest reordered variable primary is 0x04E0, exactly where it /// started. /// /// Half the space is left below the bound regardless, because relying on that /// measurement would be relying on data rather than on a guarantee, and a /// weight above the bound would misorder silently. `writeLevel` asserts it /// instead, and a test walks the band of every tailoring built. pub const quaternary_real_top: u16 = 0x7FFF; /// A collation element after variable weighting, carrying the fourth level /// that the table has nowhere to store. pub const Weighted = struct { element: Element, quaternary: u16, /// The low half of the fourth-level weight, for a tailored collation, /// which is one of two different things depending on what `quaternary` /// above is. /// /// When `shifted` moved a variable element's *primary* weight down here, /// it is that primary's sub-weight: in a tailored table a primary weight /// is a primary and a sub-weight together, the pair being one weight in /// two halves. Thai is the locale that proves it needs carrying: /// `&[before 1]<0E5A><<0E2F>` gives paiyannoi the angkhankhu's primary /// with a sub-weight of its own, and with the sub dropped the two came /// out equal under shifted handling where ICU orders them. /// /// Otherwise `quaternary` is `max_quaternary`, the marker that sits above /// every variable primary weight, and this is the element's own /// `Element.quaternary` -- the weight a `<<<<` relation gave it. The two /// uses share the level without meeting, because the marker is above /// every weight the other use can produce. quaternary_sub: u16 = 0, fn weightAt(w: Weighted, level: usize) u16 { return switch (level) { 0 => w.element.primary, 1 => w.element.secondary, 2 => w.element.tertiary, 3 => w.quaternary, else => unreachable, }; } }; /// S2.3 and section 4: apply variable weighting to `elements`, appending the /// result to `out`. /// /// The specification puts this in step 2, and for a single pass over a single /// string that is the same thing. It is a pass of its own here for two /// reasons: the element array stays exactly what the table says, which makes /// it worth keeping between calls and worth reading in a test; and the /// transformation is stateful left to right, so doing it once is the only way /// the sort key's levels -- which are each a separate pass over the elements /// -- can agree with each other. /// /// The one bit of state is section 4's "any sequence of ignorable collation /// elements that immediately follows the variable collation element is also /// affected". pub fn weigh( out: *std.ArrayList(Weighted), gpa: Allocator, table: Table, alternate: Alternate, elements: []const Element, ) Allocator.Error!void { try out.ensureUnusedCapacity(gpa, elements.len); if (alternate == .non_ignorable) { // A fourth level even here, where UTS #10 alone would have none: // `shifted` is not the only thing that can put a weight on it, since // a tailoring's `<<<<` relation does too, and that difference is not // conditional on how punctuation is handled. ICU agrees -- Japanese // orders hiragana before katakana at quaternary strength under either // alternate handling, and the two runs answer identically. // // For an untailored collation this is a level of one repeated weight, // which cannot change an ordering: two strings that are equal at the // first three levels have the same number of elements contributing to // each of them, so they have the same number here too. It costs two // bytes an element in a key built at quaternary strength or above, // and nothing at all at the default strength, where the level is not // written. for (elements) |e| out.appendAssumeCapacity(.{ .element = e, .quaternary = if (e.primary == 0 and e.secondary == 0 and e.tertiary == 0) 0 else max_quaternary, .quaternary_sub = e.quaternary, }); return; } const shifted = alternate != .blanked; var after_variable = false; for (elements) |e| { if (table.isVariable(e)) { after_variable = true; // Table 11: "L1 != 0, Variable" takes the old primary weight as // its fourth-level weight. out.appendAssumeCapacity(.{ .element = .ignorable, .quaternary = if (shifted) e.primary else 0, .quaternary_sub = if (shifted) e.primary_sub else 0, }); continue; } if (e.isPrimary()) { after_variable = false; out.appendAssumeCapacity(.{ .element = e, .quaternary = if (shifted) max_quaternary else 0, .quaternary_sub = if (shifted) e.quaternary else 0, }); continue; } // An ignorable element: zero at every level if it follows a variable // one, untouched otherwise. if (after_variable) { out.appendAssumeCapacity(.{ .element = .ignorable, .quaternary = 0 }); continue; } // A completely ignorable element stays completely ignorable. Table // 11's first row gives it a fourth-level weight of zero, not FFFF. const completely = e.primary == 0 and e.secondary == 0 and e.tertiary == 0; out.appendAssumeCapacity(.{ .element = e, .quaternary = if (shifted and !completely) max_quaternary else 0, .quaternary_sub = if (shifted and !completely) e.quaternary else 0, }); } } /// S3.1 through S3.10: write the sort key for `weighted` to `w`. /// /// `text` is the NFD of the input, needed only for the identical level; it /// may be empty at any lesser strength. pub fn write( w: *std.Io.Writer, options: Options, /// The collation's tailoring, if it has one. /// /// Two things depend on it. Level one carries `Element.primary_sub` /// behind each primary weight only for a tailored collation, so that an /// untailored key is byte for byte what it was before tailorings existed /// -- which is the encoding both conformance suites pass on. And a /// tailoring may reorder the primary weight space. tailoring: ?*const data.Tailoring, weighted: []const Weighted, text: []const u21, ) std.Io.Writer.Error!void { const levels = options.strength.levels(); var level: usize = 0; while (level < levels) : (level += 1) { try writeLevel(w, options, tailoring, weighted, level); } // The case level again, for a collation that stops at the secondary // level: `strength = .secondary` with `case_level` is the combination the // setting exists for -- ignore accents, honour case -- and the loop above // never reaches the level the case level sits in front of. if (options.case_level and levels == 2) { try w.writeAll(&.{ 0, 0 }); try writeCaseLevel(w, options, weighted); } try writeIdenticalLevel(w, options, text); } /// One level of a sort key, separator and all. /// /// Split out so that a comparison can write a level, compare it, and stop -- /// section 9.7's incremental comparison, which `Collator.order` does. The /// levels of a key are independent in exactly this way: two keys whose /// earlier levels are equal have the same number of weights at each of them, /// so comparing level by level gives the same answer as comparing the whole, /// and a level that runs out first compares less either way because the /// separator is zero and no written weight is. pub fn writeLevel( w: *std.Io.Writer, options: Options, tailoring: ?*const data.Tailoring, weighted: []const Weighted, level: usize, ) std.Io.Writer.Error!void { const tailored = tailoring != null; const ranges: []const data.ReorderRange = if (tailoring) |t| t.reorder else &.{}; { // S3.2. Zero is below every weight that can be emitted, because S3.5 // skips the zero ones. That is what gives the key its prefix // property: "abc" sorts before "abcX" for any X. if (level != 0) try w.writeAll(&.{ 0, 0 }); // S3.6 to S3.9: at a level the table is backwards at, the same // weights go in the other order. if (level == 1 and options.backwards_secondary) { // Compressed the same way, over the reversed sequence: what // 9.1.4 needs is a sequence whose order must be preserved, and // reversing happens before compression rather than after. var runs: Runs = .{ .rle = RunLength.forLevel(level, false, options.case_first).? }; var i = weighted.len; while (i > 0) { i -= 1; const weight = weighted[i].weightAt(level); if (weight == 0) continue; try runs.push(w, weight); } try runs.end(w); return; } // S3.3 to S3.5 at level one, where a tailored collation has a // sub-weight to write behind each primary weight. A zero primary is // skipped along with its sub-weight, which is what keeps the prefix // property: the pair is one weight in two halves. if (level == 0 and tailored) { for (weighted) |x| { if (x.element.primary == 0) continue; try writeWeight(w, reorderPrimary(ranges, x.element.primary)); try writeWeight(w, x.element.primary_sub); } return; } // And the fourth level of a tailored collation, which holds primary // weights that `shifted` moved down and so needs the same pair. The // `shift_trimmed` variant drops trailing maximum weights here, pair // and all. if (level == 3 and tailored) { // Compressed, with the *pair* as the unit: a run is however many // `(max_quaternary, 0)` pairs came in a row, and the pair behind // it picks the band. That works on the first weight alone even // though the unit is two wide, because a pair above COMMON can // only be `(max_quaternary, q)` -- it begins with COMMON's own // weight, which is not below it, which is the high band. A // variable element's pair begins with its primary weight, which // is below COMMON, which is the low band. var runs: Runs = .{ .rle = RunLength.forLevel(level, false, options.case_first).? }; var trailing: usize = 0; for (weighted) |x| { if (x.quaternary == 0) continue; const is_common = x.quaternary == max_quaternary and x.quaternary_sub == 0; if (is_common) { // `shift_trimmed` drops these if nothing follows them, so // they are held rather than counted into the run until // something does. if (options.alternate == .shift_trimmed) trailing += 1 else runs.run += 1; continue; } // Something followed after all, so the held pairs are a run // like any other. runs.run += trailing; trailing = 0; const weight = reorderPrimary(ranges, x.quaternary); std.debug.assert(weight <= quaternary_real_top or weight == max_quaternary); try runs.rle.flush(w, runs.run, weight); runs.run = 0; try writeWeight(w, weight); try writeWeight(w, x.quaternary_sub); } try runs.end(w); return; } // Section 5.1's case level, between the secondary and the tertiary. if (level == 2 and options.case_level) try writeCaseLevel(w, options, weighted); // S3.3 to S3.5. // // `caseFirst` is folded into the tertiary weight here when there is no // case level to carry it -- section 5.1's `p.s.t -> p.s.ct`. With a // case level the tertiary weight is written *unmodified*, which is // what that table says at every strength: the case goes on its own // level and `t` stays `t`. Folding the cased band onto the uncased // one as well was wrong twice over -- it is not what the // specification asks for, and a tailoring's tertiary weights are // chain positions rather than cases, so Arabic's tashkil, which run // from 1 to 43, had nine of them moved down by six. const case_in_tertiary = level == 2 and options.case_first != .off and !options.case_level; var runs: ?Runs = if (RunLength.forLevel(level, case_in_tertiary, options.case_first)) |r| .{ .rle = r } else null; var trailing: usize = 0; for (weighted) |x| { const raw = x.weightAt(level); const weight = if (case_in_tertiary) caseWeight(x.element, options.case_first) else if (level == 0 or level == 3) // Level three holds what `shifted` took from a variable // element, which is a value in the *primary* space, so it // reorders too: section 3.x is explicit that reordering // applies to a primary weight "regardless of whether it is // regular or shifted". reorderPrimary(ranges, raw) else raw; // S3.5 skips a *zero weight*, and the weight it means is the // one in the element rather than whatever `caseFirst` folded into // it. With the case weight in front, an element that weighs // nothing at this level comes out as class * 0x40, which is not // zero for the class that sorts second -- and `shifted` turns // every variable element into a completely ignorable one, so // Danish wrote a phantom tertiary weight for each parenthesis it // had just shifted away. It was 21 of its 8,778 comparisons under // `[caseFirst upper]`, all of them a parenthesized H against some // other compatibility H. if (raw == 0) continue; // `shift_trimmed` drops trailing maximum quaternary weights, so // they are counted rather than written until something else turns // up behind them. if (level == 3 and options.alternate == .shift_trimmed and weight == max_quaternary) { trailing += 1; continue; } if (runs) |*r| { // A tail `shift_trimmed` was holding, which something has now // turned up behind: those weights are COMMON, so they join // the run rather than being written out one by one. r.run += trailing; trailing = 0; if (level == 3) std.debug.assert(weight <= quaternary_real_top or weight == max_quaternary); try r.push(w, weight); continue; } while (trailing > 0) : (trailing -= 1) try writeWeight(w, max_quaternary); try writeWeight(w, weight); } if (runs) |*r| try r.end(w); } } /// S3.10: the identical level, which is the NFD of the string itself. pub fn writeIdenticalLevel( w: *std.Io.Writer, options: Options, text: []const u21, ) std.Io.Writer.Error!void { if (options.strength == .identical) { try w.writeAll(&.{ 0, 0 }); // Three big-endian bytes a code point rather than UTF-8. UTF-8 would // order the same way, but it cannot encode a surrogate, and the // conformance suite of section 12.2 contains lines that hold one -- // deliberately, to see what an implementation does with ill-formed // input. This encoding has an answer for every value a `u21` can hold // and still orders by code point. for (text) |cp| { try w.writeAll(&.{ @intCast((cp >> 16) & 0xFF), @intCast((cp >> 8) & 0xFF), @intCast(cp & 0xFF), }); } } } /// Section 5.1's case level: one weight per element, the case weight and /// nothing else, followed by a separator. /// /// Which elements contribute is the whole of the difference between this and /// a naive reading, and section 5.1's table says it twice over: /// /// * A *secondary ignorable* element -- zero primary, zero secondary -- /// contributes nothing, at any strength. That is the row `0.0.T -> /// 0.0.0.T`, commented "ignore case level weights of secondary-ignorable /// CEs", and it covers the completely ignorable elements too. Arabic is /// what says so: the tashkil are forty-three such elements, and giving /// each one a case weight made a string of two of them differ from a /// string of one at a level above the one the rule is about. /// * At *primary* strength a primary-ignorable element -- zero primary, /// non-zero secondary -- contributes nothing either: the row `0.S.t -> /// 0.0`, so that "ignore accents but not case" really does ignore them. /// /// Everything else contributes `c`, which is 1, 2 or 3 and so never zero. A /// zero weight would be skipped by S3.5, and skipping the lowercase elements /// would lose the prefix property that makes "abc" sort before "abcX". /// `writeCaseLevel` for `Collator.order`, which has to write the levels /// `write` writes after its own loop. pub fn writeCaseLevelPublic( w: *std.Io.Writer, options: Options, weighted: []const Weighted, ) std.Io.Writer.Error!void { return writeCaseLevel(w, options, weighted); } fn writeCaseLevel( w: *std.Io.Writer, options: Options, weighted: []const Weighted, ) std.Io.Writer.Error!void { var runs: Runs = .{ .rle = .forCaseLevel(options.case_first) }; for (weighted) |x| { const e = x.element; if (e.primary == 0 and e.secondary == 0) continue; if (e.primary == 0 and options.strength == .primary) continue; try runs.push(w, caseWeightOf(e, options.case_first)); } try runs.end(w); try w.writeAll(&.{ 0, 0 }); } /// Where a primary weight lands after reordering. /// /// A weight in no range does not move, which is how the TRAILING group, /// U+FFFE's field separator and every zero primary stay where they are -- /// the three things the specification exempts. fn reorderPrimary(ranges: []const data.ReorderRange, primary: u16) u16 { if (primary == 0 or ranges.len == 0) return primary; var lo: usize = 0; var hi: usize = ranges.len; while (lo < hi) { const mid = lo + (hi - lo) / 2; const r = ranges[mid]; if (primary < r.first) { hi = mid; } else if (primary > r.last) { lo = mid + 1; } else { return @intCast(@as(i32, primary) + r.offset); } } return primary; } fn writeWeight(w: *std.Io.Writer, weight: u16) std.Io.Writer.Error!void { try w.writeAll(&.{ @intCast(weight >> 8), @intCast(weight & 0xFF) }); } /// Step 4. The comparison is a plain binary one; the levels are already in /// the bytes. pub fn order(a: []const u8, b: []const u8) std.math.Order { return std.mem.order(u8, a, b); } const testing = std.testing; const ducet = @import("table.zig").ducet; /// A comparison through a tailored key, for the tests that need the fourth /// level's low half written -- which only a tailored collation gets. fn orderTailored( options: Options, tailoring: *const data.Tailoring, a: []const Element, b: []const Element, ) !std.math.Order { const gpa = testing.allocator; var first: std.Io.Writer.Allocating = .init(gpa); defer first.deinit(); var second: std.Io.Writer.Allocating = .init(gpa); defer second.deinit(); for ([_][]const Element{ a, b }, [_]*std.Io.Writer.Allocating{ &first, &second }) |elements, out| { var weighted: std.ArrayList(Weighted) = .empty; defer weighted.deinit(gpa); try weigh(&weighted, gpa, ducet, options.alternate, elements); try write(&out.writer, options, tailoring, weighted.items, &.{}); } return order(first.written(), second.written()); } /// Whether the DUCET table holds the ASCII characters the specification's /// examples are written with; see `table.haveAsciiExamples`, which this is /// the same question as -- a build restricted by `-Drepertoire=` need not, /// and these tests read elements straight out of the table. fn haveAsciiExamples() bool { return ducet.hasEntries(&.{ ' ', '!', '-', 'A', 'a', 'b', 'c', 'd', 'z' }); } fn keyOf(gpa: Allocator, options: Options, elements: []const Element, text: []const u21) ![]u8 { var weighted: std.ArrayList(Weighted) = .empty; defer weighted.deinit(gpa); try weigh(&weighted, gpa, ducet, options.alternate, elements); var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); try write(&out.writer, options, null, weighted.items, text); return out.toOwnedSlice(); } test "shift_trimmed is shifted with the trailing run taken off" { if (!haveAsciiExamples()) return error.SkipZigTest; // Section 4 defines `shift_trimmed` as `shifted` with the fourth level's // trailing maximum weights removed, and nothing else in this project // exercises it: the conformance files are `shifted` and `non_ignorable`, // ICU has no mode for it, and no CLDR locale asks for it. So the // definition is checked here directly, against the *compressed* // encoding, where "the trailing weights" is one synthetic weight standing // for the whole run and taking it off means writing nothing at all. // // U+0020 is variable in DUCET and 'a' is not, which is the whole // ingredient list: a fourth level of maximum weights with a space's // primary weight somewhere among them. var a_scratch: [1]Element = undefined; var space_scratch: [1]Element = undefined; const a = ducet.elementsOf(ducet.entry('a'), &a_scratch)[0]; const space = ducet.elementsOf(ducet.entry(' '), &space_scratch)[0]; try testing.expect(ducet.isVariable(space)); try testing.expect(!ducet.isVariable(a)); const shifted: Options = .{ .strength = .quaternary, .alternate = .shifted }; const trimmed: Options = .{ .strength = .quaternary, .alternate = .shift_trimmed }; // Ending in non-variable elements, so the fourth level ends in a run of // maximum weights: trimming takes the synthetic weight off, and the // trimmed key is the shifted one two bytes shorter. for ([_][]const Element{ &.{a}, &.{ a, a }, &.{ a, a, a }, &.{ space, a }, &.{ a, space, a, a }, }) |elements| { const full = try keyOf(testing.allocator, shifted, elements, &.{}); defer testing.allocator.free(full); const short = try keyOf(testing.allocator, trimmed, elements, &.{}); defer testing.allocator.free(short); try testing.expectEqual(full.len - 2, short.len); try testing.expectEqualSlices(u8, full[0 .. full.len - 2], short); } // Ending in a variable element, so there is no trailing run to take off // and the two are the same key. The interior run is still compressed -- // that is what distinguishes trimming a tail from dropping every maximum // weight, and getting it wrong would make these two differ. for ([_][]const Element{ &.{space}, &.{ a, space }, &.{ a, a, space }, &.{ a, space, a, space }, }) |elements| { const full = try keyOf(testing.allocator, shifted, elements, &.{}); defer testing.allocator.free(full); const short = try keyOf(testing.allocator, trimmed, elements, &.{}); defer testing.allocator.free(short); try testing.expectEqualSlices(u8, full, short); } } test "no reordering lifts a variable primary weight above the fourth level's bound" { // What `quaternary_real_top` claims, checked rather than trusted. Every // weight the fourth level holds is either `max_quaternary` or a variable // primary weight, and a `[reorder]` is free to move the latter -- so the // bound is only sound while no tailoring moves one above it. This walks // the whole variable band of every tailoring the build was asked for and // reports the worst it finds, which is why it is worth running with // `-Dlocales` naming a lot of them. const locales = @import("locales"); const t = if (@import("table.zig").cldr_root.stage1.len != 0) @import("table.zig").cldr_root else @import("table.zig").ducet; if (t.stage1.len == 0) return error.SkipZigTest; try testing.expect(t.max_variable_primary <= quaternary_real_top); inline for (@typeInfo(locales).@"struct".decls) |decl| { const field = @field(locales, decl.name); if (@TypeOf(field) == data.Tailoring) { var p: u32 = t.min_variable_primary; while (p <= t.max_variable_primary) : (p += 1) { const moved = reorderPrimary(field.reorder, @intCast(p)); if (moved > quaternary_real_top) { std.debug.print( "{s} reorders variable primary 0x{X} to 0x{X}, above the bound 0x{X}\n", .{ decl.name, p, moved, quaternary_real_top }, ); return error.TestUnexpectedResult; } } } } } test "compressing a run does not change how two levels compare" { // Section 9.1.4's claim is that it "results in keys that are never longer // than the original, are generally much shorter, and result in the same // comparisons". The first and the third are checkable directly: encode a // set of levels both ways, compare every pair, and require the two // answers to agree. // // A level here is a run of COMMON with one weight behind it, which is the // shape the encoding actually turns on -- a run followed by a lower // weight or by nothing goes in the bottom of the gap, one followed by a // higher weight goes in the top. The run lengths cross the point where a // single synthetic weight can no longer hold the length and a sequence of // them takes over, which needs 32,735 identical secondary weights in a // row: no corpus reaches that, so it is reached here on purpose. const rle = RunLength.forLevel(1, false, .off).?; const low_each: usize = rle.bound - 1 - rle.low_base; const high_each: usize = rle.maxbottom - rle.bound; const Level = struct { run: usize, next: ?u16 }; var levels: std.ArrayList(Level) = .empty; defer levels.deinit(testing.allocator); for ([_]usize{ 0, 1, 2, 3, low_each - 1, low_each, low_each + 1, 2 * low_each, 2 * low_each + 1, high_each - 1, high_each, high_each + 1, 2 * high_each, 2 * high_each + 3, }) |run| { // Nothing behind the run, something below COMMON, something just // above it, and the widest weight the level can hold. for ([_]?u16{ null, 0x0010, 0x0021, 0x01FF }) |next| { try levels.append(testing.allocator, .{ .run = run, .next = next }); } } var raw: std.ArrayList([]u8) = .empty; defer { for (raw.items) |bytes| testing.allocator.free(bytes); raw.deinit(testing.allocator); } var packed_keys: std.ArrayList([]u8) = .empty; defer { for (packed_keys.items) |bytes| testing.allocator.free(bytes); packed_keys.deinit(testing.allocator); } for (levels.items) |level| { var uncompressed: std.Io.Writer.Allocating = .init(testing.allocator); errdefer uncompressed.deinit(); for (0..level.run) |_| try writeWeight(&uncompressed.writer, rle.common); if (level.next) |next| try writeWeight(&uncompressed.writer, next); try raw.append(testing.allocator, try uncompressed.toOwnedSlice()); var compressed: std.Io.Writer.Allocating = .init(testing.allocator); errdefer compressed.deinit(); var runs: Runs = .{ .rle = rle }; for (0..level.run) |_| try runs.push(&compressed.writer, rle.common); if (level.next) |next| try runs.push(&compressed.writer, next); try runs.end(&compressed.writer); try packed_keys.append(testing.allocator, try compressed.toOwnedSlice()); } for (raw.items, packed_keys.items, levels.items) |a_raw, a_packed, a_level| { // Never longer, which is the other half of the claim. try testing.expect(a_packed.len <= a_raw.len); for (raw.items, packed_keys.items, levels.items) |b_raw, b_packed, b_level| { const want = order(a_raw, b_raw); const got = order(a_packed, b_packed); if (want != got) { std.debug.print( "run {d} then {?x} against run {d} then {?x}: raw says {t}, compressed says {t}\n", .{ a_level.run, a_level.next, b_level.run, b_level.next, want, got }, ); return error.TestUnexpectedResult; } } } } test "weights are appended level by level, with separators" { const a: Element = .{ .primary = 0x0706, .secondary = 0x0020, .tertiary = 0x0002 }; const b: Element = .{ .primary = 0x06D9, .secondary = 0x0020, .tertiary = 0x0008 }; const key = try keyOf(testing.allocator, .{ .strength = .tertiary, .alternate = .non_ignorable }, &.{ a, b }, &.{}); defer testing.allocator.free(key); // Levels two and three are run-length compressed, section 9.1.4, and // between them they show both halves of it. // // Level two is two secondaries of 0x0020, which is COMMON there, and // nothing follows them -- so the pair becomes one low synthetic weight, // COMMON + 2 = 0x0022. // // Level three is 0x0002, which is COMMON, and then 0x0008, which is // above it. A run followed by a higher weight becomes a *high* synthetic // weight, so that a longer run sorts below a shorter one: MAXBOTTOM - 1, // where MAXBOTTOM is COMMON + 1 lifted to the top of the space by // 0xFFFF - 0x3F, the widest tertiary weight. Then 0x0008 itself, lifted // by the same amount. try testing.expectEqualSlices(u8, &.{ 0x07, 0x06, 0x06, 0xD9, // level 1, uncompressed 0x00, 0x00, 0x00, 0x22, // level 2: a run of two, nothing behind it 0x00, 0x00, 0xFF, 0xC2, 0xFF, 0xC8, // level 3: a run of one, then 0x0008 }, key); } test "zero weights are skipped, which is what gives the prefix property" { // A secondary collation element contributes nothing to level 1, so // "a" and "a" have the same primary level and the shorter key is // a prefix of the longer. const a: Element = .{ .primary = 0x06D9, .secondary = 0x0020, .tertiary = 0x0002 }; const accent: Element = .{ .primary = 0, .secondary = 0x0021, .tertiary = 0x0002 }; const short = try keyOf(testing.allocator, .{ .strength = .primary, .alternate = .non_ignorable }, &.{a}, &.{}); defer testing.allocator.free(short); const long = try keyOf(testing.allocator, .{ .strength = .primary, .alternate = .non_ignorable }, &.{ a, accent }, &.{}); defer testing.allocator.free(long); try testing.expectEqualSlices(u8, short, long); } test "strength truncates the key" { const a: Element = .{ .primary = 0x06D9, .secondary = 0x0020, .tertiary = 0x0008 }; for ([_]Strength{ .primary, .secondary, .tertiary }) |strength| { const key = try keyOf(testing.allocator, .{ .strength = strength, .alternate = .non_ignorable }, &.{a}, &.{}); defer testing.allocator.free(key); // Two bytes a weight, two bytes a separator, one fewer separator // than levels. try testing.expectEqual(strength.levels() * 2 + (strength.levels() - 1) * 2, key.len); } } test "shifted moves a variable element to the fourth level" { if (!haveAsciiExamples()) return error.SkipZigTest; // SPACE is variable in DUCET. var scratch: [1]Element = undefined; const space = ducet.elementsOf(ducet.entry(' '), &scratch)[0]; try testing.expect(ducet.isVariable(space)); const key = try keyOf(testing.allocator, .{ .strength = .quaternary, .alternate = .shifted }, &.{space}, &.{}); defer testing.allocator.free(key); // Nothing at levels one to three, and the old primary weight at four. try testing.expectEqualSlices(u8, &.{ 0x00, 0x00, // 1 -> 2 0x00, 0x00, // 2 -> 3 0x00, 0x00, // 3 -> 4 @intCast(space.primary >> 8), @intCast(space.primary & 0xFF), }, key); } test "a shifted element writes no tertiary weight, caseFirst or not" { if (!haveAsciiExamples()) return error.SkipZigTest; // SPACE is variable, so `shifted` makes it completely ignorable and moves // its primary weight to the fourth level. It must then contribute nothing // to the third -- and with `caseFirst` folding the case weight into the // tertiary weight, "nothing" is not the same as "zero": the class of the // case that sorts second multiplied by the size of the tertiary field is // a perfectly good non-zero weight. Danish found this in 21 of its 8,778 // comparisons, a parenthesized H against some other compatibility H, // because `(` and `)` are variable and ICU writes nothing for them. var scratch: [1]Element = undefined; const space = ducet.elementsOf(ducet.entry(' '), &scratch)[0]; const h = ducet.elementsOf(ducet.entry('h'), &scratch)[0]; for ([_]CaseFirst{ .off, .upper_first, .lower_first }) |case_first| { const options: Options = .{ .strength = .tertiary, .alternate = .shifted, .case_first = case_first, }; const bare = try keyOf(testing.allocator, options, &.{h}, &.{}); defer testing.allocator.free(bare); const spaced = try keyOf(testing.allocator, options, &.{ space, h, space }, &.{}); defer testing.allocator.free(spaced); try testing.expectEqualSlices(u8, bare, spaced); } } test "the fourth level carries the sub-weight a tailoring inserted with" { // What `shifted` moves down is a *primary* weight, and in a tailored // collation a primary weight is a primary and a sub-weight together. Thai // is the locale that proves it: `&[before 1]<0E5A><<0E2F>` gives // paiyannoi the angkhankhu's primary with a sub-weight of its own, both // of them variable, and with the sub dropped the two compared equal under // shifted handling where ICU orders them. const first: Element = .{ .primary = 0x0432, .primary_sub = 0, .secondary = 0x20, .tertiary = 0x02 }; const second: Element = .{ .primary = 0x0432, .primary_sub = 1, .secondary = 0x20, .tertiary = 0x02 }; // A tailoring that reorders nothing: what matters is that there *is* one, // because that is what puts the sub-weights in the key. const none: data.Tailoring = .{ .locale = "test", .root = "ducet", .overrides = &.{}, .contractions = &.{}, .expansions = &.{}, }; const options: Options = .{ .strength = .quaternary, .alternate = .shifted }; var a: std.Io.Writer.Allocating = .init(testing.allocator); defer a.deinit(); var b: std.Io.Writer.Allocating = .init(testing.allocator); defer b.deinit(); try write(&a.writer, options, &none, &.{ .{ .element = .ignorable, .quaternary = first.primary, .quaternary_sub = first.primary_sub }, }, &.{}); try write(&b.writer, options, &none, &.{ .{ .element = .ignorable, .quaternary = second.primary, .quaternary_sub = second.primary_sub }, }, &.{}); try testing.expectEqual(std.math.Order.lt, order(a.written(), b.written())); } test "blanked and shifted differ only at the fourth level" { if (!haveAsciiExamples()) return error.SkipZigTest; var scratch: [1]Element = undefined; const space = ducet.elementsOf(ducet.entry(' '), &scratch)[0]; const a = ducet.elementsOf(ducet.entry('a'), &scratch)[0]; const blanked = try keyOf(testing.allocator, .{ .strength = .tertiary, .alternate = .blanked }, &.{ a, space, a }, &.{}); defer testing.allocator.free(blanked); const shifted = try keyOf(testing.allocator, .{ .strength = .tertiary, .alternate = .shifted }, &.{ a, space, a }, &.{}); defer testing.allocator.free(shifted); // At tertiary strength there is no fourth level to tell them apart. try testing.expectEqualSlices(u8, blanked, shifted); } test "a variable element swallows the ignorables that follow it" { if (!haveAsciiExamples()) return error.SkipZigTest; var scratch: [1]Element = undefined; const space = ducet.elementsOf(ducet.entry(' '), &scratch)[0]; // A combining grave after a space: section 4's own example, which "would // have the value [.0000.0000.0000.0000]". const grave: Element = .{ .primary = 0, .secondary = 0x0025, .tertiary = 0x0002 }; const key = try keyOf(testing.allocator, .{ .strength = .quaternary, .alternate = .shifted }, &.{ space, grave }, &.{}); defer testing.allocator.free(key); // Three separators, then the space's old primary weight and nothing for // the grave. try testing.expectEqual(@as(usize, 8), key.len); } test "the identical level distinguishes canonically distinct strings" { const a: Element = .{ .primary = 0x06D9, .secondary = 0x0020, .tertiary = 0x0002 }; const one = try keyOf(testing.allocator, .{ .strength = .identical }, &.{a}, &.{0x0041}); defer testing.allocator.free(one); const two = try keyOf(testing.allocator, .{ .strength = .identical }, &.{a}, &.{0x0042}); defer testing.allocator.free(two); try testing.expectEqual(std.math.Order.lt, order(one, two)); } test "case_first swaps the cased pairs of Table 17" { if (!haveAsciiExamples()) return error.SkipZigTest; // Lowercase a is [.23EC.0020.0002] and uppercase A is // [.23EC.0020.0008] -- the first pair in section 10.2's table, and the // one every cased script's plain letters use. var scratch: [1]Element = undefined; const lower = ducet.elementsOf(ducet.entry('a'), &scratch)[0]; var upper_scratch: [1]Element = undefined; const upper = ducet.elementsOf(ducet.entry('A'), &upper_scratch)[0]; try testing.expectEqual(@as(u16, 0x0002), lower.tertiary); try testing.expectEqual(@as(u16, 0x0008), upper.tertiary); // Off, the table's own order: lowercase first. const off_lower = try keyOf(testing.allocator, .{ .alternate = .non_ignorable }, &.{lower}, &.{}); defer testing.allocator.free(off_lower); const off_upper = try keyOf(testing.allocator, .{ .alternate = .non_ignorable }, &.{upper}, &.{}); defer testing.allocator.free(off_upper); try testing.expectEqual(std.math.Order.lt, order(off_lower, off_upper)); // Upper first, the other way round. const opts: Options = .{ .alternate = .non_ignorable, .case_first = .upper_first }; const up_lower = try keyOf(testing.allocator, opts, &.{lower}, &.{}); defer testing.allocator.free(up_lower); const up_upper = try keyOf(testing.allocator, opts, &.{upper}, &.{}); defer testing.allocator.free(up_upper); try testing.expectEqual(std.math.Order.gt, order(up_lower, up_upper)); // And only the third level moved: the primary weights are identical, // because case is a tertiary difference and swapping it must not promote // it to anything stronger. try testing.expectEqualSlices(u8, up_lower[0..2], up_upper[0..2]); } test "the case weight goes in front of the tertiary weight" { const upper: Element = .{ .primary = 0x0100, .secondary = 0x20, .tertiary = 0x08, .case = .upper }; const mixed: Element = .{ .primary = 0x0100, .secondary = 0x20, .tertiary = 0x03, .case = .mixed }; const lower: Element = .{ .primary = 0x0100, .secondary = 0x20, .tertiary = 0x02 }; // `off` is the table's own order, the tertiary weight untouched. try testing.expectEqual(@as(u16, 0x08), caseWeight(upper, .off)); try testing.expectEqual(@as(u16, 0x02), caseWeight(lower, .off)); // The case weight goes in front, so every element of the case that sorts // first is below every element of the other whatever their tertiary // weights are. The stride is 0x40, the size of the tertiary field, so // that no weight in one case can reach into the next; and the weights // are section 5.1's 1, 2 and 3 rather than 0, 1 and 2, because a // *tertiary* element takes the constant 3 and has to stay above // everything else. try testing.expectEqual(@as(u16, 0x48), caseWeight(upper, .upper_first)); try testing.expectEqual(@as(u16, 0x83), caseWeight(mixed, .upper_first)); try testing.expectEqual(@as(u16, 0xC2), caseWeight(lower, .upper_first)); try testing.expectEqual(@as(u16, 0xC8), caseWeight(upper, .lower_first)); try testing.expectEqual(@as(u16, 0x83), caseWeight(mixed, .lower_first)); try testing.expectEqual(@as(u16, 0x42), caseWeight(lower, .lower_first)); // A tertiary element -- no primary weight, no secondary weight -- takes // 3 whatever its case bits say and whatever `caseFirst` asks for, which // is what keeps it above every primary and secondary element at this // level (UCA well-formedness condition 2). Breton, Ewe and Vietnamese // all noticed when it did not. const tertiary_only: Element = .{ .primary = 0, .secondary = 0, .tertiary = 0x1E, .case = .upper }; try testing.expectEqual(@as(u16, 0xDE), caseWeight(tertiary_only, .upper_first)); try testing.expectEqual(@as(u16, 0xDE), caseWeight(tertiary_only, .lower_first)); // The weight itself does not decide the class. A tailoring shifts root // tertiary weights to make room, and a shift can take 0x0C -- `` // with Uppercase -- to 0x0D, which is small hiragana. const shifted: Element = .{ .primary = 0x0100, .secondary = 0x20, .tertiary = 0x0D, .case = .upper }; try testing.expectEqual(@as(u16, 0x4D), caseWeight(shifted, .upper_first)); } test "caseFirst orders by case before tertiary weight, not by swapping bands" { // ᴴ MODIFIER LETTER CAPITAL H is [.24C4.0020.001D] and ͪ COMBINING LATIN // SMALL LETTER H is [.24C4.0020.0004]: same primary, same secondary, and // tertiary weights that are not two halves of one pair. Danish asks for // uppercase first, so the capital must come first -- which swapping // 0x1C against 0x1D cannot deliver, because 0x1C is still above 0x04. const capital: Element = .{ .primary = 0x24C4, .secondary = 0x0020, .tertiary = 0x001D, .case = .upper }; const small: Element = .{ .primary = 0x24C4, .secondary = 0x0020, .tertiary = 0x0004 }; const off: Options = .{ .alternate = .non_ignorable }; const off_small = try keyOf(testing.allocator, off, &.{small}, &.{}); defer testing.allocator.free(off_small); const off_capital = try keyOf(testing.allocator, off, &.{capital}, &.{}); defer testing.allocator.free(off_capital); try testing.expectEqual(std.math.Order.lt, order(off_small, off_capital)); const upper: Options = .{ .alternate = .non_ignorable, .case_first = .upper_first }; const up_small = try keyOf(testing.allocator, upper, &.{small}, &.{}); defer testing.allocator.free(up_small); const up_capital = try keyOf(testing.allocator, upper, &.{capital}, &.{}); defer testing.allocator.free(up_capital); try testing.expectEqual(std.math.Order.gt, order(up_small, up_capital)); } test "backwards secondary reverses the second level only" { const a: Element = .{ .primary = 0x0100, .secondary = 0x0020, .tertiary = 0x0002 }; const b: Element = .{ .primary = 0x0200, .secondary = 0x0030, .tertiary = 0x0002 }; const forwards = try keyOf(testing.allocator, .{ .alternate = .non_ignorable }, &.{ a, b }, &.{}); defer testing.allocator.free(forwards); const backwards = try keyOf(testing.allocator, .{ .alternate = .non_ignorable, .backwards_secondary = true }, &.{ a, b }, &.{}); defer testing.allocator.free(backwards); // Level one is unchanged. try testing.expectEqualSlices(u8, forwards[0..4], backwards[0..4]); // Level two is the same weights the other way round -- and compressed, // which is what makes the two look so different. Forwards it is COMMON // and then 0x0030, so the run of one is written as the high synthetic // MAXBOTTOM - 1 = 0xFE20 followed by 0x0030 lifted to 0xFE30. Backwards // the run is at the *end*, where nothing follows it, so 0x0030 comes // first and the run becomes the low synthetic COMMON + 1 = 0x0021. try testing.expectEqualSlices(u8, &.{ 0xFE, 0x20, 0xFE, 0x30 }, forwards[6..10]); try testing.expectEqualSlices(u8, &.{ 0xFE, 0x30, 0x00, 0x21 }, backwards[6..10]); } test "the case level compares case and nothing else" { if (!haveAsciiExamples()) return error.SkipZigTest; // a is [.23EC.0020.0002] and A is [.23EC.0020.0008]: one primary, one // secondary, and a tertiary difference that is entirely the case. var lower_scratch: [1]Element = undefined; var upper_scratch: [1]Element = undefined; const lower = ducet.elementsOf(ducet.entry('a'), &lower_scratch)[0]; const upper = ducet.elementsOf(ducet.entry('A'), &upper_scratch)[0]; // At secondary strength the tertiary level is not written at all, so // without a case level the two are equal. That is the whole point of the // setting: there is no strength that ignores accents and honours case. const secondary: Options = .{ .alternate = .non_ignorable, .strength = .secondary }; const a2 = try keyOf(testing.allocator, secondary, &.{lower}, &.{}); defer testing.allocator.free(a2); const A2 = try keyOf(testing.allocator, secondary, &.{upper}, &.{}); defer testing.allocator.free(A2); try testing.expectEqualSlices(u8, a2, A2); // With one, they differ, and lowercase comes first because that is what // the table says. const cased: Options = .{ .alternate = .non_ignorable, .strength = .secondary, .case_level = true, }; const a3 = try keyOf(testing.allocator, cased, &.{lower}, &.{}); defer testing.allocator.free(a3); const A3 = try keyOf(testing.allocator, cased, &.{upper}, &.{}); defer testing.allocator.free(A3); try testing.expectEqual(std.math.Order.lt, order(a3, A3)); // `caseFirst` reorders the case level rather than the tertiary one. const upper_first: Options = .{ .alternate = .non_ignorable, .strength = .secondary, .case_level = true, .case_first = .upper_first, }; const a4 = try keyOf(testing.allocator, upper_first, &.{lower}, &.{}); defer testing.allocator.free(a4); const A4 = try keyOf(testing.allocator, upper_first, &.{upper}, &.{}); defer testing.allocator.free(A4); try testing.expectEqual(std.math.Order.gt, order(a4, A4)); } test "a case level leaves the tertiary level alone" { if (!haveAsciiExamples()) return error.SkipZigTest; // Section 5.1's table writes `p.s.t -> p.s.c.t` when the case level is // on: the case weight goes on a level of its own and the tertiary weight // is unmodified. So a and A differ at the case level and *not* at the // tertiary one -- which is the same ordering a fold would give, and not // the same key. var lower_scratch: [1]Element = undefined; var upper_scratch: [1]Element = undefined; const lower = ducet.elementsOf(ducet.entry('a'), &lower_scratch)[0]; const upper = ducet.elementsOf(ducet.entry('A'), &upper_scratch)[0]; try testing.expectEqual(@as(u16, 0x0002), lower.tertiary); try testing.expectEqual(@as(u16, 0x0008), upper.tertiary); const options: Options = .{ .strength = .tertiary, .alternate = .non_ignorable, .case_level = true, }; const small = try keyOf(testing.allocator, options, &.{lower}, &.{}); defer testing.allocator.free(small); const capital = try keyOf(testing.allocator, options, &.{upper}, &.{}); defer testing.allocator.free(capital); // Four levels now -- primary, secondary, case, tertiary -- and the last // one holds each element's own weight rather than a folded one. Both are // compressed: the lowercase 0x0002 is COMMON at that level, so a run of // one with nothing behind it becomes COMMON + 1, while the uppercase // 0x0008 is above COMMON and is written lifted. try testing.expectEqualSlices(u8, &.{ 0x00, 0x03 }, small[small.len - 2 ..]); try testing.expectEqualSlices(u8, &.{ 0xFF, 0xC8 }, capital[capital.len - 2 ..]); try testing.expectEqual(std.math.Order.lt, order(small, capital)); // And the case level is where they part: everything before it is equal. // The key is primary, separator, secondary, separator, case, separator, // tertiary -- fourteen bytes, of which the first eight are shared. const case_level_at = small.len - 6; try testing.expectEqualSlices(u8, small[0..case_level_at], capital[0..case_level_at]); } test "the case level ignores the elements section 5.1 says to ignore" { // A secondary ignorable contributes nothing at any strength, and a // primary ignorable contributes nothing at primary strength. Both are // rows of section 5.1's table, and both matter for the prefix property: // a string of two ignorables must not outrank a string of one at a level // above the one that tells them apart. const a: Element = .{ .primary = 0x06D9, .secondary = 0x0020, .tertiary = 0x0002 }; const accent: Element = .{ .primary = 0, .secondary = 0x0021, .tertiary = 0x0002 }; const mark: Element = .{ .primary = 0, .secondary = 0, .tertiary = 0x0007 }; // Secondary ignorables: at secondary strength the keys are equal, marks // or no marks, because the case level is the only level left that could // have told them apart. for ([_]CaseFirst{ .off, .upper_first }) |case_first| { const options: Options = .{ .strength = .secondary, .alternate = .non_ignorable, .case_level = true, .case_first = case_first, }; const bare = try keyOf(testing.allocator, options, &.{a}, &.{}); defer testing.allocator.free(bare); const marked = try keyOf(testing.allocator, options, &.{ a, mark, mark }, &.{}); defer testing.allocator.free(marked); try testing.expectEqualSlices(u8, bare, marked); } // And a primary ignorable, at primary strength only. const ignoring: Options = .{ .strength = .primary, .alternate = .non_ignorable, .case_level = true, }; const bare = try keyOf(testing.allocator, ignoring, &.{a}, &.{}); defer testing.allocator.free(bare); const accented = try keyOf(testing.allocator, ignoring, &.{ a, accent }, &.{}); defer testing.allocator.free(accented); try testing.expectEqualSlices(u8, bare, accented); // At secondary strength it contributes again, because then the accent is // a difference the caller asked to see. const seeing: Options = .{ .strength = .secondary, .alternate = .non_ignorable, .case_level = true, }; const bare2 = try keyOf(testing.allocator, seeing, &.{a}, &.{}); defer testing.allocator.free(bare2); const accented2 = try keyOf(testing.allocator, seeing, &.{ a, accent }, &.{}); defer testing.allocator.free(accented2); try testing.expectEqual(std.math.Order.lt, order(bare2, accented2)); } test "a quaternary weight is invisible until the fourth level" { // What `<<<<` produces: an element identical to its anchor's except for // the fourth weight. It must compare equal at tertiary strength -- that // is the whole point of writing the relation at the fourth level -- and // order at quaternary strength, under either alternate handling, which // is what ICU does for Japanese kana. const anchor: Element = .{ .primary = 0x21AC, .secondary = 0x20, .tertiary = 0x02 }; var step = anchor; step.quaternary = 1; // A tailoring is needed only because it is what puts the fourth level's // low half in the key; this one reorders nothing. const none: data.Tailoring = .{ .locale = "test", .root = "cldr", .overrides = &.{}, .contractions = &.{}, .expansions = &.{}, }; for ([_]Alternate{ .non_ignorable, .shifted }) |alternate| { for ([_]Strength{ .primary, .secondary, .tertiary }) |strength| { const options: Options = .{ .strength = strength, .alternate = alternate }; try testing.expectEqual( std.math.Order.eq, try orderTailored(options, &none, &.{anchor}, &.{step}), ); } for ([_]Strength{ .quaternary, .identical }) |strength| { const options: Options = .{ .strength = strength, .alternate = alternate }; try testing.expectEqual( std.math.Order.lt, try orderTailored(options, &none, &.{anchor}, &.{step}), ); } } } test "the fourth level keeps shifted punctuation and a quaternary weight apart" { if (!haveAsciiExamples()) return error.SkipZigTest; // Both uses share the level, so the marker that stands for "not a // variable element" has to be above every weight shifting can put there. // ICU says so: for Japanese under shifted handling, katakana sorts after // hiragana followed by a hyphen, and a hyphen followed by katakana sorts // before hiragana followed by a hyphen -- which places every shifted // primary weight below the marker. var scratch: [1]Element = undefined; const hyphen = ducet.elementsOf(ducet.entry('-'), &scratch)[0]; try testing.expect(ducet.isVariable(hyphen)); const plain: Element = .{ .primary = 0x21AC, .secondary = 0x20, .tertiary = 0x02 }; var stepped = plain; stepped.quaternary = 1; const none: data.Tailoring = .{ .locale = "test", .root = "cldr", .overrides = &.{}, .contractions = &.{}, .expansions = &.{}, }; const options: Options = .{ .strength = .quaternary, .alternate = .shifted }; // The stepped element after a hyphen, against the plain one after a // hyphen: the fourth level is [marker+1, hyphen] against [marker, // hyphen], so the quaternary weight decides. try testing.expectEqual( std.math.Order.lt, try orderTailored(options, &none, &.{ plain, hyphen }, &.{ stepped, hyphen }), ); // And a hyphen in front of either sorts below both, because a shifted // primary weight is below the marker. try testing.expectEqual( std.math.Order.lt, try orderTailored(options, &none, &.{ hyphen, stepped }, &.{ plain, hyphen }), ); } test "the levels written one at a time are the whole key" { if (!haveAsciiExamples()) return error.SkipZigTest; // `Collator.order` writes a level, compares it, and stops -- so a level // written on its own has to be byte for byte what `write` puts there. // This checks it over every combination of the settings that change the // layout, because each of them has a branch of its own inside the level: // `backwards_secondary` reverses one, `case_level` inserts one, // `caseFirst` folds into one, a tailoring writes pairs at two of them, // and `shift_trimmed` drops weights from the fourth. const none: data.Tailoring = .{ .locale = "test", .root = "cldr", .overrides = &.{}, .contractions = &.{}, .expansions = &.{}, }; var scratch: [1]Element = undefined; const a = ducet.elementsOf(ducet.entry('a'), &scratch)[0]; var upper_scratch: [1]Element = undefined; const upper = ducet.elementsOf(ducet.entry('A'), &upper_scratch)[0]; var space_scratch: [1]Element = undefined; const space = ducet.elementsOf(ducet.entry(' '), &space_scratch)[0]; const mark: Element = .{ .primary = 0, .secondary = 0x21, .tertiary = 0x02 }; var quaternary = a; quaternary.quaternary = 1; const elements = [_]Element{ a, upper, space, mark, quaternary }; const text = [_]u21{ 'a', 'A', ' ', 0x0301, 'a' }; for ([_]?*const data.Tailoring{ null, &none }) |tailoring| { for ([_]Strength{ .primary, .secondary, .tertiary, .quaternary, .identical }) |strength| { for ([_]Alternate{ .non_ignorable, .blanked, .shifted, .shift_trimmed }) |alternate| { for ([_]CaseFirst{ .off, .upper_first, .lower_first }) |case_first| { for ([_]bool{ false, true }) |case_level| { for ([_]bool{ false, true }) |backwards| { const options: Options = .{ .strength = strength, .alternate = alternate, .case_first = case_first, .case_level = case_level, .backwards_secondary = backwards, }; var weighted: std.ArrayList(Weighted) = .empty; defer weighted.deinit(testing.allocator); try weigh(&weighted, testing.allocator, ducet, alternate, &elements); var whole: std.Io.Writer.Allocating = .init(testing.allocator); defer whole.deinit(); try write(&whole.writer, options, tailoring, weighted.items, &text); // The same thing level by level, which is what a // comparison does. var piecewise: std.Io.Writer.Allocating = .init(testing.allocator); defer piecewise.deinit(); for (0..strength.levels()) |level| { try writeLevel( &piecewise.writer, options, tailoring, weighted.items, level, ); } if (case_level and strength.levels() == 2) { try piecewise.writer.writeAll(&.{ 0, 0 }); try writeCaseLevel(&piecewise.writer, options, weighted.items); } try writeIdenticalLevel(&piecewise.writer, options, &text); try testing.expectEqualSlices( u8, whole.written(), piecewise.written(), ); } } } } } } }