bilingua-model 0.10.0

Bilingua: the extracted-document model shared by every Bilingua file parser
Documentation
//! CLDR plural categories per language: one table for every format crate that fills plural forms on a
//! target-language merge. The data (`cldr_data.rs`) is generated by `tools/gen_cldr.py` from CLDR through babel
//! (the version is noted in the file), the data Localization OS reads. Not part of the semver API: each crate
//! keeps its own fallback for an unknown language (they differ, as the LocOS filters do).

#[path = "cldr_data.rs"]
mod data;

use data::{BABEL_ALIASES, CARDINAL, ORDINAL};

/// The six categories in CLDR order; bit `n` of a category set is `ORDER[n]`.
pub const ORDER: [&str; 6] = ["zero", "one", "two", "few", "many", "other"];

/// Old language codes babel still resolves, with the language they stand for.
const ALIASES: &[(&str, &str)] = &[("in", "id"), ("iw", "he"), ("ji", "yi"), ("mo", "ro"), ("tl", "fil")];

fn find(table: &[(&str, u8)], code: &str) -> Option<u8> {
    table.binary_search_by(|(c, _)| (*c).cmp(code)).ok().map(|i| table[i].1)
}

/// The language part of a tag (before the first `-` or `_`), trimmed and lower-cased.
pub fn language(locale: &str) -> String {
    locale.trim().split(['-', '_']).next().unwrap_or("").to_ascii_lowercase()
}

/// The cardinal category set of a language code (lower case, no region) the table knows; `None` otherwise. Old
/// codes (`iw`, `in`, ...) are not known here: see [`cardinal_bits_aliased`].
pub fn cardinal_bits(lang: &str) -> Option<u8> {
    find(CARDINAL, lang)
}

/// [`cardinal_bits`], and the old codes babel still resolves (`in`, `iw`, `ji`, `mo`, `tl`) as the language they
/// stand for.
pub fn cardinal_bits_aliased(lang: &str) -> Option<u8> {
    cardinal_bits(lang).or_else(|| ALIASES.iter().find(|(a, _)| *a == lang).and_then(|(_, t)| cardinal_bits(t)))
}

/// The ordinal category set of a language code; `other` (32) for a language with no ordinal rule of its own or
/// an unknown one.
pub fn ordinal_bits(lang: &str) -> u8 {
    find(ORDINAL, lang).unwrap_or(32)
}

/// The category names of a set, in CLDR order. `other` is always included.
pub fn names(bits: u8) -> Vec<&'static str> {
    let bits = bits | 32;
    ORDER.iter().enumerate().filter(|(n, _)| bits & (1 << n) != 0).map(|(_, c)| *c).collect()
}

/// The cardinal categories of a locale tag (`pl`, `pt-BR`, `zh_CN`), `other` always included; `None` for a
/// language the table does not know.
pub fn cardinal(locale: &str) -> Option<Vec<&'static str>> {
    cardinal_bits(&language(locale)).map(names)
}

/// The row of Babel's alias table for a code (`deu`, `ara`, `iw`, `root`, `und`, ...): (language, cardinal, ordinal).
fn babel_alias(lang: &str) -> Option<(&'static str, u8, u8)> {
    BABEL_ALIASES.binary_search_by(|(c, _, _, _)| (*c).cmp(lang)).ok().map(|i| (BABEL_ALIASES[i].1, BABEL_ALIASES[i].2, BABEL_ALIASES[i].3))
}

/// The language Babel resolves a code to: `deu` is `de`, `iw` is `he`, `und` is `en`; a code with a row of its
/// own (and one Babel does not know) comes back as it is.
pub fn babel_language(lang: &str) -> &str {
    if cardinal_bits(lang).is_some() {
        return lang;
    }
    babel_alias(lang).map_or(lang, |(l, _, _)| l)
}

/// The category set Babel gives a language code (lower case, no region): the language's own row, else the row of
/// the alias Babel resolves it to (`deu`, `ara`, `iw`, `root`, `und`, ...). `ordinal` asks for the ordinal set,
/// which is `other` (32) for a known language with no ordinal rule. `None` for a code Babel does not know.
pub fn bits_babel(lang: &str, ordinal: bool) -> Option<u8> {
    if let Some(card) = cardinal_bits(lang) {
        return Some(if ordinal { ordinal_bits(lang) } else { card });
    }
    babel_alias(lang).map(|(_, card, ord)| if ordinal { ord } else { card })
}

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

    #[test]
    fn tables_are_sorted_and_known_languages_match_cldr() {
        assert!(CARDINAL.windows(2).all(|w| w[0].0 < w[1].0));
        assert!(ORDINAL.windows(2).all(|w| w[0].0 < w[1].0));
        assert_eq!(cardinal("pl-PL").unwrap(), ["one", "few", "many", "other"]);
        assert_eq!(cardinal("ar").unwrap(), ["zero", "one", "two", "few", "many", "other"]);
        assert_eq!(cardinal("ja").unwrap(), ["other"]);
        assert_eq!(cardinal("fr_CA").unwrap(), ["one", "many", "other"]);
        assert!(cardinal("xx").is_none());
        assert!(cardinal("").is_none());
        assert_eq!(names(ordinal_bits("en")), ["one", "two", "few", "other"]);
        assert_eq!(names(ordinal_bits("de")), ["other"]);
    }

    #[test]
    fn old_codes_resolve_only_when_asked() {
        assert!(cardinal_bits("iw").is_none());
        assert_eq!(cardinal_bits_aliased("iw"), cardinal_bits("he"));
        assert_eq!(cardinal_bits_aliased("tl"), cardinal_bits("fil"));
        assert_eq!(cardinal_bits_aliased("de"), cardinal_bits("de"));
    }

    #[test]
    fn babel_aliases_resolve_to_their_language() {
        assert_eq!(babel_language("deu"), "de");
        assert_eq!(babel_language("iw"), "he");
        assert_eq!(babel_language("und"), "en");
        assert_eq!(babel_language("ru"), "ru");
        assert_eq!(babel_language("xx"), "xx");
        assert!(BABEL_ALIASES.windows(2).all(|w| w[0].0 < w[1].0));
        assert_eq!(names(bits_babel("rus", false).unwrap()), ["one", "few", "many", "other"]);
        assert_eq!(names(bits_babel("eng", true).unwrap()), ["one", "two", "few", "other"]);
        assert_eq!(names(bits_babel("tl", true).unwrap()), ["one", "other"]);
        assert_eq!(names(bits_babel("de", true).unwrap()), ["other"]);
        assert_eq!(names(bits_babel("root", false).unwrap()), ["other"]);
        assert!(bits_babel("xx", false).is_none() && bits_babel("", true).is_none());
        // an alias row agrees with the row of the language it names, except where Babel's ordinal data differs
        for (a, t, card, _) in BABEL_ALIASES {
            if let Some(c) = cardinal_bits(t) {
                assert_eq!(*card, c, "{a}");
            }
        }
    }
}