mcut 0.1.0

Zero-copy, low-memory multilingual word segmenter using pointwise linear classification and minimal FST
Documentation
use crate::{
  i18n::Lang,
  script::{
    RunKind, ScriptClass, alpha_lang, class, find_sentence_end, is_combining_mark, is_kana,
    zh_han::is_zh_only_han,
  },
};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum RunState {
  Cjk {
    has_kana: bool,
    has_zh_only: bool,
    pure_bmp_han: bool,
  },
  Hangul,
  Thai,
  AlphaNum {
    lang: Option<Lang>,
  },
  Space,
  Punct,
}

impl RunState {
  const fn into_kind(self) -> RunKind {
    match self {
      RunState::Cjk {
        has_kana,
        has_zh_only,
        pure_bmp_han,
      } => RunKind::Cjk {
        has_kana,
        has_zh_only,
        pure_bmp_han,
      },
      RunState::Hangul => RunKind::Hangul,
      RunState::Thai => RunKind::Thai,
      RunState::AlphaNum { lang: Some(lang) } => RunKind::Word(lang),
      RunState::AlphaNum { lang: None } => RunKind::Number,
      RunState::Space => RunKind::Space,
      RunState::Punct => RunKind::Punct,
    }
  }
}

/// Checks whether connector `c` at byte `index` joins inside an alphanumeric/word run.
#[inline]
fn is_connector_join(
  text: &str,
  index: usize,
  c: char,
  prev_is_digit: bool,
  run_lang: Option<Lang>,
) -> bool {
  let next_slice = &text[index + c.len_utf8()..];
  let Some(next_ch) = next_slice.chars().next() else {
    return false;
  };
  let next_cls = class(next_ch);
  let next_lang = alpha_lang(next_cls);
  let lang_compat = match (run_lang, next_lang) {
    (Some(a), Some(b)) => a == b,
    _ => true,
  };
  match c {
    '\'' | '\u{2019}' => run_lang.is_some() && !prev_is_digit && next_lang.is_some() && lang_compat,
    '-' | '\u{2010}' | '\u{2011}' | '_' => {
      (next_cls == ScriptClass::Digit || next_lang.is_some()) && lang_compat
    }
    '.' => prev_is_digit && next_cls == ScriptClass::Digit,
    ',' => {
      if run_lang.is_some() || !prev_is_digit {
        return false;
      }
      let b = next_slice.as_bytes();
      b.len() >= 3
        && b[0..3].iter().all(u8::is_ascii_digit)
        && !b.get(3).is_some_and(u8::is_ascii_digit)
    }
    _ => false,
  }
}

/// Returns the byte index of the next character boundary, or `text.len()`.
#[inline]
pub(crate) fn next_char(text: &str, start: usize) -> usize {
  if start >= text.len() {
    return text.len();
  }
  let byte_li = text.as_bytes();
  let mut i = start + 1;
  while i < byte_li.len() && (byte_li[i] & 0xC0) == 0x80 {
    i += 1;
  }
  i
}

/// Splits `text` at sentence-ending punctuation without allocating using SIMD delimiter scanning.
pub(crate) fn for_each_sentence<F: FnMut(usize, usize)>(text: &str, mut f: F) {
  let byte_li = text.as_bytes();
  let mut start = 0usize;
  while start < byte_li.len() {
    let rel_end = find_sentence_end(&byte_li[start..]);
    let end = start + rel_end;
    f(start, end);
    start = end;
  }
}

/// Splits a mixed CJK run into maximal Kana vs Han sub-runs when Zh+Ja appear in the same run.
pub(crate) fn for_each_han_kana_part<F: FnMut(usize, usize, bool)>(run: &str, mut f: F) {
  let mut iter = run.char_indices();
  let Some((_, first)) = iter.next() else {
    return;
  };
  let mut start = 0usize;
  let mut cur_kana = is_kana(first);
  for (i, ch) in iter {
    let next_kana = is_kana(ch);
    if next_kana != cur_kana {
      f(start, i, cur_kana);
      start = i;
      cur_kana = next_kana;
    }
  }
  f(start, run.len(), cur_kana);
}

#[inline]
fn state_from_char(c: char, track_zh_only: bool) -> (RunState, bool) {
  let cls = class(c);
  let state = match cls {
    ScriptClass::Cjk => {
      let u = c as u32;
      let kana = is_kana(c);
      RunState::Cjk {
        has_kana: kana,
        has_zh_only: track_zh_only && is_zh_only_han(c),
        pure_bmp_han: !kana && (0x4E00..=0x9FFF).contains(&u),
      }
    }
    ScriptClass::Hangul => RunState::Hangul,
    ScriptClass::Thai => RunState::Thai,
    ScriptClass::Digit => RunState::AlphaNum { lang: None },
    ScriptClass::Space => RunState::Space,
    ScriptClass::Punct => RunState::Punct,
    _ => RunState::AlphaNum {
      lang: alpha_lang(cls),
    },
  };
  (state, cls == ScriptClass::Digit)
}

#[inline]
fn is_bmp_han_byte(byte_li: &[u8], i: usize) -> bool {
  if i + 3 > byte_li.len() {
    return false;
  }
  let b0 = byte_li[i];
  (0xE5..=0xE9).contains(&b0) || (b0 == 0xE4 && byte_li[i + 1] >= 0xB8)
}

/// Invokes `f(start, end, kind)` for every maximal script run, merging
/// alphanumeric tokens (`i18n`, `UTF-8`, `GPT-4o`, `v1.20.3`, `3.14`, `1,000`)
/// when `keep_connector` is enabled.
pub(crate) fn for_each_run<F: FnMut(usize, usize, RunKind)>(
  text: &str,
  keep_connector: bool,
  track_zh_only: bool,
  mut f: F,
) {
  let byte_li = text.as_bytes();
  if byte_li.is_empty() {
    return;
  }

  let mut start = 0usize;
  let (mut state, mut prev_is_digit, mut pos) = if !track_zh_only && is_bmp_han_byte(byte_li, 0) {
    (
      RunState::Cjk {
        has_kana: false,
        has_zh_only: false,
        pure_bmp_han: true,
      },
      false,
      3usize,
    )
  } else {
    let Some(first) = text.chars().next() else {
      return;
    };
    let (st, dig) = state_from_char(first, track_zh_only);
    (st, dig, first.len_utf8())
  };

  while pos < byte_li.len() {
    // Byte-level fast path for contiguous BMP Han runs when mixed zh/ja cues are not needed.
    if !track_zh_only && matches!(state, RunState::Cjk { .. }) {
      while is_bmp_han_byte(byte_li, pos) {
        pos += 3;
      }
      if pos >= byte_li.len() {
        break;
      }
    }

    if !track_zh_only && is_bmp_han_byte(byte_li, pos) {
      f(start, pos, state.into_kind());
      start = pos;
      state = RunState::Cjk {
        has_kana: false,
        has_zh_only: false,
        pure_bmp_han: true,
      };
      prev_is_digit = false;
      pos += 3;
      continue;
    }

    let b0 = byte_li[pos];
    let (ch, next_pos) = if b0 < 0x80 {
      (b0 as char, pos + 1)
    } else {
      let Some(c) = text[pos..].chars().next() else {
        break;
      };
      (c, pos + c.len_utf8())
    };

    if b0 >= 0x80 && is_combining_mark(ch) && state != RunState::Space {
      if let RunState::Cjk { pure_bmp_han, .. } = &mut state {
        *pure_bmp_han = false;
      }
      prev_is_digit = false;
      pos = next_pos;
      continue;
    }

    if keep_connector
      && let RunState::AlphaNum { lang } = state
      && is_connector_join(text, pos, ch, prev_is_digit, lang)
    {
      prev_is_digit = false;
      pos = next_pos;
      continue;
    }

    let (next_state, is_digit) = state_from_char(ch, track_zh_only);
    prev_is_digit = is_digit;

    match (&mut state, next_state) {
      (
        RunState::Cjk {
          has_kana,
          has_zh_only,
          pure_bmp_han,
        },
        RunState::Cjk {
          has_kana: nk,
          has_zh_only: nz,
          pure_bmp_han: np,
        },
      ) => {
        *has_kana |= nk;
        *has_zh_only |= nz;
        *pure_bmp_han &= np;
      }
      (RunState::Hangul, RunState::Hangul)
      | (RunState::Thai, RunState::Thai)
      | (RunState::Space, RunState::Space)
      | (RunState::Punct, RunState::Punct) => {}
      (RunState::AlphaNum { lang: l1 }, RunState::AlphaNum { lang: l2 }) => match (*l1, l2) {
        (a, b) if a == b => {}
        (None, Some(lang)) => {
          *l1 = Some(lang);
        }
        (Some(_), None) => {}
        _ => {
          f(start, pos, state.into_kind());
          start = pos;
          state = next_state;
        }
      },
      _ => {
        f(start, pos, state.into_kind());
        start = pos;
        state = next_state;
      }
    }

    pos = next_pos;
  }

  f(start, byte_li.len(), state.into_kind());
}