use std::ops::Range;
use rust_stemmers::{Algorithm, Stemmer};
use unicode_normalization::UnicodeNormalization;
use unicode_normalization::char::is_combining_mark;
use unicode_segmentation::UnicodeSegmentation;
pub(crate) const VERSION: u32 = 1;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Word {
pub(crate) text: String,
pub(crate) stem: Option<String>,
pub(crate) at: Range<usize>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Script {
Latin,
Cyrillic,
Unspaced,
Other,
}
fn script(c: char) -> Script {
match c as u32 {
0x0041..=0x024F | 0x1E00..=0x1EFF => Script::Latin,
0x0400..=0x052F | 0x1C80..=0x1C8F | 0x2DE0..=0x2DFF | 0xA640..=0xA69F => Script::Cyrillic,
0x0E00..=0x0EFF | 0x1000..=0x109F | 0x1780..=0x17FF | 0x3040..=0x30FF | 0x31F0..=0x31FF
| 0x3400..=0x4DBF | 0x4E00..=0x9FFF
| 0xF900..=0xFAFF
| 0x20000..=0x3134F => Script::Unspaced,
_ => Script::Other,
}
}
pub(crate) fn words(text: &str) -> Vec<Word> {
words_of(&normalize(text))
}
pub(crate) fn words_of(normal: &str) -> Vec<Word> {
let mut words = Vec::new();
for at in cut(normal) {
let text: String = normal[at.clone()].chars().filter(|c| is_letter(*c)).collect();
words.push(Word { stem: stem(&text), text, at });
}
words
}
pub(crate) fn is_letter(c: char) -> bool {
c.is_alphanumeric() || is_combining_mark(c)
}
pub(crate) fn stem(word: &str) -> Option<String> {
let first = word.chars().next()?;
if script(first) != Script::Cyrillic {
return None;
}
let stem = Stemmer::create(Algorithm::Russian).stem(word).into_owned();
(stem != word).then_some(stem)
}
pub(crate) fn normalize(text: &str) -> String {
let mut out = String::with_capacity(text.len());
Folding::new().fold(text, &mut out);
out
}
struct Folding {
base: Script,
greek: bool,
}
impl Folding {
fn new() -> Folding {
Folding { base: Script::Other, greek: false }
}
fn fold(&mut self, text: &str, out: &mut String) {
for c in text.nfkc().flat_map(char::to_lowercase) {
if is_combining_mark(c) {
if !(matches!(self.base, Script::Latin | Script::Cyrillic) || self.greek) {
out.push(c);
}
continue;
}
self.base = script(c);
self.greek = (0x0370..=0x03FF).contains(&(c as u32));
match c {
'ё' => out.push('е'),
c if self.base == Script::Latin && !c.is_ascii() => {
out.extend(std::iter::once(c).nfd().filter(|c| !is_combining_mark(*c)));
}
c => out.push(c),
}
}
}
}
pub(crate) struct Mapped {
pub(crate) normal: String,
starts: Vec<(usize, usize)>,
}
pub(crate) fn mapped(text: &str) -> Option<Mapped> {
let mut folding = Folding::new();
let mut normal = String::with_capacity(text.len());
let mut starts = Vec::new();
for (at, grapheme) in text.grapheme_indices(true) {
starts.push((at, normal.len()));
folding.fold(grapheme, &mut normal);
}
starts.push((text.len(), normal.len()));
(normal == normalize(text)).then_some(Mapped { normal, starts })
}
impl Mapped {
pub(crate) fn original(&self, normal: Range<usize>) -> Range<usize> {
let holding = |at: usize| self.starts.partition_point(|(_, start)| *start <= at).saturating_sub(1);
let first = holding(normal.start);
let last = holding(normal.end.saturating_sub(1).max(normal.start));
self.starts[first].0..self.starts[last + 1].0
}
}
fn cut(text: &str) -> Vec<Range<usize>> {
let mut found = Vec::new();
let (mut spaced_from, mut run_from) = (0, None);
for (at, c) in text.char_indices() {
let unspaced = script(c) == Script::Unspaced && (c.is_alphanumeric() || is_combining_mark(c));
match (unspaced, run_from) {
(true, None) => {
spaced(text, spaced_from..at, &mut found);
run_from = Some(at);
}
(false, Some(from)) => {
pairs(text, from..at, &mut found);
(spaced_from, run_from) = (at, None);
}
_ => {}
}
}
match run_from {
Some(from) => pairs(text, from..text.len(), &mut found),
None => spaced(text, spaced_from..text.len(), &mut found),
}
found
}
fn spaced(text: &str, within: Range<usize>, found: &mut Vec<Range<usize>>) {
for (at, word) in text[within.clone()].unicode_word_indices() {
if word.chars().any(|c| c.is_alphanumeric()) {
found.push(within.start + at..within.start + at + word.len());
}
}
}
fn pairs(text: &str, within: Range<usize>, found: &mut Vec<Range<usize>>) {
let starts: Vec<usize> = text[within.clone()].grapheme_indices(true).map(|(at, _)| within.start + at).collect();
if starts.len() == 1 {
found.push(within);
return;
}
for (pair, start) in starts.iter().enumerate().take(starts.len().saturating_sub(1)) {
let end = starts.get(pair + 2).copied().unwrap_or(within.end);
found.push(*start..end);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn texts(text: &str) -> Vec<String> {
words(text).into_iter().map(|word| word.text).collect()
}
#[test]
fn stress_marks_and_yo_go_and_short_i_stays() {
assert_eq!(texts("Кари́бский ЁЖ йод"), ["карибский", "еж", "йод"]);
}
#[test]
fn unspaced_scripts_become_pairs_beside_spaced_words() {
assert_eq!(texts("café 世界和平 abc"), ["cafe", "世界", "界和", "和平", "abc"]);
assert_eq!(texts("東京タワー"), ["東京", "京タ", "タワ", "ワー"]);
assert_eq!(texts("สวัสดี"), ["สวั", "วัส", "สดี"]);
assert_eq!(texts("中"), ["中"]);
}
#[test]
fn only_cyrillic_words_are_stemmed_and_only_where_the_stem_differs() {
let stems: Vec<_> = words("кошки running кот").into_iter().map(|word| word.stem).collect();
assert_eq!(stems, [Some("кошк".to_owned()), None, None]);
}
#[test]
fn latin_accents_fold_and_a_word_keeps_only_its_letters_and_digits() {
assert_eq!(texts("Schön, Ångström! can't 4K"), ["schon", "angstrom", "cant", "4k"]);
}
#[test]
fn a_word_lies_where_its_place_in_the_normalized_text_says() {
let normal = normalize("Helo, Wörld 世界");
let places: Vec<&str> = words_of(&normal).iter().map(|word| &normal[word.at.clone()]).collect();
assert_eq!(places, ["helo", "world", "世界"]);
}
fn written(text: &str) -> Vec<&str> {
let mapped = mapped(text).unwrap();
words_of(&mapped.normal).into_iter().map(|word| &text[mapped.original(word.at)]).collect()
}
#[test]
fn a_word_reads_back_as_the_text_given_wrote_it_where_normalizing_changed_its_length() {
let mapped = mapped("finé").unwrap();
assert_eq!((mapped.normal.as_str(), mapped.original(1..4)), ("fine", 0..6), "the doc comment's example");
assert_eq!(written("Кари́бский İstanbul ЁЖ"), ["Кари́бский", "İstanbul", "ЁЖ"]);
assert_eq!(written("cafe\u{301}, TOKYO ffix"), ["cafe\u{301}", "TOKYO", "ffix"]);
assert_eq!(written("и\u{306}од"), ["и\u{306}од"]);
assert_eq!(written("can't 世界和平"), ["can't", "世界", "界和", "和平"]);
}
const TRICKY: &[&str] = &[
"a", "Z", "e", "и", "к", "ω", " ", ",", "'", "-", "\n", "\r", "4", "\u{301}", "\u{306}", "\u{307}", "\u{308}",
"\u{200d}", "fi", "ffi", "st", "İ", "ё", "Ё", "A", "b", "é", "Å", "\u{212b}", "Dž", "ẞ", "ß", "ά", "\u{2126}",
"ʼn", "ǰ", "½", "㎏", "Ⅻ", "\u{1100}", "\u{1161}", "\u{11a8}", "가", "世", "界", "タ", "ส", "\u{e31}", "क",
"\u{94d}", "ष", "\u{b47}", "\u{b3e}", "👍", "🏽", "🇷", "🇺",
];
#[test]
fn random_text_folds_a_grapheme_at_a_time_as_it_folds_whole_and_each_word_reads_back() {
let mut random = crate::search::fixture::Random::new(45);
for round in 0..20_000 {
let length = random.below(16);
let text: String = (0..length).map(|_| TRICKY[random.below(TRICKY.len() as u64) as usize]).collect();
let mapped = mapped(&text).unwrap_or_else(|| panic!("round {round}: {text:?} folds otherwise apart"));
let mut start = 0;
for word in words_of(&mapped.normal) {
let given = mapped.original(word.at.clone());
assert!(given.start >= start, "round {round}: {text:?}: a word starts before the one before it");
let read = &text[given.clone()];
assert!(normalize(read).contains(&mapped.normal[word.at.clone()]), "round {round}: {text:?} {read:?}");
start = given.start;
}
}
}
}