Skip to main content

dateoxide_core/locale/
mod.rs

1pub mod schema;
2
3use crate::settings::DateOrder;
4use rustc_hash::{FxHashMap, FxHashSet};
5use schema::RawLocale;
6use std::sync::OnceLock;
7
8static EMBEDDED_LOCALES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/locales.bin"));
9static REGISTRY: OnceLock<LocaleRegistry> = OnceLock::new();
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12#[repr(u8)]
13pub enum TimeUnit {
14    Year = 0,
15    Month = 1,
16    Week = 2,
17    Day = 3,
18    Hour = 4,
19    Minute = 5,
20    Second = 6,
21    Decade = 7,
22    Century = 8,
23    Fortnight = 9,
24}
25
26impl TimeUnit {
27    #[inline]
28    pub fn from_u8(v: u8) -> Option<Self> {
29        match v {
30            0 => Some(Self::Year),
31            1 => Some(Self::Month),
32            2 => Some(Self::Week),
33            3 => Some(Self::Day),
34            4 => Some(Self::Hour),
35            5 => Some(Self::Minute),
36            6 => Some(Self::Second),
37            7 => Some(Self::Decade),
38            8 => Some(Self::Century),
39            9 => Some(Self::Fortnight),
40            _ => None,
41        }
42    }
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct RelativeSpec {
47    /// -1 for past ("ago"), +1 for future ("in")
48    pub sign: i8,
49    pub amount: i32,
50    pub unit: TimeUnit,
51}
52
53#[derive(Debug, Clone)]
54pub struct RelativeAffix {
55    pub prefix: String,
56    pub suffix: String,
57    pub sign: i8,
58    pub unit: TimeUnit,
59}
60
61#[derive(Debug)]
62pub struct CompiledLocale {
63    pub id: u16,
64    pub code: String,
65    pub date_order: DateOrder,
66    pub months: FxHashMap<String, u8>,
67    pub weekdays: FxHashMap<String, u8>,
68    pub am: FxHashSet<String>,
69    pub pm: FxHashSet<String>,
70    pub units: FxHashMap<String, TimeUnit>,
71    pub ago: FxHashSet<String>,
72    pub in_words: FxHashSet<String>,
73    pub skip: FxHashSet<String>,
74    pub relative_exact: FxHashMap<String, Vec<RelativeSpec>>,
75    pub relative_affix: Vec<RelativeAffix>,
76    pub word_numbers: FxHashMap<String, u32>,
77    pub time_of_day: FxHashMap<String, u8>,
78    // Diacritic-folded secondary tables (populated only where folded != exact)
79    pub folded_months: FxHashMap<String, u8>,
80    pub folded_weekdays: FxHashMap<String, u8>,
81    pub folded_units: FxHashMap<String, TimeUnit>,
82    pub folded_ago: FxHashSet<String>,
83    pub folded_in_words: FxHashSet<String>,
84    pub folded_relative_exact: FxHashMap<String, Vec<RelativeSpec>>,
85    pub folded_relative_affix: Vec<RelativeAffix>,
86    pub folded_time_of_day: FxHashMap<String, u8>,
87}
88
89pub struct LocaleRegistry {
90    pub locales: Vec<CompiledLocale>,
91    pub code_to_id: FxHashMap<String, usize>,
92    /// Global inverted index: lowercase token -> priority-ordered list of locale IDs.
93    pub token_to_langs: FxHashMap<String, Vec<u16>>,
94    /// Folded inverted index: diacritic-folded token -> priority-ordered list of locale IDs.
95    pub folded_token_to_langs: FxHashMap<String, Vec<u16>>,
96    /// Global exact relative phrase index: phrase -> list of (lang_id, RelativeSpec).
97    pub exact_phrase_index: FxHashMap<String, Vec<(u16, RelativeSpec)>>,
98    /// Folded exact relative phrase index: folded phrase -> list of (lang_id, RelativeSpec).
99    pub folded_exact_phrase_index: FxHashMap<String, Vec<(u16, RelativeSpec)>>,
100    /// Tokens that can start or belong to a date expression (used for fast search_dates).
101    pub known_date_tokens: FxHashSet<String>,
102}
103
104impl LocaleRegistry {
105    #[inline]
106    pub fn global() -> &'static Self {
107        REGISTRY.get_or_init(Self::load)
108    }
109
110    fn load() -> Self {
111        let raw_locales: Vec<RawLocale> = postcard::from_bytes(EMBEDDED_LOCALES)
112            .expect("embedded locales.bin must deserialize cleanly");
113
114        let mut locales = Vec::with_capacity(raw_locales.len());
115        let mut code_to_id = FxHashMap::default();
116        let mut token_to_langs: FxHashMap<String, Vec<u16>> = FxHashMap::default();
117        let mut folded_token_to_langs: FxHashMap<String, Vec<u16>> = FxHashMap::default();
118        let mut exact_phrase_index: FxHashMap<String, Vec<(u16, RelativeSpec)>> =
119            FxHashMap::default();
120        let mut folded_exact_phrase_index: FxHashMap<String, Vec<(u16, RelativeSpec)>> =
121            FxHashMap::default();
122        let mut known_date_tokens: FxHashSet<String> = FxHashSet::default();
123
124        let mut register_token = |tok: &str, lang_id: u16, is_search_token: bool| {
125            if tok.is_empty() {
126                return;
127            }
128            let entry = token_to_langs.entry(tok.to_string()).or_default();
129            if entry.last().copied() != Some(lang_id) && !entry.contains(&lang_id) {
130                entry.push(lang_id);
131            }
132            if is_search_token {
133                known_date_tokens.insert(tok.to_string());
134            }
135            let folded = fold_diacritics(tok);
136            if folded != tok && !folded.is_empty() {
137                let fentry = folded_token_to_langs.entry(folded.clone()).or_default();
138                if fentry.last().copied() != Some(lang_id) && !fentry.contains(&lang_id) {
139                    fentry.push(lang_id);
140                }
141                if is_search_token {
142                    known_date_tokens.insert(folded);
143                }
144            }
145        };
146
147        for (idx, raw) in raw_locales.into_iter().enumerate() {
148            let lang_id = idx as u16;
149            code_to_id.insert(raw.code.to_ascii_lowercase(), idx);
150            let date_order = DateOrder::from_str(&raw.date_order).unwrap_or(DateOrder::DMY);
151
152            let mut months = FxHashMap::default();
153            let mut folded_months = FxHashMap::default();
154            for (m_idx, names) in raw.months.into_iter().enumerate() {
155                let month_num = (m_idx + 1) as u8;
156                for name in names {
157                    for part in name.split_whitespace() {
158                        if part.chars().count() >= 2 {
159                            register_token(part, lang_id, true);
160                        }
161                    }
162                    register_token(&name, lang_id, true);
163                    let norm_name = normalize_digits_and_lower(&name);
164                    if norm_name != name {
165                        register_token(&norm_name, lang_id, true);
166                        let nf = fold_diacritics(&norm_name);
167                        if nf != norm_name {
168                            folded_months.entry(nf).or_insert(month_num);
169                        }
170                        months.insert(norm_name, month_num);
171                    }
172                    let f = fold_diacritics(&name);
173                    if f != name {
174                        folded_months.entry(f).or_insert(month_num);
175                    }
176                    months.insert(name, month_num);
177                }
178            }
179
180            let mut weekdays = FxHashMap::default();
181            let mut folded_weekdays = FxHashMap::default();
182            for (d_idx, names) in raw.weekdays.into_iter().enumerate() {
183                let wd_num = d_idx as u8;
184                for name in names {
185                    for part in name.split_whitespace() {
186                        if part.chars().count() >= 2 {
187                            register_token(part, lang_id, true);
188                        }
189                    }
190                    register_token(&name, lang_id, true);
191                    let norm_name = normalize_digits_and_lower(&name);
192                    if norm_name != name {
193                        register_token(&norm_name, lang_id, true);
194                        let nf = fold_diacritics(&norm_name);
195                        if nf != norm_name {
196                            folded_weekdays.entry(nf).or_insert(wd_num);
197                        }
198                        weekdays.insert(norm_name, wd_num);
199                    }
200                    let f = fold_diacritics(&name);
201                    if f != name {
202                        folded_weekdays.entry(f).or_insert(wd_num);
203                    }
204                    weekdays.insert(name, wd_num);
205                }
206            }
207
208            let mut am = FxHashSet::default();
209            for s in raw.am {
210                register_token(&s, lang_id, true);
211                am.insert(s);
212            }
213            let mut pm = FxHashSet::default();
214            for s in raw.pm {
215                register_token(&s, lang_id, true);
216                pm.insert(s);
217            }
218
219            let mut units = FxHashMap::default();
220            let mut folded_units = FxHashMap::default();
221            for (tok, u_id) in raw.units {
222                if let Some(u) = TimeUnit::from_u8(u_id) {
223                    register_token(&tok, lang_id, true);
224                    let f = fold_diacritics(&tok);
225                    if f != tok {
226                        folded_units.entry(f).or_insert(u);
227                    }
228                    units.insert(tok, u);
229                }
230            }
231
232            let mut ago = FxHashSet::default();
233            let mut folded_ago = FxHashSet::default();
234            for s in raw.ago {
235                for part in s.split_whitespace() {
236                    register_token(part, lang_id, true);
237                }
238                register_token(&s, lang_id, true);
239                let f = fold_diacritics(&s);
240                if f != s {
241                    folded_ago.insert(f);
242                }
243                ago.insert(s);
244            }
245
246            let mut in_words = FxHashSet::default();
247            let mut folded_in_words = FxHashSet::default();
248            for s in raw.in_words {
249                for part in s.split_whitespace() {
250                    register_token(part, lang_id, true);
251                }
252                register_token(&s, lang_id, true);
253                let f = fold_diacritics(&s);
254                if f != s {
255                    folded_in_words.insert(f);
256                }
257                in_words.insert(s);
258            }
259
260            let mut skip = FxHashSet::default();
261            for s in raw.skip {
262                skip.insert(s);
263            }
264
265            let mut relative_exact: FxHashMap<String, Vec<RelativeSpec>> = FxHashMap::default();
266            let mut folded_relative_exact: FxHashMap<String, Vec<RelativeSpec>> =
267                FxHashMap::default();
268            for (phrase, sign, amount, u_id) in raw.relative_exact {
269                if let Some(unit) = TimeUnit::from_u8(u_id) {
270                    let spec = RelativeSpec { sign, amount, unit };
271                    for part in phrase.split_whitespace() {
272                        register_token(part, lang_id, true);
273                    }
274                    register_token(&phrase, lang_id, true);
275                    exact_phrase_index
276                        .entry(phrase.clone())
277                        .or_default()
278                        .push((lang_id, spec));
279                    let f = fold_diacritics(&phrase);
280                    if f != phrase {
281                        folded_exact_phrase_index
282                            .entry(f.clone())
283                            .or_default()
284                            .push((lang_id, spec));
285                        folded_relative_exact.entry(f).or_default().push(spec);
286                    }
287                    relative_exact.entry(phrase).or_default().push(spec);
288                }
289            }
290
291            let mut relative_affix = Vec::with_capacity(raw.relative_affix.len());
292            let mut folded_relative_affix = Vec::new();
293            for (prefix, suffix, sign, u_id) in raw.relative_affix {
294                if let Some(unit) = TimeUnit::from_u8(u_id) {
295                    for part in prefix.split_whitespace().chain(suffix.split_whitespace()) {
296                        if part.chars().count() >= 2 {
297                            register_token(part, lang_id, true);
298                        }
299                    }
300                    let fp = fold_diacritics(&prefix);
301                    let fs = fold_diacritics(&suffix);
302                    if fp != prefix || fs != suffix {
303                        folded_relative_affix.push(RelativeAffix {
304                            prefix: fp,
305                            suffix: fs,
306                            sign,
307                            unit,
308                        });
309                    }
310                    relative_affix.push(RelativeAffix {
311                        prefix,
312                        suffix,
313                        sign,
314                        unit,
315                    });
316                }
317            }
318            // Match longest affixes first for specificity
319            let sort_affix = |v: &mut Vec<RelativeAffix>| {
320                v.sort_by(|a, b| {
321                    let la = a.prefix.len() + a.suffix.len();
322                    let lb = b.prefix.len() + b.suffix.len();
323                    lb.cmp(&la)
324                });
325            };
326            sort_affix(&mut relative_affix);
327            sort_affix(&mut folded_relative_affix);
328
329            let mut word_numbers = FxHashMap::default();
330            for (w, n) in raw.word_numbers {
331                let f = fold_diacritics(&w);
332                if f != w {
333                    word_numbers.entry(f).or_insert(n);
334                }
335                word_numbers.insert(w, n);
336            }
337
338            let mut time_of_day = FxHashMap::default();
339            let mut folded_time_of_day = FxHashMap::default();
340            for (phrase, hour) in raw.time_of_day {
341                for part in phrase.split_whitespace() {
342                    register_token(part, lang_id, true);
343                }
344                register_token(&phrase, lang_id, true);
345                let f = fold_diacritics(&phrase);
346                if f != phrase {
347                    folded_time_of_day.entry(f).or_insert(hour);
348                }
349                time_of_day.insert(phrase, hour);
350            }
351
352            // Ensure key compound time-of-day trigger words are indexed for search_dates / lang detect
353            if raw.code == "en" {
354                register_token("tonight", lang_id, true);
355            } else if raw.code == "es" {
356                register_token("anoche", lang_id, true);
357            } else if raw.code == "tr" {
358                register_token("saat", lang_id, true);
359            }
360
361            locales.push(CompiledLocale {
362                id: lang_id,
363                code: raw.code,
364                date_order,
365                months,
366                weekdays,
367                am,
368                pm,
369                units,
370                ago,
371                in_words,
372                skip,
373                relative_exact,
374                relative_affix,
375                word_numbers,
376                time_of_day,
377                folded_months,
378                folded_weekdays,
379                folded_units,
380                folded_ago,
381                folded_in_words,
382                folded_relative_exact,
383                folded_relative_affix,
384                folded_time_of_day,
385            });
386        }
387
388        Self {
389            locales,
390            code_to_id,
391            token_to_langs,
392            folded_token_to_langs,
393            exact_phrase_index,
394            folded_exact_phrase_index,
395            known_date_tokens,
396        }
397    }
398
399    pub fn resolve_lang_id(&self, code: &str) -> Option<usize> {
400        let lower = code.trim().to_ascii_lowercase();
401        if let Some(&id) = self.code_to_id.get(&lower) {
402            return Some(id);
403        }
404        // Handle underscore/hyphen variants (e.g. "uz_cyrl" -> "uz-cyrl")
405        let dash = lower.replace('_', "-");
406        if let Some(&id) = self.code_to_id.get(&dash) {
407            return Some(id);
408        }
409        // Fallback: "en-US" or "tr_TR" -> "en" or "tr"
410        if let Some(base) = dash.split('-').next() {
411            if let Some(&id) = self.code_to_id.get(base) {
412                return Some(id);
413            }
414        }
415        // Legacy / ISO 639-1 macro aliases when exact code isn't present
416        let aliased = match lower.as_str() {
417            "no" => Some("nb"),
418            "iw" => Some("he"),
419            "in" => Some("id"),
420            "ji" => Some("yi"),
421            "fil" => Some("tl"),
422            _ => None,
423        };
424        if let Some(target) = aliased {
425            if let Some(&id) = self.code_to_id.get(target) {
426                return Some(id);
427            }
428        }
429        None
430    }
431
432    /// Detect top candidate language IDs in O(tokens) time without scanning all 205 locales.
433    pub fn detect_candidates(
434        &self,
435        normalized: &str,
436        tokens: &[&str],
437        explicit_langs: Option<&[String]>,
438        default_langs: &[String],
439        normalize: bool,
440        use_given_order: bool,
441    ) -> Vec<usize> {
442        if let Some(langs) = explicit_langs {
443            if !langs.is_empty() {
444                let mut out = Vec::with_capacity(langs.len());
445                for code in langs {
446                    if let Some(id) = self.resolve_lang_id(code) {
447                        if !out.contains(&id) {
448                            out.push(id);
449                        }
450                    }
451                }
452                return out;
453            }
454        }
455
456        let order_with_defaults = |mut ids: Vec<usize>| -> Vec<usize> {
457            if use_given_order && !default_langs.is_empty() {
458                let mut ordered = Vec::with_capacity(ids.len());
459                for code in default_langs {
460                    if let Some(did) = self.resolve_lang_id(code) {
461                        if ids.contains(&did) && !ordered.contains(&did) {
462                            ordered.push(did);
463                        }
464                    }
465                }
466                for id in ids {
467                    if !ordered.contains(&id) {
468                        ordered.push(id);
469                    }
470                }
471                ids = ordered;
472            }
473            ids
474        };
475
476        // Fast exact relative phrase lookup
477        if let Some(matches) = self.exact_phrase_index.get(normalized) {
478            let mut out: Vec<usize> = matches.iter().map(|(id, _)| *id as usize).collect();
479            out.sort_unstable();
480            out.dedup();
481            return order_with_defaults(out);
482        }
483
484        if normalize {
485            let f = fold_diacritics(normalized);
486            if let Some(matches) = self.folded_exact_phrase_index.get(&f) {
487                let mut out: Vec<usize> = matches.iter().map(|(id, _)| *id as usize).collect();
488                out.sort_unstable();
489                out.dedup();
490                return order_with_defaults(out);
491            }
492        }
493
494        // Script-based fast narrowing for non-Latin scripts
495        let script_hint = detect_script_hint(normalized);
496
497        let mut scores: FxHashMap<u16, u32> = FxHashMap::default();
498        for &tok in tokens {
499            if tok.len() <= 1 && tok.is_ascii() {
500                continue;
501            }
502            if let Some(langs) = self.token_to_langs.get(tok) {
503                let weight = if langs.len() <= 3 {
504                    8
505                } else if langs.len() <= 12 {
506                    4
507                } else {
508                    2
509                };
510                for &lid in langs {
511                    *scores.entry(lid).or_insert(0) += weight;
512                }
513            }
514            if normalize {
515                let ft = fold_diacritics(tok);
516                if let Some(langs) = self.folded_token_to_langs.get(&ft) {
517                    let weight = if langs.len() <= 3 {
518                        5
519                    } else if langs.len() <= 12 {
520                        3
521                    } else {
522                        1
523                    };
524                    for &lid in langs {
525                        *scores.entry(lid).or_insert(0) += weight;
526                    }
527                }
528            }
529        }
530
531        // Also check 2-word phrases (e.g. "il y a", "geçen hafta", "next week", "hace 2")
532        for w in tokens.windows(2) {
533            let bigram = format!("{} {}", w[0], w[1]);
534            if let Some(langs) = self.token_to_langs.get(&bigram) {
535                for &lid in langs {
536                    *scores.entry(lid).or_insert(0) += 6;
537                }
538            }
539            if normalize {
540                let fb = fold_diacritics(&bigram);
541                if fb != bigram {
542                    if let Some(langs) = self.folded_token_to_langs.get(&fb) {
543                        for &lid in langs {
544                            *scores.entry(lid).or_insert(0) += 4;
545                        }
546                    }
547                }
548            }
549        }
550
551        // Boost script-matched languages (crucial for CJK/Arabic/Thai where no spaces exist)
552        if let Some(hint_codes) = script_hint {
553            for code in hint_codes {
554                if let Some(id) = self.resolve_lang_id(code) {
555                    *scores.entry(id as u16).or_insert(0) += 5;
556                }
557            }
558        }
559
560        // Slight tie-break boost for default_languages
561        for code in default_langs {
562            if let Some(id) = self.resolve_lang_id(code) {
563                if let Some(sc) = scores.get_mut(&(id as u16)) {
564                    *sc += 2;
565                }
566            }
567        }
568
569        if scores.is_empty() {
570            return Vec::new();
571        }
572
573        let mut ranked: Vec<(u16, u32)> = scores.into_iter().collect();
574        // Highest score first; ties broken by global language priority (lower id = higher priority)
575        ranked.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
576
577        let top: Vec<usize> = ranked.into_iter().take(8).map(|(id, _)| id as usize).collect();
578        order_with_defaults(top)
579    }
580}
581
582/// Fold common Latin and Arabic diacritics for accent-tolerant matching (`NORMALIZE=True`).
583pub fn fold_diacritics(s: &str) -> String {
584    let mut out = String::with_capacity(s.len());
585    for ch in s.chars() {
586        let mapped = match ch {
587            'á' | 'à' | 'â' | 'ä' | 'ã' | 'å' | 'ā' | 'ă' | 'ą' => 'a',
588            'é' | 'è' | 'ê' | 'ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => 'e',
589            'í' | 'ì' | 'î' | 'ï' | 'ī' | 'ĭ' | 'į' | 'ı' => 'i',
590            'ó' | 'ò' | 'ô' | 'ö' | 'õ' | 'ø' | 'ō' | 'ŏ' | 'ő' => 'o',
591            'ú' | 'ù' | 'û' | 'ü' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => 'u',
592            'ç' | 'ć' | 'ĉ' | 'ċ' | 'č' => 'c',
593            'ğ' | 'ĝ' | 'ġ' | 'ģ' => 'g',
594            'ş' | 'ś' | 'ŝ' | 'š' => 's',
595            'ñ' | 'ń' | 'ņ' | 'ň' => 'n',
596            'ý' | 'ÿ' | 'ŷ' => 'y',
597            'ž' | 'ź' | 'ż' => 'z',
598            'ł' | 'ĺ' | 'ļ' | 'ľ' => 'l',
599            'ř' | 'ŕ' | 'ŗ' => 'r',
600            'ď' | 'đ' => 'd',
601            'ť' | 'ţ' => 't',
602            // Arabic alef normalization & harakat/tatweel/ZWNJ stripping
603            'أ' | 'إ' | 'آ' | 'ٱ' => 'ا',
604            'ى' => 'ي',
605            '\u{200C}' => ' ',
606            '\u{064B}'..='\u{065F}' | '\u{0670}' | '\u{0640}' | '\u{0300}'..='\u{036F}' => {
607                continue;
608            }
609            other => other,
610        };
611        out.push(mapped);
612    }
613    out
614}
615
616fn detect_script_hint(s: &str) -> Option<&'static [&'static str]> {
617    let mut has_hiragana_katakana = false;
618    let mut has_han = false;
619    let mut has_hangul = false;
620    let mut has_cyrillic = false;
621    let mut has_arabic = false;
622    let mut has_hebrew = false;
623    let mut has_greek = false;
624    let mut has_thai = false;
625    let mut has_devanagari = false;
626    let mut has_bengali = false;
627    let mut has_gurmukhi = false;
628    let mut has_gujarati = false;
629    let mut has_oriya = false;
630    let mut has_tamil = false;
631    let mut has_telugu = false;
632    let mut has_kannada = false;
633    let mut has_malayalam = false;
634    let mut has_sinhala = false;
635    let mut has_lao = false;
636    let mut has_tibetan = false;
637    let mut has_myanmar = false;
638    let mut has_georgian = false;
639    let mut has_armenian = false;
640    let mut has_ethiopic = false;
641    let mut has_cherokee = false;
642    let mut has_khmer = false;
643    let mut has_tifinagh = false;
644    let mut has_yi = false;
645
646    for ch in s.chars() {
647        let c = ch as u32;
648        match c {
649            0x3040..=0x30FF => has_hiragana_katakana = true,
650            0x4E00..=0x9FFF => has_han = true,
651            0xAC00..=0xD7AF => has_hangul = true,
652            0x0400..=0x04FF => has_cyrillic = true,
653            0x0600..=0x06FF => has_arabic = true,
654            0x0590..=0x05FF => has_hebrew = true,
655            0x0370..=0x03FF => has_greek = true,
656            0x0E00..=0x0E7F => has_thai = true,
657            0x0900..=0x097F => has_devanagari = true,
658            0x0980..=0x09FF => has_bengali = true,
659            0x0A00..=0x0A7F => has_gurmukhi = true,
660            0x0A80..=0x0AFF => has_gujarati = true,
661            0x0B00..=0x0B7F => has_oriya = true,
662            0x0B80..=0x0BFF => has_tamil = true,
663            0x0C00..=0x0C7F => has_telugu = true,
664            0x0C80..=0x0CFF => has_kannada = true,
665            0x0D00..=0x0D7F => has_malayalam = true,
666            0x0D80..=0x0DFF => has_sinhala = true,
667            0x0E80..=0x0EFF => has_lao = true,
668            0x0F00..=0x0FFF => has_tibetan = true,
669            0x1000..=0x109F => has_myanmar = true,
670            0x10A0..=0x10FF => has_georgian = true,
671            0x0530..=0x058F => has_armenian = true,
672            0x1200..=0x137F => has_ethiopic = true,
673            0x13A0..=0x13FF | 0xAB70..=0xABBF => has_cherokee = true,
674            0x1780..=0x17FF => has_khmer = true,
675            0x2D30..=0x2D7F => has_tifinagh = true,
676            0xA000..=0xA4CF => has_yi = true,
677            _ => {}
678        }
679    }
680
681    if has_hiragana_katakana {
682        Some(&["ja"])
683    } else if has_hangul {
684        Some(&["ko"])
685    } else if has_han {
686        Some(&["zh", "ja", "zh-hans", "zh-hant", "yue"])
687    } else if has_cyrillic {
688        Some(&[
689            "ru", "uk", "bg", "sr", "be", "kk", "mk", "ky", "mn", "az-cyrl", "uz-cyrl",
690            "bs-cyrl", "sr-cyrl", "ce", "os", "sah",
691        ])
692    } else if has_arabic {
693        Some(&[
694            "ar", "fa", "ur", "ps", "ckb", "ug", "ks", "pa-arab", "uz-arab", "lrc", "mzn",
695        ])
696    } else if has_hebrew {
697        Some(&["he", "yi"])
698    } else if has_greek {
699        Some(&["el"])
700    } else if has_thai {
701        Some(&["th"])
702    } else if has_devanagari {
703        Some(&["hi", "mr", "ne", "kok", "brx"])
704    } else if has_bengali {
705        Some(&["bn", "as"])
706    } else if has_gurmukhi {
707        Some(&["pa", "pa-guru"])
708    } else if has_gujarati {
709        Some(&["gu"])
710    } else if has_oriya {
711        Some(&["or"])
712    } else if has_tamil {
713        Some(&["ta"])
714    } else if has_telugu {
715        Some(&["te"])
716    } else if has_kannada {
717        Some(&["kn"])
718    } else if has_malayalam {
719        Some(&["ml"])
720    } else if has_sinhala {
721        Some(&["si"])
722    } else if has_lao {
723        Some(&["lo"])
724    } else if has_tibetan {
725        Some(&["bo", "dz"])
726    } else if has_myanmar {
727        Some(&["my"])
728    } else if has_georgian {
729        Some(&["ka"])
730    } else if has_armenian {
731        Some(&["hy"])
732    } else if has_ethiopic {
733        Some(&["am", "ti"])
734    } else if has_cherokee {
735        Some(&["chr"])
736    } else if has_khmer {
737        Some(&["km"])
738    } else if has_tifinagh {
739        Some(&["zgh", "shi-tfng", "shi"])
740    } else if has_yi {
741        Some(&["ii"])
742    } else {
743        None
744    }
745}
746
747/// Normalize all 18 Unicode decimal numeral systems to ASCII 0-9
748/// and collapse whitespace/punctuation for fast matching.
749pub fn normalize_digits_and_lower(input: &str) -> String {
750    let mut out = String::with_capacity(input.len());
751    let mut prev_space = true;
752    for ch in input.chars() {
753        let mapped = match ch {
754            '\u{0660}'..='\u{0669}' => char::from_u32('0' as u32 + (ch as u32 - 0x0660)).unwrap(),
755            '\u{06F0}'..='\u{06F9}' => char::from_u32('0' as u32 + (ch as u32 - 0x06F0)).unwrap(),
756            '\u{0966}'..='\u{096F}' => char::from_u32('0' as u32 + (ch as u32 - 0x0966)).unwrap(),
757            '\u{09E6}'..='\u{09EF}' => char::from_u32('0' as u32 + (ch as u32 - 0x09E6)).unwrap(),
758            '\u{0A66}'..='\u{0A6F}' => char::from_u32('0' as u32 + (ch as u32 - 0x0A66)).unwrap(),
759            '\u{0AE6}'..='\u{0AEF}' => char::from_u32('0' as u32 + (ch as u32 - 0x0AE6)).unwrap(),
760            '\u{0B66}'..='\u{0B6F}' => char::from_u32('0' as u32 + (ch as u32 - 0x0B66)).unwrap(),
761            '\u{0BE6}'..='\u{0BEF}' => char::from_u32('0' as u32 + (ch as u32 - 0x0BE6)).unwrap(),
762            '\u{0C66}'..='\u{0C6F}' => char::from_u32('0' as u32 + (ch as u32 - 0x0C66)).unwrap(),
763            '\u{0CE6}'..='\u{0CEF}' => char::from_u32('0' as u32 + (ch as u32 - 0x0CE6)).unwrap(),
764            '\u{0D66}'..='\u{0D6F}' => char::from_u32('0' as u32 + (ch as u32 - 0x0D66)).unwrap(),
765            '\u{0DE6}'..='\u{0DEF}' => char::from_u32('0' as u32 + (ch as u32 - 0x0DE6)).unwrap(),
766            '\u{0E50}'..='\u{0E59}' => char::from_u32('0' as u32 + (ch as u32 - 0x0E50)).unwrap(),
767            '\u{0ED0}'..='\u{0EDF}' => char::from_u32('0' as u32 + (ch as u32 - 0x0ED0)).unwrap(),
768            '\u{0F20}'..='\u{0F29}' => char::from_u32('0' as u32 + (ch as u32 - 0x0F20)).unwrap(),
769            '\u{1040}'..='\u{1049}' => char::from_u32('0' as u32 + (ch as u32 - 0x1040)).unwrap(),
770            '\u{17E0}'..='\u{17E9}' => char::from_u32('0' as u32 + (ch as u32 - 0x17E0)).unwrap(),
771            '\u{FF10}'..='\u{FF19}' => char::from_u32('0' as u32 + (ch as u32 - 0xFF10)).unwrap(),
772            // Turkish dotted/dotless I normalization to match lowercase tables cleanly
773            '\u{0130}' => 'i',
774            '\u{00A0}' | '\u{2009}' | '\u{202F}' => ' ',
775            other => other,
776        };
777        if mapped.is_whitespace() {
778            if !prev_space {
779                out.push(' ');
780                prev_space = true;
781            }
782        } else if mapped == '\u{0307}' {
783            continue;
784        } else {
785            for lc in mapped.to_lowercase() {
786                if lc != '\u{0307}' {
787                    out.push(lc);
788                }
789            }
790            prev_space = false;
791        }
792    }
793    if out.ends_with(' ') {
794        out.pop();
795    }
796    out
797}