use unicode_normalization::UnicodeNormalization;
const SPECIAL: [(char, &str); 12] = [
('ß', "ss"),
('æ', "ae"),
('œ', "oe"),
('ø', "o"),
('ł', "l"),
('đ', "d"),
('ð', "d"),
('þ', "th"),
('ı', "i"),
('ŋ', "n"),
('ħ', "h"),
('ŧ', "t"),
];
pub(super) fn fold(token: &str) -> String {
let mut out = String::with_capacity(token.len());
for c in token.chars() {
if c.is_ascii() {
out.push(c);
} else if unicode_normalization::char::is_combining_mark(c) {
} else if let Some((_, ascii)) = SPECIAL.iter().find(|(from, _)| *from == c) {
out.push_str(ascii);
} else {
let base: String = std::iter::once(c)
.nfkd()
.filter(|part| !unicode_normalization::char::is_combining_mark(*part))
.collect();
if base.is_ascii() && !base.is_empty() {
out.push_str(&base);
} else {
out.push(c);
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::fold;
#[test]
fn latin_diacritics_ligatures_and_variants_fold() {
for (from, to) in [
("eifrém", "eifrem"),
("müller", "muller"),
("zoë", "zoe"),
("naïve", "naive"),
("æther", "aether"),
("straße", "strasse"),
("œuvre", "oeuvre"),
("łódź", "lodz"),
("ångström", "angstrom"),
("fish", "fish"),
("abc", "abc"),
("dž", "dz"),
("ijssel", "ijssel"),
("ø", "o"),
("þ", "th"),
("ı", "i"),
("plain_ascii", "plain_ascii"),
] {
assert_eq!(fold(from), to, "{from}");
}
assert_eq!(fold(&"İ".to_lowercase()), "i");
assert_eq!(fold("e\u{301}"), "e");
}
#[test]
fn non_latin_scripts_are_untouched() {
for token in ["άλφα", "ελλάς", "йод", "日本語"] {
assert_eq!(fold(token), token);
}
}
}