mcut 0.1.1

Zero-copy, low-memory multilingual word segmenter using pointwise linear classification and minimal FST
Documentation
use crate::{
  format::{Model, UserDict},
  mode::{CutMode, CutOption},
  plc::PlcSegmenter,
  script,
  token::Token,
};

/// Unified zero-cost segmentation interface across mixed-language cutters and single-script engines.
pub trait Cut: Send + Sync {
  /// Streams tokens for `text` with `opt` into `emit` in O(1) working memory.
  fn cut_opt<'a, F: FnMut(Token<'a>)>(&self, text: &'a str, opt: CutOption, emit: F);

  /// Streams tokens for `text` into `emit`, accepting [`CutMode`] or [`CutOption`].
  fn cut_each<'a, F: FnMut(Token<'a>)>(&self, text: &'a str, opt: impl Into<CutOption>, emit: F) {
    self.cut_opt(text, opt.into(), emit);
  }

  /// Appends tokens for `text` into `out`.
  fn cut_into<'a>(&self, text: &'a str, opt: impl Into<CutOption>, out: &mut Vec<Token<'a>>) {
    self.cut_opt(text, opt.into(), |tok| out.push(tok));
  }

  /// Cuts `text` into a vector of borrowed tokens.
  fn cut<'a>(&self, text: &'a str, opt: impl Into<CutOption>) -> Vec<Token<'a>> {
    let mut out = Vec::new();
    self.cut_into(text, opt, &mut out);
    out
  }
}

impl<T: Cut + ?Sized> Cut for &T {
  fn cut_opt<'a, F: FnMut(Token<'a>)>(&self, text: &'a str, opt: CutOption, emit: F) {
    (*self).cut_opt(text, opt, emit);
  }
}

/// Pluggable language segmenter routed automatically inside mixed-language text.
pub trait LangCut: Send + Sync {
  /// Returns `true` if character `ch` should be routed to this language segmenter.
  fn matches(&self, ch: char) -> bool;

  /// Streams tokens for a contiguous matched run into `emit`.
  fn cut_run<'a, F: FnMut(Token<'a>)>(&self, run: &'a str, mode: CutMode, emit: F);
}

impl<T: LangCut + ?Sized> LangCut for &T {
  fn matches(&self, ch: char) -> bool {
    (*self).matches(ch)
  }

  fn cut_run<'a, F: FnMut(Token<'a>)>(&self, run: &'a str, mode: CutMode, emit: F) {
    (*self).cut_run(run, mode, emit);
  }
}

/// Static-dispatch collection of pluggable [`LangCut`] extensions.
pub trait LangPack: Send + Sync {
  /// Compile-time hint used to eliminate extension scanning when empty.
  const IS_EMPTY: bool = false;

  /// Returns `true` if any registered language claims `ch`.
  fn matches_any(&self, ch: char) -> bool;

  /// Cuts the maximal matched run starting at `start` (whose first character is `first_ch`)
  /// and returns its exclusive end byte offset within `text`.
  fn cut_prefix<'a, F: FnMut(Token<'a>)>(
    &self,
    text: &'a str,
    start: usize,
    base: usize,
    first_ch: char,
    mode: CutMode,
    emit: &mut F,
  ) -> usize;
}

impl<T: LangPack + ?Sized> LangPack for &T {
  const IS_EMPTY: bool = T::IS_EMPTY;

  fn matches_any(&self, ch: char) -> bool {
    (*self).matches_any(ch)
  }

  fn cut_prefix<'a, F: FnMut(Token<'a>)>(
    &self,
    text: &'a str,
    start: usize,
    base: usize,
    first_ch: char,
    mode: CutMode,
    emit: &mut F,
  ) -> usize {
    (*self).cut_prefix(text, start, base, first_ch, mode, emit)
  }
}

/// Empty language extension placeholder compiled to zero machine instructions.
#[derive(Clone, Copy, Debug, Default)]
pub struct NoLang;

impl LangPack for NoLang {
  const IS_EMPTY: bool = true;

  #[inline]
  fn matches_any(&self, _ch: char) -> bool {
    false
  }

  #[inline]
  fn cut_prefix<'a, F: FnMut(Token<'a>)>(
    &self,
    _text: &'a str,
    start: usize,
    _base: usize,
    _first_ch: char,
    _mode: CutMode,
    _emit: &mut F,
  ) -> usize {
    start
  }
}

/// Compile-time linked chain of [`LangCut`] extensions (zero `dyn`, zero allocation).
#[derive(Clone, Copy, Debug)]
pub struct LangChain<L, Next> {
  lang: L,
  next: Next,
}

impl<L, Next> LangChain<L, Next> {
  /// Prepends `lang` in front of `next` so `lang` has higher match priority.
  pub const fn new(lang: L, next: Next) -> Self {
    Self { lang, next }
  }
}

impl<L: LangCut, Next: LangPack> LangPack for LangChain<L, Next> {
  #[inline]
  fn matches_any(&self, ch: char) -> bool {
    self.lang.matches(ch) || self.next.matches_any(ch)
  }

  #[inline]
  fn cut_prefix<'a, F: FnMut(Token<'a>)>(
    &self,
    text: &'a str,
    start: usize,
    base: usize,
    first_ch: char,
    mode: CutMode,
    emit: &mut F,
  ) -> usize {
    if self.lang.matches(first_ch) {
      return cut_lang_prefix(&self.lang, text, start, base, mode, emit);
    }
    self
      .next
      .cut_prefix(text, start, base, first_ch, mode, emit)
  }
}

impl<L: LangCut> LangPack for [L] {
  #[inline]
  fn matches_any(&self, ch: char) -> bool {
    self.iter().any(|lang| lang.matches(ch))
  }

  #[inline]
  fn cut_prefix<'a, F: FnMut(Token<'a>)>(
    &self,
    text: &'a str,
    start: usize,
    base: usize,
    first_ch: char,
    mode: CutMode,
    emit: &mut F,
  ) -> usize {
    cut_slice_prefix(self, text, start, base, first_ch, mode, emit)
  }
}

impl<L: LangCut, const N: usize> LangPack for [L; N] {
  const IS_EMPTY: bool = N == 0;

  #[inline]
  fn matches_any(&self, ch: char) -> bool {
    self.as_slice().matches_any(ch)
  }

  #[inline]
  fn cut_prefix<'a, F: FnMut(Token<'a>)>(
    &self,
    text: &'a str,
    start: usize,
    base: usize,
    first_ch: char,
    mode: CutMode,
    emit: &mut F,
  ) -> usize {
    self
      .as_slice()
      .cut_prefix(text, start, base, first_ch, mode, emit)
  }
}

impl<L: LangCut> LangPack for Vec<L> {
  #[inline]
  fn matches_any(&self, ch: char) -> bool {
    self.as_slice().matches_any(ch)
  }

  #[inline]
  fn cut_prefix<'a, F: FnMut(Token<'a>)>(
    &self,
    text: &'a str,
    start: usize,
    base: usize,
    first_ch: char,
    mode: CutMode,
    emit: &mut F,
  ) -> usize {
    self
      .as_slice()
      .cut_prefix(text, start, base, first_ch, mode, emit)
  }
}

fn cut_slice_prefix<'a, L: LangCut, F: FnMut(Token<'a>)>(
  item_li: &[L],
  text: &'a str,
  start: usize,
  base: usize,
  first_ch: char,
  mode: CutMode,
  emit: &mut F,
) -> usize {
  for lang in item_li {
    if lang.matches(first_ch) {
      return cut_lang_prefix(lang, text, start, base, mode, emit);
    }
  }
  script::next_char(text, start)
}

fn cut_lang_prefix<'a, L: LangCut + ?Sized, F: FnMut(Token<'a>)>(
  lang: &L,
  text: &'a str,
  start: usize,
  base: usize,
  mode: CutMode,
  emit: &mut F,
) -> usize {
  let tail = &text[start..];
  let mut run_end = text.len();
  for (rel, ch) in tail.char_indices() {
    if rel > 0 && !lang.matches(ch) && !script::is_combining_mark(ch) {
      run_end = start + rel;
      break;
    }
  }
  lang.cut_run(&text[start..run_end], mode, |mut tok| {
    tok.start += base + start;
    tok.end += base + start;
    emit(tok);
  });
  run_end
}

/// Helper binding any `.mcut` [`PlcSegmenter`] to a character predicate for [`LangCut`].
#[derive(Clone, Copy, Debug)]
pub struct PlcLang<'a, M> {
  seg: PlcSegmenter<'a>,
  matcher: M,
}

impl<'a, M> PlcLang<'a, M> {
  /// Wraps a zero-copy [`Model`], optional [`UserDict`], and character matcher predicate.
  pub const fn new(model: Model<'a>, user_dict: Option<UserDict<'a>>, matcher: M) -> Self {
    Self {
      seg: PlcSegmenter::new(model, user_dict),
      matcher,
    }
  }
}

impl<M: Fn(char) -> bool + Send + Sync> LangCut for PlcLang<'_, M> {
  #[inline]
  fn matches(&self, ch: char) -> bool {
    (self.matcher)(ch)
  }

  #[inline]
  fn cut_run<'a, F: FnMut(Token<'a>)>(&self, run: &'a str, mode: CutMode, emit: F) {
    self.seg.cut_stream(run, mode, emit);
  }
}