use std::collections::BTreeSet; use unicode_normalization::UnicodeNormalization; pub(crate) fn normalize(text: &str) -> String { text.nfkc() .flat_map(char::to_lowercase) .collect::() .split_whitespace() .collect::>() .join(" ") } fn han(c: char) -> bool { matches!(c as u32, 0x3400..=0x4dbf | 0x4e00..=0x9fff | 0xf900..=0xfaff | 0x20000..=0x323af) } // Keep individual Han characters in the index for one-character queries; // for longer Han runs query only the more selective overlapping bigrams. fn tokens(text: &str, indexing: bool) -> Vec { let mut output = Vec::new(); let mut chars = text.chars().peekable(); while let Some(c) = chars.next() { if han(c) { let mut previous = c; let mut single = true; if indexing { output.push(c.to_string()); } while let Some(next) = chars.next_if(|&n| han(n)) { output.push(format!("{previous}{next}")); if indexing { output.push(next.to_string()); } single = false; previous = next; } if single && !indexing { output.push(c.to_string()); } } else if c.is_alphanumeric() || c == '_' { let mut word = String::from(c); while let Some(next) = chars.next_if(|&n| !han(n) && (n.is_alphanumeric() || n == '_')) { word.push(next); } output.push(word); } } output } pub(crate) fn index_tokens(text: &str) -> Vec { tokens(text, true) } pub(crate) fn query_terms(text: &str) -> BTreeSet { tokens(text, false).into_iter().collect() }