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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
use core::str::from_utf8;

use ihash::{HashMap, HashMapExt};

use crate::{
  error::{Error, Result},
  format::bmp::{BmpPageIndex, encode_bmp_page_header},
};

const FST_HEADER_SIZE: usize = 12;
const FLAG_FINAL: u8 = 0x80;
const FLAG_FAST: u8 = 0x40;
const FAST_NODE_MIN_EDGE: usize = 8;
const ROOT_JUMP_MIN_WORD: usize = 64;

/// Unweighted minimal acyclic finite-state transducer (Daciuk 2000) stored in a
/// zero-copy buffer with hybrid LEB128 / quadrant-bitmap popcount nodes and
/// O(1) BMP first-character root jump table.
#[derive(Clone, Copy, Debug)]
pub struct WordFst<'a> {
  root_off: u32,
  word_count: u32,
  jump_len: usize,
  jump_index: BmpPageIndex<'a>,
  jump_state: &'a [u8],
  node_buf: &'a [u8],
}

impl<'a> WordFst<'a> {
  pub const fn empty() -> Self {
    Self {
      root_off: u32::MAX,
      word_count: 0,
      jump_len: 0,
      jump_index: BmpPageIndex::empty(),
      jump_state: &[],
      node_buf: &[],
    }
  }

  pub fn from_slice(slice: &'a [u8]) -> Result<Self> {
    if slice.is_empty() {
      return Ok(Self::empty());
    }
    if slice.len() < FST_HEADER_SIZE {
      return Err(Error::InvalidModel {
        reason: "truncated fst header",
      });
    }
    let root_off = u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]);
    let word_count = u32::from_le_bytes([slice[4], slice[5], slice[6], slice[7]]);
    let jump_len = u32::from_le_bytes([slice[8], slice[9], slice[10], slice[11]]) as usize;
    let body = &slice[FST_HEADER_SIZE..];

    if body.len() < jump_len {
      return Err(Error::InvalidModel {
        reason: "truncated fst jump section",
      });
    }
    let (jump_slice, node_buf) = body.split_at(jump_len);

    if word_count == 0 {
      if root_off != u32::MAX || jump_len != 0 || !node_buf.is_empty() {
        return Err(Error::InvalidModel {
          reason: "corrupted empty fst header",
        });
      }
      return Ok(Self::empty());
    }

    if root_off == u32::MAX || (root_off as usize) >= node_buf.len() {
      return Err(Error::InvalidModel {
        reason: "fst root offset out of bounds",
      });
    }

    let (jump_index, jump_state) = if jump_len == 0 {
      (BmpPageIndex::empty(), &[][..])
    } else {
      let (idx, tail) = BmpPageIndex::from_slice(jump_slice)?;
      if tail.len() != idx.entry_count() * 4 {
        return Err(Error::InvalidModel {
          reason: "fst jump state length mismatch",
        });
      }
      let (chunk_li, _) = tail.as_chunks::<4>();
      for chunk in chunk_li {
        let st = u32::from_le_bytes(*chunk) as usize;
        if st >= node_buf.len() {
          return Err(Error::InvalidModel {
            reason: "fst jump target out of bounds",
          });
        }
      }
      (idx, tail)
    };

    Ok(Self {
      root_off,
      word_count,
      jump_len,
      jump_index,
      jump_state,
      node_buf,
    })
  }

  pub const fn is_empty(&self) -> bool {
    self.word_count == 0
  }

  pub const fn word_count(&self) -> u32 {
    self.word_count
  }

  pub const fn byte_len(&self) -> usize {
    if self.word_count == 0 && self.node_buf.is_empty() {
      0
    } else {
      FST_HEADER_SIZE + self.jump_len + self.node_buf.len()
    }
  }

  #[inline]
  fn jump_first(&self, ch0: char) -> Option<usize> {
    let idx = self.jump_index.get(ch0)?;
    let (chunk_li, _) = self.jump_state.as_chunks::<4>();
    let chunk = chunk_li.get(idx)?;
    Some(u32::from_le_bytes(*chunk) as usize)
  }

  #[inline]
  pub fn contains(&self, word: &str) -> bool {
    if self.is_empty() || word.is_empty() {
      return false;
    }
    let Some(ch0) = word.chars().next() else {
      return false;
    };
    let (mut state, tail) = if !self.jump_index.is_empty() && (ch0 as u32) <= u32::from(u16::MAX) {
      let Some(s1) = self.jump_first(ch0) else {
        return false;
      };
      (s1, &word.as_bytes()[ch0.len_utf8()..])
    } else {
      (self.root_off as usize, word.as_bytes())
    };

    for &byte in tail {
      let Some(next) = step_state(self.node_buf, state, byte) else {
        return false;
      };
      state = next;
    }
    self.is_final(state)
  }

  /// Calls `f(end_byte, char_len)` for every dictionary word that starts at
  /// `start` and is a prefix of `text[start..]`.
  #[inline]
  pub fn for_each_prefix<F: FnMut(usize, usize)>(&self, text: &str, start: usize, f: F) {
    if self.is_empty() {
      return;
    }
    let Some(tail) = text.get(start..) else {
      return;
    };
    let Some(ch0) = tail.chars().next() else {
      return;
    };
    self.walk_prefix(tail.as_bytes(), start, ch0, f);
  }

  /// Calls `f(end_byte, char_len)` for every prefix starting at `start` when `ch0`
  /// at `start` is already decoded by the caller.
  #[inline]
  pub fn for_each_prefix_char<F: FnMut(usize, usize)>(
    &self,
    text: &str,
    start: usize,
    ch0: char,
    f: F,
  ) {
    if self.is_empty() {
      return;
    }
    let Some(tail) = text.get(start..) else {
      return;
    };
    self.walk_prefix(tail.as_bytes(), start, ch0, f);
  }

  #[inline]
  fn walk_prefix<F: FnMut(usize, usize)>(&self, byte_li: &[u8], start: usize, ch0: char, mut f: F) {
    let (mut state, mut pos, mut char_len) =
      if !self.jump_index.is_empty() && (ch0 as u32) <= u32::from(u16::MAX) {
        let Some(s1) = self.jump_first(ch0) else {
          return;
        };
        let pos0 = ch0.len_utf8();
        if self.is_final(s1) {
          f(start + pos0, 1);
        }
        (s1, pos0, 1usize)
      } else {
        (self.root_off as usize, 0usize, 0usize)
      };

    while let Some(&b0) = byte_li.get(pos) {
      let step_len = utf8_char_len(b0);
      let Some(chunk) = byte_li.get(pos..pos + step_len) else {
        return;
      };
      for &byte in chunk {
        let Some(next) = step_state(self.node_buf, state, byte) else {
          return;
        };
        state = next;
      }
      pos += step_len;
      char_len += 1;
      if self.is_final(state) {
        f(start + pos, char_len);
      }
    }
  }

  #[inline]
  fn is_final(&self, state: usize) -> bool {
    self
      .node_buf
      .get(state)
      .is_some_and(|&head| (head & FLAG_FINAL) != 0)
  }
}

#[inline]
fn step_state(buf: &[u8], state: usize, target: u8) -> Option<usize> {
  let head = *buf.get(state)?;
  if (head & FLAG_FAST) != 0 {
    return step_fast(buf, state, head, target);
  }

  let edge_count = (head & 0x3F) as usize;
  let mut cursor = state + 1;
  for _ in 0..edge_count {
    let label = *buf.get(cursor)?;
    cursor += 1;
    let (delta, next_cursor) = read_uleb128(buf, cursor)?;
    cursor = next_cursor;
    if label == target {
      if delta == 0 {
        return None;
      }
      return state.checked_sub(delta);
    }
    if label > target {
      return None;
    }
  }
  None
}

#[inline]
fn step_fast(buf: &[u8], state: usize, head: u8, target: u8) -> Option<usize> {
  let qmask = head & 0x0F;
  let quad = target >> 6;
  let qbit = 1u8 << quad;
  if (qmask & qbit) == 0 {
    return None;
  }

  let q_total = qmask.count_ones() as usize;
  let q_idx = (qmask & (qbit - 1)).count_ones() as usize;
  let bm_base = state + 1;
  let bm_byte = buf.get(bm_base..bm_base + q_total * 8)?;
  let (word_li, _) = bm_byte.as_chunks::<8>();
  let word = u64::from_le_bytes(word_li[q_idx]);
  let bit = 1u64 << (target & 63);
  if (word & bit) == 0 {
    return None;
  }

  let mut rank = (word & (bit - 1)).count_ones() as usize;
  for prev_chunk in &word_li[..q_idx] {
    rank += u64::from_le_bytes(*prev_chunk).count_ones() as usize;
  }

  let width = (((head >> 4) & 0x03) as usize) + 1;
  let delta_off = bm_base + q_total * 8 + rank * width;
  let delta = read_delta(buf, delta_off, width)?;
  if delta == 0 {
    return None;
  }
  state.checked_sub(delta)
}

#[inline]
fn read_delta(buf: &[u8], off: usize, width: usize) -> Option<usize> {
  let s = buf.get(off..off + width)?;
  let val = match width {
    1 => u32::from(s[0]),
    2 => u32::from(u16::from_le_bytes([s[0], s[1]])),
    3 => u32::from(s[0]) | (u32::from(s[1]) << 8) | (u32::from(s[2]) << 16),
    _ => u32::from_le_bytes([s[0], s[1], s[2], s[3]]),
  };
  Some(val as usize)
}

#[inline]
const fn utf8_char_len(first_byte: u8) -> usize {
  if first_byte < 0x80 {
    1
  } else if first_byte < 0xE0 {
    2
  } else if first_byte < 0xF0 {
    3
  } else {
    4
  }
}

#[inline]
fn read_uleb128(buf: &[u8], mut cursor: usize) -> Option<(usize, usize)> {
  let mut val = 0u32;
  let mut shift = 0u32;
  loop {
    let byte = *buf.get(cursor)?;
    cursor += 1;
    let part = u32::from(byte & 0x7F);
    if shift == 28 && part > 0x0F {
      return None;
    }
    val |= part << shift;
    if (byte & 0x80) == 0 {
      return Some((val as usize, cursor));
    }
    shift += 7;
  }
}

#[derive(Default, Clone, PartialEq, Eq, Hash)]
struct StateKey {
  final_flag: bool,
  edge_li: Vec<(u8, u32)>,
}

/// Builds a minimal acyclic unweighted FST from an arbitrary list of words.
#[cfg(feature = "build")]
pub fn build_fst(word_li: &[&str]) -> Vec<u8> {
  build_fst_iter(word_li.iter().map(|w| w.as_bytes()))
}

/// Builds a minimal acyclic unweighted FST from an iterator of UTF-8 byte slices.
#[cfg(feature = "build")]
pub fn build_fst_iter<'a, I: IntoIterator<Item = &'a [u8]>>(iter: I) -> Vec<u8> {
  let mut sorted: Vec<&[u8]> = iter.into_iter().filter(|b| !b.is_empty()).collect();
  if sorted.is_empty() {
    return Vec::new();
  }
  sorted.sort_unstable();
  sorted.dedup();
  let count = sorted.len();
  build_fst_presorted(sorted, count)
}

/// Builds a minimal acyclic unweighted FST from strictly sorted, unique, non-empty slices.
pub(crate) fn build_fst_presorted<'a, I: IntoIterator<Item = &'a [u8]>>(
  iter: I,
  word_count: usize,
) -> Vec<u8> {
  if word_count == 0 {
    return Vec::new();
  }
  let word_count_u32 = u32::try_from(word_count).expect("fst word count fits u32");
  let mut node_buf = Vec::with_capacity(word_count * 4);
  let mut registry: HashMap<StateKey, u32> = HashMap::with_capacity(word_count);
  let mut stack = vec![StateKey::default()];
  let mut prev: &[u8] = &[];

  let want_jump = word_count >= ROOT_JUMP_MIN_WORD;
  let mut first_cp_li: Vec<u16> = if want_jump {
    Vec::with_capacity(word_count.min(4096))
  } else {
    Vec::new()
  };

  for word in iter {
    if word.is_empty() {
      continue;
    }
    if want_jump
      && let Ok(text) = from_utf8(word)
      && let Some(ch0) = text.chars().next()
    {
      let cp = ch0 as u32;
      if cp <= u32::from(u16::MAX) {
        let cp16 = cp as u16;
        if first_cp_li.last().copied() != Some(cp16) {
          first_cp_li.push(cp16);
        }
      }
    }

    let lcp = prev.iter().zip(word).take_while(|(a, b)| a == b).count();

    freeze_to(&mut stack, lcp, prev, &mut node_buf, &mut registry);
    for _ in lcp..word.len() {
      stack.push(StateKey::default());
    }
    if let Some(top) = stack.last_mut() {
      top.final_flag = true;
    }
    prev = word;
  }

  freeze_to(&mut stack, 0, prev, &mut node_buf, &mut registry);
  let root = stack.pop().expect("root state exists");
  let root_off = register_state(root, &mut node_buf, &mut registry);

  let mut jump_buf = Vec::new();
  if want_jump && !first_cp_li.is_empty() {
    encode_bmp_page_header(&first_cp_li, &mut jump_buf);
    jump_buf.reserve(first_cp_li.len() * 4);
    for &cp in &first_cp_li {
      let ch = char::from_u32(u32::from(cp)).expect("valid bmp char");
      let mut utf8 = [0u8; 4];
      let slice = ch.encode_utf8(&mut utf8);
      let mut state = root_off as usize;
      for &byte in slice.as_bytes() {
        state = step_state(&node_buf, state, byte).expect("fst root jump state exists");
      }
      jump_buf.extend_from_slice(&(state as u32).to_le_bytes());
    }
  }
  let jump_len = u32::try_from(jump_buf.len()).expect("fst jump fits u32");

  let mut out = Vec::with_capacity(FST_HEADER_SIZE + jump_buf.len() + node_buf.len());
  out.extend_from_slice(&root_off.to_le_bytes());
  out.extend_from_slice(&word_count_u32.to_le_bytes());
  out.extend_from_slice(&jump_len.to_le_bytes());
  out.extend_from_slice(&jump_buf);
  out.extend_from_slice(&node_buf);
  out
}

fn freeze_to(
  stack: &mut Vec<StateKey>,
  lcp: usize,
  prev: &[u8],
  node_buf: &mut Vec<u8>,
  registry: &mut HashMap<StateKey, u32>,
) {
  while stack.len() > lcp + 1 {
    let child = stack.pop().expect("stack depth exceeds lcp");
    let label = prev[stack.len() - 1];
    let child_off = register_state(child, node_buf, registry);
    stack
      .last_mut()
      .expect("parent state exists")
      .edge_li
      .push((label, child_off));
  }
}

fn register_state(
  key: StateKey,
  node_buf: &mut Vec<u8>,
  registry: &mut HashMap<StateKey, u32>,
) -> u32 {
  if let Some(&existing) = registry.get(&key) {
    return existing;
  }

  let state_off = u32::try_from(node_buf.len()).expect("fst buffer fits u32");
  let edge_count = key.edge_li.len();
  let flag_bit = if key.final_flag { FLAG_FINAL } else { 0u8 };

  if edge_count < FAST_NODE_MIN_EDGE {
    node_buf.push(flag_bit | (edge_count as u8));
    for &(label, child_off) in &key.edge_li {
      node_buf.push(label);
      let delta = state_off - child_off;
      debug_assert!(delta >= 1);
      write_uleb128(delta as usize, node_buf);
    }
  } else {
    let mut quad_word = [0u64; 4];
    let mut quad_mask = 0u8;
    let mut max_delta = 0u32;

    for (idx, &(label, child_off)) in key.edge_li.iter().enumerate() {
      debug_assert!(idx == 0 || key.edge_li[idx - 1].0 < label);
      let q = (label >> 6) as usize;
      quad_mask |= 1u8 << q;
      quad_word[q] |= 1u64 << (label & 63);
      let delta = state_off - child_off;
      debug_assert!(delta >= 1);
      if delta > max_delta {
        max_delta = delta;
      }
    }

    let width = delta_width(max_delta);
    node_buf.push(flag_bit | FLAG_FAST | ((width - 1) << 4) | quad_mask);
    for (q, &word) in quad_word.iter().enumerate() {
      if (quad_mask & (1u8 << q)) != 0 {
        node_buf.extend_from_slice(&word.to_le_bytes());
      }
    }
    for &(_, child_off) in &key.edge_li {
      let delta = state_off - child_off;
      write_delta(delta, width, node_buf);
    }
  }

  registry.insert(key, state_off);
  state_off
}

#[inline]
const fn delta_width(max_delta: u32) -> u8 {
  if max_delta <= 0xFF {
    1
  } else if max_delta <= 0xFFFF {
    2
  } else if max_delta <= 0x00FF_FFFF {
    3
  } else {
    4
  }
}

#[inline]
fn write_delta(delta: u32, width: u8, out: &mut Vec<u8>) {
  let byte_li = delta.to_le_bytes();
  out.extend_from_slice(&byte_li[..usize::from(width)]);
}

fn write_uleb128(mut val: usize, out: &mut Vec<u8>) {
  loop {
    let mut byte = (val & 0x7F) as u8;
    val >>= 7;
    if val != 0 {
      byte |= 0x80;
    }
    out.push(byte);
    if val == 0 {
      break;
    }
  }
}