lexf 0.1.0

Zero-unsafe multilingual morphological expander and query normalizer for search indexing
Documentation
//! Numeric token variants: thousands-separator removal and trailing-zero trimming.

/// Digits per thousands group.
const GROUP_LEN: usize = 3;

/// Emits `1000.50` and `1000.5` for `1,000.50`; the surface itself is emitted by the caller.
pub(crate) fn emit(surface: &str, plain: &mut String, out: &mut impl FnMut(&str)) {
  let base = if strip_group(surface, plain) {
    out(plain);
    plain.as_str()
  } else {
    surface
  };
  out(trim_decimal(base));
}

/// Writes `num` without `,` when the integer part has valid `1..=3` + `,ddd`+ grouping
/// and any fractional part is pure ASCII digits.
///
/// Leaves decimal-comma numbers (`3,14`) and malformed strings (`1,000.50,00`, `1234,567`) untouched.
fn strip_group(num: &str, out: &mut String) -> bool {
  let (int, frac) = num
    .split_once('.')
    .map_or((num, None), |(i, f)| (i, Some(f)));
  if frac.is_some_and(|f| !f.bytes().all(|b| b.is_ascii_digit())) {
    return false;
  }
  let Some((head, tail)) = int.split_once(',') else {
    return false;
  };
  let head_num = head.strip_prefix(['+', '-']).unwrap_or(head);
  if !(1..=GROUP_LEN).contains(&head_num.len())
    || head_num.starts_with('0')
    || !head_num.bytes().all(|b| b.is_ascii_digit())
    || !tail
      .split(',')
      .all(|g| g.len() == GROUP_LEN && g.bytes().all(|b| b.is_ascii_digit()))
  {
    return false;
  }
  out.clear();
  for part in num.split(',') {
    out.push_str(part);
  }
  true
}

/// Trims trailing fractional zeros (`1000.50` -> `1000.5`, `10.0` -> `10`) of a
/// single-dot numeric string; non-numeric punctuation (`3.5/10`, `1.2.0`) is left as is.
fn trim_decimal(num: &str) -> &str {
  let Some((int, frac)) = num.split_once('.') else {
    return num;
  };
  let int_num = int.strip_prefix(['+', '-']).unwrap_or(int);
  if !int_num.bytes().all(|b| b.is_ascii_digit()) || !frac.bytes().all(|b| b.is_ascii_digit()) {
    return num;
  }
  let t = num.trim_end_matches('0');
  let t = t.strip_suffix('.').unwrap_or(t);
  let mag = t.strip_prefix(['+', '-']).unwrap_or(t);
  if mag.bytes().all(|b| b == b'0') {
    "0"
  } else {
    t
  }
}