The Unicode Collation Algorithm (UTS #10) and CLDR locale tailorings in Zig: sort text the way people expect rather than by code point.
zig-collate README.md
62 kB · 1,093 lines
Markdown
at main

<!-- SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us> SPDX-License-Identifier: MIT --> # zig-collate The Unicode Collation Algorithm, [UTS #10][uca], in Zig. Sorting text by code point is not merely unlocalized, it is wrong in a way people notice: `Mueller` sorts before `Märtens`, because `u` is U+0075 and `ä` is U+00E4. This library exists so that a program which needs to put names in order does not have to reimplement a collation to get that right — and so that it does not get it wrong in the same way every such reimplementation does. **The API documentation is generated from the doc comments in the source and published at <https://jeff.jcollie.page/zig-collate/>.** Those comments carry most of the explanation, including which paragraph of the specification each piece implements, and every public function has a worked example beside it — a doctest, which `zig build test` runs, so an example that stops being true fails the build rather than misleading a reader. It passes the UCA conformance suite of [UTS #10 section 12.2][conformance] in full: 212,066 cases with `non_ignorable` variable weighting and 212,066 with `shifted`, all at identical strength, nothing filtered. Built with `-Dembed-cldr` it also passes CLDR's own suite for the CLDR root collation, 210,186 cases in each. Those are the acceptance criteria rather than smoke tests — see [Testing](#testing). [uca]: https://www.unicode.org/reports/tr10/ [conformance]: https://www.unicode.org/reports/tr10/#Data_Files [incremental]: https://www.unicode.org/reports/tr10/#Incremental_Comparison ## Using it ```zig const collate = @import("collate"); const c: collate.Collator = .{}; const order = try c.order(gpa, "Märtens", "Mueller"); // .lt ``` `order` allocates nothing for strings of ordinary length — both keys and the scratch come off the stack — so it is safe to hand to a sort comparator, and it does not write a whole key to answer: it compares a level at a time and stops at the first level that decides, which is [section 9.7][increment…