Skip to main content

mcut/
cut.rs

1use crate::{
2  format::{Model, UserDict},
3  mode::{CutMode, CutOption},
4  plc::PlcSegmenter,
5  script,
6  token::Token,
7};
8
9/// Unified zero-cost segmentation interface across mixed-language cutters and single-script engines.
10pub trait Cut: Send + Sync {
11  /// Streams tokens for `text` with `opt` into `emit` in O(1) working memory.
12  fn cut_opt<'a, F: FnMut(Token<'a>)>(&self, text: &'a str, opt: CutOption, emit: F);
13
14  /// Streams tokens for `text` into `emit`, accepting [`CutMode`] or [`CutOption`].
15  fn cut_each<'a, F: FnMut(Token<'a>)>(&self, text: &'a str, opt: impl Into<CutOption>, emit: F) {
16    self.cut_opt(text, opt.into(), emit);
17  }
18
19  /// Appends tokens for `text` into `out`.
20  fn cut_into<'a>(&self, text: &'a str, opt: impl Into<CutOption>, out: &mut Vec<Token<'a>>) {
21    self.cut_opt(text, opt.into(), |tok| out.push(tok));
22  }
23
24  /// Cuts `text` into a vector of borrowed tokens.
25  fn cut<'a>(&self, text: &'a str, opt: impl Into<CutOption>) -> Vec<Token<'a>> {
26    let mut out = Vec::new();
27    self.cut_into(text, opt, &mut out);
28    out
29  }
30}
31
32impl<T: Cut + ?Sized> Cut for &T {
33  fn cut_opt<'a, F: FnMut(Token<'a>)>(&self, text: &'a str, opt: CutOption, emit: F) {
34    (*self).cut_opt(text, opt, emit);
35  }
36}
37
38/// Pluggable language segmenter routed automatically inside mixed-language text.
39pub trait LangCut: Send + Sync {
40  /// Returns `true` if character `ch` should be routed to this language segmenter.
41  fn matches(&self, ch: char) -> bool;
42
43  /// Streams tokens for a contiguous matched run into `emit`.
44  fn cut_run<'a, F: FnMut(Token<'a>)>(&self, run: &'a str, mode: CutMode, emit: F);
45}
46
47impl<T: LangCut + ?Sized> LangCut for &T {
48  fn matches(&self, ch: char) -> bool {
49    (*self).matches(ch)
50  }
51
52  fn cut_run<'a, F: FnMut(Token<'a>)>(&self, run: &'a str, mode: CutMode, emit: F) {
53    (*self).cut_run(run, mode, emit);
54  }
55}
56
57/// Static-dispatch collection of pluggable [`LangCut`] extensions.
58pub trait LangPack: Send + Sync {
59  /// Compile-time hint used to eliminate extension scanning when empty.
60  const IS_EMPTY: bool = false;
61
62  /// Returns `true` if any registered language claims `ch`.
63  fn matches_any(&self, ch: char) -> bool;
64
65  /// Cuts the maximal matched run starting at `start` (whose first character is `first_ch`)
66  /// and returns its exclusive end byte offset within `text`.
67  fn cut_prefix<'a, F: FnMut(Token<'a>)>(
68    &self,
69    text: &'a str,
70    start: usize,
71    base: usize,
72    first_ch: char,
73    mode: CutMode,
74    emit: &mut F,
75  ) -> usize;
76}
77
78impl<T: LangPack + ?Sized> LangPack for &T {
79  const IS_EMPTY: bool = T::IS_EMPTY;
80
81  fn matches_any(&self, ch: char) -> bool {
82    (*self).matches_any(ch)
83  }
84
85  fn cut_prefix<'a, F: FnMut(Token<'a>)>(
86    &self,
87    text: &'a str,
88    start: usize,
89    base: usize,
90    first_ch: char,
91    mode: CutMode,
92    emit: &mut F,
93  ) -> usize {
94    (*self).cut_prefix(text, start, base, first_ch, mode, emit)
95  }
96}
97
98/// Empty language extension placeholder compiled to zero machine instructions.
99#[derive(Clone, Copy, Debug, Default)]
100pub struct NoLang;
101
102impl LangPack for NoLang {
103  const IS_EMPTY: bool = true;
104
105  #[inline]
106  fn matches_any(&self, _ch: char) -> bool {
107    false
108  }
109
110  #[inline]
111  fn cut_prefix<'a, F: FnMut(Token<'a>)>(
112    &self,
113    _text: &'a str,
114    start: usize,
115    _base: usize,
116    _first_ch: char,
117    _mode: CutMode,
118    _emit: &mut F,
119  ) -> usize {
120    start
121  }
122}
123
124/// Compile-time linked chain of [`LangCut`] extensions (zero `dyn`, zero allocation).
125#[derive(Clone, Copy, Debug)]
126pub struct LangChain<L, Next> {
127  lang: L,
128  next: Next,
129}
130
131impl<L, Next> LangChain<L, Next> {
132  /// Prepends `lang` in front of `next` so `lang` has higher match priority.
133  pub const fn new(lang: L, next: Next) -> Self {
134    Self { lang, next }
135  }
136}
137
138impl<L: LangCut, Next: LangPack> LangPack for LangChain<L, Next> {
139  #[inline]
140  fn matches_any(&self, ch: char) -> bool {
141    self.lang.matches(ch) || self.next.matches_any(ch)
142  }
143
144  #[inline]
145  fn cut_prefix<'a, F: FnMut(Token<'a>)>(
146    &self,
147    text: &'a str,
148    start: usize,
149    base: usize,
150    first_ch: char,
151    mode: CutMode,
152    emit: &mut F,
153  ) -> usize {
154    if self.lang.matches(first_ch) {
155      return cut_lang_prefix(&self.lang, text, start, base, mode, emit);
156    }
157    self
158      .next
159      .cut_prefix(text, start, base, first_ch, mode, emit)
160  }
161}
162
163impl<L: LangCut> LangPack for [L] {
164  #[inline]
165  fn matches_any(&self, ch: char) -> bool {
166    self.iter().any(|lang| lang.matches(ch))
167  }
168
169  #[inline]
170  fn cut_prefix<'a, F: FnMut(Token<'a>)>(
171    &self,
172    text: &'a str,
173    start: usize,
174    base: usize,
175    first_ch: char,
176    mode: CutMode,
177    emit: &mut F,
178  ) -> usize {
179    cut_slice_prefix(self, text, start, base, first_ch, mode, emit)
180  }
181}
182
183impl<L: LangCut, const N: usize> LangPack for [L; N] {
184  const IS_EMPTY: bool = N == 0;
185
186  #[inline]
187  fn matches_any(&self, ch: char) -> bool {
188    self.as_slice().matches_any(ch)
189  }
190
191  #[inline]
192  fn cut_prefix<'a, F: FnMut(Token<'a>)>(
193    &self,
194    text: &'a str,
195    start: usize,
196    base: usize,
197    first_ch: char,
198    mode: CutMode,
199    emit: &mut F,
200  ) -> usize {
201    self
202      .as_slice()
203      .cut_prefix(text, start, base, first_ch, mode, emit)
204  }
205}
206
207impl<L: LangCut> LangPack for Vec<L> {
208  #[inline]
209  fn matches_any(&self, ch: char) -> bool {
210    self.as_slice().matches_any(ch)
211  }
212
213  #[inline]
214  fn cut_prefix<'a, F: FnMut(Token<'a>)>(
215    &self,
216    text: &'a str,
217    start: usize,
218    base: usize,
219    first_ch: char,
220    mode: CutMode,
221    emit: &mut F,
222  ) -> usize {
223    self
224      .as_slice()
225      .cut_prefix(text, start, base, first_ch, mode, emit)
226  }
227}
228
229fn cut_slice_prefix<'a, L: LangCut, F: FnMut(Token<'a>)>(
230  item_li: &[L],
231  text: &'a str,
232  start: usize,
233  base: usize,
234  first_ch: char,
235  mode: CutMode,
236  emit: &mut F,
237) -> usize {
238  for lang in item_li {
239    if lang.matches(first_ch) {
240      return cut_lang_prefix(lang, text, start, base, mode, emit);
241    }
242  }
243  script::next_char(text, start)
244}
245
246fn cut_lang_prefix<'a, L: LangCut + ?Sized, F: FnMut(Token<'a>)>(
247  lang: &L,
248  text: &'a str,
249  start: usize,
250  base: usize,
251  mode: CutMode,
252  emit: &mut F,
253) -> usize {
254  let tail = &text[start..];
255  let mut run_end = text.len();
256  for (rel, ch) in tail.char_indices() {
257    if rel > 0 && !lang.matches(ch) && !script::is_combining_mark(ch) {
258      run_end = start + rel;
259      break;
260    }
261  }
262  lang.cut_run(&text[start..run_end], mode, |mut tok| {
263    tok.start += base + start;
264    tok.end += base + start;
265    emit(tok);
266  });
267  run_end
268}
269
270/// Helper binding any `.mcut` [`PlcSegmenter`] to a character predicate for [`LangCut`].
271#[derive(Clone, Copy, Debug)]
272pub struct PlcLang<'a, M> {
273  seg: PlcSegmenter<'a>,
274  matcher: M,
275}
276
277impl<'a, M> PlcLang<'a, M> {
278  /// Wraps a zero-copy [`Model`], optional [`UserDict`], and character matcher predicate.
279  pub const fn new(model: Model<'a>, user_dict: Option<UserDict<'a>>, matcher: M) -> Self {
280    Self {
281      seg: PlcSegmenter::new(model, user_dict),
282      matcher,
283    }
284  }
285}
286
287impl<M: Fn(char) -> bool + Send + Sync> LangCut for PlcLang<'_, M> {
288  #[inline]
289  fn matches(&self, ch: char) -> bool {
290    (self.matcher)(ch)
291  }
292
293  #[inline]
294  fn cut_run<'a, F: FnMut(Token<'a>)>(&self, run: &'a str, mode: CutMode, emit: F) {
295    self.seg.cut_stream(run, mode, emit);
296  }
297}