lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! Counts user-perceived characters (extended grapheme clusters, UAX #29), like `Intl.Segmenter`
//! does for `countLumenCharacters` in lumen-core. The break classes live in the generated
//! `character_count_grapheme_data` table.

// cspell:words jamo Kirat viramas

use super::character_count_grapheme_data::GRAPHEME_RANGES;

/// The grapheme cluster break class of a code point, folded with the Indic conjunct break
/// (`InCB`) property that rule `GB9c` needs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum GraphemeClass {
    /// Anything without a special rule.
    Other,
    /// Carriage return.
    Cr,
    /// Line feed.
    Lf,
    /// Controls, separators, and most format characters: always a cluster of their own.
    Control,
    /// Combining marks and other extenders that are not `InCB=Extend`.
    Extend,
    /// Extenders that may also sit inside an Indic conjunct (`InCB=Extend`).
    ExtendConjunct,
    /// Viramas that join two consonants into a conjunct (`InCB=Linker`).
    Linker,
    /// Zero width joiner.
    Zwj,
    /// Flag halves; two make one cluster.
    RegionalIndicator,
    /// Characters that join the following character.
    Prepend,
    /// Spacing combining marks.
    SpacingMark,
    /// Hangul leading jamo.
    L,
    /// Hangul vowel jamo (and Kirat Rai vowel signs).
    V,
    /// Hangul trailing jamo.
    T,
    /// Hangul syllable without a trailing consonant.
    Lv,
    /// Hangul syllable with a trailing consonant.
    Lvt,
    /// Extended pictographic characters (emoji).
    Pictographic,
    /// Consonants that a linker can join (`InCB=Consonant`).
    Consonant,
}

const HANGUL_FIRST: u32 = 0xAC00;
const HANGUL_LAST: u32 = 0xD7A3;
const HANGUL_TRAILING_COUNT: u32 = 28;

/// The class of one character: a binary search over the generated ranges.
pub(super) fn grapheme_class(character: char) -> GraphemeClass {
    let code_point = u32::from(character);

    if (HANGUL_FIRST..=HANGUL_LAST).contains(&code_point) {
        return if (code_point - HANGUL_FIRST).is_multiple_of(HANGUL_TRAILING_COUNT) {
            GraphemeClass::Lv
        } else {
            GraphemeClass::Lvt
        };
    }

    GRAPHEME_RANGES
        .binary_search_by(|(first, last, _)| {
            if *last < code_point {
                std::cmp::Ordering::Less
            } else if *first > code_point {
                std::cmp::Ordering::Greater
            } else {
                std::cmp::Ordering::Equal
            }
        })
        .map_or(GraphemeClass::Other, |index| GRAPHEME_RANGES[index].2)
}

/// Progress through an Indic conjunct (GB9c): consonant, then extenders and at least one linker.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Conjunct {
    None,
    Consonant,
    Linker,
}

/// Progress through an emoji ZWJ sequence (GB11): pictograph, extenders, then a joiner.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Emoji {
    None,
    Pictographic,
    Joiner,
}

fn is_extend(class: GraphemeClass) -> bool {
    matches!(
        class,
        GraphemeClass::Extend | GraphemeClass::ExtendConjunct | GraphemeClass::Linker
    )
}

fn is_control(class: GraphemeClass) -> bool {
    matches!(
        class,
        GraphemeClass::Control | GraphemeClass::Cr | GraphemeClass::Lf
    )
}

/// Whether there is no cluster boundary between `previous` and `current` (rules GB3 to GB13).
fn joins(
    previous: GraphemeClass,
    current: GraphemeClass,
    conjunct: Conjunct,
    emoji: Emoji,
    regional_run: usize,
) -> bool {
    use GraphemeClass::{Cr, L, Lf, Lv, Lvt, Pictographic, Prepend, RegionalIndicator, T, V};

    if previous == Cr && current == Lf {
        return true;
    }

    if is_control(previous) || is_control(current) {
        return false;
    }

    match (previous, current) {
        (L, L | V | Lv | Lvt) | (Lv | V, V | T) | (Lvt | T, T) => return true,
        _ => {}
    }

    if is_extend(current) || matches!(current, GraphemeClass::Zwj | GraphemeClass::SpacingMark) {
        return true;
    }

    if previous == Prepend {
        return true;
    }

    if conjunct == Conjunct::Linker && current == GraphemeClass::Consonant {
        return true;
    }

    if emoji == Emoji::Joiner && current == Pictographic {
        return true;
    }

    previous == RegionalIndicator && current == RegionalIndicator && regional_run % 2 == 1
}

/// Counts extended grapheme clusters in one linear pass: an emoji with modifiers or joiners, a
/// flag, a letter with combining marks, a Hangul syllable, an Indic conjunct, or CR LF each count
/// once.
pub(super) fn count_graphemes(value: &str) -> usize {
    let mut count = 0;
    let mut previous: Option<GraphemeClass> = None;
    let mut conjunct = Conjunct::None;
    let mut emoji = Emoji::None;
    let mut regional_run = 0;

    for character in value.chars() {
        let current = grapheme_class(character);

        if previous.is_none_or(|previous| !joins(previous, current, conjunct, emoji, regional_run))
        {
            count += 1;
        }

        conjunct = match current {
            GraphemeClass::Consonant => Conjunct::Consonant,
            GraphemeClass::Linker if conjunct != Conjunct::None => Conjunct::Linker,
            GraphemeClass::ExtendConjunct | GraphemeClass::Zwj => conjunct,
            _ => Conjunct::None,
        };

        emoji = match current {
            GraphemeClass::Pictographic => Emoji::Pictographic,
            class if is_extend(class) && emoji == Emoji::Pictographic => Emoji::Pictographic,
            GraphemeClass::Zwj if emoji == Emoji::Pictographic => Emoji::Joiner,
            _ => Emoji::None,
        };

        regional_run = if current == GraphemeClass::RegionalIndicator {
            regional_run + 1
        } else {
            0
        };
        previous = Some(current);
    }

    count
}

#[cfg(test)]
mod tests {
    use super::{GraphemeClass, count_graphemes, grapheme_class};
    use crate::inputs::character_count_grapheme_data::GRAPHEME_RANGES;

    #[test]
    fn the_generated_ranges_are_sorted_and_disjoint() {
        for pair in GRAPHEME_RANGES.windows(2) {
            assert!(pair[0].0 <= pair[0].1, "{:x?}", pair[0]);
            assert!(
                pair[0].1 < pair[1].0,
                "{:x?} overlaps {:x?}",
                pair[0],
                pair[1]
            );
        }
    }

    #[test]
    fn classes_follow_unicode() {
        assert_eq!(grapheme_class('a'), GraphemeClass::Other);
        assert_eq!(grapheme_class('\r'), GraphemeClass::Cr);
        assert_eq!(grapheme_class('\n'), GraphemeClass::Lf);
        assert_eq!(grapheme_class('\u{301}'), GraphemeClass::ExtendConjunct);
        assert_eq!(grapheme_class('\u{94D}'), GraphemeClass::Linker);
        assert_eq!(grapheme_class('\u{915}'), GraphemeClass::Consonant);
        assert_eq!(grapheme_class('\u{93E}'), GraphemeClass::SpacingMark);
        assert_eq!(grapheme_class('\u{200D}'), GraphemeClass::Zwj);
        assert_eq!(grapheme_class('\u{1F44D}'), GraphemeClass::Pictographic);
        assert_eq!(grapheme_class('\u{1F3FD}'), GraphemeClass::ExtendConjunct);
        assert_eq!(
            grapheme_class('\u{1F1E8}'),
            GraphemeClass::RegionalIndicator
        );
        assert_eq!(grapheme_class('\u{600}'), GraphemeClass::Prepend);
        assert_eq!(grapheme_class('\u{AC00}'), GraphemeClass::Lv);
        assert_eq!(grapheme_class('\u{AC01}'), GraphemeClass::Lvt);
        assert_eq!(grapheme_class('\u{1100}'), GraphemeClass::L);
        assert_eq!(grapheme_class('\u{10FFFF}'), GraphemeClass::Other);
    }

    // Expected counts come from `Intl.Segmenter` (Node.js 22, Unicode 17).
    #[test]
    fn counts_match_intl_segmenter() {
        let cases: &[(&str, usize)] = &[
            ("", 0),
            ("hello", 5),
            ("πŸ‘πŸ½Γ©πŸ‘¨β€πŸ‘©β€πŸ‘§", 3),
            ("πŸ‘πŸ½Γ©πŸ‘¨β€πŸ‘©β€πŸ‘§!", 4),
            ("e\u{301}", 1),
            ("\r\n", 1),
            ("\n\r", 2),
            ("πŸ‡¨πŸ‡΄πŸ‡ΊπŸ‡Έ", 2),
            ("πŸ‡¨πŸ‡΄πŸ‡Ί", 2),
            ("ΰ€•ΰ₯ΰ€·", 1),
            ("ΰ€•ΰ₯\u{200D}ΰ€·", 1),
            ("ΰ€•ΰ€Ώ", 1),
            ("각", 1),
            ("\u{1100}\u{1161}\u{11A8}", 1),
            ("a\u{200B}b", 3),
            ("\u{600}1", 1),
            ("a\u{200D}πŸ‘", 2),
            ("πŸ³οΈβ€πŸŒˆ", 1),
            ("\u{301}", 1),
            ("\u{1F3FB}\u{1F3FB}", 1),
            ("\u{16D63}\u{16D63}", 1),
        ];

        for (text, expected) in cases {
            assert_eq!(count_graphemes(text), *expected, "{text:?}");
        }
    }

    #[test]
    fn long_and_adversarial_input_counts_linearly() {
        let marks = format!("a{}", "\u{301}".repeat(100_000));
        let flags = "\u{1F1E8}".repeat(100_001);
        let joiners = "πŸ‘\u{200D}".repeat(50_000);
        let conjuncts = "ΰ€•ΰ₯".repeat(50_000);

        assert_eq!(count_graphemes(&marks), 1);
        assert_eq!(count_graphemes(&flags), 50_001);
        assert_eq!(count_graphemes(&joiners), 1);
        assert_eq!(count_graphemes(&conjuncts), 1);
        assert_eq!(count_graphemes(&"\r\n".repeat(100_000)), 100_000);
    }
}