mcut 0.1.0

Zero-copy, low-memory multilingual word segmenter using pointwise linear classification and minimal FST
Documentation
mod run;
mod simd;
mod zh_han;

pub(crate) use run::{for_each_han_kana_part, for_each_run, for_each_sentence, next_char};
pub(crate) use simd::{find_sentence_end, has_kana_byte};
pub(crate) use zh_han::is_zh_only_han;

use crate::i18n::Lang;

/// Coarse script class used for mixed-language routing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ScriptClass {
  /// Han, Hiragana, Katakana and CJK marks.
  Cjk,
  /// Hangul syllables and Jamo.
  Hangul,
  /// Thai letters and combining marks.
  Thai,
  /// Latin letters (ASCII, Extended, Fullwidth).
  Latin,
  /// Cyrillic letters.
  Cyrillic,
  /// Arabic letters.
  Arabic,
  /// Other alphabetic scripts (Greek, Hebrew, Devanagari, etc.).
  OtherAlpha,
  /// Numeric characters.
  Digit,
  /// Whitespace.
  Space,
  /// Punctuation and symbols.
  Punct,
}

/// High-level script-run kind emitted by [`for_each_run`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum RunKind {
  Cjk {
    has_kana: bool,
    has_zh_only: bool,
    pure_bmp_han: bool,
  },
  Hangul,
  Thai,
  Word(Lang),
  Number,
  Space,
  Punct,
}

/// Sentence-level CJK disambiguation hint.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CjkHint {
  Zh,
  Ja,
  Mixed,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FineScript {
  Han,
  Hiragana,
  Katakana,
  Other(ScriptClass),
}

/// ASCII O(1) lookup table matching [`ScriptClass`].
const ASCII_CLASS: [ScriptClass; 128] = build_ascii_class();

const fn build_ascii_class() -> [ScriptClass; 128] {
  let mut table = [ScriptClass::Punct; 128];
  let mut b = 0usize;
  while b < 128 {
    let c = b as u8;
    if matches!(c, b'\t'..=b'\r' | b' ') {
      table[b] = ScriptClass::Space;
    } else if c.is_ascii_digit() {
      table[b] = ScriptClass::Digit;
    } else if c.is_ascii_alphabetic() {
      table[b] = ScriptClass::Latin;
    }
    b += 1;
  }
  table
}

/// Classifies a single character without slow Unicode table lookups for ASCII and CJK.
#[inline(always)]
pub(crate) fn class(c: char) -> ScriptClass {
  let u = c as u32;
  if u < 128 {
    return ASCII_CLASS[u as usize];
  }
  if is_han(u) || is_hiragana(u) || is_katakana(u) {
    return ScriptClass::Cjk;
  }
  class_non_cjk(c, u)
}

#[inline]
fn class_non_cjk(c: char, u: u32) -> ScriptClass {
  // Fast-path CJK/fullwidth/general punctuation and ideographic space to avoid slow Unicode tables.
  if u == 0x3000 {
    return ScriptClass::Space;
  }
  if matches!(
    u,
    0x2010..=0x2027
      | 0x2030..=0x205E
      | 0x3001..=0x3020
      | 0xFE10..=0xFE1F
      | 0xFE30..=0xFE6B
      | 0xFF01..=0xFF0F
      | 0xFF1A..=0xFF20
      | 0xFF3B..=0xFF40
      | 0xFF5B..=0xFF65
  ) {
    return ScriptClass::Punct;
  }
  if matches!(u, 0xFF10..=0xFF19) {
    return ScriptClass::Digit;
  }
  if matches!(u, 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7AF) {
    return ScriptClass::Hangul;
  }
  if matches!(u, 0x0E00..=0x0E4F) {
    return ScriptClass::Thai;
  }
  if matches!(u, 0x0400..=0x052F | 0x2DE0..=0x2DFF | 0xA640..=0xA69F) {
    return ScriptClass::Cyrillic;
  }
  if c.is_whitespace() {
    return ScriptClass::Space;
  }
  if is_digit_char(c) {
    return ScriptClass::Digit;
  }
  if matches!(u, 0x0E50..=0x0E7F) {
    return ScriptClass::Thai;
  }
  if matches!(u, 0x0600..=0x06FF | 0x0750..=0x077F | 0x08A0..=0x08FF | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF)
  {
    return ScriptClass::Arabic;
  }
  if matches!(
    u,
    0x00C0..=0x024F | 0x1E00..=0x1EFF | 0x2C60..=0x2C7F | 0xA720..=0xA7FF | 0xFF21..=0xFF3A | 0xFF41..=0xFF5A
  ) {
    return ScriptClass::Latin;
  }
  if c.is_alphabetic() {
    return ScriptClass::OtherAlpha;
  }

  ScriptClass::Punct
}

#[inline]
pub(crate) fn is_digit_char(c: char) -> bool {
  let u = c as u32;
  if u < 128 {
    return (b'0' as u32..=b'9' as u32).contains(&u);
  }
  if is_han(u)
    || is_hiragana(u)
    || is_katakana(u)
    || matches!(
      u,
      0x0E00..=0x0E4F | 0x1100..=0x11FF | 0x3130..=0x318F | 0xAC00..=0xD7AF | 0x0400..=0x052F
    )
  {
    return false;
  }
  c.is_numeric() && !is_han_numeral(c)
}

#[inline]
pub(crate) const fn is_combining_mark(c: char) -> bool {
  matches!(
    c as u32,
    0x0300..=0x036F
      | 0x0591..=0x05BD
      | 0x05BF
      | 0x05C1..=0x05C2
      | 0x05C4..=0x05C5
      | 0x05C7
      | 0x0900..=0x0903
      | 0x093A..=0x094F
      | 0x0951..=0x0957
      | 0x0962..=0x0963
      | 0x0F71..=0x0F84
      | 0x102B..=0x103E
      | 0x17B4..=0x17D3
      | 0x1AB0..=0x1AFF
      | 0x1DC0..=0x1DFF
      | 0x20D0..=0x20FF
      | 0xFE20..=0xFE2F
  )
}

#[inline]
pub(crate) const fn alpha_lang(cls: ScriptClass) -> Option<Lang> {
  match cls {
    ScriptClass::Latin | ScriptClass::OtherAlpha => Some(Lang::En),
    ScriptClass::Cyrillic => Some(Lang::Ru),
    ScriptClass::Arabic => Some(Lang::Ar),
    _ => None,
  }
}

const fn is_han_numeral(c: char) -> bool {
  matches!(
    c,
    '〇'
      | '一'
      | '二'
      | '三'
      | '四'
      | '五'
      | '六'
      | '七'
      | '八'
      | '九'
      | '十'
      | '百'
      | '千'
      | '万'
      | '亿'
  )
}

#[inline]
pub(crate) const fn is_han(u: u32) -> bool {
  matches!(
    u,
    0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xF900..=0xFAFF | 0x20000..=0x2FA1F | 0x3005 | 0x3007 | 0x303B
  )
}

#[inline]
pub(crate) const fn is_hiragana(u: u32) -> bool {
  matches!(u, 0x3040..=0x309F)
}

#[inline]
pub(crate) const fn is_katakana(u: u32) -> bool {
  matches!(u, 0x30A0..=0x30FF | 0x31F0..=0x31FF | 0xFF66..=0xFF9F)
}

/// Whether `c` is Hiragana or Katakana.
pub(crate) fn is_kana(c: char) -> bool {
  let u = c as u32;
  is_hiragana(u) || is_katakana(u)
}

fn fine_class(c: char) -> FineScript {
  let u = c as u32;
  if is_hiragana(u) {
    return FineScript::Hiragana;
  }
  if is_katakana(u) {
    return FineScript::Katakana;
  }
  if is_han(u) {
    return FineScript::Han;
  }
  FineScript::Other(class_non_cjk(c, u))
}

/// Whether two adjacent characters belong to different fine Japanese script classes.
pub(crate) fn is_fine_boundary(prev: char, curr: char) -> bool {
  fine_class(prev) != fine_class(curr)
}

/// Inspects CJK cues within a sentence slice to decide Zh vs Ja vs intra-sentence Mixed.
pub(crate) fn cjk_hint(sentence: &str) -> CjkHint {
  if !simd::has_kana_byte(sentence.as_bytes()) {
    return CjkHint::Zh;
  }
  for ch in sentence.chars() {
    if is_zh_only_han(ch) {
      return CjkHint::Mixed;
    }
  }
  CjkHint::Ja
}

/// Detects the dominant language of a text using script counts and Simplified-only Han cues.
pub(crate) fn detect_lang(text: &str) -> Lang {
  let mut kana = 0usize;
  let mut han = 0usize;
  let mut zh_only = 0usize;
  let mut hangul = 0usize;
  let mut thai = 0usize;
  let mut cyrillic = 0usize;
  let mut arabic = 0usize;

  for c in text.chars() {
    match class(c) {
      ScriptClass::Cjk => {
        if is_kana(c) {
          kana += 1;
        } else {
          han += 1;
          if is_zh_only_han(c) {
            zh_only += 1;
          }
        }
      }
      ScriptClass::Hangul => hangul += 1,
      ScriptClass::Thai => thai += 1,
      ScriptClass::Cyrillic => cyrillic += 1,
      ScriptClass::Arabic => arabic += 1,
      ScriptClass::Latin
      | ScriptClass::OtherAlpha
      | ScriptClass::Digit
      | ScriptClass::Space
      | ScriptClass::Punct => {}
    }
  }

  let (ja_score, zh_score) = if kana > 0 && (zh_only == 0 || kana * 2 >= zh_only * 3) {
    (kana + han, 0)
  } else {
    (0, han + kana)
  };

  let mut best_lang = Lang::En;
  let mut best_count = 0usize;
  for (lang, count) in [
    (Lang::Ja, ja_score),
    (Lang::Zh, zh_score),
    (Lang::Ko, hangul),
    (Lang::Th, thai),
    (Lang::Ru, cyrillic),
    (Lang::Ar, arabic),
  ] {
    if count > best_count {
      best_count = count;
      best_lang = lang;
    }
  }
  best_lang
}