mcut 0.1.0

Zero-copy, low-memory multilingual word segmenter using pointwise linear classification and minimal FST
Documentation
use crate::error::{Error, Result};

pub const TYPE_LUT_COUNT: usize = 4096;
pub const TYPE_LUT_BYTE_LEN: usize = TYPE_LUT_COUNT * 2;

/// Flat 4,096-entry lookup table for 4-character-type context windows.
#[derive(Clone, Copy, Debug)]
pub struct TypeLut<'a> {
  byte: &'a [u8],
}

impl<'a> TypeLut<'a> {
  pub const fn empty() -> Self {
    Self { byte: &[] }
  }

  pub fn from_slice(byte: &'a [u8]) -> Result<Self> {
    if !byte.is_empty() && byte.len() != TYPE_LUT_BYTE_LEN {
      return Err(Error::InvalidModel {
        reason: "invalid type lut length",
      });
    }
    Ok(Self { byte })
  }

  pub const fn byte_len(&self) -> usize {
    self.byte.len()
  }

  #[inline]
  pub fn get(&self, idx: usize) -> i16 {
    let (chunk_li, _) = self.byte.as_chunks::<2>();
    chunk_li
      .get(idx & (TYPE_LUT_COUNT - 1))
      .map_or(0, |pair| i16::from_le_bytes(*pair))
  }
}

#[cfg(feature = "build")]
pub fn encode_type_lut(table: &[i16; TYPE_LUT_COUNT]) -> Vec<u8> {
  if table.iter().all(|&v| v == 0) {
    return Vec::new();
  }
  let mut out = Vec::with_capacity(TYPE_LUT_BYTE_LEN);
  for &v in table {
    out.extend_from_slice(&v.to_le_bytes());
  }
  out
}