mod builder;
mod overlay;
use core::ops::Range;
pub use builder::CutterBuilder;
use crate::{
cut::{Cut, LangPack, NoLang},
format::{Model, UserDict},
i18n::{self, Lang},
mode::{CutMode, CutOption},
plc::PlcSegmenter,
script::{self, CjkHint, RunKind},
token::{Token, TokenKind},
};
#[derive(Clone, Copy, Debug)]
pub struct Cutter<'a, E = NoLang> {
pub(crate) zh: Option<Model<'a>>,
pub(crate) ja: Option<Model<'a>>,
pub(crate) th: Option<Model<'a>>,
pub(crate) user_dict: Option<UserDict<'a>>,
pub(crate) ext: E,
}
impl Default for Cutter<'static, NoLang> {
fn default() -> Self {
Self::new_const()
}
}
impl Cutter<'static, NoLang> {
pub const fn new_const() -> Self {
Self {
zh: None,
ja: None,
th: None,
user_dict: None,
ext: NoLang,
}
}
}
impl<'a> Cutter<'a, NoLang> {
pub const fn builder() -> CutterBuilder<'a, NoLang> {
CutterBuilder::new()
}
}
impl<E: LangPack> Cut for Cutter<'_, E> {
fn cut_opt<'t, F: FnMut(Token<'t>)>(&self, text: &'t str, opt: CutOption, mut emit: F) {
if text.is_empty() {
return;
}
if let Some(ud) = self.user_dict
&& ud.has_mixed_script()
{
self.cut_with_user_overlay(ud, text, opt, &mut emit);
} else {
self.cut_auto_segment(text, opt, None, &mut emit);
}
}
}
#[derive(Clone, Copy)]
struct SliceCtx {
base: usize,
opt: CutOption,
hint: CjkHint,
}
impl<E: LangPack> Cutter<'_, E> {
pub(crate) fn cut_segment_shifted<'t, F: FnMut(Token<'t>)>(
&self,
text: &'t str,
start: usize,
end: usize,
opt: CutOption,
hint: Option<CjkHint>,
emit: &mut F,
) {
let slice = &text[start..end];
let mut forward = |mut tok: Token<'t>| {
tok.start += start;
tok.end += start;
emit(tok);
};
self.cut_auto_segment(slice, opt, hint, &mut forward);
}
fn cut_plc_shifted<'t, F: FnMut(Token<'t>)>(
&self,
lang: Lang,
run: &'t str,
base: usize,
mode: CutMode,
pure_bmp_han: bool,
emit: &mut F,
) {
let custom = match lang {
Lang::Zh => self.zh,
Lang::Ja => self.ja,
Lang::Th => self.th,
Lang::Ko | Lang::En | Lang::Ru | Lang::Ar => return,
};
let model = match custom {
Some(m) => m,
None => match lang {
Lang::Zh => *i18n::zh::default_model(),
Lang::Ja => *i18n::ja::default_model(),
Lang::Th => *i18n::th::default_model(),
Lang::Ko | Lang::En | Lang::Ru | Lang::Ar => return,
},
};
let seg = PlcSegmenter::new(model, self.user_dict);
let mut shifted = |mut token: Token<'t>| {
token.start += base;
token.end += base;
emit(token);
};
if pure_bmp_han && mode == CutMode::Precise {
seg.cut_han_precise_stream(run, &mut shifted);
} else {
seg.cut_stream(run, mode, shifted);
}
}
fn cut_auto_segment<'t, F: FnMut(Token<'t>)>(
&self,
text: &'t str,
opt: CutOption,
forced_hint: Option<CjkHint>,
emit: &mut F,
) {
if forced_hint.is_none() && !opt.keep_separator && !script::has_kana_byte(text.as_bytes()) {
self.cut_sentence_slice(text, 0, text.len(), opt, CjkHint::Zh, emit);
return;
}
script::for_each_sentence(text, |s_start, s_end| {
let sentence = &text[s_start..s_end];
let hint = forced_hint.unwrap_or_else(|| script::cjk_hint(sentence));
self.cut_sentence_slice(text, s_start, s_end, opt, hint, emit);
});
}
fn cut_sentence_slice<'t, F: FnMut(Token<'t>)>(
&self,
text: &'t str,
s_start: usize,
s_end: usize,
opt: CutOption,
hint: CjkHint,
emit: &mut F,
) {
let sentence = &text[s_start..s_end];
if E::IS_EMPTY {
let ctx = SliceCtx {
base: s_start,
opt,
hint,
};
self.cut_unclaimed_slice(text, sentence, ctx, emit);
return;
}
let mut cursor = 0usize;
let mut pos = 0usize;
while let Some(ch) = sentence[pos..].chars().next() {
if self.ext.matches_any(ch) {
if pos > cursor {
let ctx = SliceCtx {
base: s_start + cursor,
opt,
hint,
};
self.cut_unclaimed_slice(text, &sentence[cursor..pos], ctx, emit);
}
let end = self
.ext
.cut_prefix(sentence, pos, s_start, ch, opt.mode, emit);
let next = end.max(pos + ch.len_utf8());
cursor = next;
pos = next;
} else {
pos += ch.len_utf8();
}
}
if cursor < sentence.len() {
let ctx = SliceCtx {
base: s_start + cursor,
opt,
hint,
};
self.cut_unclaimed_slice(text, &sentence[cursor..], ctx, emit);
}
}
fn cut_unclaimed_slice<'t, F: FnMut(Token<'t>)>(
&self,
full_text: &'t str,
slice: &'t str,
ctx: SliceCtx,
emit: &mut F,
) {
let keep_conn = ctx.opt.mode != CutMode::Full;
let track_zh_only = ctx.hint == CjkHint::Mixed;
script::for_each_run(slice, keep_conn, track_zh_only, |r_start, r_end, kind| {
self.emit_run(
full_text,
(ctx.base + r_start)..(ctx.base + r_end),
kind,
ctx,
emit,
);
});
}
fn emit_run<'t, F: FnMut(Token<'t>)>(
&self,
text: &'t str,
range: Range<usize>,
kind: RunKind,
ctx: SliceCtx,
emit: &mut F,
) {
let start = range.start;
let end = range.end;
match kind {
RunKind::Space => {
if ctx.opt.keep_separator {
emit(Token::new(text, start, end, TokenKind::Space));
}
}
RunKind::Punct => {
if ctx.opt.keep_separator {
emit(Token::new(text, start, end, TokenKind::Punct));
}
}
RunKind::Number => {
emit(Token::number(text, start, end));
if ctx.opt.mode == CutMode::Search {
emit_compound_subword(text, start, end, emit);
}
}
RunKind::Hangul | RunKind::Word(_) => {
emit(Token::word(text, start, end));
if ctx.opt.mode == CutMode::Search {
emit_compound_subword(text, start, end, emit);
emit_camel_subword(text, start, end, emit);
}
}
RunKind::Thai => {
self.cut_plc_shifted(
Lang::Th,
&text[start..end],
start,
ctx.opt.mode,
false,
emit,
);
}
RunKind::Cjk {
has_kana,
has_zh_only,
pure_bmp_han,
} => match (ctx.hint, has_kana, has_zh_only) {
(CjkHint::Zh, ..) | (CjkHint::Mixed, false, _) => {
self.cut_plc_shifted(
Lang::Zh,
&text[start..end],
start,
ctx.opt.mode,
pure_bmp_han,
emit,
);
}
(CjkHint::Ja, ..) | (CjkHint::Mixed, true, false) => {
self.cut_plc_shifted(
Lang::Ja,
&text[start..end],
start,
ctx.opt.mode,
pure_bmp_han,
emit,
);
}
(CjkHint::Mixed, true, true) => {
let run = &text[start..end];
script::for_each_han_kana_part(run, |p_start, p_end, is_kana_part| {
let lang = if is_kana_part { Lang::Ja } else { Lang::Zh };
self.cut_plc_shifted(
lang,
&run[p_start..p_end],
start + p_start,
ctx.opt.mode,
false,
emit,
);
});
}
},
}
}
}
fn emit_compound_subword<'t, F: FnMut(Token<'t>)>(
text: &'t str,
start: usize,
end: usize,
emit: &mut F,
) {
let slice = &text[start..end];
let has_connector = slice
.chars()
.any(|c| matches!(c, '-' | '\u{2010}' | '\u{2011}' | '_' | '\'' | '\u{2019}'));
let dot_count = slice.bytes().filter(|&b| b == b'.').count();
let split_dots =
dot_count >= 2 || (dot_count == 1 && slice.bytes().any(|b| b.is_ascii_alphabetic()));
if !has_connector && !split_dots {
return;
}
let mut part_start = None;
let mut has_alpha = false;
for (rel, ch) in slice.char_indices() {
let is_sep = matches!(ch, '-' | '\u{2010}' | '\u{2011}' | '_' | '\'' | '\u{2019}')
|| (split_dots && ch == '.');
if is_sep {
if let Some(ps) = part_start.take()
&& rel > ps
&& (rel - ps) < slice.len()
{
let abs_s = start + ps;
let abs_e = start + rel;
emit(if has_alpha {
Token::word(text, abs_s, abs_e)
} else {
Token::number(text, abs_s, abs_e)
});
if has_alpha {
emit_camel_subword(text, abs_s, abs_e, emit);
}
}
has_alpha = false;
} else {
if part_start.is_none() {
part_start = Some(rel);
}
if ch.is_alphabetic() {
has_alpha = true;
}
}
}
if let Some(ps) = part_start
&& ps > 0
&& slice.len() > ps
{
let abs_s = start + ps;
emit(if has_alpha {
Token::word(text, abs_s, end)
} else {
Token::number(text, abs_s, end)
});
if has_alpha {
emit_camel_subword(text, abs_s, end, emit);
}
}
}
fn emit_camel_subword<'t, F: FnMut(Token<'t>)>(
text: &'t str,
start: usize,
end: usize,
emit: &mut F,
) {
let slice = &text[start..end];
if !slice.is_ascii() || slice.len() < 4 {
return;
}
let b = slice.as_bytes();
if b.iter().any(|&c| !c.is_ascii_alphanumeric()) {
return;
}
let mut split_cnt = 0_usize;
let mut seg_start = 0_usize;
for i in 1..b.len() {
let lower_to_upper = b[i - 1].is_ascii_lowercase() && b[i].is_ascii_uppercase();
let acronym_to_word = b[i - 1].is_ascii_uppercase()
&& b[i].is_ascii_uppercase()
&& b.get(i + 1).is_some_and(u8::is_ascii_lowercase);
if (lower_to_upper || acronym_to_word) && i > seg_start {
emit(Token::word(text, start + seg_start, start + i));
seg_start = i;
split_cnt += 1;
}
}
if split_cnt > 0 && seg_start < b.len() {
emit(Token::word(text, start + seg_start, end));
}
}