mcut 0.1.0

Zero-copy, low-memory multilingual word segmenter using pointwise linear classification and minimal FST
Documentation
use crate::{
  cut::LangPack,
  cutter::Cutter,
  format::{UserDict, dict::is_mixed_word},
  mode::{CutMode, CutOption},
  script::{self, CjkHint},
  token::Token,
};

impl<E: LangPack> Cutter<'_, E> {
  pub(crate) fn cut_with_user_overlay<'t, F: FnMut(Token<'t>)>(
    &self,
    ud: UserDict<'_>,
    text: &'t str,
    opt: CutOption,
    emit: &mut F,
  ) {
    let mut cursor = 0usize;
    let mut pos = 0usize;
    let mut sent_end = 0usize;
    let mut sent_hint = CjkHint::Zh;

    while pos < text.len() {
      if pos >= sent_end {
        if pos > cursor {
          self.cut_segment_shifted(text, cursor, sent_end, opt, Some(sent_hint), emit);
          cursor = sent_end;
        }
        (sent_end, sent_hint) = next_sentence_hint(text, pos);
      }
      if let Some(best_end) = find_mixed_user_match(ud, text, pos) {
        if pos > cursor {
          self.cut_segment_shifted(text, cursor, pos, opt, Some(sent_hint), emit);
        }

        let match_hint = (best_end <= sent_end).then_some(sent_hint);
        if opt.mode == CutMode::Full {
          emit(Token::word(text, pos, best_end));
        }
        if opt.mode != CutMode::Precise {
          // Keep internal punctuation (e.g. `C++`, `GPT-4o`) out of sub-token emission.
          let sub_opt = CutOption {
            mode: opt.mode,
            keep_separator: false,
          };
          let matched = &text[pos..best_end];
          self.cut_segment_shifted(text, pos, best_end, sub_opt, match_hint, &mut |tok| {
            if tok.text != matched {
              emit(tok);
            }
          });
        }
        if opt.mode != CutMode::Full {
          emit(Token::word(text, pos, best_end));
        }

        cursor = best_end;
        pos = best_end;
        continue;
      }
      pos = script::next_char(text, pos);
    }

    if cursor < text.len() {
      self.cut_segment_shifted(text, cursor, text.len(), opt, Some(sent_hint), emit);
    }
  }
}

fn next_sentence_hint(text: &str, from: usize) -> (usize, CjkHint) {
  let tail = &text[from..];
  let rel_end = script::find_sentence_end(tail.as_bytes());
  (from + rel_end, script::cjk_hint(&tail[..rel_end]))
}

fn find_mixed_user_match(ud: UserDict<'_>, text: &str, pos: usize) -> Option<usize> {
  let mut best_end = pos;
  ud.fst().for_each_prefix(text, pos, |end, _| {
    if end > best_end && is_mixed_word(&text[pos..end]) {
      best_end = end;
    }
  });
  (best_end > pos).then_some(best_end)
}