geolith 0.1.6

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
Documentation
//! Splitting a name that holds several scripts into one segment per script.
//!
//! Port of `ScriptSegmenter.java` from protomaps/basemaps (BSD-3-Clause, see
//! `NOTICE.md`). OSM names such as `Quartier 7 / حارة 7` carry the local name
//! in two scripts. The tile keeps the segments as `name` and `name2` (and
//! `name3`) so the style can show the one in the reader's script first.

use std::collections::HashSet;

use unicode_script::Script;

use super::script::{char_script, script_of};

/// Strip spaces, one trailing separator, an unmatched closing parenthesis and
/// zero width spaces.
#[must_use]
pub(crate) fn clean_ends_and_zwsp(input: &str) -> String {
    let mut result = input.trim().to_string();
    if result.ends_with(['/', '-', ';', '(', ',']) {
        result.pop();
        result = result.trim().to_string();
    }
    if result.ends_with(')') && !result.contains('(') {
        result.pop();
        result = result.trim().to_string();
    }
    result.replace('\u{200B}', "")
}

/// Whether two segments have the same script.
#[must_use]
pub(crate) fn has_repeated_script(segments: &[String]) -> bool {
    let mut seen = HashSet::with_capacity(segments.len());
    segments
        .iter()
        .any(|segment| !seen.insert(script_of(segment)))
}

/// Whether a segment is one UTF-16 unit long (the Java `String.length`).
#[must_use]
pub(crate) fn has_length_one_segment(segments: &[String]) -> bool {
    segments
        .iter()
        .any(|segment| segment.encode_utf16().count() == 1)
}

/// The line without a trailing Roman numeral, which is Latin in any text.
fn without_roman_numeral(line: &str) -> &str {
    let mut line = line;
    for suffix in [" I", "-I", " V", "-V"] {
        if line.ends_with(suffix) {
            line = &line[..line.len() - 2];
            break;
        }
    }
    for suffix in [" II", "-II", " IV", "-IV", " VI", "-VI"] {
        if line.ends_with(suffix) {
            line = &line[..line.len() - 3];
            break;
        }
    }
    for suffix in [" III", "-III"] {
        if line.ends_with(suffix) {
            line = &line[..line.len() - 4];
            break;
        }
    }
    line
}

/// Whether `line` holds several scripts that belong to separate names.
///
/// Han with Hiragana or Katakana is one Japanese name, and a trailing Roman
/// numeral does not count as Latin.
#[must_use]
pub(crate) fn should_segment(line: &str) -> bool {
    let scripts: HashSet<Script> = without_roman_numeral(line)
        .chars()
        .filter_map(char_script)
        .collect();
    if scripts.len() == 2
        && scripts.contains(&Script::Han)
        && (scripts.contains(&Script::Hiragana) || scripts.contains(&Script::Katakana))
    {
        return false;
    }
    if scripts.len() == 3
        && scripts.contains(&Script::Han)
        && scripts.contains(&Script::Hiragana)
        && scripts.contains(&Script::Katakana)
    {
        return false;
    }
    scripts.len() > 1
}

/// Split `input` at each change of script.
///
/// The input comes back whole when it holds one script, when two segments
/// share a script (`第2D區 Area 2D`) or when a segment is one character long
/// (a stray Greek letter inside a Latin name).
#[must_use]
pub fn segment_by_script(input: &str) -> Vec<String> {
    let Some(first) = input.chars().next() else {
        return Vec::new();
    };
    if !should_segment(input) {
        return vec![input.to_string()];
    }

    let mut segments: Vec<String> = Vec::with_capacity(3);
    let mut current = String::with_capacity(input.len());
    let mut current_script = char_script(first);
    let mut flush = |segment: &mut String| {
        let cleaned = clean_ends_and_zwsp(segment);
        if !cleaned.is_empty() {
            segments.push(cleaned);
        }
        segment.clear();
    };

    for ch in input.chars() {
        let script = char_script(ch);
        match current_script {
            None => {
                current_script = script;
                current.push(ch);
            }
            Some(open) if script.is_none() || script == Some(open) => current.push(ch),
            Some(_) => {
                flush(&mut current);
                current.push(ch);
                current_script = script;
            }
        }
    }
    flush(&mut current);

    if has_repeated_script(&segments) || has_length_one_segment(&segments) {
        return vec![input.to_string()];
    }
    segments
}

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

    fn segs(input: &str) -> Vec<String> {
        segment_by_script(input)
    }

    // Expected values below: protomaps/basemaps `ScriptSegmenterTest.java`.
    #[test]
    fn characters_without_a_script_have_none() {
        assert_eq!(char_script('1'), None);
        assert_eq!(char_script(' '), None);
        assert_eq!(char_script('-'), None);
        assert_eq!(char_script('A'), Some(Script::Latin));
    }

    #[test]
    fn clean_ends_and_zwsp_strips_separators() {
        for (input, want) in [
            ("  Zürich ", "Zürich"),
            ("Zürich/", "Zürich"),
            ("Zürich /", "Zürich"),
            ("Zürich-", "Zürich"),
            ("Zürich,", "Zürich"),
            ("Zürich;", "Zürich"),
            ("Zürich(", "Zürich"),
            ("Zürich)", "Zürich"),
            ("Zürich (ZH)", "Zürich (ZH)"),
            ("Zür\u{200B}ich", "Zürich"),
        ] {
            assert_eq!(clean_ends_and_zwsp(input), want, "{input:?}");
        }
    }

    #[test]
    fn repeated_script_is_found_across_a_gap() {
        let owned = |parts: &[&str]| parts.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        assert!(has_repeated_script(&owned(&["t", "t"])));
        assert!(has_repeated_script(&owned(&["_", "A", "_"])));
        assert!(has_repeated_script(&owned(&["t", "τ", "t"])));
        assert!(!has_repeated_script(&owned(&["t", "τ"])));
    }

    #[test]
    fn length_one_segment_is_found() {
        let owned = |parts: &[&str]| parts.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        assert!(has_length_one_segment(&owned(&["Zür", "i", "ch"])));
        assert!(!has_length_one_segment(&owned(&["Zürich"])));
    }

    #[test]
    fn should_segment_follows_the_japanese_and_numeral_rules() {
        for (line, want) in [
            ("Дугинка I", false),
            ("Дугинка-II", false),
            ("Дугинка III", false),
            ("さいたま市", false),
            ("金冷シ", false),
            ("つつじケ丘五丁目", false),
            ("Athens Αθήνα", true),
        ] {
            assert_eq!(should_segment(line), want, "{line:?}");
        }
    }

    #[test]
    fn one_script_stays_whole() {
        for input in [
            "つつじケ丘五丁目",
            "Tazaγart",
            "Æлбортыхъæу",
            "第2D區 Area 2D",
        ] {
            assert_eq!(segs(input), vec![input.to_string()], "{input}");
        }
    }

    #[test]
    fn two_scripts_split_in_two() {
        assert_eq!(segs("Quartier 7 / حارة 7"), ["Quartier 7", "حارة 7"]);
        assert_eq!(segs("긴계단 (Gingyedan)"), ["긴계단", "Gingyedan"]);
    }

    #[test]
    fn three_scripts_split_in_three() {
        assert_eq!(
            segs("Casablanca ⴰⵏⴼⴰ الدار البيضاء"),
            ["Casablanca", "ⴰⵏⴼⴰ", "الدار البيضاء"]
        );
    }

    #[test]
    fn empty_input_has_no_segments() {
        assert!(segs("").is_empty());
    }
}