Cotton code
59 lines · 2.9 KB · RustRaw
use super::*;fn cut(text: &str, mark: [u32; 2]) -> String {    let units: Vec<u16> = text.encode_utf16().collect();    String::from_utf16(&units[mark[0] as usize..mark[1] as usize]).unwrap()}// RULE: A search matches inside a word in any script, case folded, and says where in UTF-16.#[test]fn a_match_stands_inside_a_word_in_any_script() {    let hindi = "कल शाम को मिलते हैं";    let found = marks(hindi, "िलत");    assert_eq!(found.len(), 1);    assert_eq!(cut(hindi, found[0]), "िलत");    let tamil = "நாளை சந்திப்போம்";    assert_eq!(cut(tamil, marks(tamil, "சந்தி")[0]), "சந்தி");    let thai = "พรุ่งนี้เจอกัน";    assert_eq!(cut(thai, marks(thai, "เจอ")[0]), "เจอ");    let latin = "Dinner at EIGHT, eight sharp";    let both = marks(latin, "Eight");    assert_eq!(both.iter().map(|m| cut(latin, *m)).collect::<Vec<_>>(), ["EIGHT", "eight"]);    // Outside the basic plane: an emoji is two UTF-16 units, and the mark after it says so.    let emoji = "🎉 party tonight";    assert_eq!(marks(emoji, "party"), [[3, 8]]);    assert!(marks("nothing here", "absent").is_empty());}// RULE: What was typed is trimmed and composed; the index is asked one phrase only from three characters, and a shorter search reads LIKE with its wildcards escaped.#[test]fn what_is_typed_becomes_one_phrase_or_a_pattern() {    assert_eq!(query_of("  see   you  "), Some("see you".into()));    assert_eq!(query_of("   "), None);    // e + combining acute composes to é.    assert_eq!(query_of("cafe\u{301}"), Some("café".into()));    assert_eq!(fts_phrase("see you"), Some("\"see you\"".into()));    assert_eq!(fts_phrase("say \"hi\""), Some("\"say \"\"hi\"\"\"".into()));    assert_eq!(fts_phrase("कल"), None, "two characters: the index cannot match it");    assert_eq!(fts_phrase("कलम"), Some("\"कलम\"".into()));    assert_eq!(like_pattern("50%_off\\"), "%50\\%\\_off\\\\%");}// RULE: A result's line is one line around its first match, cut at a word with "…", and marks the match in the line.#[test]fn a_results_line_is_cut_around_its_match() {    let long = "The first part of a long message that goes on and on about nothing much before it finally says the train leaves at seven from platform four and then goes on again for a while longer still, past the bridge, the market, the school and the long road home after dark";    let (line, found) = snippet(long, "train").unwrap();    assert!(line.starts_with('…') && line.ends_with('…'), "{line}");    assert!(!line.starts_with("… ") && line.chars().count() <= 122, "{line}");    assert_eq!(cut(&line, found[0]), "train");    let (short, found) = snippet("Lunch\n\ntomorrow?", "tomorrow").unwrap();    assert_eq!(short, "Lunch tomorrow?");    assert_eq!(found, [[6, 14]]);    assert!(snippet("no match", "absent").is_none());}