mcut 0.1.1

Zero-copy, low-memory multilingual word segmenter using pointwise linear classification and minimal FST
Documentation
use crate::{
  format::header::DICT_BUCKET_COUNT,
  script::{is_digit_char, is_han, is_hiragana, is_katakana},
};

pub const MAX_WORD_CHAR: usize = 32;

/// Coarse character type used for context type-4gram lookup.
#[repr(u8)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum CharType {
  #[default]
  Other = 0,
  Han = 1,
  Hiragana = 2,
  Katakana = 3,
  ThaiConsonant = 4,
  ThaiVowelTone = 5,
  Digit = 6,
  Alpha = 7,
}

const ASCII_TYPE: [CharType; 128] = build_ascii_type();

const fn build_ascii_type() -> [CharType; 128] {
  let mut table = [CharType::Other; 128];
  let mut b = 0usize;
  while b < 128 {
    let c = b as u8;
    if c.is_ascii_digit() {
      table[b] = CharType::Digit;
    } else if c.is_ascii_alphabetic() {
      table[b] = CharType::Alpha;
    }
    b += 1;
  }
  table
}

/// Maps a Unicode scalar to its coarse [`CharType`] without hitting Unicode digit tables on CJK.
#[inline(always)]
pub fn char_type(ch: char) -> CharType {
  let u = ch as u32;
  if u < 128 {
    return ASCII_TYPE[u as usize];
  }
  char_type_non_ascii(ch, u)
}

#[inline(always)]
pub(crate) fn char_type_non_ascii(ch: char, u: u32) -> CharType {
  if is_han(u) {
    return CharType::Han;
  }
  if is_hiragana(u) {
    return CharType::Hiragana;
  }
  // Trained Japanese models map halfwidth voiced marks U+FF9E..=U+FF9F to Other.
  if is_katakana(u) && !matches!(u, 0xFF9E..=0xFF9F) {
    return CharType::Katakana;
  }
  if matches!(u, 0x0E01..=0x0E2E) {
    return CharType::ThaiConsonant;
  }
  if matches!(u, 0x0E2F..=0x0E4E) {
    return CharType::ThaiVowelTone;
  }
  if is_digit_char(ch) {
    return CharType::Digit;
  }
  if ch.is_alphabetic() {
    return CharType::Alpha;
  }
  CharType::Other
}

#[inline]
pub const fn pack_type4(t0: CharType, t1: CharType, t2: CharType, t3: CharType) -> usize {
  ((t0 as usize) << 9) | ((t1 as usize) << 6) | ((t2 as usize) << 3) | (t3 as usize)
}

#[inline]
pub const fn dict_bucket(char_len: usize) -> usize {
  let clamped = if char_len > 6 { 6 } else { char_len };
  clamped - 2
}

/// Maps `(word_tier, char_len)` (`word_tier` in `1..=2`, `char_len >= 2`) to a `0..10` slot index.
#[inline(always)]
pub const fn dict_slot(word_tier: u8, char_len: usize) -> usize {
  let tier_idx = if word_tier >= 2 { 1 } else { 0 };
  tier_idx * DICT_BUCKET_COUNT + dict_bucket(char_len)
}