sea-orm-sluggable 0.1.0

Unique, transliterated slugs for SeaORM entities
Documentation
use crate::transliterate::Transliterator;

/// Official Ukrainian romanization: Cabinet of Ministers resolution No. 55 (2010).
///
/// Є, Ї, Й, Ю, Я are written differently at the start of a word ("Юрій" ->
/// "Yurii"), "зг" becomes "zgh", and the soft sign and apostrophe are dropped.
/// Characters outside the Ukrainian alphabet fall back to `any_ascii`.
///
/// ```
/// use sea_orm_sluggable::{languages::Ukrainian, Transliterator};
///
/// assert_eq!(Ukrainian.transliterate("Юрій"), "Yurii");
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct Ukrainian;

impl Transliterator for Ukrainian {
    fn transliterate(&self, text: &str) -> String {
        let mut out = String::with_capacity(text.len());
        let mut previous: Option<char> = None;

        for ch in text.chars() {
            let at_word_start = previous.is_none_or(|p| !is_word_char(p));
            let after_z = matches!(previous, Some('з' | 'З'));

            match romanize(
                ch.to_lowercase().next().unwrap_or(ch),
                at_word_start,
                after_z,
            ) {
                Some(latin) if ch.is_uppercase() => push_capitalized(&mut out, latin),
                Some(latin) => out.push_str(latin),
                None => out.push_str(any_ascii::any_ascii_char(ch)),
            }
            previous = Some(ch);
        }
        out
    }
}

/// Letters and apostrophes belong to a word: in "Знам'янка" the "я" is not at
/// the start of one.
fn is_word_char(ch: char) -> bool {
    ch.is_alphabetic() || matches!(ch, '\'' | '’' | 'ʼ')
}

/// Latin spelling of a lowercase Ukrainian letter, or `None` for anything else.
// One arm per letter, in alphabet order, so the table can be checked against the
// resolution line by line; merging equal arms would scramble that order.
#[allow(clippy::match_same_arms)]
const fn romanize(ch: char, at_word_start: bool, after_z: bool) -> Option<&'static str> {
    let latin = match ch {
        'а' => "a",
        'б' => "b",
        'в' => "v",
        'г' if after_z => "gh",
        'г' => "h",
        'ґ' => "g",
        'д' => "d",
        'е' => "e",
        'є' if at_word_start => "ye",
        'є' => "ie",
        'ж' => "zh",
        'з' => "z",
        'и' => "y",
        'і' => "i",
        'ї' if at_word_start => "yi",
        'ї' => "i",
        'й' if at_word_start => "y",
        'й' => "i",
        'к' => "k",
        'л' => "l",
        'м' => "m",
        'н' => "n",
        'о' => "o",
        'п' => "p",
        'р' => "r",
        'с' => "s",
        'т' => "t",
        'у' => "u",
        'ф' => "f",
        'х' => "kh",
        'ц' => "ts",
        'ч' => "ch",
        'ш' => "sh",
        'щ' => "shch",
        'ю' if at_word_start => "yu",
        'ю' => "iu",
        'я' if at_word_start => "ya",
        'я' => "ia",
        'ь' | '\'' | '’' | 'ʼ' => "",
        _ => return None,
    };
    Some(latin)
}

fn push_capitalized(out: &mut String, latin: &str) {
    let mut chars = latin.chars();
    if let Some(first) = chars.next() {
        out.push(first.to_ascii_uppercase());
        out.push_str(chars.as_str());
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Examples from the resolution itself.
    #[test]
    fn follows_the_official_examples() {
        let cases = [
            ("Згорани", "Zghorany"),
            ("Розгон", "Rozghon"),
            ("Єнакієве", "Yenakiieve"),
            ("Їжакевич", "Yizhakevych"),
            ("Кадіївка", "Kadiivka"),
            ("Йосипівка", "Yosypivka"),
            ("Стрий", "Stryi"),
            ("Юрій", "Yurii"),
            ("Корюківка", "Koriukivka"),
            ("Яготин", "Yahotyn"),
            ("Костянтин", "Kostiantyn"),
            ("Знам'янка", "Znamianka"),
            ("Ґалаґан", "Galagan"),
            ("Щербухи", "Shcherbukhy"),
            ("Гоща", "Hoshcha"),
            ("Феодосія", "Feodosiia"),
        ];
        for (ukrainian, latin) in cases {
            assert_eq!(Ukrainian.transliterate(ukrainian), latin, "{ukrainian}");
        }
    }

    #[test]
    fn treats_each_word_separately() {
        assert_eq!(Ukrainian.transliterate("Юрій Яковенко"), "Yurii Yakovenko");
    }

    #[test]
    fn keeps_latin_and_digits() {
        assert_eq!(Ukrainian.transliterate("Rust для PHP 8"), "Rust dlia PHP 8");
    }
}