Something went wrong. Try again.
The Unicode Collation Algorithm (UTS #10) and CLDR locale tailorings in Zig: sort text the way people expect rather than by code point.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The shapes a collation element table is made of.//!//! A module of its own, with no dependencies, because the generated DUCET//! imports it too. Zig types are nominal, so a struct declared twice is two//! types; the generator and the code that reads what it generated have to be//! naming the same declarations, and that means one module they both import.
const std = @import("std");
/// One collation element: UTS10-D2, an ordered list of collation weights.////// Three levels, which is what DUCET uses -- every one of its 45,860/// collation elements has exactly three. The widths come from the data too:/// primary weights reach 0xFFFD, secondary weights 0x0127 and tertiary/// weights 0x001E, which is thirty bits between them. What makes the element/// forty-eight is what a tailoring needs: the sub-weight it inserts with, the/// case bits section 5.1 asks for, and a fourth weight for the one collation/// that writes a quaternary relation.////// A fourth level exists in the algorithm (UTS10-D7) and, in the DUCET,/// never in a table: `Alternate.shifted` computes it from the primary weight/// when the sort key is built. A *tailoring* can put one there, and one/// does -- see `quaternary` below./// The case of the characters a collation element came from.////// Three values rather than two, which section 3.3 of [UTS #35 part 5][ldml]/// is explicit about: "&aE=Ch yields an uppercase CE and a lowercase CE, but/// &a=Ch/E yields a mixed-case CE". Danish needs the third one to order/// `&å<<<aa<<<Aa<<<AA` under `[caseFirst upper]` -- AA is uppercase, Aa is/// mixed, and they are not the same thing -- and so does Maltese, whose/// `&[before 1]h<għ<<<gĦ<<<Għ<<<GĦ` has two mixed spellings between the/// lowercase one and the uppercase one.////// [ldml]: https://www.unicode.org/reports/tr35/tr35-collation.htmlpub const Case = enum(u2) { lower, mixed, upper,};
pub const Element = packed struct(u48) { primary: u16,
/// Where this element sits *between* two root primary weights, for an /// element a tailoring inserted. Zero for everything in a root table. /// /// This exists because a tailoring rule like Swedish's `&z<å` asks for a /// primary weight strictly between z's and whatever follows it, and /// there is nowhere to put one: DUCET's primary weights are essentially /// consecutive, 29,123 values filling a range 29,123 wide. ICU solves /// that with variable-length fractional weights, because it applies /// rules at run time to a fixed table. /// /// The obvious alternative -- scale every root primary so that gaps /// appear -- does not survive the data. CLDR 48.2's Burmese rules insert /// 255 consecutive primaries after a single anchor, so a factor of 256 /// fits with nothing to spare, and any larger factor pushes primary /// weights past 24 bits and lengthens the sort keys of callers who asked /// for no tailoring at all. /// /// So the subdivision is a field rather than a scale factor, and it is /// written to a sort key only by a collation that actually has a /// tailoring. An untailored key is exactly what it was before this /// existed, which matters: that is the encoding both conformance suites /// pass on. /// /// Eleven bits and not sixteen, because the other five are worth more /// elsewhere: one went to the tertiary level, where Arabic needs 43 and /// five bits give 31, and four to the quaternary weight below. The most /// any CLDR 48.2 tailoring reaches here is 265, Burmese's, which inserts /// 255 consecutive primaries after one anchor -- so eleven bits is still /// seven times the headroom the data asks for, and a rule that wanted /// more is refused by name rather than wrapping. primary_sub: u11 = 0,
secondary: u9,
/// Six bits rather than the five DUCET needs, for one rule: Arabic hangs /// forty-three tertiary relations off `&[last secondary ignorable]` -- /// the tashkil, which it makes tertiary differences -- and the chain runs /// from one, so the top of it is 43. The bit comes out of `primary_sub` /// rather than widening the element. tertiary: u6,
/// The fourth level, for a tailoring that asks for one: `<<<<`. /// /// Zero for everything in a root table and for almost everything in a /// tailored one, which is what makes four bits enough. Japanese is the /// only collation CLDR ships that writes a quaternary relation at all -- /// its private kana collation has 116 of them, separating katakana from /// hiragana, which is a distinction it does not want at tertiary /// strength -- and every one of those chains is one step deep. /// /// UTS #10 says a fourth level exists in the algorithm and never in a /// table, and for the DUCET that is true: `Alternate.shifted` computes /// the fourth level from the primary weight of a variable element. Both /// uses have to share the level, and `key.write` does that by writing it /// as a pair -- a marker above every variable primary weight, then this. quaternary: u4 = 0,
/// The case of the characters this element came from: the case bits of /// [UTS #35 part 5][ldml] section 5.1, which `caseFirst` orders by. /// /// A field of its own rather than a reading of the tertiary weight, even /// though for a *root* element the weight does say it: section 5.1 gives /// the set outright, UPPER for a tertiary weight in /// `{08-0C, 0E, 11, 12, 1D}` and uncased otherwise, with no mixed value /// in the root collation at all. /// /// Three things break that reading once a tailoring is involved. /// `makeRoom` shifts a root element's tertiary weight up to free a slot, /// and one shift takes 0x0C to 0x0D, which is `<small>` hiragana and not /// uppercase anything; Danish shifts weights under the primary of H, and /// SCRIPT CAPITAL H then read as lowercase in 330 of its 6,786 /// comparisons. A rule's target can be a string of more than one letter, /// where a single weight has one value to say something about two /// characters. And a tailoring's tertiary weights are chain positions /// rather than cases at all: Arabic's tashkil run from 1 to 43, nine of /// them straight through the uppercase set. /// /// So a tailored mapping's bits are computed by section 5.1's own /// algorithm, from the root elements of the string the rule is about -- /// `applyCaseBits` in `tools/gen_tailoring.zig`, which is also where the /// reason it is not a reading of Unicode's case properties is written /// down. /// /// ICU keeps the case bits in a field of their own for the same reasons. /// They are not part of the ordering here either: a sort key writes the /// tertiary weight alone unless `caseFirst` or `case_level` asks /// otherwise, so this costs nothing until it is wanted. /// /// [ldml]: https://www.unicode.org/reports/tr35/tr35-collation.html case: Case = .lower,
/// A completely ignorable collation element, UTS10-D13. pub const ignorable: Element = .{ .primary = 0, .secondary = 0, .tertiary = 0 };
/// UTS10-D9. The cover term for everything else is "ignorable collation /// element", UTS10-D14. pub fn isPrimary(e: Element) bool { return e.primary != 0; }
/// The weight at one level, for the loop in S3.4 that does not care /// which level it is walking. pub fn weight(e: Element, level: Level) u16 { return switch (level) { .primary => e.primary, .secondary => e.secondary, .tertiary => e.tertiary, }; }
/// The notation of section 3.1: weights in hexadecimal, dot separated. /// Whether an element is variable depends on the table it came from, so /// this cannot write the `*` that `allkeys.txt` uses; `Table.format` is /// where that lives. pub fn format(e: Element, w: *std.Io.Writer) std.Io.Writer.Error!void { try w.print("[.{X:0>4}.{X:0>4}.{X:0>4}]", .{ e.primary, @as(u16, e.secondary), @as(u16, e.tertiary), }); }};
/// The bit that marks the *low* half of a derived weight pair.////// Section 10.1.3 gives a code point the table says nothing about two/// elements, and `Table.implicitPrimaries` computes the second one's primary/// as `(cp & 0x7FFF) | 0x8000` -- so every primary weight from here up is/// either that low half or the `implicit_primary_base` lead above it, and no/// regular character has one. A tailoring that allocates primary weights of/// its own must stay below this.pub const implicit_tail_bit: u16 = 0x8000;
/// The lowest primary weight section 10.1.3 derives rather than tabulates.////// Every weight from here up belongs to a code point the table says nothing/// about -- Han by radical and stroke, then the siniform scripts, then the/// unassigned -- so a root table's own mappings all sit below it, and so must/// any primary weight a tailoring allocates. `Table.implicitPrimaries` is/// what computes the weights above it; `&[last regular]` is the one rule that/// allocates towards it, and the generator refuses by name rather than/// running into it.pub const implicit_primary_base: u16 = 0xFB40;
/// The most collation elements one table entry maps to: an expansion,/// UTS10-D20.////// Eighteen, measured over DUCET 17.0.0, and the witness is U+FDFA ARABIC/// LIGATURE SALLALLAHOU ALAYHE WASALLAM. The generator checks the table/// against this rather than trusting it, so a future DUCET with a longer/// expansion stops the build here instead of being silently truncated.pub const max_expansion = 18;
/// UTS10-D3, a collation level, named by the weight that sits at it.pub const Level = enum(u2) { primary = 0, secondary = 1, tertiary = 2,};
/// What one code point maps to, found by the two-stage lookup in `Table`.pub const Entry = packed struct(u64) { /// The element itself when `len == 1`, an index into `Table.expansions` /// when `len > 1`, and meaningless when `len == 0`. /// /// One element is the overwhelmingly common case -- 34,876 of DUCET's /// 39,749 entries -- so it is worth not making all of them an /// indirection. Forty-eight bits because that is what an `Element` is, /// which is what leaves exactly enough room for the rest of this to /// stay one word. payload: u48,
/// How many collation elements this code point maps to. Zero means the /// table has no mapping and the weights are derived instead, by section /// 10.1. len: u8,
/// This code point is the first code point of at least one contraction, /// so a match on it has to try to grow (S2.1). Only 77 code points in /// DUCET have it set, which is why the contractions live in a list off to /// the side rather than in a trie. starts_contraction: bool,
/// The payload indexes a tailoring's expansions rather than the root /// table's. Never set by a generated root table. tailored: bool = false,
_reserved: u6 = 0,
pub const none: Entry = .{ .payload = 0, .len = 0, .starts_contraction = false };
pub fn single(e: Element) Entry { return .{ .payload = @bitCast(e), .len = 1, .starts_contraction = false }; }};
/// The most code points a contraction may be.////// A bound on the buffer step 2 keeps a partial match in, not on the data:/// DUCET's longest contraction is three code points and CLDR's rules ask for/// more, so the code points themselves live in a pool and this is only the/// ceiling the generator refuses above. Sixteen is far past anything either/// uses.pub const max_contraction = 16;
/// A mapping from a sequence of code points to collation elements: UTS10-D18,/// a contraction. DUCET has 964, none longer than three code points; CLDR's/// tailorings go further.pub const Contraction = struct { /// The first code point, which is also what `Entry.starts_contraction` /// is set on, and what the table is searched by. first: u21, /// Index and count in `contraction_points`, for the code points after /// the first. /// /// A pool rather than a fixed array. It began as `[2]u21`, which is all /// DUCET needs, and CLDR's rules contract longer sequences than that -- /// so the choice was between raising a cap that would be wrong again and /// not having one. Widening the array also pays for the longest /// contraction on all 964 of the root's, most of which are two code /// points. rest_index: u32, rest_len: u8, /// Index and count in `expansions`. Always an indirection, even for a /// single element: there are few enough of these that saving the hop is /// not worth a second representation. elements_index: u32, elements_len: u8,
/// The code points that must come *before* this one for the mapping to /// apply: [UTS #35 part 5][ldml] section 3.3's `prefix|target`, which it /// calls a contextual mapping. Into the same pool as `rest`, and empty -- /// `prefix_len == 0` -- for every mapping that is not conditional, which /// is every one in a root table and all but one locale's. /// /// A condition rather than part of the match: the prefix has already /// been weighed as itself by the time this mapping is reached, and it is /// not consumed. That is why it lives here rather than in a list of its /// own -- a contextual mapping is a contraction with a condition on it, /// so S2.1's longest-match search, its discontiguous growth and /// `Entry.starts_contraction` all serve it unchanged. /// /// Japanese is the only collation CLDR 48.2 ships that writes one, 633 /// times in the private kana collation it imports: an iteration mark or /// the prolonged sound mark takes the weights of the kana it follows, so /// that `あー` sorts where `ああ` does. In NFD both halves are one or two /// code points -- `が` is か and U+3099 -- which is why both are pooled /// sequences rather than single values. /// /// [ldml]: https://www.unicode.org/reports/tr35/tr35-collation.html prefix_index: u32 = 0, prefix_len: u8 = 0,
/// Longest first, so that S2.1's "longest initial substring" is the /// first match found, and by code point within a length so that a binary /// search can find the group for `first`. /// /// A longer *prefix* comes first among mappings for the same sequence, /// which puts the more specific condition first, and an unconditional /// mapping last of all. /// /// Takes the pool as its context, because the code points are no longer /// in the struct. pub fn lessThan(points: []const u21, a: Contraction, b: Contraction) bool { if (a.first != b.first) return a.first < b.first; if (a.rest_len != b.rest_len) return a.rest_len > b.rest_len; if (a.prefix_len != b.prefix_len) return a.prefix_len > b.prefix_len; const ra = points[a.rest_index..][0..a.rest_len]; const rb = points[b.rest_index..][0..b.rest_len]; for (ra, rb) |x, y| { if (x != y) return x < y; } const pa = points[a.prefix_index..][0..a.prefix_len]; const pb = points[b.prefix_index..][0..b.prefix_len]; for (pa, pb) |x, y| { if (x != y) return x < y; } return false; }};
/// A per-locale tailoring: UTS #10 section 8, and the rules of/// [UTS #35 part 5][ldml].////// A delta rather than a table of its own. A generated root table is 1.4 MB/// of Zig source, and CLDR carries a `standard` tailoring for 112 locales, so/// a table apiece is not a thing anybody can compile. What a tailoring holds/// instead is only what it changes -- the code points whose collation/// elements differ from the root's, and the contractions it adds -- and/// `Table.entry` consults it before the root.////// The weights of an inserted element come from `Element.primary_sub`, which/// is what makes the delta possible at all: an element inserted after the/// anchor `z` takes z's own primary weight with a sub-weight above z's, so it/// sorts after z and before whatever followed z without anything else in the/// table moving.////// [ldml]: https://www.unicode.org/reports/tr35/tr35-collation.html/// How many levels a comparison looks at, section 3.7 and the `strength`/// setting of section 8.1.pub const Strength = enum { /// Base letters only: `a` == `A` == `á`. primary, /// And accents. secondary, /// And case. The UCA default. tertiary, /// And the level `Alternate.shifted` synthesizes, which is where the /// difference between shifted and blanked actually shows up. quaternary, /// And, last, the NFD of the string itself: S3.10, which the /// specification calls semi-stability. Two strings compare equal at this /// strength only if they are canonically equivalent. The conformance /// suite of section 12.2 is defined in terms of it. identical,
/// How many levels a sort key built at this strength has. pub fn levels(s: Strength) usize { return switch (s) { .primary => 1, .secondary => 2, .tertiary => 3, .quaternary, .identical => 4, }; }};
/// Variable weighting, section 4 of UTS #10: what happens to the elements/// the table marks variable, which is punctuation, symbols and digits.pub const Alternate = enum { /// Leave the table alone. Punctuation sorts at its own primary weight. non_ignorable, /// Variable elements, and the ignorable elements that follow them, /// weigh nothing at all: "black-bird" == "blackbird". blanked, /// The same, but with a fourth level that remembers what was blanked, so /// that "black-bird" and "blackbird" are distinguished after everything /// else has been compared. shifted, /// `shifted` with trailing 0xFFFF weights trimmed. Section 4 says this /// exists to emulate POSIX and is "otherwise not recommended", which is /// the whole of its rationale. shift_trimmed,};
/// Which case sorts first at the tertiary level: the `caseFirst` setting of/// [UTS #35 part 5][ldml] section 5.1, and what `xsl:sort case-order=` asks/// for.pub const CaseFirst = enum { /// Whatever the table says, which for DUCET is lowercase first. off, /// Uppercase before lowercase. upper_first, /// Lowercase before uppercase. lower_first,};
/// The parametric settings a locale's rules ask for, [UTS #35 part 5][ldml]/// section 5.1.////// Not table data: these change how a sort key is *built* rather than what/// any character weighs, so they belong to the collator and a tailoring only/// carries what its locale asked for. Danish's rules open with/// `[caseFirst upper]`, which is a statement about Danish and not about the/// caller, who may be sorting a list where case is to be ignored entirely./// `key.Options.applying` is how the two meet.////// Every field is optional, and null means the rules said nothing, which is/// not the same as saying `off`.pub const Settings = struct { case_first: ?CaseFirst = null, /// The default number of levels to compare, written `[strength 3]`. strength: ?Strength = null, /// Whether to compare case on a level of its own, written /// `[caseLevel on]`. case_level: ?bool = null, /// Section 3.8.1's backwards secondary level, written `[backwards 2]`. backwards_secondary: ?bool = null, alternate: ?Alternate = null,};
pub const Tailoring = struct { /// The locale identifier the rules came from, for diagnostics. locale: []const u8, /// Which root table the rules were resolved against: `"ducet"` or /// `"cldr"`. /// /// A tailoring is only valid over the root it was generated against, /// because its inserted elements take their primary weights from that /// root's. Recorded so that a mismatch is visible rather than silent -- /// CLDR writes its rules against CLDR's root, so `"ducet"` here is a /// convenience that happens to work wherever the two roots agree, which /// for the Latin letters they do. root: []const u8 = "ducet", /// Overridden single code points, sorted by code point. overrides: []const Override, /// Contractions the tailoring adds. Sorted like `Table.contractions`: /// grouped by first code point, longest first inside a group. contractions: []const Contraction, /// Where both of the above keep their elements. expansions: []const Element, /// Where the contractions keep the code points after their first. contraction_points: []const u21 = &.{},
/// Script reordering, [UTS #35 part 5][ldml]'s `[reorder …]`: a /// permutation of the primary weight space, as the ranges that moved and /// how far. /// /// Sorted by `first` and non-overlapping, so a weight's range is found by /// bisection. A weight in none of them does not move, which is how the /// three things the specification exempts stay put: the TRAILING group, /// U+FFFE's field separator, and every collation element whose primary /// weight is zero. reorder: []const ReorderRange = &.{},
/// What the locale's rules asked for that is a collator setting rather /// than a weight. Applied with `key.Options.applying`, not automatically: /// see `Settings`. settings: Settings = .{},
/// Code points whose *root* contractions the rules suppress, sorted. /// /// `[suppressContractions [Ии]]`, which Macedonian and Serbian both ask /// for: the root contracts и with a following combining breve into й, and /// they want the two letters ordered separately instead. Contractions the /// tailoring adds itself are not affected -- the setting is about the /// root's. suppressed: []const u21 = &.{},
pub const empty: Tailoring = .{ .locale = "", .root = "", .overrides = &.{}, .contractions = &.{}, .expansions = &.{}, };
/// What this tailoring says about one code point, or null if it says /// nothing and the root's answer stands. pub fn entry(t: *const Tailoring, cp: u21) ?Entry { var lo: usize = 0; var hi: usize = t.overrides.len; while (lo < hi) { const mid = lo + (hi - lo) / 2; const o = t.overrides[mid]; if (o.cp < cp) { lo = mid + 1; } else if (o.cp > cp) { hi = mid; } else { return o.toEntry(); } } return null; }
/// The code points after a contraction's first. pub fn restOf(t: *const Tailoring, c: Contraction) []const u21 { return t.contraction_points[c.rest_index..][0..c.rest_len]; }
pub fn contractionsFor(t: *const Tailoring, cp: u21) []const Contraction { var lo: usize = 0; var hi: usize = t.contractions.len; while (lo < hi) { const mid = lo + (hi - lo) / 2; if (t.contractions[mid].first < cp) lo = mid + 1 else hi = mid; } var end = lo; while (end < t.contractions.len and t.contractions[end].first == cp) end += 1; return t.contractions[lo..end]; }};
/// One stretch of primary weights that a reordering moves, and by how far.////// A reorder is a permutation of whole reordering groups, and a group is a/// contiguous range of primary weights -- not by luck but by construction:/// `FractionalUCA.txt` declares where each group starts and each runs to the/// next one's start. So the whole of `[reorder Grek Latn digit]` is a handful/// of ranges and an integer apiece.////// This is where a fixed-width primary weight pays for itself. The/// specification's notes for implementations that write sort keys are all/// about fractional weights: primaries have to move by whole lead bytes, a/// group that does not begin and end on a lead-byte boundary needs a reserved/// byte so one can be split, and primary compression has to be terminable by/// comparing adjacent weights. None of it applies to a `u16`.pub const ReorderRange = struct { first: u16, last: u16, /// Added to a primary weight in the range. Signed, because a group can /// move either way. offset: i32,};
/// One code point's replacement collation elements.////// Always an indirection into `Tailoring.expansions`, even for a single/// element: a tailoring is small enough that saving the hop is not worth a/// second representation, which is the opposite of the trade `Entry` makes.pub const Override = struct { cp: u21, elements_index: u32, elements_len: u8, starts_contraction: bool,
pub fn toEntry(o: Override) Entry { return .{ .payload = o.elements_index, .len = o.elements_len, .starts_contraction = o.starts_contraction, // Marks the payload as an index into the *tailoring's* // expansions rather than the root's, which is how one `Entry` // can come from either. .tailored = true, }; }};
/// A range of code points whose primary weights are computed rather than/// looked up: section 10.1.3 and its Table 16./// A run of Han ideographs consecutive in CLDR's order, for `Table.han_order`.////// CLDR's root collation orders the Unified Repertoire by radical and stroke/// count rather than by code point, and says so in `FractionalUCA.txt`: 214/// lines of the form `[radical 87=⽖爫:爫-爯…]`, each listing one radical's/// ideographs in sequence. `allkeys_CLDR.txt` carries no Han mappings at all,/// so a table built from that file alone keeps section 10.1.3's code-point/// order and disagrees with ICU about any two ideographs whose radicals are/// not in the same relative order as their code points -- `9FFE` before/// `9FEF`, for instance.////// So the order is kept as the ranges those lines describe, with the rank of/// each range's first ideograph, and an implicit weight is computed from the/// rank instead of from the code point. 23,985 ranges cover 101,996/// ideographs, which is every Han code point CLDR classifies -- the/// compatibility ideographs are not there because NFD has already replaced/// them by the time anything is looked up.pub const HanRange = packed struct(u64) { first: u21, last: u21, /// Where `first` sits in CLDR's order, counting from zero. base: u21, _reserved: u1 = 0,};
pub const ImplicitRange = struct { first: u21, last: u21, kind: Kind, /// `siniform` only: the AAAA weight the whole range shares, and the code /// point its offsets are measured from. The two Tangut ranges share a /// lead and a base, which is why the base cannot be taken to be `first`. lead: u16 = 0, base: u21 = 0,
pub const Kind = enum { /// Tangut, Nushu, Khitan Small Script: the scripts `allkeys.txt` /// names in its `@implicitweights` lines. Unassigned code points /// inside these ranges are excluded and fall through to `unassigned`. siniform, /// Unified_Ideograph inside the CJK Unified Ideographs or CJK /// Compatibility Ideographs blocks. core_han, /// Unified_Ideograph anywhere else. other_han, };};
test "element packing" { // `@bitSizeOf` rather than `@sizeOf`, because what matters is that an // element and the rest of an entry share one word -- the payload is // exactly an element wide and the flags fit in what is left. `@sizeOf` // rounds a 48-bit packed struct up to the ABI size and would hide that. try std.testing.expectEqual(48, @bitSizeOf(Element)); try std.testing.expectEqual(48, @bitSizeOf(@FieldType(Entry, "payload"))); try std.testing.expectEqual(64, @bitSizeOf(Entry));
const a: Element = .{ .primary = 0x06D9, .secondary = 0x0020, .tertiary = 0x0008 }; try std.testing.expect(a.isPrimary()); try std.testing.expect(!Element.ignorable.isPrimary()); try std.testing.expectEqual(@as(u16, 0x06D9), a.weight(.primary)); try std.testing.expectEqual(@as(u16, 0x0020), a.weight(.secondary)); try std.testing.expectEqual(@as(u16, 0x0008), a.weight(.tertiary));}
test "an entry round trips its element" { const e: Element = .{ .primary = 0x0706, .secondary = 0x0020, .tertiary = 0x0002 }; const entry: Entry = .single(e); try std.testing.expectEqual(@as(u8, 1), entry.len); try std.testing.expectEqual(e, @as(Element, @bitCast(entry.payload)));}
test "element format uses the notation from section 3.1" { var buf: [64]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try w.print("{f}", .{Element{ .primary = 0x06D9, .secondary = 0x0020, .tertiary = 0x0008 }}); try std.testing.expectEqualStrings("[.06D9.0020.0008]", w.buffered());}
test "contractions sort longest first within a starter" { const points = [_]u21{ 'b', 'c', 'b', 'a' }; const long: Contraction = .{ .first = 'a', .rest_index = 0, .rest_len = 2, .elements_index = 0, .elements_len = 1 }; const short: Contraction = .{ .first = 'a', .rest_index = 2, .rest_len = 1, .elements_index = 0, .elements_len = 1 }; const other: Contraction = .{ .first = 'b', .rest_index = 3, .rest_len = 1, .elements_index = 0, .elements_len = 1 }; try std.testing.expect(Contraction.lessThan(&points, long, short)); try std.testing.expect(!Contraction.lessThan(&points, short, long)); try std.testing.expect(Contraction.lessThan(&points, short, other));}