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 f = fold_diacritics(&name);
164                    if f != name {
165                        folded_months.entry(f).or_insert(month_num);
166                    }
167                    months.insert(name, month_num);
168                }
169            }
170
171            let mut weekdays = FxHashMap::default();
172            let mut folded_weekdays = FxHashMap::default();
173            for (d_idx, names) in raw.weekdays.into_iter().enumerate() {
174                let wd_num = d_idx 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 f = fold_diacritics(&name);
183                    if f != name {
184                        folded_weekdays.entry(f).or_insert(wd_num);
185                    }
186                    weekdays.insert(name, wd_num);
187                }
188            }
189
190            let mut am = FxHashSet::default();
191            for s in raw.am {
192                register_token(&s, lang_id, true);
193                am.insert(s);
194            }
195            let mut pm = FxHashSet::default();
196            for s in raw.pm {
197                register_token(&s, lang_id, true);
198                pm.insert(s);
199            }
200
201            let mut units = FxHashMap::default();
202            let mut folded_units = FxHashMap::default();
203            for (tok, u_id) in raw.units {
204                if let Some(u) = TimeUnit::from_u8(u_id) {
205                    register_token(&tok, lang_id, true);
206                    let f = fold_diacritics(&tok);
207                    if f != tok {
208                        folded_units.entry(f).or_insert(u);
209                    }
210                    units.insert(tok, u);
211                }
212            }
213
214            let mut ago = FxHashSet::default();
215            let mut folded_ago = FxHashSet::default();
216            for s in raw.ago {
217                for part in s.split_whitespace() {
218                    register_token(part, lang_id, true);
219                }
220                register_token(&s, lang_id, true);
221                let f = fold_diacritics(&s);
222                if f != s {
223                    folded_ago.insert(f);
224                }
225                ago.insert(s);
226            }
227
228            let mut in_words = FxHashSet::default();
229            let mut folded_in_words = FxHashSet::default();
230            for s in raw.in_words {
231                for part in s.split_whitespace() {
232                    register_token(part, lang_id, true);
233                }
234                register_token(&s, lang_id, true);
235                let f = fold_diacritics(&s);
236                if f != s {
237                    folded_in_words.insert(f);
238                }
239                in_words.insert(s);
240            }
241
242            let mut skip = FxHashSet::default();
243            for s in raw.skip {
244                skip.insert(s);
245            }
246
247            let mut relative_exact: FxHashMap<String, Vec<RelativeSpec>> = FxHashMap::default();
248            let mut folded_relative_exact: FxHashMap<String, Vec<RelativeSpec>> =
249                FxHashMap::default();
250            for (phrase, sign, amount, u_id) in raw.relative_exact {
251                if let Some(unit) = TimeUnit::from_u8(u_id) {
252                    let spec = RelativeSpec { sign, amount, unit };
253                    for part in phrase.split_whitespace() {
254                        register_token(part, lang_id, true);
255                    }
256                    register_token(&phrase, lang_id, true);
257                    exact_phrase_index
258                        .entry(phrase.clone())
259                        .or_default()
260                        .push((lang_id, spec));
261                    let f = fold_diacritics(&phrase);
262                    if f != phrase {
263                        folded_exact_phrase_index
264                            .entry(f.clone())
265                            .or_default()
266                            .push((lang_id, spec));
267                        folded_relative_exact.entry(f).or_default().push(spec);
268                    }
269                    relative_exact.entry(phrase).or_default().push(spec);
270                }
271            }
272
273            let mut relative_affix = Vec::with_capacity(raw.relative_affix.len());
274            let mut folded_relative_affix = Vec::new();
275            for (prefix, suffix, sign, u_id) in raw.relative_affix {
276                if let Some(unit) = TimeUnit::from_u8(u_id) {
277                    for part in prefix.split_whitespace().chain(suffix.split_whitespace()) {
278                        if part.chars().count() >= 2 {
279                            register_token(part, lang_id, true);
280                        }
281                    }
282                    let fp = fold_diacritics(&prefix);
283                    let fs = fold_diacritics(&suffix);
284                    if fp != prefix || fs != suffix {
285                        folded_relative_affix.push(RelativeAffix {
286                            prefix: fp,
287                            suffix: fs,
288                            sign,
289                            unit,
290                        });
291                    }
292                    relative_affix.push(RelativeAffix {
293                        prefix,
294                        suffix,
295                        sign,
296                        unit,
297                    });
298                }
299            }
300            // Match longest affixes first for specificity
301            let sort_affix = |v: &mut Vec<RelativeAffix>| {
302                v.sort_by(|a, b| {
303                    let la = a.prefix.len() + a.suffix.len();
304                    let lb = b.prefix.len() + b.suffix.len();
305                    lb.cmp(&la)
306                });
307            };
308            sort_affix(&mut relative_affix);
309            sort_affix(&mut folded_relative_affix);
310
311            let mut word_numbers = FxHashMap::default();
312            for (w, n) in raw.word_numbers {
313                let f = fold_diacritics(&w);
314                if f != w {
315                    word_numbers.entry(f).or_insert(n);
316                }
317                word_numbers.insert(w, n);
318            }
319
320            let mut time_of_day = FxHashMap::default();
321            let mut folded_time_of_day = FxHashMap::default();
322            for (phrase, hour) in raw.time_of_day {
323                for part in phrase.split_whitespace() {
324                    register_token(part, lang_id, true);
325                }
326                register_token(&phrase, lang_id, true);
327                let f = fold_diacritics(&phrase);
328                if f != phrase {
329                    folded_time_of_day.entry(f).or_insert(hour);
330                }
331                time_of_day.insert(phrase, hour);
332            }
333
334            // Ensure key compound time-of-day trigger words are indexed for search_dates / lang detect
335            if raw.code == "en" {
336                register_token("tonight", lang_id, true);
337            } else if raw.code == "es" {
338                register_token("anoche", lang_id, true);
339            } else if raw.code == "tr" {
340                register_token("saat", lang_id, true);
341            }
342
343            locales.push(CompiledLocale {
344                id: lang_id,
345                code: raw.code,
346                date_order,
347                months,
348                weekdays,
349                am,
350                pm,
351                units,
352                ago,
353                in_words,
354                skip,
355                relative_exact,
356                relative_affix,
357                word_numbers,
358                time_of_day,
359                folded_months,
360                folded_weekdays,
361                folded_units,
362                folded_ago,
363                folded_in_words,
364                folded_relative_exact,
365                folded_relative_affix,
366                folded_time_of_day,
367            });
368        }
369
370        Self {
371            locales,
372            code_to_id,
373            token_to_langs,
374            folded_token_to_langs,
375            exact_phrase_index,
376            folded_exact_phrase_index,
377            known_date_tokens,
378        }
379    }
380
381    pub fn resolve_lang_id(&self, code: &str) -> Option<usize> {
382        let lower = code.trim().to_ascii_lowercase();
383        if let Some(&id) = self.code_to_id.get(&lower) {
384            return Some(id);
385        }
386        // Handle underscore/hyphen variants (e.g. "uz_cyrl" -> "uz-cyrl")
387        let dash = lower.replace('_', "-");
388        if let Some(&id) = self.code_to_id.get(&dash) {
389            return Some(id);
390        }
391        // Fallback: "en-US" or "tr_TR" -> "en" or "tr"
392        if let Some(base) = dash.split('-').next() {
393            if let Some(&id) = self.code_to_id.get(base) {
394                return Some(id);
395            }
396        }
397        // Legacy / ISO 639-1 macro aliases when exact code isn't present
398        let aliased = match lower.as_str() {
399            "no" => Some("nb"),
400            "iw" => Some("he"),
401            "in" => Some("id"),
402            "ji" => Some("yi"),
403            "fil" => Some("tl"),
404            _ => None,
405        };
406        if let Some(target) = aliased {
407            if let Some(&id) = self.code_to_id.get(target) {
408                return Some(id);
409            }
410        }
411        None
412    }
413
414    /// Detect top candidate language IDs in O(tokens) time without scanning all 205 locales.
415    pub fn detect_candidates(
416        &self,
417        normalized: &str,
418        tokens: &[&str],
419        explicit_langs: Option<&[String]>,
420        default_langs: &[String],
421        normalize: bool,
422        use_given_order: bool,
423    ) -> Vec<usize> {
424        if let Some(langs) = explicit_langs {
425            if !langs.is_empty() {
426                let mut out = Vec::with_capacity(langs.len());
427                for code in langs {
428                    if let Some(id) = self.resolve_lang_id(code) {
429                        if !out.contains(&id) {
430                            out.push(id);
431                        }
432                    }
433                }
434                return out;
435            }
436        }
437
438        let order_with_defaults = |mut ids: Vec<usize>| -> Vec<usize> {
439            if use_given_order && !default_langs.is_empty() {
440                let mut ordered = Vec::with_capacity(ids.len());
441                for code in default_langs {
442                    if let Some(did) = self.resolve_lang_id(code) {
443                        if ids.contains(&did) && !ordered.contains(&did) {
444                            ordered.push(did);
445                        }
446                    }
447                }
448                for id in ids {
449                    if !ordered.contains(&id) {
450                        ordered.push(id);
451                    }
452                }
453                ids = ordered;
454            }
455            ids
456        };
457
458        // Fast exact relative phrase lookup
459        if let Some(matches) = self.exact_phrase_index.get(normalized) {
460            let mut out: Vec<usize> = matches.iter().map(|(id, _)| *id as usize).collect();
461            out.sort_unstable();
462            out.dedup();
463            return order_with_defaults(out);
464        }
465
466        if normalize {
467            let f = fold_diacritics(normalized);
468            if let Some(matches) = self.folded_exact_phrase_index.get(&f) {
469                let mut out: Vec<usize> = matches.iter().map(|(id, _)| *id as usize).collect();
470                out.sort_unstable();
471                out.dedup();
472                return order_with_defaults(out);
473            }
474        }
475
476        // Script-based fast narrowing for non-Latin scripts
477        let script_hint = detect_script_hint(normalized);
478
479        let mut scores: FxHashMap<u16, u32> = FxHashMap::default();
480        for &tok in tokens {
481            if tok.len() <= 1 && tok.is_ascii() {
482                continue;
483            }
484            if let Some(langs) = self.token_to_langs.get(tok) {
485                let weight = if langs.len() <= 3 {
486                    8
487                } else if langs.len() <= 12 {
488                    4
489                } else {
490                    2
491                };
492                for &lid in langs {
493                    *scores.entry(lid).or_insert(0) += weight;
494                }
495            }
496            if normalize {
497                let ft = fold_diacritics(tok);
498                if let Some(langs) = self.folded_token_to_langs.get(&ft) {
499                    let weight = if langs.len() <= 3 {
500                        5
501                    } else if langs.len() <= 12 {
502                        3
503                    } else {
504                        1
505                    };
506                    for &lid in langs {
507                        *scores.entry(lid).or_insert(0) += weight;
508                    }
509                }
510            }
511        }
512
513        // Also check 2-word phrases (e.g. "il y a", "geçen hafta", "next week", "hace 2")
514        for w in tokens.windows(2) {
515            let bigram = format!("{} {}", w[0], w[1]);
516            if let Some(langs) = self.token_to_langs.get(&bigram) {
517                for &lid in langs {
518                    *scores.entry(lid).or_insert(0) += 6;
519                }
520            }
521            if normalize {
522                let fb = fold_diacritics(&bigram);
523                if fb != bigram {
524                    if let Some(langs) = self.folded_token_to_langs.get(&fb) {
525                        for &lid in langs {
526                            *scores.entry(lid).or_insert(0) += 4;
527                        }
528                    }
529                }
530            }
531        }
532
533        // Boost script-matched languages (crucial for CJK/Arabic/Thai where no spaces exist)
534        if let Some(hint_codes) = script_hint {
535            for code in hint_codes {
536                if let Some(id) = self.resolve_lang_id(code) {
537                    *scores.entry(id as u16).or_insert(0) += 5;
538                }
539            }
540        }
541
542        // Slight tie-break boost for default_languages
543        for code in default_langs {
544            if let Some(id) = self.resolve_lang_id(code) {
545                if let Some(sc) = scores.get_mut(&(id as u16)) {
546                    *sc += 2;
547                }
548            }
549        }
550
551        if scores.is_empty() {
552            return Vec::new();
553        }
554
555        let mut ranked: Vec<(u16, u32)> = scores.into_iter().collect();
556        // Highest score first; ties broken by global language priority (lower id = higher priority)
557        ranked.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
558
559        let top: Vec<usize> = ranked.into_iter().take(8).map(|(id, _)| id as usize).collect();
560        order_with_defaults(top)
561    }
562}
563
564/// Fold common Latin and Arabic diacritics for accent-tolerant matching (`NORMALIZE=True`).
565pub fn fold_diacritics(s: &str) -> String {
566    let mut out = String::with_capacity(s.len());
567    for ch in s.chars() {
568        let mapped = match ch {
569            'á' | 'à' | 'â' | 'ä' | 'ã' | 'å' | 'ā' | 'ă' | 'ą' => 'a',
570            'é' | 'è' | 'ê' | 'ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => 'e',
571            'í' | 'ì' | 'î' | 'ï' | 'ī' | 'ĭ' | 'į' | 'ı' => 'i',
572            'ó' | 'ò' | 'ô' | 'ö' | 'õ' | 'ø' | 'ō' | 'ŏ' | 'ő' => 'o',
573            'ú' | 'ù' | 'û' | 'ü' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => 'u',
574            'ç' | 'ć' | 'ĉ' | 'ċ' | 'č' => 'c',
575            'ğ' | 'ĝ' | 'ġ' | 'ģ' => 'g',
576            'ş' | 'ś' | 'ŝ' | 'š' => 's',
577            'ñ' | 'ń' | 'ņ' | 'ň' => 'n',
578            'ý' | 'ÿ' | 'ŷ' => 'y',
579            'ž' | 'ź' | 'ż' => 'z',
580            'ł' | 'ĺ' | 'ļ' | 'ľ' => 'l',
581            'ř' | 'ŕ' | 'ŗ' => 'r',
582            'ď' | 'đ' => 'd',
583            'ť' | 'ţ' => 't',
584            // Arabic alef normalization & harakat/tatweel stripping
585            'أ' | 'إ' | 'آ' | 'ٱ' => 'ا',
586            'ى' => 'ي',
587            '\u{064B}'..='\u{065F}' | '\u{0670}' | '\u{0640}' | '\u{0300}'..='\u{036F}' => {
588                continue;
589            }
590            other => other,
591        };
592        out.push(mapped);
593    }
594    out
595}
596
597fn detect_script_hint(s: &str) -> Option<&'static [&'static str]> {
598    let mut has_hiragana_katakana = false;
599    let mut has_han = false;
600    let mut has_hangul = false;
601    let mut has_cyrillic = false;
602    let mut has_arabic = false;
603    let mut has_hebrew = false;
604    let mut has_greek = false;
605    let mut has_thai = false;
606    let mut has_devanagari = false;
607
608    for ch in s.chars() {
609        let c = ch as u32;
610        match c {
611            0x3040..=0x30FF => has_hiragana_katakana = true,
612            0x4E00..=0x9FFF => has_han = true,
613            0xAC00..=0xD7AF => has_hangul = true,
614            0x0400..=0x04FF => has_cyrillic = true,
615            0x0600..=0x06FF => has_arabic = true,
616            0x0590..=0x05FF => has_hebrew = true,
617            0x0370..=0x03FF => has_greek = true,
618            0x0E00..=0x0E7F => has_thai = true,
619            0x0900..=0x097F => has_devanagari = true,
620            _ => {}
621        }
622    }
623
624    if has_hiragana_katakana {
625        Some(&["ja"])
626    } else if has_hangul {
627        Some(&["ko"])
628    } else if has_han {
629        Some(&["zh", "ja"])
630    } else if has_cyrillic {
631        Some(&["ru", "uk", "bg", "sr", "be", "kk"])
632    } else if has_arabic {
633        Some(&["ar", "fa", "ur"])
634    } else if has_hebrew {
635        Some(&["he"])
636    } else if has_greek {
637        Some(&["el"])
638    } else if has_thai {
639        Some(&["th"])
640    } else if has_devanagari {
641        Some(&["hi", "mr", "ne"])
642    } else {
643        None
644    }
645}
646
647/// Normalize Unicode digits (Arabic-Indic, Eastern Arabic, Devanagari, Fullwidth) to ASCII 0-9
648/// and collapse whitespace/punctuation for fast matching.
649pub fn normalize_digits_and_lower(input: &str) -> String {
650    let mut out = String::with_capacity(input.len());
651    let mut prev_space = true;
652    for ch in input.chars() {
653        let mapped = match ch {
654            '\u{0660}'..='\u{0669}' => char::from_u32('0' as u32 + (ch as u32 - 0x0660)).unwrap(),
655            '\u{06F0}'..='\u{06F9}' => char::from_u32('0' as u32 + (ch as u32 - 0x06F0)).unwrap(),
656            '\u{0966}'..='\u{096F}' => char::from_u32('0' as u32 + (ch as u32 - 0x0966)).unwrap(),
657            '\u{FF10}'..='\u{FF19}' => char::from_u32('0' as u32 + (ch as u32 - 0xFF10)).unwrap(),
658            // Turkish dotted/dotless I normalization to match lowercase tables cleanly
659            '\u{0130}' => 'i',
660            '\u{00A0}' | '\u{2009}' | '\u{202F}' => ' ',
661            other => other,
662        };
663        if mapped.is_whitespace() {
664            if !prev_space {
665                out.push(' ');
666                prev_space = true;
667            }
668        } else if mapped == '\u{0307}' {
669            continue;
670        } else {
671            for lc in mapped.to_lowercase() {
672                if lc != '\u{0307}' {
673                    out.push(lc);
674                }
675            }
676            prev_space = false;
677        }
678    }
679    if out.ends_with(' ') {
680        out.pop();
681    }
682    out
683}