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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
use core::hint::black_box;

#[cfg(feature = "build")]
use ihash::{HashMap, HashMapExt};

use crate::{
  error::{Error, Result},
  format::bmp::BmpPageIndex,
};
#[cfg(feature = "build")]
use crate::{format::bmp::encode_bmp_page_header, format::header::MAX_WORD_CHAR, i18n::Lang};

const TRIE_HEADER_SIZE: usize = 32;
pub const ROOT_STRIDE: usize = 4;
pub const SLOT_STRIDE: usize = 12;
const GROUP_WIDTH: usize = 8;

const MAX_CHAR_ID: usize = (1 << 14) - 1;
const MAX_INTERNAL_ID: usize = (1 << 18) - 1;
const CHILD_MASK: u32 = (1 << 18) - 1;
const TIER_SHIFT: u32 = 18;
const TIER_MASK: u32 = 0b11;
const BLOOM12_SHIFT: u32 = 20;

const HASH_MUL: u32 = 0x9E37_79B1;
const MIX_MUL: u32 = 0x85EB_CA6B;
const SWAR_ONE: u64 = 0x0101_0101_0101_0101;
const SWAR_LO7: u64 = 0x7F7F_7F7F_7F7F_7F7F;
const SWAR_MSB: u64 = 0x8080_8080_8080_8080;

/// Fixed-width n-gram key hashed directly without byte-slice allocation.
#[cfg(feature = "build")]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NgramKey {
  /// Two adjacent characters `(c0, c1)`.
  Bi(char, char),
  /// Three adjacent characters `(c0, c1, c2)`.
  Tri(char, char, char),
}

/// Decoded slot match returned by [`FusedTrie::probe_slot`].
#[derive(Clone, Copy, Debug)]
pub(crate) struct TrieSlot {
  pub child_id: u32,
  pub word_tier: u8,
  pub bloom12: u16,
  pub bloom8: u8,
  pub weight: [i8; 3],
}

/// Zero-copy static 8-slot `u64`-SWAR SwissTable trie fusing L1-resident unigram weights,
/// bigram/trigram weights, 2-tier dictionary prefix matching, and 20-bit depth>=2 child Bloom filters.
#[derive(Clone, Copy, Debug)]
pub struct FusedTrie<'a> {
  raw_len: usize,
  char_count: u32,
  group_count: u32,
  total_group: u32,
  hot0_base: u32,
  hot0_len: u32,
  hot1_base: u32,
  hot1_len: u32,
  hot0_lut: &'a [[u8; 2]],
  hot1_lut: &'a [[u8; 2]],
  bmp_fb_index: BmpPageIndex<'a>,
  bmp_fb_id: &'a [[u8; 2]],
  non_bmp_key: &'a [[u8; 4]],
  non_bmp_id: &'a [[u8; 2]],
  root_table: &'a [[u8; ROOT_STRIDE]],
  ctrl_table: &'a [[u8; GROUP_WIDTH]],
  slot_group_table: &'a [[[u8; SLOT_STRIDE]; GROUP_WIDTH]],
}

/// Output produced by [`build_fused_trie`].
#[cfg(feature = "build")]
#[derive(Clone, Debug)]
pub struct TrieBuild {
  pub byte_li: Vec<u8>,
  pub word_count: u32,
  pub ngram_count: u32,
}

impl<'a> FusedTrie<'a> {
  pub const fn empty() -> Self {
    Self {
      raw_len: 0,
      char_count: 0,
      group_count: 0,
      total_group: 0,
      hot0_base: 0,
      hot0_len: 0,
      hot1_base: 0,
      hot1_len: 0,
      hot0_lut: &[],
      hot1_lut: &[],
      bmp_fb_index: BmpPageIndex::empty(),
      bmp_fb_id: &[],
      non_bmp_key: &[],
      non_bmp_id: &[],
      root_table: &[],
      ctrl_table: &[],
      slot_group_table: &[],
    }
  }

  pub fn from_slice(slice: &'a [u8]) -> Result<Self> {
    if slice.is_empty() {
      return Ok(Self::empty());
    }
    if slice.len() < TRIE_HEADER_SIZE {
      return Err(Error::InvalidModel {
        reason: "truncated fused trie header",
      });
    }

    let char_count = u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]);
    let group_count = u32::from_le_bytes([slice[4], slice[5], slice[6], slice[7]]);
    let total_group = u32::from_le_bytes([slice[8], slice[9], slice[10], slice[11]]);
    let hot0_base = u32::from(u16::from_le_bytes([slice[12], slice[13]]));
    let hot0_len = u32::from(u16::from_le_bytes([slice[14], slice[15]]));
    let hot1_base = u32::from(u16::from_le_bytes([slice[16], slice[17]]));
    let hot1_len = u32::from(u16::from_le_bytes([slice[18], slice[19]]));
    let bmp_fb_len = u32::from_le_bytes([slice[20], slice[21], slice[22], slice[23]]) as usize;
    let non_bmp_count = u32::from_le_bytes([slice[24], slice[25], slice[26], slice[27]]) as usize;
    let internal_count = u32::from_le_bytes([slice[28], slice[29], slice[30], slice[31]]);

    if char_count as usize > MAX_CHAR_ID
      || internal_count as usize > MAX_INTERNAL_ID
      || internal_count < char_count
    {
      return Err(Error::InvalidModel {
        reason: "fused trie counts out of bit budget",
      });
    }
    if group_count == 0 || total_group <= group_count {
      return Err(Error::InvalidModel {
        reason: "fused trie group geometry invalid",
      });
    }
    if hot0_base + hot0_len > 65_536 || hot1_base + hot1_len > 65_536 {
      return Err(Error::InvalidModel {
        reason: "fused trie hot lut range out of bmp bounds",
      });
    }

    let hot0_byte_len = (hot0_len as usize) * 2;
    let hot1_byte_len = (hot1_len as usize) * 2;
    let non_bmp_byte_len = non_bmp_count.checked_mul(6).ok_or(Error::InvalidModel {
      reason: "fused trie non-bmp overflow",
    })?;
    let root_byte_len =
      (char_count as usize + 1)
        .checked_mul(ROOT_STRIDE)
        .ok_or(Error::InvalidModel {
          reason: "fused trie root length overflow",
        })?;
    let ctrl_byte_len =
      (total_group as usize)
        .checked_mul(GROUP_WIDTH)
        .ok_or(Error::InvalidModel {
          reason: "fused trie ctrl length overflow",
        })?;
    let slot_byte_len = ctrl_byte_len
      .checked_mul(SLOT_STRIDE)
      .ok_or(Error::InvalidModel {
        reason: "fused trie slot length overflow",
      })?;

    let mut off = TRIE_HEADER_SIZE;
    let hot0_slice = take_sub(slice, &mut off, hot0_byte_len)?;
    let hot1_slice = take_sub(slice, &mut off, hot1_byte_len)?;
    let bmp_fb_slice = take_sub(slice, &mut off, bmp_fb_len)?;
    let non_bmp_slice = take_sub(slice, &mut off, non_bmp_byte_len)?;
    let root_slice = take_sub(slice, &mut off, root_byte_len)?;
    let ctrl_slice = take_sub(slice, &mut off, ctrl_byte_len)?;
    let slot_slice = take_sub(slice, &mut off, slot_byte_len)?;
    if off != slice.len() {
      return Err(Error::InvalidModel {
        reason: "fused trie trailing bytes mismatch",
      });
    }

    let (hot0_lut, hot0_rem) = hot0_slice.as_chunks::<2>();
    let (hot1_lut, hot1_rem) = hot1_slice.as_chunks::<2>();
    if !hot0_rem.is_empty() || !hot1_rem.is_empty() {
      return Err(Error::InvalidModel {
        reason: "fused trie hot lut alignment mismatch",
      });
    }

    let (bmp_fb_index, bmp_fb_id) = if bmp_fb_slice.is_empty() {
      (BmpPageIndex::empty(), &[][..])
    } else {
      let (idx, rem) = BmpPageIndex::from_slice(bmp_fb_slice)?;
      if rem.len() != idx.entry_count() * 2 {
        return Err(Error::InvalidModel {
          reason: "fused trie bmp fallback id length mismatch",
        });
      }
      let (id_li, id_rem) = rem.as_chunks::<2>();
      if !id_rem.is_empty() {
        return Err(Error::InvalidModel {
          reason: "fused trie bmp fallback alignment mismatch",
        });
      }
      (idx, id_li)
    };

    let non_bmp_key_len = non_bmp_count * 4;
    let (non_bmp_key, nb_key_rem) = non_bmp_slice[..non_bmp_key_len].as_chunks::<4>();
    let (non_bmp_id, nb_id_rem) = non_bmp_slice[non_bmp_key_len..].as_chunks::<2>();
    if !nb_key_rem.is_empty() || !nb_id_rem.is_empty() {
      return Err(Error::InvalidModel {
        reason: "fused trie non-bmp alignment mismatch",
      });
    }

    validate_char_id(hot0_lut, char_count)?;
    validate_char_id(hot1_lut, char_count)?;
    validate_char_id(bmp_fb_id, char_count)?;
    validate_char_id(non_bmp_id, char_count)?;

    let mut prev = u32::from(u16::MAX);
    for chunk in non_bmp_key {
      let cp = u32::from_le_bytes(*chunk);
      if cp <= prev {
        return Err(Error::InvalidModel {
          reason: "fused trie non-bmp keys unsorted",
        });
      }
      prev = cp;
    }

    let (root_table, root_rem) = root_slice.as_chunks::<ROOT_STRIDE>();
    let (ctrl_table, ctrl_rem) = ctrl_slice.as_chunks::<GROUP_WIDTH>();
    let (slot_li, slot_rem) = slot_slice.as_chunks::<SLOT_STRIDE>();
    let (slot_group_table, group_rem) = slot_li.as_chunks::<GROUP_WIDTH>();
    if !root_rem.is_empty()
      || !ctrl_rem.is_empty()
      || !slot_rem.is_empty()
      || !group_rem.is_empty()
      || slot_group_table.len() != ctrl_table.len()
    {
      return Err(Error::InvalidModel {
        reason: "fused trie table geometry mismatch",
      });
    }

    // Validate trailing all-zero sentinel control group so probing always terminates.
    if ctrl_table.last() != Some(&[0u8; GROUP_WIDTH]) {
      return Err(Error::InvalidModel {
        reason: "fused trie missing trailing sentinel group",
      });
    }

    // Validate stored child_id bounds once at load time so hot-path probes omit redundant checks.
    for slot in slot_li {
      let w0 = u32::from_le_bytes([slot[0], slot[1], slot[2], slot[3]]);
      if w0 != 0 {
        let w1 = u32::from_le_bytes([slot[4], slot[5], slot[6], slot[7]]);
        if (w1 & CHILD_MASK) > internal_count {
          return Err(Error::InvalidModel {
            reason: "fused trie child_id out of range",
          });
        }
      }
    }

    Ok(Self {
      raw_len: slice.len(),
      char_count,
      group_count,
      total_group,
      hot0_base,
      hot0_len,
      hot1_base,
      hot1_len,
      hot0_lut,
      hot1_lut,
      bmp_fb_index,
      bmp_fb_id,
      non_bmp_key,
      non_bmp_id,
      root_table,
      ctrl_table,
      slot_group_table,
    })
  }

  #[inline]
  pub const fn is_empty(&self) -> bool {
    self.raw_len == 0 || self.char_count == 0
  }

  #[inline]
  pub const fn byte_len(&self) -> usize {
    self.raw_len
  }

  #[inline]
  pub const fn char_count(&self) -> u32 {
    self.char_count
  }

  #[inline]
  pub const fn slot_count(&self) -> u32 {
    self.total_group.saturating_mul(GROUP_WIDTH as u32)
  }

  /// Whether `hot0_lut` directly covers the entire CJK Unified Ideographs block `U+4E00..=U+9FFF`.
  #[inline(always)]
  pub const fn has_direct_han_lut(&self) -> bool {
    self.hot0_base == 0x4E00 && self.hot0_len == 0x5200
  }

  /// Single-table `char_id` lookup for BMP Han codepoints `0x4E00..=0x9FFF`.
  #[inline(always)]
  pub fn char_id_han(&self, u: u32) -> u16 {
    let idx = u.wrapping_sub(0x4E00) as usize;
    self
      .hot0_lut
      .get(idx)
      .map_or(0, |pair| u16::from_le_bytes(*pair))
  }

  /// Resolves a BMP codepoint `u <= 0xFFFF` directly to its compact `char_id` (`0` = OOV).
  #[inline(always)]
  pub fn char_id_bmp(&self, u: u32) -> u16 {
    let r0 = u.wrapping_sub(self.hot0_base);
    if r0 < self.hot0_len
      && let Some(pair) = self.hot0_lut.get(r0 as usize)
    {
      return u16::from_le_bytes(*pair);
    }
    let r1 = u.wrapping_sub(self.hot1_base);
    if r1 < self.hot1_len
      && let Some(pair) = self.hot1_lut.get(r1 as usize)
    {
      return u16::from_le_bytes(*pair);
    }
    if let Some(idx) = self.bmp_fb_index.get_u16(u as u16)
      && let Some(pair) = self.bmp_fb_id.get(idx)
    {
      return u16::from_le_bytes(*pair);
    }
    0
  }

  /// Resolves any Unicode scalar `ch` to its compact `char_id` (`0` = OOV).
  #[inline(always)]
  pub fn char_id(&self, ch: char) -> u16 {
    let u = ch as u32;
    if u <= u32::from(u16::MAX) {
      return self.char_id_bmp(u);
    }
    if let Ok(idx) = self
      .non_bmp_key
      .binary_search_by_key(&u, |chunk| u32::from_le_bytes(*chunk))
      && let Some(pair) = self.non_bmp_id.get(idx)
    {
      return u16::from_le_bytes(*pair);
    }
    0
  }

  /// Reads forward-offset unigram weights `[w_m1, w_0, w_p1, w_p2]` from the L1-resident root table.
  #[inline(always)]
  pub fn root_weight(&self, ch_id: u16) -> [i8; 4] {
    match self.root_table.get(usize::from(ch_id)) {
      Some(rec) => [rec[0] as i8, rec[1] as i8, rec[2] as i8, rec[3] as i8],
      None => [0; 4],
    }
  }

  /// Checks whether `ch_id` passes an internal node's 20-bit child Bloom filter.
  #[inline(always)]
  pub const fn child_may_have_child(bloom12: u16, bloom8: u8, ch_id: u16) -> bool {
    let (bit12, bit8) = bloom20_bit(ch_id);
    ((bloom12 & bit12) != 0) && ((bloom8 & bit8) != 0)
  }

  /// Safe software prefetch of the 8-byte SwissTable control word `LOOKAHEAD` positions ahead.
  #[inline(always)]
  pub fn prefetch_depth2(&self, id0: u16, id1: u16) {
    if id0 != 0 && id1 != 0 {
      let key = (u32::from(id0) << 14) | u32::from(id1);
      let h = hash_key(key);
      let g = group_bucket(h, self.group_count);
      if let Some(ctrl) = self.ctrl_table.get(g) {
        let _ = black_box(ctrl[0]);
      }
    }
  }

  /// Probes `(parent_id, ch_id)` via 8-slot `u64`-SWAR SwissTable tag matching.
  /// Callers guarantee `1 <= parent_id <= internal_count` and `ch_id != 0` (validated at load time).
  #[inline(always)]
  pub(crate) fn probe_slot(&self, parent_id: u32, ch_id: u16) -> Option<TrieSlot> {
    let key = (parent_id << 14) | u32::from(ch_id);
    let h = hash_key(key);
    let tag = (h as u8) | 0x80;
    let mut g = group_bucket(h, self.group_count);

    loop {
      let ctrl_byte = self.ctrl_table.get(g)?;
      let ctrl = u64::from_le_bytes(*ctrl_byte);
      let mut mask = match_tag_u64(ctrl, tag);
      if mask != 0 {
        let group = self.slot_group_table.get(g)?;
        while mask != 0 {
          let lane = ((mask.trailing_zeros() >> 3) as usize) & 7;
          mask &= mask - 1;
          let slot = &group[lane];
          let w0 = u32::from_le_bytes([slot[0], slot[1], slot[2], slot[3]]);
          if w0 == key {
            let w1 = u32::from_le_bytes([slot[4], slot[5], slot[6], slot[7]]);
            return Some(TrieSlot {
              child_id: w1 & CHILD_MASK,
              word_tier: ((w1 >> TIER_SHIFT) & TIER_MASK) as u8,
              bloom12: (w1 >> BLOOM12_SHIFT) as u16,
              bloom8: slot[11],
              weight: [slot[8] as i8, slot[9] as i8, slot[10] as i8],
            });
          }
        }
      }
      if has_empty_u64(ctrl) {
        return None;
      }
      g += 1;
    }
  }

  /// Advances one character from `slot` through the 20-bit Bloom filter and SwissTable probe.
  #[inline(always)]
  fn step_slot(&self, slot: TrieSlot, ch: char) -> Option<TrieSlot> {
    if slot.child_id == 0 {
      return None;
    }
    let id = self.char_id(ch);
    if id == 0 || !Self::child_may_have_child(slot.bloom12, slot.bloom8, id) {
      return None;
    }
    self.probe_slot(slot.child_id, id)
  }

  /// Calls `f(end_byte, char_len)` for every dictionary word starting at `start` in `text`.
  #[inline]
  pub fn for_each_word_prefix<F: FnMut(usize, usize)>(&self, text: &str, start: usize, mut f: F) {
    if self.is_empty() {
      return;
    }
    let Some(tail) = text.get(start..) else {
      return;
    };
    let mut iter = tail.char_indices();
    let Some((_, c0)) = iter.next() else {
      return;
    };
    let id0 = self.char_id(c0);
    if id0 == 0 {
      return;
    }
    let Some((rel1, c1)) = iter.next() else {
      return;
    };
    let id1 = self.char_id(c1);
    if id1 == 0 {
      return;
    }
    let Some(mut slot) = self.probe_slot(u32::from(id0), id1) else {
      return;
    };
    let mut char_len = 2usize;
    if slot.word_tier != 0 {
      f(start + rel1 + c1.len_utf8(), char_len);
    }

    for (rel, ch) in iter {
      let Some(next_slot) = self.step_slot(slot, ch) else {
        break;
      };
      slot = next_slot;
      char_len += 1;
      if slot.word_tier != 0 {
        f(start + rel + ch.len_utf8(), char_len);
      }
    }
  }

  /// Exact dictionary membership check for `Search` and `Full` modes.
  #[inline]
  pub fn contains(&self, word: &str) -> bool {
    if self.is_empty() {
      return false;
    }
    let mut iter = word.chars();
    let Some(c0) = iter.next() else {
      return false;
    };
    let id0 = self.char_id(c0);
    let Some(c1) = iter.next() else {
      return false;
    };
    let id1 = self.char_id(c1);
    if id0 == 0 || id1 == 0 {
      return false;
    }
    let Some(mut slot) = self.probe_slot(u32::from(id0), id1) else {
      return false;
    };
    for ch in iter {
      let Some(next_slot) = self.step_slot(slot, ch) else {
        return false;
      };
      slot = next_slot;
    }
    slot.word_tier != 0
  }
}

fn validate_char_id(pair_li: &[[u8; 2]], char_count: u32) -> Result<()> {
  for pair in pair_li {
    if u32::from(u16::from_le_bytes(*pair)) > char_count {
      return Err(Error::InvalidModel {
        reason: "fused trie char_id out of range",
      });
    }
  }
  Ok(())
}

fn take_sub<'a>(slice: &'a [u8], off: &mut usize, len: usize) -> Result<&'a [u8]> {
  let end = off.checked_add(len).ok_or(Error::InvalidModel {
    reason: "fused trie section offset overflow",
  })?;
  if end > slice.len() {
    return Err(Error::InvalidModel {
      reason: "fused trie section truncated",
    });
  }
  let sub = &slice[*off..end];
  *off = end;
  Ok(sub)
}

#[inline(always)]
const fn hash_key(key: u32) -> u32 {
  let mut h = key.wrapping_mul(HASH_MUL);
  h ^= h >> 16;
  h = h.wrapping_mul(MIX_MUL);
  h ^ (h >> 15)
}

#[inline(always)]
const fn group_bucket(h: u32, group_count: u32) -> usize {
  (((h as u64) * (group_count as u64)) >> 32) as usize
}

/// Zero-carry exact 8-lane byte equality mask: sets bit `8 * lane + 7` iff `ctrl[lane] == tag`.
#[inline(always)]
const fn match_tag_u64(ctrl: u64, tag: u8) -> u64 {
  let x = ctrl ^ (tag as u64).wrapping_mul(SWAR_ONE);
  let lo7 = (x & SWAR_LO7).wrapping_add(SWAR_LO7);
  !(lo7 | x | SWAR_LO7)
}

/// Returns `true` iff any lane in `ctrl` is empty (`0x00`; occupied tags always have bit 7 set).
#[inline(always)]
const fn has_empty_u64(ctrl: u64) -> bool {
  (!ctrl & SWAR_MSB) != 0
}

#[inline(always)]
const fn bloom20_bit(ch_id: u16) -> (u16, u8) {
  let h = (ch_id as u32).wrapping_mul(HASH_MUL);
  let b12 = ((h >> 24) * 12) >> 8;
  let b8 = (h >> 21) & 7;
  (1u16 << b12, 1u8 << b8)
}

#[cfg(feature = "build")]
pub fn build_fused_trie(
  lang: Lang,
  uni_li: &[(char, [i8; 4])],
  ngram_li: &[(NgramKey, [i8; 3])],
  word_li: &[(String, u8)],
) -> Result<TrieBuild> {
  if uni_li.is_empty() && ngram_li.is_empty() && word_li.is_empty() {
    return Ok(TrieBuild {
      byte_li: Vec::new(),
      word_count: 0,
      ngram_count: 0,
    });
  }

  let mut char_map: HashMap<char, u16> = HashMap::with_capacity(uni_li.len() + 256);
  let mut char_li: Vec<char> = Vec::with_capacity(uni_li.len() + 256);
  let mut register_char = |ch: char| -> Result<u16> {
    if let Some(&id) = char_map.get(&ch) {
      return Ok(id);
    }
    let next_id = char_li.len() + 1;
    if next_id > MAX_CHAR_ID {
      return Err(Error::ModelBuild {
        reason: "distinct characters exceed 16383 FusedTrie limit",
      });
    }
    let id = next_id as u16;
    char_map.insert(ch, id);
    char_li.push(ch);
    Ok(id)
  };

  for &(ch, _) in uni_li {
    register_char(ch)?;
  }
  for &(key, _) in ngram_li {
    match key {
      NgramKey::Bi(c0, c1) => {
        register_char(c0)?;
        register_char(c1)?;
      }
      NgramKey::Tri(c0, c1, c2) => {
        register_char(c0)?;
        register_char(c1)?;
        register_char(c2)?;
      }
    }
  }
  for (w, _) in word_li {
    let char_len = w.chars().count();
    if !(2..=MAX_WORD_CHAR).contains(&char_len) {
      continue;
    }
    for ch in w.chars() {
      register_char(ch)?;
    }
  }

  let char_count = char_li.len();
  let mut uni_weight_li = vec![[0i8; 4]; char_count + 1];
  for &(ch, w) in uni_li {
    let id = usize::from(char_map[&ch]);
    // Forward boundary offset order relative to p: [p-1, p, p+1, p+2].
    uni_weight_li[id] = [w[3], w[2], w[1], w[0]];
  }

  struct BuildNode {
    parent_id: u32,
    ch_id: u16,
    child_id: u32,
    word_tier: u8,
    weight: [i8; 3],
    bloom12: u16,
    bloom8: u8,
  }

  // Index 0..=char_count reserved as depth-1 pseudo-nodes indexed directly by ch_id.
  // Depth >= 2 transitions start at index `char_count + 1` in `node_li`.
  let mut node_li: Vec<BuildNode> = Vec::with_capacity(word_li.len() + ngram_li.len() + char_count);
  for id in 0..=char_count {
    node_li.push(BuildNode {
      parent_id: 0,
      ch_id: id as u16,
      child_id: 0,
      word_tier: 0,
      weight: [0; 3],
      bloom12: 0,
      bloom8: 0,
    });
  }
  let mut edge_map: HashMap<u32, usize> = HashMap::with_capacity(word_li.len() + ngram_li.len());
  let mut next_internal = char_count + 1;

  let ensure_child = |parent_idx: usize,
                      ch_id: u16,
                      node_li: &mut Vec<BuildNode>,
                      edge_map: &mut HashMap<u32, usize>,
                      next_internal: &mut usize|
   -> Result<usize> {
    let parent_id = if parent_idx <= char_count {
      parent_idx as u32
    } else {
      if node_li[parent_idx].child_id == 0 {
        if *next_internal > MAX_INTERNAL_ID {
          return Err(Error::ModelBuild {
            reason: "fused trie internal nodes exceed 262143 limit",
          });
        }
        node_li[parent_idx].child_id = *next_internal as u32;
        *next_internal += 1;
      }
      node_li[parent_idx].child_id
    };
    let key = (parent_id << 14) | u32::from(ch_id);
    if let Some(&idx) = edge_map.get(&key) {
      return Ok(idx);
    }
    let idx = node_li.len();
    node_li.push(BuildNode {
      parent_id,
      ch_id,
      child_id: 0,
      word_tier: 0,
      weight: [0; 3],
      bloom12: 0,
      bloom8: 0,
    });
    edge_map.insert(key, idx);
    Ok(idx)
  };

  for &(key, w) in ngram_li {
    match key {
      NgramKey::Bi(c0, c1) => {
        let p0 = usize::from(char_map[&c0]);
        let idx = ensure_child(
          p0,
          char_map[&c1],
          &mut node_li,
          &mut edge_map,
          &mut next_internal,
        )?;
        // Forward order at depth 2: [score[p], score[p+1], score[p+2]].
        node_li[idx].weight = [w[2], w[1], w[0]];
      }
      NgramKey::Tri(c0, c1, c2) => {
        let p0 = usize::from(char_map[&c0]);
        let p1 = ensure_child(
          p0,
          char_map[&c1],
          &mut node_li,
          &mut edge_map,
          &mut next_internal,
        )?;
        let idx = ensure_child(
          p1,
          char_map[&c2],
          &mut node_li,
          &mut edge_map,
          &mut next_internal,
        )?;
        // Forward order at depth 3: [score[p+1], score[p+2], 0].
        node_li[idx].weight = [w[1], w[0], 0];
      }
    }
  }

  let mut distinct_word = 0u32;
  for (w, raw_tier) in word_li {
    let char_len = w.chars().count();
    if !(2..=MAX_WORD_CHAR).contains(&char_len) {
      continue;
    }
    let tier = (*raw_tier).clamp(1, 2);
    let mut ch_iter = w.chars();
    let Some(c0) = ch_iter.next() else {
      continue;
    };
    let mut cur_idx = usize::from(char_map[&c0]);
    for ch in ch_iter {
      cur_idx = ensure_child(
        cur_idx,
        char_map[&ch],
        &mut node_li,
        &mut edge_map,
        &mut next_internal,
      )?;
    }
    if node_li[cur_idx].word_tier == 0 {
      distinct_word += 1;
    }
    node_li[cur_idx].word_tier = node_li[cur_idx].word_tier.max(tier);
  }

  let internal_count = next_internal - 1;
  let mut child_to_idx: HashMap<u32, usize> = HashMap::with_capacity(node_li.len());
  for (idx, n) in node_li.iter().enumerate().skip(char_count + 1) {
    if n.child_id != 0 {
      child_to_idx.insert(n.child_id, idx);
    }
  }

  for idx in (char_count + 1)..node_li.len() {
    let parent_id = node_li[idx].parent_id;
    let ch_id = node_li[idx].ch_id;
    if (parent_id as usize) > char_count
      && let Some(&p_idx) = child_to_idx.get(&parent_id)
    {
      let (b12, b8) = bloom20_bit(ch_id);
      node_li[p_idx].bloom12 |= b12;
      node_li[p_idx].bloom8 |= b8;
    }
  }

  let edge_count = node_li.len() - (char_count + 1);
  // Target ~80% load (~6.4/8 slots per group) for compact L2-friendly SwissTable.
  let group_count = ((edge_count * 5) / 32 + 1).max(2) as u32;
  let mut ctrl_group_li: Vec<[u8; GROUP_WIDTH]> = vec![[0; GROUP_WIDTH]; group_count as usize + 8];
  let mut slot_group_li: Vec<[[u32; 3]; GROUP_WIDTH]> =
    vec![[[0; 3]; GROUP_WIDTH]; group_count as usize + 8];
  let mut occ_li: Vec<u8> = vec![0; group_count as usize + 8];

  struct PendingEdge {
    home: usize,
    tag: u8,
    rec: [u32; 3],
  }

  let mut overflow_li: Vec<PendingEdge> = Vec::new();
  for n in node_li.iter().skip(char_count + 1) {
    let key = (n.parent_id << 14) | u32::from(n.ch_id);
    let w1 = (n.child_id & CHILD_MASK)
      | (u32::from(n.word_tier & 0b11) << TIER_SHIFT)
      | (u32::from(n.bloom12) << BLOOM12_SHIFT);
    let w2 = u32::from_le_bytes([
      n.weight[0] as u8,
      n.weight[1] as u8,
      n.weight[2] as u8,
      n.bloom8,
    ]);
    let h = hash_key(key);
    let home = group_bucket(h, group_count);
    let tag = (h as u8) | 0x80;
    let rec = [key, w1, w2];

    // Pass 1: pack into home group whenever a lane is free to maximize single-group hits.
    let occ = usize::from(occ_li[home]);
    if occ < GROUP_WIDTH {
      ctrl_group_li[home][occ] = tag;
      slot_group_li[home][occ] = rec;
      occ_li[home] = (occ + 1) as u8;
    } else {
      overflow_li.push(PendingEdge { home, tag, rec });
    }
  }

  // Pass 2: place overflow edges in the first non-full group >= home (invariant preserved).
  for edge in overflow_li {
    let mut g = edge.home + 1;
    loop {
      if g + 1 >= occ_li.len() {
        ctrl_group_li.resize(ctrl_group_li.len() + 8, [0; GROUP_WIDTH]);
        slot_group_li.resize(slot_group_li.len() + 8, [[0; 3]; GROUP_WIDTH]);
        occ_li.resize(occ_li.len() + 8, 0);
      }
      let occ = usize::from(occ_li[g]);
      if occ < GROUP_WIDTH {
        ctrl_group_li[g][occ] = edge.tag;
        slot_group_li[g][occ] = edge.rec;
        occ_li[g] = (occ + 1) as u8;
        break;
      }
      g += 1;
    }
  }

  // Trim unused trailing overflow groups while guaranteeing one all-zero sentinel group.
  while occ_li.len() > (group_count as usize) + 1 && occ_li[occ_li.len() - 2] == 0 {
    ctrl_group_li.pop();
    slot_group_li.pop();
    occ_li.pop();
  }
  if occ_li.last().is_none_or(|&occ| occ != 0) {
    ctrl_group_li.push([0; GROUP_WIDTH]);
    slot_group_li.push([[0; 3]; GROUP_WIDTH]);
  }
  let total_group = ctrl_group_li.len() as u32;

  let (hot0_base, hot0_len, hot1_base, hot1_len) = hot_range(lang, char_count);
  let mut hot0_lut = vec![0u16; hot0_len as usize];
  let mut hot1_lut = vec![0u16; hot1_len as usize];
  let mut bmp_fb_li: Vec<(u16, u16)> = Vec::new();
  let mut non_bmp_li: Vec<(u32, u16)> = Vec::new();

  for (idx, &ch) in char_li.iter().enumerate() {
    let id = (idx + 1) as u16;
    let cp = ch as u32;
    let r0 = cp.wrapping_sub(u32::from(hot0_base));
    if r0 < u32::from(hot0_len) {
      hot0_lut[r0 as usize] = id;
      continue;
    }
    let r1 = cp.wrapping_sub(u32::from(hot1_base));
    if r1 < u32::from(hot1_len) {
      hot1_lut[r1 as usize] = id;
      continue;
    }
    if cp <= u32::from(u16::MAX) {
      bmp_fb_li.push((cp as u16, id));
    } else {
      non_bmp_li.push((cp, id));
    }
  }
  bmp_fb_li.sort_unstable_by_key(|&(cp, _)| cp);
  non_bmp_li.sort_unstable_by_key(|&(cp, _)| cp);

  let mut bmp_fb_buf = Vec::new();
  if !bmp_fb_li.is_empty() {
    let cp_li: Vec<u16> = bmp_fb_li.iter().map(|&(cp, _)| cp).collect();
    encode_bmp_page_header(&cp_li, &mut bmp_fb_buf);
    for (_, id) in bmp_fb_li {
      bmp_fb_buf.extend_from_slice(&id.to_le_bytes());
    }
  }

  let bmp_fb_len = bmp_fb_buf.len() as u32;
  let non_bmp_count = non_bmp_li.len() as u32;
  let ctrl_byte_len = (total_group as usize) * GROUP_WIDTH;
  let total_cap = TRIE_HEADER_SIZE
    + hot0_lut.len() * 2
    + hot1_lut.len() * 2
    + bmp_fb_buf.len()
    + non_bmp_li.len() * 6
    + (char_count + 1) * ROOT_STRIDE
    + ctrl_byte_len
    + ctrl_byte_len * SLOT_STRIDE;

  let mut out = Vec::with_capacity(total_cap);
  out.extend_from_slice(&(char_count as u32).to_le_bytes());
  out.extend_from_slice(&group_count.to_le_bytes());
  out.extend_from_slice(&total_group.to_le_bytes());
  out.extend_from_slice(&hot0_base.to_le_bytes());
  out.extend_from_slice(&hot0_len.to_le_bytes());
  out.extend_from_slice(&hot1_base.to_le_bytes());
  out.extend_from_slice(&hot1_len.to_le_bytes());
  out.extend_from_slice(&bmp_fb_len.to_le_bytes());
  out.extend_from_slice(&non_bmp_count.to_le_bytes());
  out.extend_from_slice(&(internal_count as u32).to_le_bytes());

  for id in hot0_lut {
    out.extend_from_slice(&id.to_le_bytes());
  }
  for id in hot1_lut {
    out.extend_from_slice(&id.to_le_bytes());
  }
  out.extend_from_slice(&bmp_fb_buf);
  for &(cp, _) in &non_bmp_li {
    out.extend_from_slice(&cp.to_le_bytes());
  }
  for &(_, id) in &non_bmp_li {
    out.extend_from_slice(&id.to_le_bytes());
  }
  for w in &uni_weight_li {
    for &b in w {
      out.push(b as u8);
    }
  }
  for grp in &ctrl_group_li {
    out.extend_from_slice(grp);
  }
  for grp in &slot_group_li {
    for rec in grp {
      out.extend_from_slice(&rec[0].to_le_bytes());
      out.extend_from_slice(&rec[1].to_le_bytes());
      out.extend_from_slice(&rec[2].to_le_bytes());
    }
  }

  Ok(TrieBuild {
    byte_li: out,
    word_count: distinct_word,
    ngram_count: ngram_li.len() as u32,
  })
}

#[cfg(feature = "build")]
fn hot_range(lang: Lang, char_count: usize) -> (u16, u16, u16, u16) {
  if char_count < 128 {
    return (0, 0, 0, 0);
  }
  match lang {
    Lang::Zh => (0x4E00, 0x9FFF - 0x4E00 + 1, 0, 0),
    Lang::Ja => (0x4E00, 0x9FFF - 0x4E00 + 1, 0x3000, 0x0100),
    Lang::Th => (0x0E00, 0x0080, 0, 0),
    Lang::Ko | Lang::En | Lang::Ru | Lang::Ar => (0, 0, 0, 0),
  }
}