mcut 0.1.0

Zero-copy, low-memory multilingual word segmenter using pointwise linear classification and minimal FST
Documentation
use ihash::hash32;

use crate::{
  error::{Error, Result},
  i18n::Lang,
};

pub const MAGIC: [u8; 4] = *b"MCUT";
pub const FORMAT_VERSION: u8 = 1;
pub const HEADER_SIZE: usize = 80;
pub const DICT_TIER_COUNT: usize = 2;
pub const DICT_BUCKET_COUNT: usize = 5;
pub const DICT_SLOT_COUNT: usize = DICT_TIER_COUNT * DICT_BUCKET_COUNT;
pub const DICT_WEIGHT_LEN: usize = DICT_SLOT_COUNT * 3;
pub const MAX_WORD_CHAR: usize = 32;

pub const FLAG_USE_TCC: u8 = 1 << 0;
pub const FLAG_HAS_TRIE: u8 = 1 << 1;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Header {
  pub lang: Lang,
  pub flag: u8,
  pub max_word_char: u8,
  pub bias: i16,
  pub search_threshold: i16,
  pub scale_x100: u16,
  pub dict_weight: [i8; DICT_WEIGHT_LEN],
  pub type_lut_len: u32,
  pub trie_len: u32,
  pub word_count: u32,
  pub ngram_count: u32,
  pub checksum: u32,
}

impl Header {
  pub const fn empty(lang: Lang, use_tcc: bool) -> Self {
    Self {
      lang,
      flag: if use_tcc { FLAG_USE_TCC } else { 0 },
      max_word_char: MAX_WORD_CHAR as u8,
      bias: 0,
      search_threshold: -1,
      scale_x100: 100,
      dict_weight: [0; DICT_WEIGHT_LEN],
      type_lut_len: 0,
      trie_len: 0,
      word_count: 0,
      ngram_count: 0,
      checksum: 0,
    }
  }

  pub const fn use_tcc(self) -> bool {
    (self.flag & FLAG_USE_TCC) != 0
  }

  pub fn parse(slice: &[u8]) -> Result<Self> {
    if slice.len() < HEADER_SIZE {
      return Err(Error::InvalidModel {
        reason: "model shorter than 80-byte header",
      });
    }
    if slice[0..4] != MAGIC {
      return Err(Error::InvalidModel {
        reason: "bad magic header",
      });
    }
    if slice[4] != FORMAT_VERSION {
      return Err(Error::InvalidModel {
        reason: "unsupported model format version",
      });
    }
    let lang = Lang::from_id(slice[5]).ok_or(Error::InvalidModel {
      reason: "unknown language id",
    })?;
    let flag = slice[6];
    if (flag & !(FLAG_USE_TCC | FLAG_HAS_TRIE)) != 0
      || slice[46..48] != [0u8; 2]
      || slice[68..80] != [0u8; 12]
    {
      return Err(Error::InvalidModel {
        reason: "unsupported model flags or reserved bytes",
      });
    }
    let max_word_char = slice[7];
    if max_word_char as usize > MAX_WORD_CHAR {
      return Err(Error::InvalidModel {
        reason: "max_word_char exceeds limit",
      });
    }

    let bias = i16::from_le_bytes([slice[8], slice[9]]);
    let search_threshold = i16::from_le_bytes([slice[10], slice[11]]);
    let scale_x100 = u16::from_le_bytes([slice[12], slice[13]]);
    let dict_slot = u16::from_le_bytes([slice[14], slice[15]]);
    if dict_slot as usize != DICT_SLOT_COUNT {
      return Err(Error::InvalidModel {
        reason: "unexpected dict slot count",
      });
    }

    let mut dict_weight = [0i8; DICT_WEIGHT_LEN];
    for (dst, &byte) in dict_weight.iter_mut().zip(&slice[16..46]) {
      *dst = byte as i8;
    }

    let type_lut_len = u32::from_le_bytes([slice[48], slice[49], slice[50], slice[51]]);
    let trie_len = u32::from_le_bytes([slice[52], slice[53], slice[54], slice[55]]);
    let word_count = u32::from_le_bytes([slice[56], slice[57], slice[58], slice[59]]);
    let ngram_count = u32::from_le_bytes([slice[60], slice[61], slice[62], slice[63]]);
    let checksum = u32::from_le_bytes([slice[64], slice[65], slice[66], slice[67]]);
    if ((flag & FLAG_HAS_TRIE) != 0) != (trie_len > 0) {
      return Err(Error::InvalidModel {
        reason: "inconsistent trie flag",
      });
    }

    let total = (HEADER_SIZE as u64)
      .checked_add(u64::from(type_lut_len))
      .and_then(|v| v.checked_add(u64::from(trie_len)))
      .ok_or(Error::InvalidModel {
        reason: "section length overflow",
      })?;

    if total != slice.len() as u64 {
      return Err(Error::InvalidModel {
        reason: "model byte length mismatch",
      });
    }

    let expected_sum = compute_checksum(&slice[0..64], &slice[HEADER_SIZE..]);
    if checksum != expected_sum {
      return Err(Error::InvalidModel {
        reason: "checksum mismatch",
      });
    }

    Ok(Self {
      lang,
      flag,
      max_word_char,
      bias,
      search_threshold,
      scale_x100,
      dict_weight,
      type_lut_len,
      trie_len,
      word_count,
      ngram_count,
      checksum,
    })
  }
}

pub fn compute_checksum(header_prefix: &[u8], payload: &[u8]) -> u32 {
  hash32(header_prefix) ^ hash32(payload)
}

#[cfg(feature = "build")]
pub fn encode_header(header: &Header, payload: &[u8]) -> [u8; HEADER_SIZE] {
  let mut out = [0u8; HEADER_SIZE];
  out[0..4].copy_from_slice(&MAGIC);
  out[4] = FORMAT_VERSION;
  out[5] = header.lang.id();
  out[6] = header.flag;
  out[7] = header.max_word_char;
  out[8..10].copy_from_slice(&header.bias.to_le_bytes());
  out[10..12].copy_from_slice(&header.search_threshold.to_le_bytes());
  out[12..14].copy_from_slice(&header.scale_x100.to_le_bytes());
  out[14..16].copy_from_slice(&(DICT_SLOT_COUNT as u16).to_le_bytes());
  for (dst, &w) in out[16..46].iter_mut().zip(&header.dict_weight) {
    *dst = w as u8;
  }
  out[48..52].copy_from_slice(&header.type_lut_len.to_le_bytes());
  out[52..56].copy_from_slice(&header.trie_len.to_le_bytes());
  out[56..60].copy_from_slice(&header.word_count.to_le_bytes());
  out[60..64].copy_from_slice(&header.ngram_count.to_le_bytes());
  let sum = compute_checksum(&out[0..64], payload);
  out[64..68].copy_from_slice(&sum.to_le_bytes());
  out
}