Cotton code
65 lines · 2.3 KB · RustRaw
//! JavaScript text rules shared by the phone's keyboard and dictation writers.use cotton_store::protocol::js::is_js_whitespace;/// The keyboard's `text.trim().split(/\s+/)` count, including BOM but not NEL.pub fn count_words(text: &str) -> i64 {    text.split(is_js_whitespace)        .filter(|word| !word.is_empty())        .count() as i64}/// English localeCompare: compiled ICU data, independent of the process locale.pub fn compare_names(a: &str, b: &str) -> std::cmp::Ordering {    let collator = icu_collator::Collator::try_new(Default::default(), Default::default())        .expect("ICU's compiled root collation data is present");    collator.compare(a, b)}/// Sort by name the way the app sorts the fan: [`compare_names`] (case-/// insensitive, accents after their letter), then by `tie` where two names/// collate equal, so the answer never depends on the order things came in.pub fn sort_by_name<T>(items: &mut Vec<T>, name: impl Fn(&T) -> String, tie: impl Fn(&T) -> String) {    let collator = icu_collator::Collator::try_new(Default::default(), Default::default())        .expect("ICU's compiled root collation data is present");    let mut keyed: Vec<(String, String, T)> = items.drain(..).map(|item| (name(&item), tie(&item), item)).collect();    keyed.sort_by(|a, b| collator.compare(&a.0, &b.0).then_with(|| a.1.cmp(&b.1)));    items.extend(keyed.into_iter().map(|(_, _, item)| item));}#[cfg(test)]mod tests {    use super::*;    #[test]    fn javascript_whitespace_is_not_rust_whitespace() {        for (text, count) in [            ("", 0),            (" \t\n", 0),            (" a  b ", 2),            ("a\u{feff}b", 2),            ("a\u{85}b", 1),            ("\u{feff}", 0),            ("\u{85}", 1),        ] {            assert_eq!(count_words(text), count, "{text:?}");        }    }    #[test]    fn names_use_collation_not_uppercase_first_byte_order() {        let mut names = [            "Zeta Synthetic",            "alpha Synthetic",            "Écho Synthetic",            "echo Synthetic",        ];        names.sort_by(|a, b| compare_names(a, b));        assert_eq!(            names,            [                "alpha Synthetic",                "echo Synthetic",                "Écho Synthetic",                "Zeta Synthetic"            ]        );    }}