forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

text_fold.rs164 lines, 6.6 KiBHistoryRawDownload
1//! Two different folds, for two different jobs — never swap them:
2//!
3//! * [`search_fold`] / [`search_fold_sql`] are the **search** fold:
4//! deliberately *destructive*, collapsing `ı ş ğ ç ö ü â î û` onto their
5//! ASCII bases so a teacher on an ASCII keyboard still finds accented data.
6//! * [`case_fold_tr`] is the **identity** fold: Turkish-correct case folding
7//! only. It answers "are these two entries the same word?" and must never
8//! conflate distinct letters (`tur` ≠ `tür`, `kir` ≠ `kır`).
9//!
10//! The search fold is shared by the needle (Rust side) and the column
11//! (PostgreSQL side) so the two can never disagree.
12//!
13//! Rust's `to_lowercase` and PostgreSQL's `lower()` are both
14//! locale-invariant here: Turkish `İ` (U+0130) lowercases to `i` + U+0307
15//! (combining dot above), so plain `lower(text) LIKE '%q%'` never matched
16//! `İSTANBUL` for a teacher who typed `istanbul`. Folding strips that
17//! leftover dot and maps the Turkish letters onto their ASCII base, which also
18//! makes the search work in both directions (`istanbul` ↔ `İSTANBUL`,
19//! `ıgdır` ↔ `Iğdır`).
20
21use crate::constant::TEXT_FOLD_REPLACEMENTS;
22
23/// Fold a search needle (or any Rust-side string) for comparison. **Search
24/// only** — this is lossy, `tür` and `tur` both fold to `tur`. For "is this
25/// the same word?" use [`case_fold_tr`].
26pub fn search_fold(text: &str) -> String {
27 let mut folded = text.to_lowercase();
28 for (from, to) in TEXT_FOLD_REPLACEMENTS {
29 folded = folded.replace(from, to);
30 }
31 folded
32}
33
34/// The same folding as a PostgreSQL expression over `column`, for use inside
35/// a `WHERE`. `column` is always a literal field name we wrote — never user
36/// input.
37pub fn search_fold_sql(column: &str) -> String {
38 let mut expr = format!("lower({column})");
39 for (from, to) in TEXT_FOLD_REPLACEMENTS {
40 expr = format!("replace({expr}, '{from}', '{to}')");
41 }
42 expr
43}
44
45/// Case-fold under the **Turkish** casing rule, for identity comparisons
46/// (list dedup). Only the two dotted/dotless pairs are folded together —
47/// `i` ↔ `İ` and `ı` ↔ `I` — so `TÜR` and `tür` are one word while `tur` and
48/// `tür` stay two. Never use this for search: it will not match an ASCII
49/// spelling of an accented word (that is [`search_fold`]'s job).
50pub fn case_fold_tr(text: &str) -> String {
51 let mut folded = String::with_capacity(text.len());
52 for ch in text.chars() {
53 match ch {
54 // Rust would lowercase these locale-invariantly: `İ` → `i` plus a
55 // combining dot, and `I` → `i` (the *dotted* i, wrong letter).
56 'İ' => folded.push('i'),
57 'I' => folded.push('ı'),
58 _ => folded.extend(ch.to_lowercase()),
59 }
60 }
61 // A decomposed `İ` (`i` + combining dot above) is the same letter as `i`.
62 folded.replace("i\u{307}", "i")
63}
64
65#[cfg(test)]
66mod tests {
67 use super::*;
68
69 #[test]
70 fn folds_turkish_casing_both_ways() {
71 assert_eq!(search_fold("İSTANBUL"), "istanbul");
72 assert_eq!(search_fold("istanbul"), "istanbul");
73 assert_eq!(search_fold("İstanbul"), "istanbul");
74 assert_eq!(search_fold("ISTANBUL"), "istanbul");
75 assert_eq!(search_fold("ıstanbul"), "istanbul");
76 assert_eq!(search_fold("Iğdır"), "igdir");
77 assert_eq!(search_fold("ÇÖZÜM"), "cozum");
78 assert_eq!(search_fold("Şekil"), "sekil");
79 }
80
81 /// Circumflexed vowels fold too. Pinned because they are the tail of the
82 /// table and a silent truncation of it still passes every other test here.
83 #[test]
84 fn folds_circumflexed_vowels() {
85 assert_eq!(search_fold("Kâğıt"), "kagit");
86 assert_eq!(search_fold("HÂLÂ"), "hala");
87 assert_eq!(search_fold("Îmân"), "iman");
88 assert_eq!(search_fold("sükûn"), "sukun");
89 }
90
91 /// `search_fold` and `search_fold_sql` are one table, two consumers — the
92 /// SQL must emit a `replace()` for every rule, or the column and the
93 /// needle drift apart and a search silently stops matching.
94 #[test]
95 fn sql_covers_every_replacement() {
96 let sql = search_fold_sql("name");
97 assert_eq!(
98 sql.matches("replace(").count(),
99 TEXT_FOLD_REPLACEMENTS.len(),
100 "one replace() per rule"
101 );
102 // The base is PostgreSQL's locale-invariant lower(), applied before
103 // any letter folding, over the exact column named — every rule wraps
104 // a `replace()` around it, so the base sits innermost.
105 assert!(
106 sql.contains(&format!("lower({})", "name")),
107 "the fold must be lower() of the column, wrapped in replaces: {sql}"
108 );
109 }
110
111 /// The expression folds a sample exactly like the Rust side does: same
112 /// table, same order. (The old engine-checked variant of this test ran
113 /// the SQL against a live store; the string shape above plus this fold
114 /// pin the generator, and the live round-trip belongs to the integration
115 /// suite.)
116 #[test]
117 fn sql_folding_mirrors_rust_folding_rules() {
118 let sql = search_fold_sql("name");
119 for (from, to) in TEXT_FOLD_REPLACEMENTS {
120 assert!(
121 sql.contains(&"replace(".to_string()) && sql.contains(&format!("'{from}', '{to}'")),
122 "rule {from} -> {to} missing from the emitted expression"
123 );
124 assert_eq!(search_fold(from), *to);
125 }
126 }
127
128 /// The identity fold folds case (Turkish rules) and *nothing else* — the
129 /// truth table the settings dedup depends on.
130 #[test]
131 fn case_fold_tr_folds_case_but_not_letters() {
132 // Same word, different case.
133 for (upper, lower) in [
134 ("TÜR", "tür"),
135 ("KIR", "kır"),
136 ("İSTANBUL", "istanbul"),
137 ("ISPARTA", "ısparta"),
138 ("İZİN", "izin"),
139 ("SINAV", "sınav"),
140 ("LAB", "lab"),
141 ] {
142 assert_eq!(
143 case_fold_tr(upper),
144 case_fold_tr(lower),
145 "{upper} and {lower} are the same word"
146 );
147 }
148 // Distinct words the destructive search fold wrongly collapsed.
149 for (a, b) in [("tur", "tür"), ("kir", "kır"), ("sıra", "sira")] {
150 assert_ne!(
151 case_fold_tr(a),
152 case_fold_tr(b),
153 "{a} and {b} are different words"
154 );
155 assert_eq!(
156 search_fold(a),
157 search_fold(b),
158 "search fold still collapses {a}/{b}"
159 );
160 }
161 // Decomposed `İ` (i + combining dot) is still plain `i`.
162 assert_eq!(case_fold_tr("i\u{307}zin"), "izin");
163 }
164}