Cotton code
84 lines · 2.9 KB · RustRaw
//! FIND — words found in a text, any case, accents ignored: the matches'//! UTF-16 ranges for find-in-a-note, and the yes-or-no the list's search//! asks of each note.use serde::{Deserialize, Serialize};use super::Offsets;#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pub struct Match {    pub start: u32,    pub end: u32,}/// One character as it is compared: lowercased, its accent taken off.pub fn fold_char(c: char) -> char {    let lower = c.to_lowercase().next().unwrap_or(c);    match lower {        'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' | 'ā' | 'ă' | 'ą' => 'a',        'ç' | 'ć' | 'ĉ' | 'ċ' | 'č' => 'c',        'ď' | 'đ' => 'd',        'è' | 'é' | 'ê' | 'ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => 'e',        'ĝ' | 'ğ' | 'ġ' | 'ģ' => 'g',        'ĥ' | 'ħ' => 'h',        'ì' | 'í' | 'î' | 'ï' | 'ĩ' | 'ī' | 'ĭ' | 'į' | 'ı' => 'i',        'ĵ' => 'j',        'ķ' => 'k',        'ĺ' | 'ļ' | 'ľ' | 'ŀ' | 'ł' => 'l',        'ñ' | 'ń' | 'ņ' | 'ň' => 'n',        'ò' | 'ó' | 'ô' | 'õ' | 'ö' | 'ø' | 'ō' | 'ŏ' | 'ő' => 'o',        'ŕ' | 'ŗ' | 'ř' => 'r',        'ś' | 'ŝ' | 'ş' | 'š' | 'ș' => 's',        'ţ' | 'ť' | 'ŧ' | 'ț' => 't',        'ù' | 'ú' | 'û' | 'ü' | 'ũ' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => 'u',        'ŵ' => 'w',        'ý' | 'ÿ' | 'ŷ' => 'y',        'ź' | 'ż' | 'ž' => 'z',        '’' | '‘' => '\'',        '“' | '”' => '"',        other => other,    }}/// A text folded for comparing: each character's fold and its byte range.fn folded(text: &str) -> Vec<(char, usize, usize)> {    text.char_indices().map(|(at, c)| (fold_char(c), at, at + c.len_utf8())).collect()}/// `words` folded, spaces collapsed, quotes taken off a phrase.fn wanted(words: &str) -> Vec<char> {    let words = words.trim().trim_matches('"').trim();    words.split_whitespace().collect::<Vec<_>>().join(" ").chars().map(fold_char).collect()}/// Every place `words` stands in `text`, in order, never overlapping.pub fn find(text: &str, words: &str) -> Vec<Match> {    let want = wanted(words);    if want.is_empty() {        return Vec::new();    }    let have = folded(text);    let offsets = Offsets::new(text);    let mut out = Vec::new();    let mut k = 0;    while k + want.len() <= have.len() {        if have[k..k + want.len()].iter().zip(&want).all(|((c, _, _), w)| c == w) {            out.push(Match { start: offsets.u16(have[k].1), end: offsets.u16(have[k + want.len() - 1].2) });            k += want.len();        } else {            k += 1;        }    }    out}/// Does `text` hold `words` (any case, accents ignored)?pub fn holds(text: &str, words: &str) -> bool {    let want = wanted(words);    if want.is_empty() {        return true;    }    let have: Vec<char> = text.chars().map(fold_char).collect();    have.windows(want.len()).any(|window| window == want.as_slice())}