lexf 0.1.0

Zero-unsafe multilingual morphological expander and query normalizer for search indexing
Documentation
//! Pure algorithmic multilingual stemmers and shared suffix helpers.

pub(crate) mod ar;
pub(crate) mod cjk;
pub(crate) mod el;
mod en;
mod euro;
pub(crate) mod ru;

use crate::lang::LangHint;

/// Stems a diacritic-folded Latin word: Snowball-aligned rules for supported
/// European languages, English Porter2 plus lemma heuristics otherwise.
pub(crate) fn latin(
  lang: LangHint,
  word: &str,
  aux: &mut String,
  stem: &mut String,
  byte: &mut Vec<u8>,
  out: &mut impl FnMut(&str),
) {
  if euro::stem(lang, word, stem) {
    out(stem);
  } else {
    en::emit(word, aux, byte, out);
  }
}

/// Returns `true` if `s` has at least `n` chars, scanning at most `n` of them.
#[inline]
pub(crate) fn has_char_n(s: &str, n: usize) -> bool {
  n == 0 || s.chars().nth(n - 1).is_some()
}

/// Strips the first suffix in `list` lying entirely at or after byte `min`.
pub(crate) fn strip_in(buf: &mut String, min: usize, list: &[&str]) -> bool {
  let Some(len) = list
    .iter()
    .find(|suf| buf.len() >= min + suf.len() && buf.ends_with(*suf))
    .map(|suf| buf.len() - suf.len())
  else {
    return false;
  };
  buf.truncate(len);
  true
}

/// Borrows `word` minus the longest matching suffix in `list` (ordered longest-first),
/// provided the remaining stem has at least `min` chars.
pub(crate) fn strip_keep<'a>(word: &'a str, list: &[&str], min: usize) -> Option<&'a str> {
  list
    .iter()
    .find_map(|suf| word.strip_suffix(suf))
    .filter(|stem| has_char_n(stem, min))
}

/// Snowball region start: the byte after the first non-vowel that follows a vowel at or after `start`.
pub(crate) fn next_region(word: &str, start: usize, is_vowel: impl Fn(char) -> bool) -> usize {
  let mut prev_vowel = false;
  word
    .get(start..)
    .and_then(|tail| {
      tail.char_indices().find_map(|(i, ch)| {
        let vowel = is_vowel(ch);
        let hit = prev_vowel && !vowel;
        prev_vowel = vowel;
        hit.then(|| start + i + ch.len_utf8())
      })
    })
    .unwrap_or(word.len())
}