Cotton code
135 lines · 4.8 KB · RustRaw
//! Chat's search: what a typed search matches, where a match stands in a//! message's words, and the short line a result shows (chat-search, 21 Nov//! 2026).//!//! RULE: a search is a run of characters, never a word. It matches anywhere//! inside a message's text, in any script, with case folded and nothing else//! (no stemming, no word boundary): Hindi or Tamil, whose vowel signs split//! "words" for a word index, and Thai written without spaces, all match//! inside a word. The phone's own copy answers it (`fts_chat`, a trigram//! index, v149); the server holds the messages sealed and learns nothing.//!//! Every place a match stands is said in UTF-16 code units, `[start, end)`,//! the unit Android's and iPhone's strings index by.use unicode_normalization::UnicodeNormalization;/// The fewest characters the index can match by itself: a shorter search is/// matched by reading the messages (`like_pattern`), newest first.pub const INDEXED_FROM: usize = 3;/// How far a result's line reaches before its match, in characters.const LEAD: usize = 24;/// The longest a result's line is, in characters.const LINE: usize = 120;/// What was typed, as it is searched: trimmed, composed (NFC, as a phone's/// keyboard writes), runs of spaces as one. `None` when nothing is left.pub fn query_of(typed: &str) -> Option<String> {    let composed: String = typed.nfc().collect();    let words: Vec<&str> = composed.split_whitespace().collect();    (!words.is_empty()).then(|| words.join(" "))}/// The index's statement for `query`: one phrase, so it matches as one run of/// characters. `None` when the search is shorter than the index can match.pub fn fts_phrase(query: &str) -> Option<String> {    (query.chars().count() >= INDEXED_FROM).then(|| format!("\"{}\"", query.replace('"', "\"\"")))}/// A `LIKE … ESCAPE '\'` pattern holding `query` anywhere, for a search the/// index cannot match (too short, or rows it does not hold yet). SQLite's/// LIKE folds only ASCII case; [`marks`] then keeps only real matches.pub fn like_pattern(query: &str) -> String {    let mut out = String::with_capacity(query.len() + 2);    out.push('%');    for c in query.chars() {        if matches!(c, '%' | '_' | '\\') {            out.push('\\');        }        out.push(c);    }    out.push('%');    out}/// The text folded for matching, each folded character with the UTF-16/// range of the character it came from.fn folded(text: &str) -> Vec<(char, u32, u32)> {    let mut out = Vec::with_capacity(text.len());    let mut at = 0u32;    for c in text.chars() {        let end = at + c.len_utf16() as u32;        for f in c.to_lowercase() {            out.push((f, at, end));        }        at = end;    }    out}fn fold_query(query: &str) -> Vec<char> {    query.chars().flat_map(char::to_lowercase).collect()}/// Where `query` stands in `text`, each match once, left to right, never/// overlapping, in UTF-16 `[start, end)`. Empty when it does not.pub fn marks(text: &str, query: &str) -> Vec<[u32; 2]> {    let needle = fold_query(query);    if needle.is_empty() {        return Vec::new();    }    let hay = folded(text);    let mut out = Vec::new();    let mut i = 0;    while i + needle.len() <= hay.len() {        if hay[i..i + needle.len()].iter().zip(&needle).all(|((h, _, _), n)| h == n) {            out.push([hay[i].1, hay[i + needle.len() - 1].2]);            i += needle.len();        } else {            i += 1;        }    }    out}/// A result's line: the message's words around its first match, on one line,/// cut with "…" where it was cut, and where the match stands in it. `None`/// when the words do not hold the search.pub fn snippet(text: &str, query: &str) -> Option<(String, Vec<[u32; 2]>)> {    let flat: String = text.split_whitespace().collect::<Vec<_>>().join(" ");    let first = *marks(&flat, query).first()?;    let chars: Vec<char> = flat.chars().collect();    // The match's first character, counted in characters.    let mut u16s = 0u32;    let mut start_char = 0;    for (i, c) in chars.iter().enumerate() {        if u16s >= first[0] {            start_char = i;            break;        }        u16s += c.len_utf16() as u32;    }    let mut from = start_char.saturating_sub(LEAD);    // Begin at a word where one is near, never inside one.    if from > 0 {        if let Some(space) = chars[from..start_char].iter().position(|c| *c == ' ') {            from += space + 1;        }    }    let to = (from + LINE).min(chars.len()).max(start_char + query.chars().count().min(LINE)).min(chars.len());    let mut line = String::new();    if from > 0 {        line.push('…');    }    line.extend(&chars[from..to]);    if to < chars.len() {        line.push('…');    }    let found = marks(&line, query);    (!found.is_empty()).then_some((line, found))}#[cfg(test)]#[path = "find_tests.rs"]mod tests;