mcut 0.1.1

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

use crate::script;

macro_rules! define_lang_model {
  ($mod_name:ident, $lg_feat:literal, $lg_crate:ident, $sm_feat:literal, $sm_crate:ident, $lang:ident) => {
    pub(crate) mod $mod_name {
      use std::sync::LazyLock;

      #[cfg(all(feature = $lg_feat, feature = $sm_feat))]
      use $sm_crate as _;

      use crate::format::Model;
      #[cfg(not(any(feature = $lg_feat, feature = $sm_feat)))]
      use crate::i18n::Lang;

      static DEFAULT_MODEL: LazyLock<Model<'static>> = LazyLock::new(|| {
        #[cfg(feature = $lg_feat)]
        {
          Model::from_slice($lg_crate::MODEL).expect(concat!(
            "embedded ",
            $lg_feat,
            " model is valid"
          ))
        }
        #[cfg(all(not(feature = $lg_feat), feature = $sm_feat))]
        {
          Model::from_slice($sm_crate::MODEL).expect(concat!(
            "embedded ",
            $sm_feat,
            " model is valid"
          ))
        }
        #[cfg(not(any(feature = $lg_feat, feature = $sm_feat)))]
        {
          Model::empty(Lang::$lang)
        }
      });

      pub(crate) fn default_model() -> &'static Model<'static> {
        &DEFAULT_MODEL
      }
    }
  };
}

define_lang_model!(zh, "zh", mcut_zh, "zh-sm", mcut_zh_sm, Zh);
define_lang_model!(ja, "ja", mcut_ja, "ja-sm", mcut_ja_sm, Ja);
define_lang_model!(th, "th", mcut_th, "th-sm", mcut_th_sm, Th);

macro_rules! define_lang {
  ($( $variant:ident => $id:literal => $code:literal ),+ $(,)?) => {
    /// Built-in language identifier encoded in `.mcut` headers and returned by [`detect_lang`].
    #[repr(u8)]
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub enum Lang {
      $(
        #[doc = concat!("`", $code, "`")]
        $variant = $id,
      )+
    }

    impl Lang {
      /// Number of built-in languages.
      pub const COUNT: usize = [$(Lang::$variant),+].len();

      /// All built-in languages.
      pub const ALL: &'static [Lang] = &[$(Lang::$variant),+];

      /// Stable numeric identifier stored in `.mcut` headers.
      pub const fn id(self) -> u8 {
        self as u8
      }

      /// Array index matching [`Lang::COUNT`].
      pub const fn index(self) -> usize {
        self as usize
      }

      /// Parses a numeric identifier from a `.mcut` header.
      pub const fn from_id(id: u8) -> Option<Self> {
        match id {
          $($id => Some(Lang::$variant),)+
          _ => None,
        }
      }

      /// Stable language code.
      pub const fn code(self) -> &'static str {
        match self {
          $(Lang::$variant => $code),+
        }
      }

      /// Parses a stable language code.
      pub fn from_code(code: &str) -> Option<Self> {
        match code {
          $($code => Some(Lang::$variant),)+
          _ => None,
        }
      }
    }

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

define_lang! {
  Zh => 0 => "zh",
  Ja => 1 => "ja",
  Ko => 2 => "ko",
  En => 3 => "en",
  Th => 4 => "th",
  Ru => 5 => "ru",
  Ar => 6 => "ar",
}

/// Detects the dominant language of `text` from its scripts.
///
/// Kana and Simplified-Chinese Han cues disambiguate Japanese and Chinese. Hangul,
/// Thai, Cyrillic and Arabic are detected by their scripts. Everything else
/// falls back to English.
pub fn detect_lang(text: &str) -> Lang {
  script::detect_lang(text)
}