1use std::collections::HashMap;
4
5#[inline]
9pub fn is_cjk_char(c: char) -> bool {
10 matches!(c,
11 '\u{3040}'..='\u{309F}' | '\u{30A0}'..='\u{30FF}' | '\u{3400}'..='\u{4DBF}' | '\u{4E00}'..='\u{9FFF}' | '\u{F900}'..='\u{FAFF}' | '\u{AC00}'..='\u{D7AF}' | '\u{20000}'..='\u{2A6DF}' )
19}
20
21pub fn contains_cjk(text: &str) -> bool {
23 let (cjk_count, char_count) = cjk_counts(text);
24 if char_count == 0 {
25 return false;
26 }
27 (cjk_count as f64 / char_count as f64) > 0.15
28}
29
30pub fn contains_cjk_f32(text: &str) -> bool {
33 let (cjk_count, char_count) = cjk_counts(text);
34 if char_count == 0 {
35 return false;
36 }
37 (cjk_count as f32 / char_count as f32) > 0.15
38}
39
40fn cjk_counts(text: &str) -> (usize, usize) {
41 text.chars().fold((0, 0), |(cjk, total), ch| {
42 (cjk + usize::from(is_cjk_char(ch)), total + 1)
43 })
44}
45
46#[derive(Debug, Clone, PartialEq)]
50pub struct ScriptProfile {
51 pub cjk_fraction: f64,
53 pub latin_fraction: f64,
55 pub char_count: usize,
57}
58
59impl ScriptProfile {
60 pub fn analyze(text: &str) -> Self {
62 let chars: Vec<char> = text.chars().collect();
63 let n = chars.len();
64 if n == 0 {
65 return Self {
66 cjk_fraction: 0.0,
67 latin_fraction: 0.0,
68 char_count: 0,
69 };
70 }
71 let cjk = chars.iter().filter(|&&c| is_cjk_char(c)).count();
72 let latin = chars.iter().filter(|&&c| c.is_ascii_alphabetic()).count();
73 Self {
74 cjk_fraction: cjk as f64 / n as f64,
75 latin_fraction: latin as f64 / n as f64,
76 char_count: n,
77 }
78 }
79
80 pub fn is_cjk_dominant(&self) -> bool {
82 self.cjk_fraction > 0.15
83 }
84}
85
86pub fn is_meaningful_text_query(query: &str) -> bool {
91 let trimmed = query.trim();
92 if trimmed.is_empty() {
93 return false;
94 }
95
96 let non_ws: Vec<char> = trimmed.chars().filter(|c| !c.is_whitespace()).collect();
97 if non_ws.is_empty() {
98 return false;
99 }
100
101 if !non_ws.iter().any(|c| c.is_alphanumeric()) {
103 return false;
104 }
105
106 if non_ws.len() == 1 && non_ws[0].is_ascii_alphabetic() {
108 return false;
109 }
110
111 let total = non_ws.len();
114 if total > 1 {
115 let mut counts: HashMap<char, usize> = HashMap::new();
116 for c in &non_ws {
117 *counts.entry(*c).or_insert(0) += 1;
118 }
119 if let Some(&max_count) = counts.values().max() {
120 if max_count as f64 / total as f64 > 0.80 {
121 return false;
122 }
123 }
124 }
125
126 true
127}
128
129#[deprecated(note = "use is_meaningful_text_query")]
131pub fn is_meaningful_query(query: &str) -> bool {
132 is_meaningful_text_query(query)
133}
134
135#[cfg(test)]
136#[path = "lang/tests.rs"]
137mod tests;