use unicode_normalization::char::is_combining_mark;
use unicode_normalization::UnicodeNormalization;
pub fn normalize(s: &str) -> String {
let pre: String = {
let ch: Vec<char> = s.chars().collect();
let mut o = String::with_capacity(s.len());
let mut i = 0;
while i < ch.len() {
let c = ch[i];
if c == '-'
&& i > 0
&& i + 1 < ch.len()
&& ch[i - 1].is_ascii_digit()
&& ch[i + 1].is_ascii_digit()
{
i += 1;
while i < ch.len() && ch[i].is_ascii_digit() {
i += 1; }
continue;
}
if c == '-'
&& i > 0
&& i + 1 < ch.len()
&& ch[i - 1].is_alphabetic()
&& ch[i + 1].is_ascii_digit()
&& (i == 1 || !ch[i - 2].is_alphanumeric())
{
i += 1;
continue;
}
o.push(c);
i += 1;
}
o
};
let mut out = String::with_capacity(pre.len());
let mut prev_space = true;
for ch in pre.chars().flat_map(|c| c.to_lowercase()) {
for d in ch.nfd() {
if is_combining_mark(d) {
continue; }
let mapped: Option<char> = match d {
'-' | '\'' | '’' | '‘' | 'ʻ' | 'ʼ' | '`' | '.' | '/' | ',' | ';' | '(' | ')' => {
None
}
c if c.is_whitespace() => None,
'\u{0111}' => Some('d'),
'\u{200B}'..='\u{200F}'
| '\u{2028}'..='\u{202E}'
| '\u{FE00}'..='\u{FE0F}'
| '\u{2190}'..='\u{2BFF}'
| '\u{1F000}'..='\u{1FFFF}' => None,
c if c.is_control() => None,
c => Some(c),
};
match mapped {
Some(c) => {
out.push(c);
prev_space = false;
}
None => {
if !prev_space {
out.push(' ');
prev_space = true;
}
}
}
}
}
let mut out = split_glued_postcode(&out);
while out.ends_with(' ') {
out.pop();
}
out
}
fn is_glued_postcode_boundary(digit_run: usize, character: char, output_ends_space: bool) -> bool {
digit_run >= 4 && character.is_alphabetic() && !output_ends_space
}
fn split_glued_postcode(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
let mut digit_run = 0usize;
for c in s.chars() {
if c.is_ascii_digit() {
digit_run += 1;
} else {
if is_glued_postcode_boundary(digit_run, c, out.ends_with(' ')) {
out.push(' ');
}
digit_run = 0;
}
out.push(c);
}
out
}
#[cfg(test)]
pub(crate) fn de_postcode_seam_trace(raw: &str) -> Option<String> {
let mut digit_run = 0usize;
let mut ends_space = true;
for character in raw.chars() {
if character.is_ascii_digit() {
digit_run += 1;
} else {
if is_glued_postcode_boundary(digit_run, character, ends_space) {
return Some(format!("{raw} -> {}", normalize(raw)));
}
digit_run = 0;
}
ends_space = character.is_whitespace();
}
None
}
pub fn translit_cyr_lat(s: &str) -> String {
let mut out = String::with_capacity(s.len() * 2);
for c in s.chars() {
match c {
'а' => out.push('a'),
'б' => out.push('b'),
'в' => out.push('v'),
'г' => out.push('g'),
'д' => out.push('d'),
'ђ' => out.push('đ'),
'е' => out.push('e'),
'ж' => out.push('ž'),
'з' => out.push('z'),
'и' => out.push('i'),
'ј' => out.push('j'),
'к' => out.push('k'),
'л' => out.push('l'),
'љ' => out.push_str("lj"),
'м' => out.push('m'),
'н' => out.push('n'),
'њ' => out.push_str("nj"),
'о' => out.push('o'),
'п' => out.push('p'),
'р' => out.push('r'),
'с' => out.push('s'),
'т' => out.push('t'),
'ћ' => out.push('ć'),
'у' => out.push('u'),
'ф' => out.push('f'),
'х' => out.push('h'),
'ц' => out.push('c'),
'ч' => out.push('č'),
'џ' => out.push_str("dž"),
'ш' => out.push('š'),
'я' => out.push_str("ja"),
'ю' => out.push_str("ju"),
'щ' => out.push_str("šč"),
'ы' => out.push('i'),
'э' => out.push('e'),
'ь' | 'ъ' => {}
other => out.push(other),
}
}
out
}
pub fn translit_cyr_lat_en(s: &str) -> String {
let mut out = String::with_capacity(s.len() * 2);
for c in s.chars() {
match c {
'а' => out.push('a'),
'б' => out.push('b'),
'в' => out.push('v'),
'г' => out.push('g'),
'д' => out.push('d'),
'е' | 'э' => out.push('e'),
'ё' => out.push_str("yo"),
'ж' => out.push_str("zh"),
'з' => out.push('z'),
'и' | 'ы' => out.push('i'),
'й' => out.push('y'), 'к' => out.push('k'),
'л' => out.push('l'),
'м' => out.push('m'),
'н' => out.push('n'),
'о' => out.push('o'),
'п' => out.push('p'),
'р' => out.push('r'),
'с' => out.push('s'),
'т' => out.push('t'),
'у' => out.push('u'),
'ф' => out.push('f'),
'х' => out.push('h'),
'ц' => out.push_str("ts"),
'ч' => out.push_str("ch"),
'ш' => out.push_str("sh"),
'щ' => out.push_str("shch"),
'ю' => out.push_str("yu"),
'я' => out.push_str("ya"),
'ў' => out.push('o'),
'ғ' => out.push('g'),
'қ' => out.push('q'),
'ҳ' => out.push('h'),
'ҷ' => out.push('j'),
'ь' | 'ъ' => {}
other => out.push(other),
}
}
out
}
pub fn has_cyrillic(s: &str) -> bool {
s.chars().any(|c| ('\u{0400}'..='\u{04FF}').contains(&c))
}
pub fn has_latin(s: &str) -> bool {
s.chars().any(|c| c.is_ascii_alphabetic())
}
const PHON_GROUPS: &[(&str, char)] = &[
("aou", 'o'), ("eiy", 'i'), ("qk", 'k'),
("xh", 'h'),
("wv", 'v'), ];
pub fn phonetic_key(s: &str) -> String {
let lat = if has_cyrillic(s) {
translit_cyr_lat_en(s)
} else {
s.to_string()
};
let n = normalize(&lat);
let mut out = String::with_capacity(n.len());
let mut prev = '\0';
for ch in n.chars() {
if ch == ' ' {
out.push(' ');
prev = '\0';
continue;
}
let c = PHON_GROUPS
.iter()
.find(|(set, _)| set.contains(ch))
.map(|(_, k)| *k)
.unwrap_or(ch);
if c != prev {
out.push(c); prev = c;
}
}
out
}
pub fn fold_homoglyphs(s: &str) -> String {
fn homoglyph(c: char) -> Option<char> {
Some(match c {
'a' => 'а',
'b' => 'в',
'c' => 'с',
'e' => 'е',
'h' => 'н',
'k' => 'к',
'm' => 'м',
'o' => 'о',
'p' => 'р',
't' => 'т',
'x' => 'х',
'y' => 'у',
_ => return None,
})
}
if !s.chars().any(|c| c.is_ascii_alphabetic()) || !has_cyrillic(s) {
return s.to_string(); }
s.split(' ')
.map(|tok| {
let cyr = tok
.chars()
.filter(|c| ('\u{0400}'..='\u{04FF}').contains(c))
.count();
let lat = tok.chars().filter(|c| c.is_ascii_alphabetic()).count();
if cyr == 0 || lat == 0 || cyr <= lat {
return tok.to_string();
}
tok.chars().map(|c| homoglyph(c).unwrap_or(c)).collect()
})
.collect::<Vec<_>>()
.join(" ")
}
pub fn translit_lat_cyr(s: &str) -> String {
let ch: Vec<char> = s.chars().collect();
let n = ch.len();
let starts = |i: usize, p: &str| -> bool {
let pc: Vec<char> = p.chars().collect();
i + pc.len() <= n && ch[i..i + pc.len()] == pc[..]
};
let mut out = String::with_capacity(s.len() * 2);
let mut i = 0;
while i < n {
if starts(i, "shch") {
out.push('щ');
i += 4;
} else if starts(i, "sch") {
out.push('щ');
i += 3;
} else if starts(i, "zh") {
out.push('ж');
i += 2;
} else if starts(i, "kh") {
out.push('х');
i += 2;
} else if starts(i, "ch") {
out.push('ч');
i += 2;
} else if starts(i, "sh") {
out.push('ш');
i += 2;
} else if starts(i, "yo") {
out.push('ё');
i += 2;
} else if starts(i, "yu") {
out.push('ю');
i += 2;
} else if starts(i, "ya") {
out.push('я');
i += 2;
} else if ch[i] == 'y' {
let prev_vowel = matches!(
out.chars().last(),
Some('а' | 'е' | 'ё' | 'и' | 'о' | 'у' | 'ы' | 'э' | 'ю' | 'я')
);
out.push(if prev_vowel { 'й' } else { 'ы' });
i += 1;
} else {
out.push(match ch[i] {
'a' => 'а',
'b' => 'б',
'c' => 'к',
'd' => 'д',
'e' => 'е',
'f' => 'ф',
'g' => 'г',
'h' => 'х',
'i' => 'и',
'j' => 'й',
'k' => 'к',
'l' => 'л',
'm' => 'м',
'n' => 'н',
'o' => 'о',
'p' => 'п',
'q' => 'к',
'r' => 'р',
's' => 'с',
't' => 'т',
'u' => 'у',
'v' => 'в',
'w' => 'в',
'x' => 'х',
'z' => 'з',
other => other,
});
i += 1;
}
}
out
}
#[cfg(test)]
mod tests {
use super::normalize;
#[test]
fn mirrors_duckdb() {
assert_eq!(
normalize("Avenue du Général-Leclerc"),
"avenue du general leclerc"
);
assert_eq!(normalize("Rue de l'Église"), "rue de l eglise");
assert_eq!(normalize("Bulevar Oslobođenja"), "bulevar oslobodenja"); assert_eq!(normalize("Šafarikova ČĆŽ"), "safarikova ccz");
assert_eq!(normalize("Ёлки-Йод"), "елки иод"); assert_eq!(normalize("oʻzbekiston g‘afur"), "o zbekiston g afur");
}
#[test]
fn translit_serbian_pair() {
use super::translit_cyr_lat;
assert_eq!(
normalize(&translit_cyr_lat("милентија поповића")),
"milentija popovica"
);
assert_eq!(
normalize(&translit_cyr_lat("милентия поповича")),
"milentija popovica"
);
assert_eq!(
normalize(&translit_cyr_lat("кнеза михаила")),
"kneza mihaila"
);
}
#[test]
fn translit_latin_to_cyrillic() {
use super::translit_lat_cyr;
assert_eq!(normalize(&translit_lat_cyr("bratsk")), "братск");
assert_eq!(normalize(&translit_lat_cyr("tashkent")), "ташкент");
assert_eq!(
normalize(&translit_lat_cyr("улица возрождения 1 bratsk")),
"улица возрождения 1 братск"
);
assert_eq!(normalize(&translit_lat_cyr("leninskiy")), "ленинскии");
assert_eq!(
normalize(&translit_lat_cyr("novoyasenevskiy")),
"новоясеневскии"
);
assert_eq!(normalize(&translit_lat_cyr("tolstoy")), "толстои");
assert_eq!(normalize(&translit_lat_cyr("krym")), "крым"); }
#[test]
fn fold_homoglyphs_mixed_script() {
use super::fold_homoglyphs;
assert_eq!(
fold_homoglyphs("тв\u{0065}рск\u{0061}я 6 москва"),
"тверская 6 москва"
);
assert_eq!(fold_homoglyphs("tverskaya 6 moskva"), "tverskaya 6 moskva");
assert_eq!(fold_homoglyphs("тверская 6 москва"), "тверская 6 москва");
assert_eq!(fold_homoglyphs("ab\u{0432}"), "ab\u{0432}"); assert_eq!(
fold_homoglyphs("\u{0079}\u{0062}\u{043E}\u{0440}\u{043A}\u{0430}"),
"уворка"
);
}
}