mcut 0.1.1

Zero-copy, low-memory multilingual word segmenter using pointwise linear classification and minimal FST
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
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},
};

/// Automatic mixed-language cutter with zero-copy model/dictionary overrides
/// and compile-time pluggable [`crate::LangCut`] extensions.
///
/// External models supplied through [`Cutter::builder`] bypass built-in embedded
/// models completely so unused `.rodata` pages are never touched.
#[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> {
  /// Creates a default mixed-language cutter in `const` context with zero startup cost.
  pub const fn new_const() -> Self {
    Self {
      zh: None,
      ja: None,
      th: None,
      user_dict: None,
      ext: NoLang,
    }
  }
}

impl<'a> Cutter<'a, NoLang> {
  /// Creates a [`CutterBuilder`] for attaching external models, user dictionaries, or new languages.
  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::Full {
      seg.cut_han_stream(run, mode == CutMode::Search, &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,
  ) {
    // Fast path: when no Kana exists anywhere in `text` and separator splitting is disabled,
    // every CJK run is Chinese, skipping sentence splitting and per-sentence scanning.
    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,
            );
          });
        }
      },
    }
  }
}

#[inline(always)]
const fn is_compound_connector(c: char) -> bool {
  matches!(c, '-' | '\u{2010}' | '\u{2011}' | '_' | '\'' | '\u{2019}')
}

#[inline(always)]
fn emit_compound_part<'t, F: FnMut(Token<'t>)>(
  text: &'t str,
  abs_s: usize,
  abs_e: usize,
  has_alpha: bool,
  emit: &mut F,
) {
  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);
  }
}

/// Emits connector-delimited subwords for search mode (`state-of-the-art`, `foo_bar`, `v1.20.3`, `2026-12-03`).
///
/// Leaves plain decimals (`3.14`) and thousands-separated numbers (`1,000,000`) intact.
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(is_compound_connector);
  let dot_count = slice.bytes().filter(|&b| b == b'.').count();
  let split_dot =
    dot_count >= 2 || (dot_count == 1 && slice.bytes().any(|b| b.is_ascii_alphabetic()));
  if !has_connector && !split_dot {
    return;
  }
  let mut part_start = None;
  let mut has_alpha = false;
  for (rel, ch) in slice.char_indices() {
    let is_sep = is_compound_connector(ch) || (split_dot && ch == '.');
    if is_sep {
      if let Some(ps) = part_start.take()
        && rel > ps
        && (rel - ps) < slice.len()
      {
        emit_compound_part(text, start + ps, start + rel, has_alpha, 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
  {
    emit_compound_part(text, start + ps, end, has_alpha, emit);
  }
}

/// Emits CamelCase/PascalCase subwords for search mode (`PostgreSQL` -> `Postgre`, `SQL`).
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));
  }
}