1use unicode_normalization::UnicodeNormalization;
30
31#[cfg(feature = "icu_segmenter")]
32mod icu_segmenter;
33#[cfg(feature = "icu_segmenter")]
34use icu_segmenter::icu_segment;
35
36#[cfg(feature = "lindera")]
37mod lindera_segmenter;
38#[cfg(feature = "lindera")]
39use lindera_segmenter::lindera_segment;
40
41pub trait Segmenter: Send + Sync {
46 fn segment(&self, text: &str) -> Box<dyn Iterator<Item = String> + '_>;
48
49 fn name(&self) -> &'static str;
51}
52
53impl Segmenter for Box<dyn Segmenter> {
55 fn segment(&self, text: &str) -> Box<dyn Iterator<Item = String> + '_> {
56 self.as_ref().segment(text)
57 }
58
59 fn name(&self) -> &'static str {
60 self.as_ref().name()
61 }
62}
63
64pub struct BigramFirstCharSegmenter;
66
67impl Segmenter for BigramFirstCharSegmenter {
68 fn segment(&self, text: &str) -> Box<dyn Iterator<Item = String> + '_> {
69 let tokens = collect_bigram_first_char(text);
70 Box::new(tokens.into_iter())
71 }
72
73 fn name(&self) -> &'static str {
74 "bigram-first-char"
75 }
76}
77
78#[cfg(feature = "jieba-rs")]
80pub struct JiebaSegmenter {
81 jieba: jieba_rs::Jieba,
82}
83
84#[cfg(feature = "jieba-rs")]
85impl Default for JiebaSegmenter {
86 fn default() -> Self {
87 Self::new()
88 }
89}
90
91#[cfg(feature = "jieba-rs")]
92impl JiebaSegmenter {
93 pub fn new() -> Self {
94 Self {
95 jieba: jieba_rs::Jieba::new(),
96 }
97 }
98}
99
100#[cfg(feature = "jieba-rs")]
101impl Segmenter for JiebaSegmenter {
102 fn segment(&self, text: &str) -> Box<dyn Iterator<Item = String> + '_> {
103 let tokens: Vec<String> = self
104 .jieba
105 .cut(text, false)
106 .into_iter()
107 .map(String::from)
108 .collect();
109 Box::new(tokens.into_iter())
110 }
111
112 fn name(&self) -> &'static str {
113 "jieba"
114 }
115}
116
117static SEGMENTER: std::sync::OnceLock<Box<dyn Segmenter>> = std::sync::OnceLock::new();
119
120pub fn init_segmenter() -> &'static dyn Segmenter {
123 SEGMENTER.get_or_init(|| {
124 #[cfg(feature = "jieba-rs")]
125 {
126 return Box::new(JiebaSegmenter::new()) as Box<dyn Segmenter>;
127 }
128 #[allow(unreachable_code)]
129 Box::new(BigramFirstCharSegmenter)
130 })
131}
132
133pub fn segmenter() -> &'static dyn Segmenter {
135 init_segmenter()
136}
137
138fn dense_script(c: char) -> Option<u8> {
142 match c as u32 {
143 0x0E00..=0x0E7F | 0x0E80..=0x0EFF | 0x1000..=0x109F | 0x1780..=0x17FF => Some(2),
148 0x2E80..=0x2FFF | 0x3000..=0x303F | 0x3040..=0x30FF | 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xAC00..=0xD7AF | 0xF900..=0xFAFF | 0x20000..=0x2FA1F => Some(1),
157 _ => None,
158 }
159}
160
161pub fn is_dense_script(c: char) -> bool {
163 dense_script(c).is_some()
164}
165
166pub fn is_searchable_query(query: &str) -> bool {
172 let mut chars = query.chars().filter(|c| !c.is_whitespace());
173 match chars.next() {
174 None => false,
175 Some(c) if is_dense_script(c) => true,
176 Some(_) => query.chars().filter(|c| !c.is_whitespace()).count() >= 3,
177 }
178}
179
180fn collect_bigram_first_char(text: &str) -> Vec<String> {
186 let normalised: String = text.nfkc().collect();
187 let mut tokens = Vec::new();
188 let mut run: Vec<char> = Vec::new();
189 let mut word: String = String::new(); fn flush_run(run: &mut Vec<char>, tokens: &mut Vec<String>) {
192 if run.is_empty() {
193 return;
194 }
195 if let Some(kind) = run.first().and_then(|c| dense_script(*c)) {
196 match kind {
197 2 => {
198 for c in run.iter() {
200 tokens.push(c.to_string());
201 }
202 }
203 _ => {
204 if let Some(first) = run.first() {
206 tokens.push(first.to_string());
207 }
208 for pair in run.windows(2) {
209 let mut s = String::new();
210 s.push(pair[0]);
211 s.push(pair[1]);
212 tokens.push(s);
213 }
214 }
215 }
216 }
217 run.clear();
218 }
219
220 for c in normalised.chars() {
221 if dense_script(c).is_some() {
222 if !word.is_empty() {
224 tokens.push(std::mem::take(&mut word));
225 }
226 run.push(c);
228 } else {
229 flush_run(&mut run, &mut tokens);
231 if c.is_whitespace() {
232 if !word.is_empty() {
234 tokens.push(std::mem::take(&mut word));
235 }
236 } else {
237 word.push(c);
239 }
240 }
241 }
242 if !word.is_empty() {
243 tokens.push(std::mem::take(&mut word));
244 }
245 flush_run(&mut run, &mut tokens);
246 tokens
247}
248
249pub fn detect_language(text: &str) -> Option<&'static str> {
255 let mut script_counts: std::collections::HashMap<&'static str, usize> =
257 std::collections::HashMap::new();
258
259 for c in text.chars() {
260 let script = match c as u32 {
261 0x2E80..=0x2FFF | 0x3000..=0x303F | 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xF900..=0xFAFF | 0x20000..=0x2FA1F => "zh",
269 0x3040..=0x30FF
271 => "ja",
272 0xAC00..=0xD7AF
274 => "ko",
275 0x0E00..=0x0E7F
277 => "th",
278 0x0E80..=0x0EFF
280 => "lo",
281 0x1000..=0x109F
283 => "my",
284 0x1780..=0x17FF
286 => "km",
287 0x0600..=0x06FF | 0x0750..=0x077F | 0x08A0..=0x08FF | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF => "ar",
294 0x0590..=0x05FF
296 => "he",
297 0x0900..=0x097F
299 => "hi",
300 _ => continue,
301 };
302 *script_counts.entry(script).or_insert(0) += 1;
303 }
304
305 script_counts
307 .into_iter()
308 .max_by_key(|(_, count)| *count)
309 .map(|(script, _)| script)
310}
311
312#[cfg(feature = "lindera")]
314fn is_japanese(text: &str) -> bool {
315 text.chars().any(|c| {
316 let cp = c as u32;
317 (0x3040..=0x309F).contains(&cp) || (0x30A0..=0x30FF).contains(&cp) })
320}
321
322pub fn fts_segment(text: &str) -> String {
327 let seg = segmenter();
330 match seg.name() {
331 "bigram-first-char" => {
332 #[cfg(feature = "icu_segmenter")]
334 if let Some(lang) = detect_language(text) {
335 return icu_segment(text, lang);
336 }
337 #[cfg(feature = "lindera")]
339 if is_japanese(text) {
340 return lindera_segment(text);
341 }
342 let tokens = collect_bigram_first_char(text);
344 tokens.join(" ")
345 }
346 _ => {
347 let tokens = seg.segment(text);
349 tokens.collect::<Vec<_>>().join(" ")
350 }
351 }
352}
353
354pub fn same_tokens(a: &str, b: &str) -> bool {
361 a.split_whitespace().eq(b.split_whitespace())
362}
363
364pub fn query_terms(query: &str) -> Vec<String> {
366 fts_segment(query)
367 .split_whitespace()
368 .map(|t| t.to_string())
369 .collect()
370}
371
372pub const SNIPPET_CHARS: usize = 240;
374
375pub fn excerpt(text: &str, terms: &[String], max_chars: usize) -> String {
377 let collapsed = collapse_whitespace(text);
378 let chars: Vec<char> = collapsed.chars().collect();
379 if chars.len() <= max_chars {
380 return collapsed;
381 }
382
383 let lower: Vec<char> = chars
384 .iter()
385 .map(|c| c.to_lowercase().next().unwrap_or(*c))
386 .collect();
387 let mut hit: Option<usize> = None;
388 for term in terms {
389 let needle: Vec<char> = term
390 .chars()
391 .map(|c| c.to_lowercase().next().unwrap_or(c))
392 .collect();
393 if needle.is_empty() {
394 continue;
395 }
396 if let Some(pos) = lower
397 .windows(needle.len())
398 .position(|window| window == needle.as_slice())
399 {
400 hit = Some(hit.map_or(pos, |best: usize| best.min(pos)));
401 }
402 }
403
404 let start = hit
405 .map(|pos| pos.saturating_sub(max_chars / 3))
406 .unwrap_or(0);
407 let end = (start + max_chars).min(chars.len());
408 let mut out: String = chars[start..end].iter().collect();
409 if start > 0 {
410 out.insert(0, '…');
411 }
412 if end < chars.len() {
413 out.push('…');
414 }
415 out
416}
417
418fn collapse_whitespace(text: &str) -> String {
419 let mut out = String::with_capacity(text.len());
420 let mut prev_space = false;
421 for c in text.chars() {
422 if c.is_whitespace() {
423 if !prev_space {
424 out.push(' ');
425 }
426 prev_space = true;
427 } else {
428 out.push(c);
429 prev_space = false;
430 }
431 }
432 out.trim().to_string()
433}
434
435#[cfg(test)]
436mod tests {
437 use super::*;
438
439 #[cfg(not(feature = "icu_segmenter"))]
441 #[test]
442 fn cjk_runs_become_bigrams() {
443 let s = fts_segment("全文檢索");
444 let tokens: Vec<&str> = s.split_whitespace().collect();
445 assert_eq!(tokens, ["全", "全文", "文檢", "檢索"]);
446 }
447
448 #[cfg(feature = "icu_segmenter")]
450 #[test]
451 fn cjk_runs_become_words() {
452 let s = fts_segment("全文檢索");
453 let tokens: Vec<&str> = s.split_whitespace().collect();
454 assert!(tokens.contains(&"檢索"), "{tokens:?}");
455 assert!(
456 !tokens.contains(&"文檢"),
457 "no cross-word bigrams under ICU: {tokens:?}"
458 );
459 }
460
461 #[test]
462 fn two_character_words_survive() {
463 let doc = fts_segment("南投縣魚池鄉");
464 let query = fts_segment("魚池");
465 let query_tokens: Vec<&str> = query.split_whitespace().collect();
466 let doc_tokens: Vec<&str> = doc.split_whitespace().collect();
467 assert!(
468 query_tokens.iter().any(|qt| doc_tokens.contains(qt)),
469 "query tokens: {:?}, doc tokens: {:?}",
470 query_tokens,
471 doc_tokens
472 );
473 }
474
475 #[test]
476 fn leaves_latin_alone() {
477 assert_eq!(fts_segment("fridge warranty 2027"), "fridge warranty 2027");
478 }
479
480 #[test]
481 fn normalises_full_width() {
482 assert_eq!(fts_segment("WARRANTY"), "WARRANTY");
483 }
484
485 #[cfg(not(feature = "icu_segmenter"))]
487 #[test]
488 fn thai_is_indexed_per_character() {
489 let s = fts_segment("การรับประกัน");
490 assert!(s.split_whitespace().count() > 3, "{s}");
491 }
492
493 #[cfg(feature = "icu_segmenter")]
495 #[test]
496 fn thai_is_indexed_per_word() {
497 let s = fts_segment("การรับประกัน");
498 let tokens: Vec<&str> = s.split_whitespace().collect();
499 assert!(tokens.contains(&"การ"), "{tokens:?}");
500 assert!(tokens.contains(&"รับประกัน"), "{tokens:?}");
501 }
502
503 #[test]
504 fn short_dense_queries_are_searchable() {
505 assert!(is_searchable_query("検索"));
506 assert!(is_searchable_query("法"));
507 assert!(!is_searchable_query("ab"));
508 assert!(!is_searchable_query(" "));
509 assert!(is_searchable_query("tax"));
510 }
511
512 #[test]
513 fn excerpt_is_a_verbatim_window() {
514 let text = "alpha beta gamma delta epsilon zeta eta theta";
515 let out = excerpt(text, &["delta".to_string()], 24);
516 assert!(out.contains("delta"), "{out}");
517 assert!(text.contains(out.trim_matches('…')), "{out}");
518 }
519
520 #[test]
521 fn excerpt_leaves_short_text_whole() {
522 assert_eq!(
523 excerpt("fridge warranty", &["warranty".to_string()], 240),
524 "fridge warranty"
525 );
526 }
527
528 #[test]
529 fn segmenter_name_default() {
530 assert_eq!(segmenter().name(), "bigram-first-char");
531 }
532}