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;
#[cfg(feature = "build")]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NgramKey {
Bi(char, char),
Tri(char, char, char),
}
#[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],
}
#[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],
hot1_lut: &'a [u8],
bmp_fb_index: BmpPageIndex<'a>,
bmp_fb_id: &'a [u8],
non_bmp_key: &'a [u8],
non_bmp_id: &'a [u8],
root_table: &'a [u8],
ctrl_table: &'a [u8],
slot_table: &'a [u8],
}
#[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_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_lut = take_sub(slice, &mut off, hot0_byte_len)?;
let hot1_lut = 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_table = take_sub(slice, &mut off, root_byte_len)?;
let ctrl_table = take_sub(slice, &mut off, ctrl_byte_len)?;
let slot_table = take_sub(slice, &mut off, slot_byte_len)?;
if off != slice.len() {
return Err(Error::InvalidModel {
reason: "fused trie trailing bytes 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",
});
}
(idx, rem)
};
let non_bmp_key_len = non_bmp_count * 4;
let non_bmp_key = &non_bmp_slice[..non_bmp_key_len];
let non_bmp_id = &non_bmp_slice[non_bmp_key_len..];
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);
let (nb_chunk_li, _) = non_bmp_key.as_chunks::<4>();
for chunk in nb_chunk_li {
let cp = u32::from_le_bytes(*chunk);
if cp <= prev {
return Err(Error::InvalidModel {
reason: "fused trie non-bmp keys unsorted",
});
}
prev = cp;
}
let sentinel_off = ctrl_byte_len - GROUP_WIDTH;
if ctrl_table[sentinel_off..ctrl_byte_len] != [0u8; GROUP_WIDTH] {
return Err(Error::InvalidModel {
reason: "fused trie missing trailing sentinel group",
});
}
let (slot_li, _) = slot_table.as_chunks::<SLOT_STRIDE>();
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_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)
}
#[inline(always)]
pub const fn has_direct_han_lut(&self) -> bool {
self.hot0_base == 0x4E00 && self.hot0_len == 0x5200
}
#[inline(always)]
pub fn char_id_han(&self, u: u32) -> u16 {
let idx = u.wrapping_sub(0x4E00) as usize;
let (lut_li, _) = self.hot0_lut.as_chunks::<2>();
lut_li.get(idx).map_or(0, |pair| u16::from_le_bytes(*pair))
}
#[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 (lut_li, _) = self.hot0_lut.as_chunks::<2>();
if let Some(pair) = lut_li.get(r0 as usize) {
return u16::from_le_bytes(*pair);
}
}
let r1 = u.wrapping_sub(self.hot1_base);
if r1 < self.hot1_len {
let (lut_li, _) = self.hot1_lut.as_chunks::<2>();
if let Some(pair) = lut_li.get(r1 as usize) {
return u16::from_le_bytes(*pair);
}
}
if let Some(idx) = self.bmp_fb_index.get_u16(u as u16) {
let (id_li, _) = self.bmp_fb_id.as_chunks::<2>();
if let Some(pair) = id_li.get(idx) {
return u16::from_le_bytes(*pair);
}
}
0
}
#[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);
}
let (key_li, _) = self.non_bmp_key.as_chunks::<4>();
if let Ok(idx) = key_li.binary_search_by_key(&u, |chunk| u32::from_le_bytes(*chunk)) {
let (id_li, _) = self.non_bmp_id.as_chunks::<2>();
if let Some(pair) = id_li.get(idx) {
return u16::from_le_bytes(*pair);
}
}
0
}
#[inline(always)]
pub fn root_weight(&self, ch_id: u16) -> [i8; 4] {
let (root_li, _) = self.root_table.as_chunks::<ROOT_STRIDE>();
match root_li.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],
}
}
#[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)
}
#[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(byte) = self.ctrl_table.get(g * GROUP_WIDTH) {
let _ = black_box(*byte);
}
}
}
#[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 (ctrl_li, _) = self.ctrl_table.as_chunks::<GROUP_WIDTH>();
let (slot_li, _) = self.slot_table.as_chunks::<SLOT_STRIDE>();
let mut g = group_bucket(h, self.group_count);
loop {
let ctrl_byte = ctrl_li.get(g)?;
let ctrl = u64::from_le_bytes(*ctrl_byte);
let mut mask = match_tag_u64(ctrl, tag);
while mask != 0 {
let lane = (mask.trailing_zeros() >> 3) as usize;
mask &= mask - 1;
let idx = g * GROUP_WIDTH + lane;
if let Some(slot) = slot_li.get(idx) {
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;
}
}
#[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 {
if slot.child_id == 0 {
break;
}
let id = self.char_id(ch);
if id == 0 || !Self::child_may_have_child(slot.bloom12, slot.bloom8, id) {
break;
}
let Some(next_slot) = self.probe_slot(slot.child_id, id) else {
break;
};
slot = next_slot;
char_len += 1;
if slot.word_tier != 0 {
f(start + rel + ch.len_utf8(), char_len);
}
}
}
#[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 {
if slot.child_id == 0 {
return false;
}
let id = self.char_id(ch);
if id == 0 || !Self::child_may_have_child(slot.bloom12, slot.bloom8, id) {
return false;
}
let Some(next_slot) = self.probe_slot(slot.child_id, id) else {
return false;
};
slot = next_slot;
}
slot.word_tier != 0
}
}
fn validate_char_id(slice: &[u8], char_count: u32) -> Result<()> {
let (pair_li, _) = slice.as_chunks::<2>();
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
}
#[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)
}
#[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]);
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,
}
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,
)?;
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,
)?;
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);
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];
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 });
}
}
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;
}
}
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),
}
}