mcut 0.1.0

Zero-copy, low-memory multilingual word segmenter using pointwise linear classification and minimal FST
Documentation
use core::{fmt, str::FromStr};

/// Cross-language cut granularity.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum CutMode {
  /// One best segmentation.
  #[default]
  Precise,
  /// All lexicon words at every position, overlapping allowed.
  Full,
  /// Precise tokens plus shorter subwords for search indexing.
  Search,
}

impl CutMode {
  /// All modes, in declaration order.
  pub const ALL: &'static [CutMode] = &[CutMode::Precise, CutMode::Full, CutMode::Search];

  /// Stable string form, useful for configuration and logging.
  pub const fn as_str(self) -> &'static str {
    match self {
      CutMode::Precise => "precise",
      CutMode::Full => "full",
      CutMode::Search => "search",
    }
  }
}

impl fmt::Display for CutMode {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str(self.as_str())
  }
}

impl FromStr for CutMode {
  type Err = ();

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    match s {
      "precise" => Ok(CutMode::Precise),
      "full" => Ok(CutMode::Full),
      "search" => Ok(CutMode::Search),
      _ => Err(()),
    }
  }
}

/// Cut options passed to [`crate::Cut`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CutOption {
  /// Segmentation granularity.
  pub mode: CutMode,
  /// Emit whitespace and punctuation runs.
  pub keep_separator: bool,
}

impl CutOption {
  /// Creates options with `mode` and `keep_separator = false`.
  pub const fn new(mode: CutMode) -> Self {
    Self {
      mode,
      keep_separator: false,
    }
  }

  /// Creates [`CutMode::Precise`] options.
  pub const fn precise() -> Self {
    Self::new(CutMode::Precise)
  }

  /// Creates [`CutMode::Full`] options.
  pub const fn full() -> Self {
    Self::new(CutMode::Full)
  }

  /// Creates [`CutMode::Search`] options.
  pub const fn search() -> Self {
    Self::new(CutMode::Search)
  }

  /// Enables whitespace and punctuation token emission.
  pub const fn with_separator(mut self) -> Self {
    self.keep_separator = true;
    self
  }
}

impl From<CutMode> for CutOption {
  fn from(mode: CutMode) -> Self {
    Self::new(mode)
  }
}