mcut 0.1.0

Zero-copy, low-memory multilingual word segmenter using pointwise linear classification and minimal FST
Documentation
pub mod bmp;
pub mod dict;
pub mod fst;
pub mod header;
pub mod lut;
pub mod trie;

use core::fmt;

pub use dict::{OwnedUserDict, UserDict};
use header::{DICT_WEIGHT_LEN, HEADER_SIZE, Header};
#[cfg(feature = "build")]
use header::{FLAG_HAS_TRIE, FLAG_USE_TCC, encode_header};
use lut::TypeLut;
#[cfg(feature = "build")]
use lut::{TYPE_LUT_COUNT, encode_type_lut};
use trie::FusedTrie;
#[cfg(feature = "build")]
use trie::{NgramKey, build_fused_trie};

#[cfg(feature = "build")]
use crate::error::Error;
use crate::{error::Result, i18n::Lang};

/// Zero-copy view over a `.mcut` model slice.
#[derive(Clone, Copy, Debug)]
pub struct Model<'a> {
  raw: &'a [u8],
  header: Header,
  type_lut: TypeLut<'a>,
  trie: FusedTrie<'a>,
}

/// Owned `.mcut` model backed by a heap byte buffer.
#[derive(Clone, Debug)]
pub struct OwnedModel {
  byte_li: Vec<u8>,
}

/// Size and section statistics for a loaded [`Model`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ModelStat {
  /// Target language.
  pub lang: Lang,
  /// Total byte size of the `.mcut` buffer.
  pub total_byte: usize,
  /// Bytes in the 4-type context LUT.
  pub type_lut_byte: usize,
  /// Bytes in the zero-copy fused hash trie.
  pub trie_byte: usize,
  /// Distinct indexed characters in the fused trie.
  pub char_count: u32,
  /// Slot count in the fused trie hash table.
  pub trie_slot: u32,
  /// Distinct words stored in the fused trie.
  pub word_count: u32,
  /// N-gram weight entries encoded into the fused trie.
  pub ngram_count: u32,
  /// Quantization scale multiplied by 100.
  pub scale_x100: u16,
  /// Whether Thai Character Cluster locking is enabled.
  pub use_tcc: bool,
}

impl<'a> Model<'a> {
  /// Creates an empty fallback model for `lang` with zero memory footprint.
  pub const fn empty(lang: Lang) -> Self {
    let use_tcc = matches!(lang, Lang::Th);
    Self {
      raw: &[],
      header: Header::empty(lang, use_tcc),
      type_lut: TypeLut::empty(),
      trie: FusedTrie::empty(),
    }
  }

  /// Parses and validates a zero-copy `.mcut` binary slice.
  pub fn from_slice(slice: &'a [u8]) -> Result<Self> {
    let header = Header::parse(slice)?;

    let type_start = HEADER_SIZE;
    let trie_start = type_start + header.type_lut_len as usize;

    let type_lut = TypeLut::from_slice(&slice[type_start..trie_start])?;
    let trie = FusedTrie::from_slice(&slice[trie_start..])?;

    Ok(Self {
      raw: slice,
      header,
      type_lut,
      trie,
    })
  }

  /// Underlying byte slice, or `&[]` for [`Model::empty`].
  pub const fn as_slice(&self) -> &'a [u8] {
    self.raw
  }

  /// Language stored in the model header.
  pub const fn lang(&self) -> Lang {
    self.header.lang
  }

  /// Summary statistics of every zero-copy section.
  pub const fn stat(&self) -> ModelStat {
    ModelStat {
      lang: self.header.lang,
      total_byte: self.raw.len(),
      type_lut_byte: self.type_lut.byte_len(),
      trie_byte: self.trie.byte_len(),
      char_count: self.trie.char_count(),
      trie_slot: self.trie.slot_count(),
      word_count: self.header.word_count,
      ngram_count: self.header.ngram_count,
      scale_x100: self.header.scale_x100,
      use_tcc: self.header.use_tcc(),
    }
  }

  /// Byte footprint of the backing slice.
  pub const fn memory_usage(&self) -> usize {
    self.raw.len()
  }

  #[inline]
  pub(crate) const fn is_empty(&self) -> bool {
    self.raw.is_empty()
  }

  #[inline]
  pub(crate) const fn bias(&self) -> i16 {
    self.header.bias
  }

  #[inline]
  pub(crate) const fn search_threshold(&self) -> i16 {
    self.header.search_threshold
  }

  #[inline]
  pub(crate) const fn use_tcc(&self) -> bool {
    self.header.use_tcc()
  }

  #[inline]
  pub(crate) const fn max_word_char(&self) -> usize {
    self.header.max_word_char as usize
  }

  #[inline]
  pub(crate) const fn dict_weight(&self) -> &[i8; DICT_WEIGHT_LEN] {
    &self.header.dict_weight
  }

  #[inline]
  pub(crate) const fn type_lut(&self) -> &TypeLut<'a> {
    &self.type_lut
  }

  #[inline]
  pub(crate) const fn trie(&self) -> &FusedTrie<'a> {
    &self.trie
  }
}

impl OwnedModel {
  /// Validates and wraps an owned `.mcut` byte buffer.
  pub fn from_vec(byte_li: Vec<u8>) -> Result<Self> {
    let _ = Model::from_slice(&byte_li)?;
    Ok(Self { byte_li })
  }

  /// Borrows a validated zero-copy [`Model`] view.
  pub fn as_model(&self) -> Model<'_> {
    Model::from_slice(&self.byte_li).expect("owned model already validated")
  }

  /// Underlying byte slice.
  pub fn as_slice(&self) -> &[u8] {
    &self.byte_li
  }

  /// Heap capacity used by the owned buffer.
  pub fn memory_usage(&self) -> usize {
    self.byte_li.capacity()
  }
}

impl fmt::Display for ModelStat {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(
      f,
      "lang={} total={}B (type_lut={}B, trie={}B/{} chars/{} slots, words={}, ngrams={}, tcc={})",
      self.lang,
      self.total_byte,
      self.type_lut_byte,
      self.trie_byte,
      self.char_count,
      self.trie_slot,
      self.word_count,
      self.ngram_count,
      self.use_tcc,
    )
  }
}

#[cfg(feature = "build")]
#[derive(Clone, Debug)]
pub struct ModelDraft {
  pub lang: Lang,
  pub use_tcc: bool,
  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: [i16; TYPE_LUT_COUNT],
  pub uni_li: Vec<(char, [i8; 4])>,
  pub ngram_li: Vec<(NgramKey, [i8; 3])>,
  pub word_li: Vec<(String, u8)>,
}

#[cfg(feature = "build")]
pub fn encode_model(draft: &ModelDraft) -> Result<Vec<u8>> {
  if draft.max_word_char as usize > header::MAX_WORD_CHAR {
    return Err(Error::ModelBuild {
      reason: "max_word_char exceeds 32",
    });
  }

  let type_buf = encode_type_lut(&draft.type_lut);
  let trie_build = build_fused_trie(draft.lang, &draft.uni_li, &draft.ngram_li, &draft.word_li)?;

  let mut payload = Vec::with_capacity(type_buf.len() + trie_build.byte_li.len());
  payload.extend_from_slice(&type_buf);
  payload.extend_from_slice(&trie_build.byte_li);

  let mut flag = 0u8;
  if draft.use_tcc {
    flag |= FLAG_USE_TCC;
  }
  if !trie_build.byte_li.is_empty() {
    flag |= FLAG_HAS_TRIE;
  }

  let header = Header {
    lang: draft.lang,
    flag,
    max_word_char: draft.max_word_char,
    bias: draft.bias,
    search_threshold: draft.search_threshold,
    scale_x100: draft.scale_x100,
    dict_weight: draft.dict_weight,
    type_lut_len: u32::try_from(type_buf.len()).map_err(|_| Error::ModelBuild {
      reason: "type lut exceeds u32",
    })?,
    trie_len: u32::try_from(trie_build.byte_li.len()).map_err(|_| Error::ModelBuild {
      reason: "trie exceeds u32",
    })?,
    word_count: trie_build.word_count,
    ngram_count: trie_build.ngram_count,
    checksum: 0,
  };

  let header_buf = encode_header(&header, &payload);
  let mut out = Vec::with_capacity(HEADER_SIZE + payload.len());
  out.extend_from_slice(&header_buf);
  out.extend_from_slice(&payload);
  Ok(out)
}