use core::str;
type Rule = (&'static [u8], &'static [u8]);
const MIN_STEM_LEN: usize = 3;
const MIN_LEMMA_LEN: usize = 3;
const MIN_BASE_LEN: usize = 2;
const R1_PREFIX: &[&[u8]] = &[b"gener", b"commun", b"arsen"];
const STEP1B: &[&[u8]] = &[b"eedly", b"ingly", b"edly", b"eed", b"ing", b"ed"];
const STEP2: &[Rule] = &[
(b"ization", b"ize"),
(b"ational", b"ate"),
(b"fulness", b"ful"),
(b"ousness", b"ous"),
(b"iveness", b"ive"),
(b"tional", b"tion"),
(b"biliti", b"ble"),
(b"lessli", b"less"),
(b"entli", b"ent"),
(b"ation", b"ate"),
(b"alism", b"al"),
(b"aliti", b"al"),
(b"ousli", b"ous"),
(b"iviti", b"ive"),
(b"fulli", b"ful"),
(b"enci", b"ence"),
(b"anci", b"ance"),
(b"abli", b"able"),
(b"izer", b"ize"),
(b"ator", b"ate"),
(b"alli", b"al"),
(b"bli", b"ble"),
(b"ogi", b"og"),
(b"li", b""),
];
const STEP3: &[Rule] = &[
(b"ational", b"ate"),
(b"tional", b"tion"),
(b"alize", b"al"),
(b"icate", b"ic"),
(b"iciti", b"ic"),
(b"ative", b""),
(b"ical", b"ic"),
(b"ness", b""),
(b"ful", b""),
];
const STEP4: &[Rule] = &[
(b"ement", b""),
(b"ance", b""),
(b"ence", b""),
(b"able", b""),
(b"ible", b""),
(b"ment", b""),
(b"ant", b""),
(b"ent", b""),
(b"ism", b""),
(b"ate", b""),
(b"iti", b""),
(b"ous", b""),
(b"ive", b""),
(b"ize", b""),
(b"ion", b""),
(b"al", b""),
(b"er", b""),
(b"ic", b""),
];
fn exception(w: &[u8]) -> Option<&'static [u8]> {
match w {
b"skis" => Some(b"ski"),
b"skies" => Some(b"sky"),
b"dying" => Some(b"die"),
b"lying" => Some(b"lie"),
b"tying" => Some(b"tie"),
b"idly" => Some(b"idl"),
b"gently" => Some(b"gentl"),
b"ugly" => Some(b"ugli"),
b"early" => Some(b"earli"),
b"only" => Some(b"onli"),
b"singly" => Some(b"singl"),
b"sky" => Some(b"sky"),
b"news" => Some(b"news"),
b"howe" => Some(b"howe"),
b"atlas" => Some(b"atlas"),
b"cosmos" => Some(b"cosmos"),
b"bias" => Some(b"bias"),
b"andes" => Some(b"andes"),
_ => None,
}
}
fn is_invariant_1a(w: &[u8]) -> bool {
matches!(
w,
b"inning"
| b"outing"
| b"canning"
| b"herring"
| b"earring"
| b"proceed"
| b"exceed"
| b"succeed"
)
}
#[inline]
const fn is_vowel(b: u8) -> bool {
matches!(b, b'a' | b'e' | b'i' | b'o' | b'u' | b'y')
}
fn has_vowel(w: &[u8]) -> bool {
w.iter().any(|&b| is_vowel(b))
}
const fn is_double(b: u8) -> bool {
matches!(
b,
b'b' | b'd' | b'f' | b'g' | b'm' | b'n' | b'p' | b'r' | b't'
)
}
#[inline]
const fn ends_double(w: &[u8]) -> bool {
matches!(w, [.., a, b] if *a == *b && is_double(*b))
}
const fn is_li_end(b: u8) -> bool {
matches!(
b,
b'c' | b'd' | b'e' | b'g' | b'h' | b'k' | b'm' | b'n' | b'r' | b't'
)
}
fn ends_short(w: &[u8]) -> bool {
match *w {
[a, b] => is_vowel(a) && !is_vowel(b),
[.., a, b, c] => {
!is_vowel(a) && is_vowel(b) && !is_vowel(c) && !matches!(c, b'w' | b'x' | b'Y')
}
_ => false,
}
}
fn region(w: &[u8], start: usize) -> usize {
w.get(start..)
.and_then(|t| t.windows(2).position(|p| is_vowel(p[0]) && !is_vowel(p[1])))
.map_or(w.len(), |i| start + i + 2)
}
fn replace(w: &mut Vec<u8>, list: &[Rule], min: usize, ok: impl Fn(&[u8], &[u8]) -> bool) {
if let Some(&(suf, rep)) = list.iter().find(|(suf, _)| w.ends_with(suf)) {
let at = w.len() - suf.len();
if at >= min && ok(suf, &w[..at]) {
w.truncate(at);
w.extend_from_slice(rep);
}
}
}
fn porter2<'a>(word: &str, w: &'a mut Vec<u8>) -> &'a [u8] {
w.clear();
w.extend_from_slice(word.as_bytes());
if w.len() < MIN_STEM_LEN {
return w;
}
if let Some(rep) = exception(w) {
w.clear();
w.extend_from_slice(rep);
return w;
}
let mut prev_vowel = true;
for b in w.iter_mut() {
if *b == b'y' && prev_vowel {
*b = b'Y';
}
prev_vowel = is_vowel(*b);
}
run_step(w);
w.iter_mut().filter(|b| **b == b'Y').for_each(|b| *b = b'y');
w
}
fn run_step(w: &mut Vec<u8>) {
let r1 = R1_PREFIX
.iter()
.find(|p| w.starts_with(p))
.map_or_else(|| region(w, 0), |p| p.len());
let r2 = region(w, r1);
if let Some(suf) = [b"'s'".as_slice(), b"'s", b"'"]
.into_iter()
.find(|s| w.ends_with(s))
{
w.truncate(w.len() - suf.len());
}
if w.ends_with(b"sses") {
w.truncate(w.len() - 2);
} else if w.ends_with(b"ied") || w.ends_with(b"ies") {
w.truncate(w.len() - if w.len() > 4 { 2 } else { 1 });
} else if !(w.ends_with(b"us") || w.ends_with(b"ss"))
&& w.ends_with(b"s")
&& has_vowel(&w[..w.len().saturating_sub(2)])
{
w.pop();
}
if is_invariant_1a(w) {
return;
}
if let Some(&suf) = STEP1B.iter().find(|s| w.ends_with(s)) {
let at = w.len() - suf.len();
if suf.starts_with(b"eed") {
if at >= r1 {
w.truncate(at + 2);
}
} else if has_vowel(&w[..at]) {
w.truncate(at);
if w.ends_with(b"at") || w.ends_with(b"bl") || w.ends_with(b"iz") {
w.push(b'e');
} else if ends_double(w) {
w.pop();
} else if w.len() <= r1 && ends_short(w) {
w.push(b'e');
}
}
}
if let [_, .., p, last @ (b'y' | b'Y')] = w.as_mut_slice()
&& !is_vowel(*p)
{
*last = b'i';
}
replace(w, STEP2, r1, |suf, stem| match suf {
b"ogi" => stem.last() == Some(&b'l'),
b"li" => stem.last().is_some_and(|&b| is_li_end(b)),
_ => true,
});
replace(w, STEP3, r1, |suf, stem| {
suf != b"ative" || stem.len() >= r2
});
replace(w, STEP4, r2, |suf, stem| {
suf != b"ion" || matches!(stem.last(), Some(b's' | b't'))
});
if let Some(stem) = w.strip_suffix(b"e") {
if w.len() > r2 || (w.len() > r1 && !ends_short(stem)) {
w.pop();
}
} else if w.ends_with(b"ll") && w.len() > r2 {
w.pop();
}
}
pub(super) fn emit(token: &str, aux: &mut String, byte: &mut Vec<u8>, out: &mut impl FnMut(&str)) {
if !token.is_ascii() {
return;
}
let core = token.trim_start_matches('\'');
if core.len() != token.len() && core.len() >= MIN_BASE_LEN {
out(core);
}
let token = core;
if token.len() < MIN_STEM_LEN {
return;
}
let raw = token.as_bytes();
if let Some(rep) = exception(raw) {
if let Ok(stem) = str::from_utf8(rep) {
out(stem);
}
return;
}
if is_invariant_1a(raw) {
return;
}
if let Some(base) = token
.strip_suffix("'s")
.or_else(|| token.strip_suffix('\''))
{
if base.len() >= MIN_BASE_LEN {
out(base);
}
} else if token.contains('\'') {
aux.clear();
for part in token.split('\'') {
aux.push_str(part);
}
if aux.len() >= MIN_BASE_LEN {
out(aux);
}
}
if let Some(stem) = token
.strip_suffix("ing")
.or_else(|| token.strip_suffix("ed").filter(|s| !s.ends_with('e')))
&& stem.len() >= MIN_LEMMA_LEN
&& has_vowel(stem.as_bytes())
{
if ends_double(stem.as_bytes()) {
out(&stem[..stem.len() - 1]);
} else {
out(stem);
}
}
if let Some(stem) = token
.strip_suffix("ies")
.or_else(|| token.strip_suffix("ied"))
&& stem.len() >= MIN_BASE_LEN
{
aux.clear();
aux.push_str(stem);
aux.push('y');
out(aux);
}
if let Some(stem) = token.strip_suffix("es")
&& stem.len() >= MIN_LEMMA_LEN
&& let [.., p, last] = *stem.as_bytes()
{
if matches!(
(p, last),
(_, b'x' | b'z') | (b's' | b'u', b's') | (b'c' | b's', b'h')
) {
out(stem);
} else if !is_vowel(last) {
out(&token[..token.len() - 1]);
}
}
if let Ok(stem) = str::from_utf8(porter2(token, byte)) {
out(stem);
}
}