Skip to main content

dateoxide_core/locale/
mod.rs

1pub mod schema;
2
3use crate::settings::{DateOrder, Settings};
4use rustc_hash::{FxHashMap, FxHashSet};
5use schema::RawLocale;
6use std::borrow::Cow;
7use std::sync::OnceLock;
8
9static EMBEDDED_LOCALES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/locales.bin"));
10static REGISTRY: OnceLock<LocaleRegistry> = OnceLock::new();
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[repr(u8)]
14pub enum TimeUnit {
15    Year = 0,
16    Month = 1,
17    Week = 2,
18    Day = 3,
19    Hour = 4,
20    Minute = 5,
21    Second = 6,
22    Decade = 7,
23    Century = 8,
24    Fortnight = 9,
25}
26
27impl TimeUnit {
28    #[inline]
29    pub fn from_u8(v: u8) -> Option<Self> {
30        match v {
31            0 => Some(Self::Year),
32            1 => Some(Self::Month),
33            2 => Some(Self::Week),
34            3 => Some(Self::Day),
35            4 => Some(Self::Hour),
36            5 => Some(Self::Minute),
37            6 => Some(Self::Second),
38            7 => Some(Self::Decade),
39            8 => Some(Self::Century),
40            9 => Some(Self::Fortnight),
41            _ => None,
42        }
43    }
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct RelativeSpec {
48    /// -1 for past ("ago"), +1 for future ("in")
49    pub sign: i8,
50    pub amount: i32,
51    pub unit: TimeUnit,
52}
53
54#[derive(Debug, Clone)]
55pub struct RelativeAffix {
56    pub prefix: String,
57    pub suffix: String,
58    pub sign: i8,
59    pub unit: TimeUnit,
60}
61
62#[derive(Debug)]
63pub struct CompiledLocale {
64    pub id: u16,
65    pub code: String,
66    pub date_order: DateOrder,
67    pub months: FxHashMap<String, u8>,
68    pub weekdays: FxHashMap<String, u8>,
69    pub am: FxHashSet<String>,
70    pub pm: FxHashSet<String>,
71    pub folded_am: FxHashSet<String>,
72    pub folded_pm: FxHashSet<String>,
73    pub units: FxHashMap<String, TimeUnit>,
74    pub ago: FxHashSet<String>,
75    pub in_words: FxHashSet<String>,
76    pub ago_sorted: Vec<String>,
77    pub in_words_sorted: Vec<String>,
78    pub skip: FxHashSet<String>,
79    pub relative_exact: FxHashMap<String, Vec<RelativeSpec>>,
80    pub relative_affix: Vec<RelativeAffix>,
81    pub word_numbers: FxHashMap<String, u32>,
82    pub ordinals: FxHashMap<String, u32>,
83    pub time_of_day: FxHashMap<String, u8>,
84    // Diacritic-folded secondary tables (populated only where folded != exact)
85    pub folded_months: FxHashMap<String, u8>,
86    pub folded_weekdays: FxHashMap<String, u8>,
87    pub folded_units: FxHashMap<String, TimeUnit>,
88    pub folded_ago: FxHashSet<String>,
89    pub folded_in_words: FxHashSet<String>,
90    pub folded_ago_sorted: Vec<String>,
91    pub folded_in_words_sorted: Vec<String>,
92    pub folded_ordinals: FxHashMap<String, u32>,
93    pub folded_relative_exact: FxHashMap<String, Vec<RelativeSpec>>,
94    pub folded_relative_affix: Vec<RelativeAffix>,
95    pub folded_time_of_day: FxHashMap<String, u8>,
96}
97
98pub struct LocaleRegistry {
99    pub locales: Vec<CompiledLocale>,
100    pub code_to_id: FxHashMap<String, usize>,
101    /// Global inverted index: lowercase token -> priority-ordered list of locale IDs.
102    pub token_to_langs: FxHashMap<String, Vec<u16>>,
103    /// Folded inverted index: diacritic-folded token -> priority-ordered list of locale IDs.
104    pub folded_token_to_langs: FxHashMap<String, Vec<u16>>,
105    /// Global exact relative phrase index: phrase -> list of (lang_id, RelativeSpec).
106    pub exact_phrase_index: FxHashMap<String, Vec<(u16, RelativeSpec)>>,
107    /// Folded exact relative phrase index: folded phrase -> list of (lang_id, RelativeSpec).
108    pub folded_exact_phrase_index: FxHashMap<String, Vec<(u16, RelativeSpec)>>,
109    /// Tokens that can start or belong to a date expression (used for fast search_dates).
110    pub known_date_tokens: FxHashSet<String>,
111    /// Cardinal & ordinal word numeral tokens across 205 locales (cannot start bare prose matches).
112    pub known_numeral_tokens: FxHashSet<String>,
113    /// Non-ASCII numeral words for agglutinative/spaceless token prefix detection (e.g. Sinhala, Thai).
114    pub non_ascii_numeral_words: Vec<String>,
115}
116
117impl LocaleRegistry {
118    #[inline]
119    pub fn global() -> &'static Self {
120        REGISTRY.get_or_init(Self::load)
121    }
122
123    fn load() -> Self {
124        let raw_locales: Vec<RawLocale> = postcard::from_bytes(EMBEDDED_LOCALES)
125            .expect("embedded locales.bin must deserialize cleanly");
126
127        let mut locales = Vec::with_capacity(raw_locales.len());
128        let mut code_to_id = FxHashMap::default();
129        let mut token_to_langs: FxHashMap<String, Vec<u16>> = FxHashMap::default();
130        let mut folded_token_to_langs: FxHashMap<String, Vec<u16>> = FxHashMap::default();
131        let mut exact_phrase_index: FxHashMap<String, Vec<(u16, RelativeSpec)>> =
132            FxHashMap::default();
133        let mut folded_exact_phrase_index: FxHashMap<String, Vec<(u16, RelativeSpec)>> =
134            FxHashMap::default();
135        let mut known_date_tokens: FxHashSet<String> = FxHashSet::default();
136        let mut known_numeral_tokens: FxHashSet<String> = FxHashSet::default();
137
138        let mut register_token = |tok: &str, lang_id: u16, is_search_token: bool| {
139            if tok.is_empty() {
140                return;
141            }
142            let entry = token_to_langs.entry(tok.to_string()).or_default();
143            if entry.last().copied() != Some(lang_id) && !entry.contains(&lang_id) {
144                entry.push(lang_id);
145            }
146            if is_search_token {
147                known_date_tokens.insert(tok.to_string());
148                let q_trim = tok.trim_matches(|c: char| matches!(c, '\'' | '’' | 'ꞌ' | 'ʻ'));
149                if !q_trim.is_empty() && q_trim != tok {
150                    known_date_tokens.insert(q_trim.to_string());
151                }
152            }
153            let folded = fold_diacritics(tok);
154            if folded.as_ref() != tok && !folded.is_empty() {
155                let folded_s = folded.into_owned();
156                let fentry = folded_token_to_langs.entry(folded_s.clone()).or_default();
157                if fentry.last().copied() != Some(lang_id) && !fentry.contains(&lang_id) {
158                    fentry.push(lang_id);
159                }
160                if is_search_token {
161                    known_date_tokens.insert(folded_s);
162                }
163            }
164        };
165
166        for (idx, raw) in raw_locales.into_iter().enumerate() {
167            let lang_id = idx as u16;
168            code_to_id.insert(raw.code.to_ascii_lowercase(), idx);
169            let date_order = DateOrder::from_str(&raw.date_order).unwrap_or(DateOrder::DMY);
170
171            let mut months = FxHashMap::default();
172            let mut folded_months = FxHashMap::default();
173            for (m_idx, names) in raw.months.into_iter().enumerate() {
174                let month_num = (m_idx + 1) as u8;
175                for name in names {
176                    for part in name.split_whitespace() {
177                        if part.chars().count() >= 2 {
178                            register_token(part, lang_id, true);
179                        }
180                    }
181                    register_token(&name, lang_id, true);
182                    let norm_name = normalize_digits_and_lower(&name);
183                    if norm_name != name {
184                        register_token(&norm_name, lang_id, true);
185                        let nf = fold_diacritics(&norm_name);
186                        if nf.as_ref() != norm_name {
187                            folded_months.entry(nf.into_owned()).or_insert(month_num);
188                        }
189                        months.insert(norm_name, month_num);
190                    }
191                    let f = fold_diacritics(&name);
192                    if f.as_ref() != name {
193                        folded_months.entry(f.into_owned()).or_insert(month_num);
194                    }
195                    months.insert(name, month_num);
196                }
197            }
198
199            let mut weekdays = FxHashMap::default();
200            let mut folded_weekdays = FxHashMap::default();
201            for (d_idx, names) in raw.weekdays.into_iter().enumerate() {
202                let wd_num = d_idx as u8;
203                for name in names {
204                    for part in name.split_whitespace() {
205                        if part.chars().count() >= 2 {
206                            register_token(part, lang_id, true);
207                        }
208                    }
209                    register_token(&name, lang_id, true);
210                    let norm_name = normalize_digits_and_lower(&name);
211                    if norm_name != name {
212                        register_token(&norm_name, lang_id, true);
213                        let nf = fold_diacritics(&norm_name);
214                        if nf.as_ref() != norm_name {
215                            folded_weekdays.entry(nf.into_owned()).or_insert(wd_num);
216                        }
217                        weekdays.insert(norm_name, wd_num);
218                    }
219                    let f = fold_diacritics(&name);
220                    if f.as_ref() != name {
221                        folded_weekdays.entry(f.into_owned()).or_insert(wd_num);
222                    }
223                    weekdays.insert(name, wd_num);
224                }
225            }
226
227            let mut am = FxHashSet::default();
228            let mut folded_am = FxHashSet::default();
229            for s in raw.am {
230                register_token(&s, lang_id, true);
231                let f = fold_diacritics(&s);
232                if f.as_ref() != s {
233                    folded_am.insert(f.into_owned());
234                }
235                am.insert(s);
236            }
237            let mut pm = FxHashSet::default();
238            let mut folded_pm = FxHashSet::default();
239            for s in raw.pm {
240                register_token(&s, lang_id, true);
241                let f = fold_diacritics(&s);
242                if f.as_ref() != s {
243                    folded_pm.insert(f.into_owned());
244                }
245                pm.insert(s);
246            }
247
248            let mut units = FxHashMap::default();
249            let mut folded_units = FxHashMap::default();
250            for (tok, u_id) in raw.units {
251                if let Some(u) = TimeUnit::from_u8(u_id) {
252                    register_token(&tok, lang_id, true);
253                    let f = fold_diacritics(&tok);
254                    if f.as_ref() != tok {
255                        folded_units.entry(f.into_owned()).or_insert(u);
256                    }
257                    units.insert(tok, u);
258                }
259            }
260
261            let mut ago = FxHashSet::default();
262            let mut folded_ago = FxHashSet::default();
263            for s in raw.ago {
264                for part in s.split_whitespace() {
265                    register_token(part, lang_id, true);
266                }
267                register_token(&s, lang_id, true);
268                let f = fold_diacritics(&s);
269                if f.as_ref() != s {
270                    folded_ago.insert(f.into_owned());
271                }
272                ago.insert(s);
273            }
274
275            let mut in_words = FxHashSet::default();
276            let mut folded_in_words = FxHashSet::default();
277            for s in raw.in_words {
278                for part in s.split_whitespace() {
279                    register_token(part, lang_id, true);
280                }
281                register_token(&s, lang_id, true);
282                let f = fold_diacritics(&s);
283                if f.as_ref() != s {
284                    folded_in_words.insert(f.into_owned());
285                }
286                in_words.insert(s);
287            }
288
289            let mut skip = FxHashSet::default();
290            for s in raw.skip {
291                skip.insert(s);
292            }
293
294            let mut relative_exact: FxHashMap<String, Vec<RelativeSpec>> = FxHashMap::default();
295            let mut folded_relative_exact: FxHashMap<String, Vec<RelativeSpec>> =
296                FxHashMap::default();
297            for (phrase, sign, amount, u_id) in raw.relative_exact {
298                if let Some(unit) = TimeUnit::from_u8(u_id) {
299                    let spec = RelativeSpec { sign, amount, unit };
300                    for part in phrase.split_whitespace() {
301                        register_token(part, lang_id, true);
302                    }
303                    register_token(&phrase, lang_id, true);
304                    exact_phrase_index
305                        .entry(phrase.clone())
306                        .or_default()
307                        .push((lang_id, spec));
308                    let f = fold_diacritics(&phrase);
309                    if f.as_ref() != phrase {
310                        let fs = f.into_owned();
311                        folded_exact_phrase_index
312                            .entry(fs.clone())
313                            .or_default()
314                            .push((lang_id, spec));
315                        folded_relative_exact.entry(fs).or_default().push(spec);
316                    }
317                    relative_exact.entry(phrase).or_default().push(spec);
318                }
319            }
320
321            let mut relative_affix = Vec::with_capacity(raw.relative_affix.len());
322            let mut folded_relative_affix = Vec::new();
323            for (prefix, suffix, sign, u_id) in raw.relative_affix {
324                if let Some(unit) = TimeUnit::from_u8(u_id) {
325                    for part in prefix.split_whitespace().chain(suffix.split_whitespace()) {
326                        if part.chars().count() >= 2 {
327                            register_token(part, lang_id, true);
328                        }
329                    }
330                    let fp = fold_diacritics(&prefix);
331                    let fs = fold_diacritics(&suffix);
332                    if fp.as_ref() != prefix || fs.as_ref() != suffix {
333                        folded_relative_affix.push(RelativeAffix {
334                            prefix: fp.into_owned(),
335                            suffix: fs.into_owned(),
336                            sign,
337                            unit,
338                        });
339                    }
340                    relative_affix.push(RelativeAffix {
341                        prefix,
342                        suffix,
343                        sign,
344                        unit,
345                    });
346                }
347            }
348            // Match longest affixes first for specificity
349            let sort_affix = |v: &mut Vec<RelativeAffix>| {
350                v.sort_by(|a, b| {
351                    let la = a.prefix.len() + a.suffix.len();
352                    let lb = b.prefix.len() + b.suffix.len();
353                    lb.cmp(&la)
354                });
355            };
356            sort_affix(&mut relative_affix);
357            sort_affix(&mut folded_relative_affix);
358
359            let mut word_numbers = FxHashMap::default();
360            for (w, n) in raw.word_numbers {
361                let f = fold_diacritics(&w);
362                if f.as_ref() != w {
363                    let fs = f.into_owned();
364                    word_numbers.entry(fs.clone()).or_insert(n);
365                    known_numeral_tokens.insert(fs);
366                }
367                for part in w.split_whitespace() {
368                    known_numeral_tokens.insert(part.to_string());
369                    let pf = fold_diacritics(part);
370                    if pf.as_ref() != part {
371                        known_numeral_tokens.insert(pf.into_owned());
372                    }
373                    if part.chars().count() >= 3 || !part.is_ascii() {
374                        register_token(part, lang_id, false);
375                    }
376                }
377                word_numbers.insert(w, n);
378            }
379
380            let mut ordinals = FxHashMap::default();
381            let mut folded_ordinals = FxHashMap::default();
382            for (w, n) in raw.ordinals {
383                let f = fold_diacritics(&w);
384                if f.as_ref() != w {
385                    let fs = f.into_owned();
386                    folded_ordinals.entry(fs.clone()).or_insert(n);
387                    known_numeral_tokens.insert(fs);
388                }
389                known_numeral_tokens.insert(w.clone());
390                if w.chars().count() >= 3 || !w.is_ascii() {
391                    register_token(&w, lang_id, false);
392                }
393                ordinals.insert(w, n);
394            }
395
396            let mut time_of_day = FxHashMap::default();
397            let mut folded_time_of_day = FxHashMap::default();
398            for (phrase, hour) in raw.time_of_day {
399                for part in phrase.split_whitespace() {
400                    register_token(part, lang_id, true);
401                }
402                register_token(&phrase, lang_id, true);
403                let f = fold_diacritics(&phrase);
404                if f.as_ref() != phrase {
405                    folded_time_of_day.entry(f.into_owned()).or_insert(hour);
406                }
407                time_of_day.insert(phrase, hour);
408            }
409
410            // Ensure key compound time-of-day trigger words are indexed for search_dates / lang detect
411            if raw.code == "en" {
412                register_token("tonight", lang_id, true);
413            } else if raw.code == "es" {
414                register_token("anoche", lang_id, true);
415            } else if raw.code == "tr" {
416                register_token("saat", lang_id, true);
417            }
418
419            let sort_desc = |set: &FxHashSet<String>| -> Vec<String> {
420                let mut v: Vec<String> = set.iter().cloned().collect();
421                v.sort_unstable_by(|a, b| b.len().cmp(&a.len()).then_with(|| a.cmp(b)));
422                v
423            };
424            let ago_sorted = sort_desc(&ago);
425            let in_words_sorted = sort_desc(&in_words);
426            let folded_ago_sorted = sort_desc(&folded_ago);
427            let folded_in_words_sorted = sort_desc(&folded_in_words);
428
429            locales.push(CompiledLocale {
430                id: lang_id,
431                code: raw.code,
432                date_order,
433                months,
434                weekdays,
435                am,
436                pm,
437                folded_am,
438                folded_pm,
439                units,
440                ago,
441                in_words,
442                ago_sorted,
443                in_words_sorted,
444                skip,
445                relative_exact,
446                relative_affix,
447                word_numbers,
448                ordinals,
449                time_of_day,
450                folded_months,
451                folded_weekdays,
452                folded_units,
453                folded_ago,
454                folded_in_words,
455                folded_ago_sorted,
456                folded_in_words_sorted,
457                folded_ordinals,
458                folded_relative_exact,
459                folded_relative_affix,
460                folded_time_of_day,
461            });
462        }
463
464        // Register disambiguating locale connectors so candidate detection ranks e.g. it/et/id accurately
465        for &(tok, langs) in &[
466            ("alle", &["it", "de"][..]),
467            ("kell", &["et"][..]),
468            ("pukul", &["id", "ms"][..]),
469            ("ora", &["ro"][..]),
470            ("klo", &["fi"][..]),
471            ("στις", &["el"][..]),
472            ("lúc", &["vi"][..]),
473            ("เวลา", &["th"][..]),
474            ("الساعة", &["ar"][..]),
475            ("at", &["en"][..]),
476            ("um", &["de"][..]),
477        ] {
478            for &code in langs {
479                if let Some(&lid) = code_to_id.get(code) {
480                    let list = token_to_langs.entry(tok.to_string()).or_default();
481                    let lid_u16 = lid as u16;
482                    if !list.contains(&lid_u16) {
483                        list.push(lid_u16);
484                    }
485                }
486            }
487        }
488
489        let non_ascii_numeral_words: Vec<String> = known_numeral_tokens
490            .iter()
491            .filter(|w| !w.is_ascii() && w.chars().count() >= 2)
492            .cloned()
493            .collect();
494
495        Self {
496            locales,
497            code_to_id,
498            token_to_langs,
499            folded_token_to_langs,
500            exact_phrase_index,
501            folded_exact_phrase_index,
502            known_date_tokens,
503            known_numeral_tokens,
504            non_ascii_numeral_words,
505        }
506    }
507
508    pub fn resolve_lang_id(&self, code: &str) -> Option<usize> {
509        let lower = code.trim().to_ascii_lowercase();
510        if let Some(&id) = self.code_to_id.get(&lower) {
511            return Some(id);
512        }
513        // Handle underscore/hyphen variants (e.g. "uz_cyrl" -> "uz-cyrl")
514        let dash = lower.replace('_', "-");
515        if let Some(&id) = self.code_to_id.get(&dash) {
516            return Some(id);
517        }
518        // Fallback: "en-US" or "tr_TR" -> "en" or "tr"
519        if let Some(base) = dash.split('-').next() {
520            if let Some(&id) = self.code_to_id.get(base) {
521                return Some(id);
522            }
523        }
524        // Legacy / ISO 639-1 macro aliases when exact code isn't present
525        let aliased = match lower.as_str() {
526            "no" => Some("nb"),
527            "iw" => Some("he"),
528            "in" => Some("id"),
529            "ji" => Some("yi"),
530            "fil" => Some("tl"),
531            _ => None,
532        };
533        if let Some(target) = aliased {
534            if let Some(&id) = self.code_to_id.get(target) {
535                return Some(id);
536            }
537        }
538        None
539    }
540
541    /// Detect top candidate language IDs in O(tokens) time without scanning all 205 locales.
542    pub fn detect_candidates(
543        &self,
544        normalized: &str,
545        tokens: &[&str],
546        explicit_langs: Option<&[String]>,
547        default_langs: &[String],
548        normalize: bool,
549        use_given_order: bool,
550    ) -> Vec<usize> {
551        if let Some(langs) = explicit_langs {
552            if !langs.is_empty() {
553                let mut out = Vec::with_capacity(langs.len());
554                for code in langs {
555                    if let Some(id) = self.resolve_lang_id(code) {
556                        if !out.contains(&id) {
557                            out.push(id);
558                        }
559                    }
560                }
561                return out;
562            }
563        }
564
565        let order_with_defaults = |mut ids: Vec<usize>| -> Vec<usize> {
566            if use_given_order && !default_langs.is_empty() {
567                let mut ordered = Vec::with_capacity(ids.len());
568                for code in default_langs {
569                    if let Some(did) = self.resolve_lang_id(code) {
570                        if ids.contains(&did) && !ordered.contains(&did) {
571                            ordered.push(did);
572                        }
573                    }
574                }
575                for id in ids {
576                    if !ordered.contains(&id) {
577                        ordered.push(id);
578                    }
579                }
580                ids = ordered;
581            }
582            ids
583        };
584
585        // Fast exact relative phrase lookup
586        if let Some(matches) = self.exact_phrase_index.get(normalized) {
587            let mut out: Vec<usize> = matches.iter().map(|(id, _)| *id as usize).collect();
588            out.sort_unstable();
589            out.dedup();
590            return order_with_defaults(out);
591        }
592
593        if normalize
594            && !self
595                .locales
596                .first()
597                .is_some_and(|en| en.months.contains_key(normalized) || en.weekdays.contains_key(normalized))
598        {
599            let f = fold_diacritics(normalized);
600            if let Some(matches) = self.folded_exact_phrase_index.get(f.as_ref()) {
601                let mut out: Vec<usize> = matches.iter().map(|(id, _)| *id as usize).collect();
602                out.sort_unstable();
603                out.dedup();
604                return order_with_defaults(out);
605            }
606        }
607
608        // Script-based fast narrowing for non-Latin scripts
609        let script_hint = detect_script_hint(normalized);
610
611        let mut scores: FxHashMap<u16, u32> = FxHashMap::default();
612        for &tok in tokens {
613            if tok.len() <= 1 && tok.is_ascii() {
614                continue;
615            }
616            let exact_langs = self.token_to_langs.get(tok);
617            let exact_matched = if let Some(langs) = exact_langs {
618                let weight = if langs.len() <= 3 {
619                    16
620                } else if langs.len() <= 12 {
621                    10
622                } else {
623                    6
624                };
625                for &lid in langs {
626                    *scores.entry(lid).or_insert(0) += weight;
627                }
628                true
629            } else {
630                false
631            };
632            if normalize {
633                let ft = fold_diacritics(tok);
634                // Only award meaningful folded points when input wasn't already an exact token
635                // (prevents diacritic-stripped rare locales like "jûn"/"nóv"/"ápr" from outscoring "jun"/"nov"/"apr")
636                if let Some(langs) = self.folded_token_to_langs.get(ft.as_ref()) {
637                    let weight = if !exact_matched || ft.as_ref() != tok {
638                        if langs.len() <= 3 {
639                            5
640                        } else if langs.len() <= 12 {
641                            3
642                        } else {
643                            1
644                        }
645                    } else if langs.len() <= 3 {
646                        2
647                    } else {
648                        1
649                    };
650                    for &lid in langs {
651                        // Never double-count the same locale for both exact and folded on one token
652                        if let Some(ex) = exact_langs {
653                            if ex.binary_search(&lid).is_ok() {
654                                continue;
655                            }
656                        }
657                        *scores.entry(lid).or_insert(0) += weight;
658                    }
659                }
660            }
661        }
662
663        // Also check 2-word phrases (e.g. "il y a", "geçen hafta", "next week", "hace 2") using a single reused scratch buffer
664        let mut bigram = String::with_capacity(32);
665        for w in tokens.windows(2) {
666            bigram.clear();
667            bigram.push_str(w[0]);
668            bigram.push(' ');
669            bigram.push_str(w[1]);
670            if let Some(langs) = self.token_to_langs.get(&bigram) {
671                for &lid in langs {
672                    *scores.entry(lid).or_insert(0) += 6;
673                }
674            }
675            if normalize {
676                let fb = fold_diacritics(&bigram);
677                if fb.as_ref() != bigram {
678                    if let Some(langs) = self.folded_token_to_langs.get(fb.as_ref()) {
679                        for &lid in langs {
680                            *scores.entry(lid).or_insert(0) += 4;
681                        }
682                    }
683                }
684            }
685        }
686
687        // Boost script-matched languages (crucial for CJK/Arabic/Thai where no spaces exist)
688        if let Some(hint_codes) = script_hint {
689            for code in hint_codes {
690                if let Some(id) = self.resolve_lang_id(code) {
691                    *scores.entry(id as u16).or_insert(0) += 5;
692                }
693            }
694        }
695
696        // Slight tie-break boost for default_languages
697        for code in default_langs {
698            if let Some(id) = self.resolve_lang_id(code) {
699                if let Some(sc) = scores.get_mut(&(id as u16)) {
700                    *sc += 2;
701                }
702            }
703        }
704
705        if scores.is_empty() {
706            return Vec::new();
707        }
708
709        let mut ranked: Vec<(u16, u32)> = scores.into_iter().collect();
710        // Highest score first; ties broken by global language priority (lower id = higher priority)
711        ranked.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
712
713        let top: Vec<usize> = ranked.into_iter().take(12).map(|(id, _)| id as usize).collect();
714        order_with_defaults(top)
715    }
716}
717
718/// Fold common Latin and Arabic diacritics for accent-tolerant matching (`NORMALIZE=True`), zero-alloc on ASCII.
719pub fn fold_diacritics(s: &str) -> Cow<'_, str> {
720    if s.is_ascii() {
721        return Cow::Borrowed(s);
722    }
723    let mut out = String::with_capacity(s.len());
724    for ch in s.chars() {
725        let mapped = match ch {
726            'á' | 'à' | 'â' | 'ä' | 'ã' | 'å' | 'ā' | 'ă' | 'ą' => 'a',
727            'é' | 'è' | 'ê' | 'ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => 'e',
728            'í' | 'ì' | 'î' | 'ï' | 'ī' | 'ĭ' | 'į' | 'ı' => 'i',
729            'ó' | 'ò' | 'ô' | 'ö' | 'õ' | 'ø' | 'ō' | 'ŏ' | 'ő' => 'o',
730            'ú' | 'ù' | 'û' | 'ü' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => 'u',
731            'ç' | 'ć' | 'ĉ' | 'ċ' | 'č' => 'c',
732            'ğ' | 'ĝ' | 'ġ' | 'ģ' => 'g',
733            'ş' | 'ś' | 'ŝ' | 'š' => 's',
734            'ñ' | 'ń' | 'ņ' | 'ň' => 'n',
735            'ý' | 'ÿ' | 'ŷ' => 'y',
736            'ž' | 'ź' | 'ż' => 'z',
737            'ł' | 'ĺ' | 'ļ' | 'ľ' => 'l',
738            'ř' | 'ŕ' | 'ŗ' => 'r',
739            'ď' | 'đ' => 'd',
740            'ť' | 'ţ' => 't',
741            // Arabic alef normalization & harakat/tatweel/ZWNJ stripping
742            'أ' | 'إ' | 'آ' | 'ٱ' => 'ا',
743            'ى' => 'ي',
744            '\u{200C}' => ' ',
745            '\u{064B}'..='\u{065F}' | '\u{0670}' | '\u{0640}' | '\u{0300}'..='\u{036F}' => {
746                continue;
747            }
748            other => other,
749        };
750        out.push(mapped);
751    }
752    Cow::Owned(out)
753}
754
755fn detect_script_hint(s: &str) -> Option<&'static [&'static str]> {
756    let mut has_hiragana_katakana = false;
757    let mut has_han = false;
758    let mut has_hangul = false;
759    let mut has_cyrillic = false;
760    let mut has_arabic = false;
761    let mut has_hebrew = false;
762    let mut has_greek = false;
763    let mut has_thai = false;
764    let mut has_devanagari = false;
765    let mut has_bengali = false;
766    let mut has_gurmukhi = false;
767    let mut has_gujarati = false;
768    let mut has_oriya = false;
769    let mut has_tamil = false;
770    let mut has_telugu = false;
771    let mut has_kannada = false;
772    let mut has_malayalam = false;
773    let mut has_sinhala = false;
774    let mut has_lao = false;
775    let mut has_tibetan = false;
776    let mut has_myanmar = false;
777    let mut has_georgian = false;
778    let mut has_armenian = false;
779    let mut has_ethiopic = false;
780    let mut has_cherokee = false;
781    let mut has_khmer = false;
782    let mut has_tifinagh = false;
783    let mut has_yi = false;
784
785    for ch in s.chars() {
786        let c = ch as u32;
787        match c {
788            0x3040..=0x30FF => has_hiragana_katakana = true,
789            0x4E00..=0x9FFF => has_han = true,
790            0xAC00..=0xD7AF => has_hangul = true,
791            0x0400..=0x04FF => has_cyrillic = true,
792            0x0600..=0x06FF => has_arabic = true,
793            0x0590..=0x05FF => has_hebrew = true,
794            0x0370..=0x03FF => has_greek = true,
795            0x0E00..=0x0E7F => has_thai = true,
796            0x0900..=0x097F => has_devanagari = true,
797            0x0980..=0x09FF => has_bengali = true,
798            0x0A00..=0x0A7F => has_gurmukhi = true,
799            0x0A80..=0x0AFF => has_gujarati = true,
800            0x0B00..=0x0B7F => has_oriya = true,
801            0x0B80..=0x0BFF => has_tamil = true,
802            0x0C00..=0x0C7F => has_telugu = true,
803            0x0C80..=0x0CFF => has_kannada = true,
804            0x0D00..=0x0D7F => has_malayalam = true,
805            0x0D80..=0x0DFF => has_sinhala = true,
806            0x0E80..=0x0EFF => has_lao = true,
807            0x0F00..=0x0FFF => has_tibetan = true,
808            0x1000..=0x109F => has_myanmar = true,
809            0x10A0..=0x10FF => has_georgian = true,
810            0x0530..=0x058F => has_armenian = true,
811            0x1200..=0x137F => has_ethiopic = true,
812            0x13A0..=0x13FF | 0xAB70..=0xABBF => has_cherokee = true,
813            0x1780..=0x17FF => has_khmer = true,
814            0x2D30..=0x2D7F => has_tifinagh = true,
815            0xA000..=0xA4CF => has_yi = true,
816            _ => {}
817        }
818    }
819
820    if has_hiragana_katakana {
821        Some(&["ja"])
822    } else if has_hangul {
823        Some(&["ko"])
824    } else if has_han {
825        Some(&["zh", "ja", "zh-hans", "zh-hant", "yue"])
826    } else if has_cyrillic {
827        Some(&[
828            "ru", "uk", "bg", "sr", "be", "kk", "mk", "ky", "mn", "az-cyrl", "uz-cyrl",
829            "bs-cyrl", "sr-cyrl", "ce", "os", "sah",
830        ])
831    } else if has_arabic {
832        Some(&[
833            "ar", "fa", "ur", "ps", "ckb", "ug", "ks", "pa-arab", "uz-arab", "lrc", "mzn",
834        ])
835    } else if has_hebrew {
836        Some(&["he", "yi"])
837    } else if has_greek {
838        Some(&["el"])
839    } else if has_thai {
840        Some(&["th"])
841    } else if has_devanagari {
842        Some(&["hi", "mr", "ne", "kok", "brx"])
843    } else if has_bengali {
844        Some(&["bn", "as"])
845    } else if has_gurmukhi {
846        Some(&["pa", "pa-guru"])
847    } else if has_gujarati {
848        Some(&["gu"])
849    } else if has_oriya {
850        Some(&["or"])
851    } else if has_tamil {
852        Some(&["ta"])
853    } else if has_telugu {
854        Some(&["te"])
855    } else if has_kannada {
856        Some(&["kn"])
857    } else if has_malayalam {
858        Some(&["ml"])
859    } else if has_sinhala {
860        Some(&["si"])
861    } else if has_lao {
862        Some(&["lo"])
863    } else if has_tibetan {
864        Some(&["bo", "dz"])
865    } else if has_myanmar {
866        Some(&["my"])
867    } else if has_georgian {
868        Some(&["ka"])
869    } else if has_armenian {
870        Some(&["hy"])
871    } else if has_ethiopic {
872        Some(&["am", "ti"])
873    } else if has_cherokee {
874        Some(&["chr"])
875    } else if has_khmer {
876        Some(&["km"])
877    } else if has_tifinagh {
878        Some(&["zgh", "shi-tfng", "shi"])
879    } else if has_yi {
880        Some(&["ii"])
881    } else {
882        None
883    }
884}
885
886/// Whether `code` is a major auto-detect language safe for short unanchored tokens.
887#[inline]
888pub fn is_major_auto_locale(code: &str) -> bool {
889    matches!(
890        code,
891        "en" | "tr" | "de" | "fr" | "es" | "it" | "pt" | "nl" | "ru" | "ar" | "fa" | "zh"
892            | "ja" | "ko" | "pl" | "uk" | "sv" | "no" | "nb" | "nn" | "da" | "fi" | "cs"
893            | "sk" | "ro" | "hu" | "el" | "he" | "hi" | "id" | "ms" | "vi" | "th" | "tl"
894    )
895}
896
897/// Whether `settings.languages` permits the given base locale code.
898#[inline]
899pub fn settings_allows_locale(settings: &Settings, code: &str) -> bool {
900    let Some(ref ls) = settings.languages else {
901        return true;
902    };
903    let reg = LocaleRegistry::global();
904    let target_base = code.split(['-', '_']).next().unwrap_or(code);
905    ls.iter().any(|l| {
906        let base = l.split(['-', '_']).next().unwrap_or(l);
907        if l.eq_ignore_ascii_case(code) || base.eq_ignore_ascii_case(target_base) {
908            return true;
909        }
910        reg.resolve_lang_id(l)
911            .is_some_and(|id| reg.locales[id].code == code)
912    })
913}
914
915/// Returns `true` if `code` is a common uppercase 3-letter ISO-4217 currency code.
916#[inline]
917pub fn is_iso4217_currency(tok: &str) -> bool {
918    tok.len() >= 3
919        && tok.len() <= 4
920        && tok.bytes().all(|b| b.is_ascii_uppercase())
921        && matches!(
922            tok,
923            "EUR" | "USD" | "GBP" | "SEK" | "NOK" | "DKK" | "CHF" | "JPY" | "CNY" | "RMB"
924                | "CAD" | "AUD" | "NZD" | "TRY" | "PLN" | "CZK" | "HUF" | "RON" | "BGN"
925                | "RUB" | "UAH" | "INR" | "BRL" | "MXN" | "ARS" | "CLP" | "COP" | "PEN"
926                | "ZAR" | "NGN" | "KES" | "EGP" | "MAD" | "KRW" | "SGD" | "HKD" | "TWD"
927                | "THB" | "IDR" | "MYR" | "PHP" | "VND" | "ILS" | "AED" | "SAR" | "QAR"
928                | "KWD" | "BHD" | "OMR" | "JOD" | "PKR" | "BDT" | "LKR" | "ISK" | "RSD"
929                | "HRK" | "GEL" | "AMD" | "AZN" | "KZT" | "UZS" | "BTC" | "ETH" | "USDT"
930        )
931}
932
933#[inline]
934fn has_khmer_chars(s: &str) -> bool {
935    s.chars().any(|c| ('\u{1780}'..='\u{17FF}').contains(&c))
936}
937
938#[inline]
939fn is_invisible_format_control(c: char, keep_zwsp: bool) -> bool {
940    if c == '\u{200B}' {
941        return !keep_zwsp;
942    }
943    matches!(
944        c,
945        '\u{FEFF}'
946            | '\u{200E}'
947            | '\u{200F}'
948            | '\u{00AD}'
949            | '\u{202A}'..='\u{202E}'
950            | '\u{2066}'..='\u{2069}'
951    )
952}
953
954#[inline]
955fn is_edge_emoji(c: char) -> bool {
956    matches!(
957        c,
958        '\u{1F300}'..='\u{1FAFF}' | '\u{2600}'..='\u{27BF}' | '\u{FE0E}' | '\u{FE0F}'
959    )
960}
961
962#[inline]
963fn map_fullwidth_punct(c: char) -> char {
964    match c {
965        '/' => '/',
966        '-' => '-',
967        ':' => ':',
968        ',' => ',',
969        '.' => '.',
970        '\u{00A0}' | '\u{2007}' | '\u{2009}' | '\u{202F}' | '\u{3000}' => ' ',
971        _ => c,
972    }
973}
974
975/// Clean invisible Unicode controls, fullwidth ASCII punctuation, and leading/trailing emoji
976/// without altering case or stripping NUL bytes. Zero-alloc when no changes are needed.
977pub fn clean_unicode_surface(input: &str) -> Cow<'_, str> {
978    if input.contains('\0') {
979        return Cow::Borrowed(input);
980    }
981    let keep_zwsp = has_khmer_chars(input);
982    let needs_clean = input.bytes().any(|b| b >= 0x80)
983        && input.chars().any(|c| {
984            is_invisible_format_control(c, keep_zwsp)
985                || is_edge_emoji(c)
986                || matches!(
987                    c,
988                    '/' | '-' | ':' | ',' | '.' | '\u{00A0}' | '\u{2007}' | '\u{2009}' | '\u{202F}' | '\u{3000}'
989                )
990        });
991    if !needs_clean {
992        return Cow::Borrowed(input);
993    }
994
995    let trimmed = input.trim_matches(|c: char| c.is_whitespace() || is_edge_emoji(c));
996    let mut out = String::with_capacity(trimmed.len());
997    for ch in trimmed.chars() {
998        if is_invisible_format_control(ch, keep_zwsp) {
999            continue;
1000        }
1001        out.push(map_fullwidth_punct(ch));
1002    }
1003    Cow::Owned(out)
1004}
1005
1006/// Returns `true` if `ch` is an ASCII digit or a Unicode decimal digit across all 76 `Nd` scripts.
1007#[inline]
1008pub fn is_unicode_decimal_digit(ch: char) -> bool {
1009    crate::numerals::is_unicode_decimal_digit(ch)
1010}
1011
1012/// Normalize all 76 Unicode `Nd` decimal numeral systems to ASCII 0-9, strip invisible Unicode
1013/// format controls, normalize fullwidth punctuation, and lowercase cleanly for fast matching.
1014pub fn normalize_digits_and_lower(input: &str) -> String {
1015    let keep_zwsp = has_khmer_chars(input);
1016    let mut out = String::with_capacity(input.len());
1017    let mut prev_space = true;
1018    for ch in input.chars() {
1019        if is_invisible_format_control(ch, keep_zwsp) {
1020            continue;
1021        }
1022        let mapped = match ch {
1023            // Turkish dotted/dotless I normalization to match lowercase tables cleanly
1024            '\u{0130}' => 'i',
1025            other => {
1026                let nd = crate::numerals::normalize_nd_char(other);
1027                if nd != other {
1028                    nd
1029                } else {
1030                    map_fullwidth_punct(other)
1031                }
1032            }
1033        };
1034        if mapped.is_whitespace() {
1035            if !prev_space {
1036                out.push(' ');
1037                prev_space = true;
1038            }
1039        } else if mapped == '\u{0307}' {
1040            continue;
1041        } else {
1042            for lc in mapped.to_lowercase() {
1043                if lc != '\u{0307}' {
1044                    out.push(lc);
1045                }
1046            }
1047            prev_space = false;
1048        }
1049    }
1050    if out.ends_with(' ') {
1051        out.pop();
1052    }
1053    out
1054}