Unicode
import "std/text" (included in import "std") · namespace std.text
Unicode normalization: one spelling for text that looks the same. "é" can be one code point (U+00E9) or an "e" followed by a combining accent (U+0301); they print alike but compare unequal until normalized.
grav
import "std"
fn main() {
let typed = "Cre\u{301}me" // as some keyboards and macOS file names give it
let stored = "Cr\u{e9}me"
print(typed == stored)
print(Unicode.nfc(typed) == Unicode.nfc(stored))
print(Unicode.nfkc("\u{fb01}le \u{ff21}\u{ff22}\u{b2}")) // ligature, full-width letters, superscript
print(Unicode.stripAccents("Crème brûlée, São Paulo"))
}false
true
file AB2
Creme brulee, Sao Paulo- NFC (
nfc) composes: compare, store and index text users type like this. NFD (nfd) decomposes each letter into its base and marks, in a fixed order. - NFKC and NFKD also fold compatibility characters (ligatures, full-width letters, superscripts, the ohm sign) into their plain forms: for usernames, identifiers and search terms, so look-alikes match.
normalize(s, "NFC")takes the form's name;isNormalized(s, form)says whethersis in it already.stripAccentsremoves accents and other combining marks, for slugs and accent-insensitive search.- Exact and quick. The tables are Unicode 15.1's (checked against Python's
unicodedataon every code point, in all four forms), about 30 KB, unpacked on first use, and left out of programs that never normalize. Pure ASCII text is returned at once; other text takes about a microsecond.
API
class Unicode
Static members
static fn nfc(s: string) -> string— Composed (NFC): what most text uses; compare, store and index user text like this.static fn nfd(s: string) -> string— Decomposed (NFD): each letter, then its marks in a fixed order.static fn nfkc(s: string) -> string— Compatibility, composed (NFKC): "fi" is "fi", "²" is "2", full-width letters are plain: for usernames, identifiers and search terms.static fn nfkd(s: string) -> string— Compatibility, decomposed (NFKD).static fn normalize(s: string, form: string) -> string—formis "NFC", "NFD", "NFKC" or "NFKD".static fn isNormalized(s: string, form: string = "NFC") -> bool— Whethersis already inform.static fn stripAccents(s: string) -> string— The text without accents and other combining marks ("Crème" -> "Creme"): for slugs and accent-insensitive search.