#[derive(Clone, Copy)]
pub(crate) enum Rule {
Map(char, char),
Delete(char),
}
pub(crate) const RULES: &[Rule] = &[
Rule::Delete('\u{064B}'),
Rule::Delete('\u{064C}'),
Rule::Delete('\u{064D}'),
Rule::Delete('\u{064E}'),
Rule::Delete('\u{064F}'),
Rule::Delete('\u{0650}'),
Rule::Delete('\u{0651}'),
Rule::Delete('\u{0652}'),
Rule::Delete('\u{0670}'),
Rule::Delete('\u{0640}'),
Rule::Map('\u{0623}', '\u{0627}'),
Rule::Map('\u{0625}', '\u{0627}'),
Rule::Map('\u{0622}', '\u{0627}'),
Rule::Map('\u{0671}', '\u{0627}'),
Rule::Map('\u{0649}', '\u{064A}'),
Rule::Map('\u{0629}', '\u{0647}'),
Rule::Map('\u{06A9}', '\u{0643}'),
Rule::Map('\u{06CC}', '\u{064A}'),
Rule::Map('\u{0660}', '0'),
Rule::Map('\u{0661}', '1'),
Rule::Map('\u{0662}', '2'),
Rule::Map('\u{0663}', '3'),
Rule::Map('\u{0664}', '4'),
Rule::Map('\u{0665}', '5'),
Rule::Map('\u{0666}', '6'),
Rule::Map('\u{0667}', '7'),
Rule::Map('\u{0668}', '8'),
Rule::Map('\u{0669}', '9'),
Rule::Map('\u{06F0}', '0'),
Rule::Map('\u{06F1}', '1'),
Rule::Map('\u{06F2}', '2'),
Rule::Map('\u{06F3}', '3'),
Rule::Map('\u{06F4}', '4'),
Rule::Map('\u{06F5}', '5'),
Rule::Map('\u{06F6}', '6'),
Rule::Map('\u{06F7}', '7'),
Rule::Map('\u{06F8}', '8'),
Rule::Map('\u{06F9}', '9'),
];
pub fn normalize_arabic(text: &str) -> String {
text.chars()
.filter_map(|c| {
for rule in RULES {
match *rule {
Rule::Delete(d) if d == c => return None,
Rule::Map(from, to) if from == c => return Some(to),
_ => {}
}
}
Some(c)
})
.collect()
}
fn arabic_letter(c: char) -> Option<&'static str> {
Some(match c {
'ا' | 'ء' | 'ؤ' | 'ئ' | 'ع' | 'و' | 'ي' => "",
'ب' | 'پ' => "b",
'ت' | 'ط' => "t",
'ث' => "th",
'ج' => "j",
'ح' | 'ه' => "h",
'خ' => "kh",
'د' | 'ض' => "d",
'ذ' | 'ظ' => "dh",
'ر' => "r",
'ز' => "z",
'س' | 'ص' => "s",
'ش' => "sh",
'غ' => "gh",
'ف' => "f",
'ق' => "q",
'ك' => "k",
'ل' => "l",
'م' => "m",
'ن' => "n",
'چ' => "ch",
'گ' => "g",
'ژ' => "zh",
'ڤ' => "v",
_ => return None,
})
}
pub fn transliterate(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in normalize_arabic(text).chars() {
match arabic_letter(c) {
Some(latin) => out.push_str(latin),
None => out.extend(c.to_lowercase()),
}
}
out
}
fn unaccent(c: char) -> char {
match c {
'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' => 'a',
'è' | 'é' | 'ê' | 'ë' => 'e',
'ì' | 'í' | 'î' | 'ï' => 'i',
'ò' | 'ó' | 'ô' | 'õ' | 'ö' => 'o',
'ù' | 'ú' | 'û' | 'ü' => 'u',
'ç' => 'c',
'ñ' => 'n',
other => other,
}
}
fn word_key(word: &str) -> String {
let letters: Vec<char> = word.chars().map(unaccent).collect();
let mut key = String::new();
let mut push = |c: char| {
if !key.ends_with(c) {
key.push(c);
}
};
let mut i = 0;
while i < letters.len() {
let c = letters[i];
let next = letters.get(i + 1).copied();
if next == Some('h') {
let digraph = match c {
's' | 'c' => Some('x'),
'k' | 'g' => Some('k'),
't' => Some('t'),
'd' => Some('z'),
'p' => Some('f'),
'z' => Some('j'),
_ => None,
};
if let Some(d) = digraph {
push(d);
i += 2;
continue;
}
}
match c {
'a' | 'e' | 'i' | 'o' | 'u' | 'y' | 'w' => {}
'c' | 'q' | 'g' => push('k'),
'p' => push('b'),
'v' => push('f'),
other => push(other),
}
i += 1;
}
if key.chars().count() > 1 && key.ends_with('h') {
key.pop();
}
key
}
pub fn match_key(text: &str) -> String {
let skeleton = transliterate(text);
let mut key = String::new();
for word in skeleton.split(|c: char| !c.is_alphanumeric()) {
for c in word_key(word).chars() {
if !key.ends_with(c) {
key.push(c);
}
}
}
key
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_normalisation_rule() {
assert_eq!(normalize_arabic("مُحَمَّدٌ"), "محمد");
assert_eq!(normalize_arabic("كِتَابًا"), "كتابا");
assert_eq!(normalize_arabic("كِتَابٍ"), "كتاب");
assert_eq!(normalize_arabic("مَنْ"), "من");
assert_eq!(normalize_arabic("هٰذا"), "هذا");
assert_eq!(normalize_arabic("محـــمد"), "محمد");
assert_eq!(
normalize_arabic("أحمد إبراهيم آمنة ٱلله"),
"احمد ابراهيم امنه الله"
);
assert_eq!(normalize_arabic("مصطفى"), "مصطفي");
assert_eq!(normalize_arabic("فاطمة"), "فاطمه");
assert_eq!(normalize_arabic("کتاب فارسی"), "كتاب فارسي");
assert_eq!(normalize_arabic("٠١٢٣٤٥٦٧٨٩"), "0123456789");
assert_eq!(normalize_arabic("۰۱۲۳۴۵۶۷۸۹"), "0123456789");
assert_eq!(normalize_arabic("Café 東京 42"), "Café 東京 42");
assert_eq!(normalize_arabic(""), "");
let once = normalize_arabic("أَحْمَدُ ٣");
assert_eq!(normalize_arabic(&once), once);
}
#[test]
fn transliteration_is_a_consonant_skeleton() {
assert_eq!(transliterate("محمد"), "mhmd");
assert_eq!(transliterate("أَحْمَد"), "hmd");
assert_eq!(transliterate("خالد"), "khld");
assert_eq!(transliterate("شريف"), "shrf");
assert_eq!(transliterate("Ali 12"), "ali 12");
assert_eq!(transliterate("رقم ٧"), "rqm 7");
}
#[test]
fn names_get_one_key_in_both_scripts() {
let names: &[(&str, &[&str])] = &[
("محمد", &["Mohammed", "Muhammad", "Mohamed", "Mohammad"]),
("أحمد", &["Ahmad", "Ahmed"]),
("علي", &["Ali", "Aly"]),
("عمر", &["Omar", "Umar"]),
("فاطمة", &["Fatima", "Fatimah"]),
("حسن", &["Hassan", "Hasan"]),
("خالد", &["Khalid", "Khaled"]),
("يوسف", &["Yusuf", "Youssef", "Yousef"]),
("إبراهيم", &["Ibrahim", "Ebrahim"]),
("زينب", &["Zainab", "Zaynab"]),
("سارة", &["Sara", "Sarah"]),
("شريف", &["Sharif", "Shareef"]),
("نور", &["Nour", "Noor"]),
("مصطفى", &["Mustafa", "Moustafa"]),
("عبد الله", &["Abdullah", "Abd Allah", "Abdallah"]),
("عبدالله", &["Abdullah", "Abd Allah"]),
("عبد الرحمن", &["Abd al-Rahman", "Abd Al Rahman"]),
("ياسمين", &["Yasmin", "Yasmine"]),
];
for (arabic, latin) in names {
let key = match_key(arabic);
assert!(!key.is_empty(), "{arabic}");
for spelling in *latin {
assert_eq!(match_key(spelling), key, "{spelling} vs {arabic}");
}
}
assert_eq!(match_key("محمد"), "mhmd");
assert_eq!(match_key("Mohammed"), "mhmd");
}
#[test]
fn different_names_get_different_keys() {
let keys: Vec<String> = ["محمد", "أحمد", "علي", "عمر", "خالد", "Sara", "Karim"]
.iter()
.map(|n| match_key(n))
.collect();
for (i, a) in keys.iter().enumerate() {
for b in &keys[i + 1..] {
assert_ne!(a, b);
}
}
}
#[test]
fn match_key_edge_cases() {
assert_eq!(match_key(""), "");
assert_eq!(match_key(" ... "), "");
assert_eq!(match_key("aeiou"), "");
assert_eq!(match_key("MOHAMMED ALI"), "mhmdl");
assert_eq!(match_key("Zoë"), "z");
assert_eq!(match_key("Unit 42"), "nt42");
assert_eq!(match_key("هاتف ٠١٢"), "htf012");
}
}