dateoxide-core 0.1.0

High-performance, low-memory multilingual natural-language date parser core in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
pub mod schema;

use crate::settings::DateOrder;
use rustc_hash::{FxHashMap, FxHashSet};
use schema::RawLocale;
use std::sync::OnceLock;

static EMBEDDED_LOCALES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/locales.bin"));
static REGISTRY: OnceLock<LocaleRegistry> = OnceLock::new();

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum TimeUnit {
    Year = 0,
    Month = 1,
    Week = 2,
    Day = 3,
    Hour = 4,
    Minute = 5,
    Second = 6,
    Decade = 7,
    Century = 8,
    Fortnight = 9,
}

impl TimeUnit {
    #[inline]
    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            0 => Some(Self::Year),
            1 => Some(Self::Month),
            2 => Some(Self::Week),
            3 => Some(Self::Day),
            4 => Some(Self::Hour),
            5 => Some(Self::Minute),
            6 => Some(Self::Second),
            7 => Some(Self::Decade),
            8 => Some(Self::Century),
            9 => Some(Self::Fortnight),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RelativeSpec {
    /// -1 for past ("ago"), +1 for future ("in")
    pub sign: i8,
    pub amount: i32,
    pub unit: TimeUnit,
}

#[derive(Debug, Clone)]
pub struct RelativeAffix {
    pub prefix: String,
    pub suffix: String,
    pub sign: i8,
    pub unit: TimeUnit,
}

#[derive(Debug)]
pub struct CompiledLocale {
    pub id: u16,
    pub code: String,
    pub date_order: DateOrder,
    pub months: FxHashMap<String, u8>,
    pub weekdays: FxHashMap<String, u8>,
    pub am: FxHashSet<String>,
    pub pm: FxHashSet<String>,
    pub units: FxHashMap<String, TimeUnit>,
    pub ago: FxHashSet<String>,
    pub in_words: FxHashSet<String>,
    pub skip: FxHashSet<String>,
    pub relative_exact: FxHashMap<String, Vec<RelativeSpec>>,
    pub relative_affix: Vec<RelativeAffix>,
    pub word_numbers: FxHashMap<String, u32>,
    pub time_of_day: FxHashMap<String, u8>,
    // Diacritic-folded secondary tables (populated only where folded != exact)
    pub folded_months: FxHashMap<String, u8>,
    pub folded_weekdays: FxHashMap<String, u8>,
    pub folded_units: FxHashMap<String, TimeUnit>,
    pub folded_ago: FxHashSet<String>,
    pub folded_in_words: FxHashSet<String>,
    pub folded_relative_exact: FxHashMap<String, Vec<RelativeSpec>>,
    pub folded_relative_affix: Vec<RelativeAffix>,
    pub folded_time_of_day: FxHashMap<String, u8>,
}

pub struct LocaleRegistry {
    pub locales: Vec<CompiledLocale>,
    pub code_to_id: FxHashMap<String, usize>,
    /// Global inverted index: lowercase token -> priority-ordered list of locale IDs.
    pub token_to_langs: FxHashMap<String, Vec<u16>>,
    /// Folded inverted index: diacritic-folded token -> priority-ordered list of locale IDs.
    pub folded_token_to_langs: FxHashMap<String, Vec<u16>>,
    /// Global exact relative phrase index: phrase -> list of (lang_id, RelativeSpec).
    pub exact_phrase_index: FxHashMap<String, Vec<(u16, RelativeSpec)>>,
    /// Folded exact relative phrase index: folded phrase -> list of (lang_id, RelativeSpec).
    pub folded_exact_phrase_index: FxHashMap<String, Vec<(u16, RelativeSpec)>>,
    /// Tokens that can start or belong to a date expression (used for fast search_dates).
    pub known_date_tokens: FxHashSet<String>,
}

impl LocaleRegistry {
    #[inline]
    pub fn global() -> &'static Self {
        REGISTRY.get_or_init(Self::load)
    }

    fn load() -> Self {
        let raw_locales: Vec<RawLocale> = postcard::from_bytes(EMBEDDED_LOCALES)
            .expect("embedded locales.bin must deserialize cleanly");

        let mut locales = Vec::with_capacity(raw_locales.len());
        let mut code_to_id = FxHashMap::default();
        let mut token_to_langs: FxHashMap<String, Vec<u16>> = FxHashMap::default();
        let mut folded_token_to_langs: FxHashMap<String, Vec<u16>> = FxHashMap::default();
        let mut exact_phrase_index: FxHashMap<String, Vec<(u16, RelativeSpec)>> =
            FxHashMap::default();
        let mut folded_exact_phrase_index: FxHashMap<String, Vec<(u16, RelativeSpec)>> =
            FxHashMap::default();
        let mut known_date_tokens: FxHashSet<String> = FxHashSet::default();

        let mut register_token = |tok: &str, lang_id: u16, is_search_token: bool| {
            if tok.is_empty() {
                return;
            }
            let entry = token_to_langs.entry(tok.to_string()).or_default();
            if entry.last().copied() != Some(lang_id) && !entry.contains(&lang_id) {
                entry.push(lang_id);
            }
            if is_search_token {
                known_date_tokens.insert(tok.to_string());
            }
            let folded = fold_diacritics(tok);
            if folded != tok && !folded.is_empty() {
                let fentry = folded_token_to_langs.entry(folded.clone()).or_default();
                if fentry.last().copied() != Some(lang_id) && !fentry.contains(&lang_id) {
                    fentry.push(lang_id);
                }
                if is_search_token {
                    known_date_tokens.insert(folded);
                }
            }
        };

        for (idx, raw) in raw_locales.into_iter().enumerate() {
            let lang_id = idx as u16;
            code_to_id.insert(raw.code.to_ascii_lowercase(), idx);
            let date_order = DateOrder::from_str(&raw.date_order).unwrap_or(DateOrder::DMY);

            let mut months = FxHashMap::default();
            let mut folded_months = FxHashMap::default();
            for (m_idx, names) in raw.months.into_iter().enumerate() {
                let month_num = (m_idx + 1) as u8;
                for name in names {
                    for part in name.split_whitespace() {
                        if part.chars().count() >= 2 {
                            register_token(part, lang_id, true);
                        }
                    }
                    register_token(&name, lang_id, true);
                    let f = fold_diacritics(&name);
                    if f != name {
                        folded_months.entry(f).or_insert(month_num);
                    }
                    months.insert(name, month_num);
                }
            }

            let mut weekdays = FxHashMap::default();
            let mut folded_weekdays = FxHashMap::default();
            for (d_idx, names) in raw.weekdays.into_iter().enumerate() {
                let wd_num = d_idx as u8;
                for name in names {
                    for part in name.split_whitespace() {
                        if part.chars().count() >= 2 {
                            register_token(part, lang_id, true);
                        }
                    }
                    register_token(&name, lang_id, true);
                    let f = fold_diacritics(&name);
                    if f != name {
                        folded_weekdays.entry(f).or_insert(wd_num);
                    }
                    weekdays.insert(name, wd_num);
                }
            }

            let mut am = FxHashSet::default();
            for s in raw.am {
                register_token(&s, lang_id, true);
                am.insert(s);
            }
            let mut pm = FxHashSet::default();
            for s in raw.pm {
                register_token(&s, lang_id, true);
                pm.insert(s);
            }

            let mut units = FxHashMap::default();
            let mut folded_units = FxHashMap::default();
            for (tok, u_id) in raw.units {
                if let Some(u) = TimeUnit::from_u8(u_id) {
                    register_token(&tok, lang_id, true);
                    let f = fold_diacritics(&tok);
                    if f != tok {
                        folded_units.entry(f).or_insert(u);
                    }
                    units.insert(tok, u);
                }
            }

            let mut ago = FxHashSet::default();
            let mut folded_ago = FxHashSet::default();
            for s in raw.ago {
                for part in s.split_whitespace() {
                    register_token(part, lang_id, true);
                }
                register_token(&s, lang_id, true);
                let f = fold_diacritics(&s);
                if f != s {
                    folded_ago.insert(f);
                }
                ago.insert(s);
            }

            let mut in_words = FxHashSet::default();
            let mut folded_in_words = FxHashSet::default();
            for s in raw.in_words {
                for part in s.split_whitespace() {
                    register_token(part, lang_id, true);
                }
                register_token(&s, lang_id, true);
                let f = fold_diacritics(&s);
                if f != s {
                    folded_in_words.insert(f);
                }
                in_words.insert(s);
            }

            let mut skip = FxHashSet::default();
            for s in raw.skip {
                skip.insert(s);
            }

            let mut relative_exact: FxHashMap<String, Vec<RelativeSpec>> = FxHashMap::default();
            let mut folded_relative_exact: FxHashMap<String, Vec<RelativeSpec>> =
                FxHashMap::default();
            for (phrase, sign, amount, u_id) in raw.relative_exact {
                if let Some(unit) = TimeUnit::from_u8(u_id) {
                    let spec = RelativeSpec { sign, amount, unit };
                    for part in phrase.split_whitespace() {
                        register_token(part, lang_id, true);
                    }
                    register_token(&phrase, lang_id, true);
                    exact_phrase_index
                        .entry(phrase.clone())
                        .or_default()
                        .push((lang_id, spec));
                    let f = fold_diacritics(&phrase);
                    if f != phrase {
                        folded_exact_phrase_index
                            .entry(f.clone())
                            .or_default()
                            .push((lang_id, spec));
                        folded_relative_exact.entry(f).or_default().push(spec);
                    }
                    relative_exact.entry(phrase).or_default().push(spec);
                }
            }

            let mut relative_affix = Vec::with_capacity(raw.relative_affix.len());
            let mut folded_relative_affix = Vec::new();
            for (prefix, suffix, sign, u_id) in raw.relative_affix {
                if let Some(unit) = TimeUnit::from_u8(u_id) {
                    for part in prefix.split_whitespace().chain(suffix.split_whitespace()) {
                        if part.chars().count() >= 2 {
                            register_token(part, lang_id, true);
                        }
                    }
                    let fp = fold_diacritics(&prefix);
                    let fs = fold_diacritics(&suffix);
                    if fp != prefix || fs != suffix {
                        folded_relative_affix.push(RelativeAffix {
                            prefix: fp,
                            suffix: fs,
                            sign,
                            unit,
                        });
                    }
                    relative_affix.push(RelativeAffix {
                        prefix,
                        suffix,
                        sign,
                        unit,
                    });
                }
            }
            // Match longest affixes first for specificity
            let sort_affix = |v: &mut Vec<RelativeAffix>| {
                v.sort_by(|a, b| {
                    let la = a.prefix.len() + a.suffix.len();
                    let lb = b.prefix.len() + b.suffix.len();
                    lb.cmp(&la)
                });
            };
            sort_affix(&mut relative_affix);
            sort_affix(&mut folded_relative_affix);

            let mut word_numbers = FxHashMap::default();
            for (w, n) in raw.word_numbers {
                let f = fold_diacritics(&w);
                if f != w {
                    word_numbers.entry(f).or_insert(n);
                }
                word_numbers.insert(w, n);
            }

            let mut time_of_day = FxHashMap::default();
            let mut folded_time_of_day = FxHashMap::default();
            for (phrase, hour) in raw.time_of_day {
                for part in phrase.split_whitespace() {
                    register_token(part, lang_id, true);
                }
                register_token(&phrase, lang_id, true);
                let f = fold_diacritics(&phrase);
                if f != phrase {
                    folded_time_of_day.entry(f).or_insert(hour);
                }
                time_of_day.insert(phrase, hour);
            }

            // Ensure key compound time-of-day trigger words are indexed for search_dates / lang detect
            if raw.code == "en" {
                register_token("tonight", lang_id, true);
            } else if raw.code == "es" {
                register_token("anoche", lang_id, true);
            } else if raw.code == "tr" {
                register_token("saat", lang_id, true);
            }

            locales.push(CompiledLocale {
                id: lang_id,
                code: raw.code,
                date_order,
                months,
                weekdays,
                am,
                pm,
                units,
                ago,
                in_words,
                skip,
                relative_exact,
                relative_affix,
                word_numbers,
                time_of_day,
                folded_months,
                folded_weekdays,
                folded_units,
                folded_ago,
                folded_in_words,
                folded_relative_exact,
                folded_relative_affix,
                folded_time_of_day,
            });
        }

        Self {
            locales,
            code_to_id,
            token_to_langs,
            folded_token_to_langs,
            exact_phrase_index,
            folded_exact_phrase_index,
            known_date_tokens,
        }
    }

    pub fn resolve_lang_id(&self, code: &str) -> Option<usize> {
        let lower = code.trim().to_ascii_lowercase();
        if let Some(&id) = self.code_to_id.get(&lower) {
            return Some(id);
        }
        // Handle underscore/hyphen variants (e.g. "uz_cyrl" -> "uz-cyrl")
        let dash = lower.replace('_', "-");
        if let Some(&id) = self.code_to_id.get(&dash) {
            return Some(id);
        }
        // Fallback: "en-US" or "tr_TR" -> "en" or "tr"
        if let Some(base) = dash.split('-').next() {
            if let Some(&id) = self.code_to_id.get(base) {
                return Some(id);
            }
        }
        None
    }

    /// Detect top candidate language IDs in O(tokens) time without scanning all 205 locales.
    pub fn detect_candidates(
        &self,
        normalized: &str,
        tokens: &[&str],
        explicit_langs: Option<&[String]>,
        default_langs: &[String],
        normalize: bool,
    ) -> Vec<usize> {
        if let Some(langs) = explicit_langs {
            if !langs.is_empty() {
                let mut out = Vec::with_capacity(langs.len());
                for code in langs {
                    if let Some(id) = self.resolve_lang_id(code) {
                        if !out.contains(&id) {
                            out.push(id);
                        }
                    }
                }
                return out;
            }
        }

        // Fast exact relative phrase lookup
        if let Some(matches) = self.exact_phrase_index.get(normalized) {
            let mut out: Vec<usize> = matches.iter().map(|(id, _)| *id as usize).collect();
            out.sort_unstable();
            out.dedup();
            return out;
        }

        if normalize {
            let f = fold_diacritics(normalized);
            if let Some(matches) = self.folded_exact_phrase_index.get(&f) {
                let mut out: Vec<usize> = matches.iter().map(|(id, _)| *id as usize).collect();
                out.sort_unstable();
                out.dedup();
                return out;
            }
        }

        // Script-based fast narrowing for non-Latin scripts
        let script_hint = detect_script_hint(normalized);

        let mut scores: FxHashMap<u16, u32> = FxHashMap::default();
        for &tok in tokens {
            if tok.len() <= 1 && tok.is_ascii() {
                continue;
            }
            if let Some(langs) = self.token_to_langs.get(tok) {
                let weight = if langs.len() <= 3 {
                    8
                } else if langs.len() <= 12 {
                    4
                } else {
                    2
                };
                for &lid in langs {
                    *scores.entry(lid).or_insert(0) += weight;
                }
            }
            if normalize {
                let ft = fold_diacritics(tok);
                if let Some(langs) = self.folded_token_to_langs.get(&ft) {
                    let weight = if langs.len() <= 3 {
                        5
                    } else if langs.len() <= 12 {
                        3
                    } else {
                        1
                    };
                    for &lid in langs {
                        *scores.entry(lid).or_insert(0) += weight;
                    }
                }
            }
        }

        // Also check 2-word phrases (e.g. "il y a", "geçen hafta", "next week", "hace 2")
        for w in tokens.windows(2) {
            let bigram = format!("{} {}", w[0], w[1]);
            if let Some(langs) = self.token_to_langs.get(&bigram) {
                for &lid in langs {
                    *scores.entry(lid).or_insert(0) += 6;
                }
            }
            if normalize {
                let fb = fold_diacritics(&bigram);
                if fb != bigram {
                    if let Some(langs) = self.folded_token_to_langs.get(&fb) {
                        for &lid in langs {
                            *scores.entry(lid).or_insert(0) += 4;
                        }
                    }
                }
            }
        }

        // Boost script-matched languages (crucial for CJK/Arabic/Thai where no spaces exist)
        if let Some(hint_codes) = script_hint {
            for code in hint_codes {
                if let Some(id) = self.resolve_lang_id(code) {
                    *scores.entry(id as u16).or_insert(0) += 5;
                }
            }
        }

        // Slight tie-break boost for default_languages
        for code in default_langs {
            if let Some(id) = self.resolve_lang_id(code) {
                if let Some(sc) = scores.get_mut(&(id as u16)) {
                    *sc += 2;
                }
            }
        }

        if scores.is_empty() {
            return Vec::new();
        }

        let mut ranked: Vec<(u16, u32)> = scores.into_iter().collect();
        // Highest score first; ties broken by global language priority (lower id = higher priority)
        ranked.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));

        ranked.into_iter().take(8).map(|(id, _)| id as usize).collect()
    }
}

/// Fold common Latin and Arabic diacritics for accent-tolerant matching (`NORMALIZE=True`).
pub fn fold_diacritics(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        let mapped = match ch {
            'á' | 'à' | 'â' | 'ä' | 'ã' | 'å' | 'ā' | 'ă' | 'ą' => 'a',
            'é' | 'è' | 'ê' | 'ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => 'e',
            'í' | 'ì' | 'î' | 'ï' | 'ī' | 'ĭ' | 'į' | 'ı' => 'i',
            'ó' | 'ò' | 'ô' | 'ö' | 'õ' | 'ø' | 'ō' | 'ŏ' | 'ő' => 'o',
            'ú' | 'ù' | 'û' | 'ü' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => 'u',
            'ç' | 'ć' | 'ĉ' | 'ċ' | 'č' => 'c',
            'ğ' | 'ĝ' | 'ġ' | 'ģ' => 'g',
            'ş' | 'ś' | 'ŝ' | 'š' => 's',
            'ñ' | 'ń' | 'ņ' | 'ň' => 'n',
            'ý' | 'ÿ' | 'ŷ' => 'y',
            'ž' | 'ź' | 'ż' => 'z',
            'ł' | 'ĺ' | 'ļ' | 'ľ' => 'l',
            'ř' | 'ŕ' | 'ŗ' => 'r',
            'ď' | 'đ' => 'd',
            'ť' | 'ţ' => 't',
            // Arabic alef normalization & harakat/tatweel stripping
            'أ' | 'إ' | 'آ' | 'ٱ' => 'ا',
            'ى' => 'ي',
            '\u{064B}'..='\u{065F}' | '\u{0670}' | '\u{0640}' | '\u{0300}'..='\u{036F}' => {
                continue;
            }
            other => other,
        };
        out.push(mapped);
    }
    out
}

fn detect_script_hint(s: &str) -> Option<&'static [&'static str]> {
    let mut has_hiragana_katakana = false;
    let mut has_han = false;
    let mut has_hangul = false;
    let mut has_cyrillic = false;
    let mut has_arabic = false;
    let mut has_hebrew = false;
    let mut has_greek = false;
    let mut has_thai = false;
    let mut has_devanagari = false;

    for ch in s.chars() {
        let c = ch as u32;
        match c {
            0x3040..=0x30FF => has_hiragana_katakana = true,
            0x4E00..=0x9FFF => has_han = true,
            0xAC00..=0xD7AF => has_hangul = true,
            0x0400..=0x04FF => has_cyrillic = true,
            0x0600..=0x06FF => has_arabic = true,
            0x0590..=0x05FF => has_hebrew = true,
            0x0370..=0x03FF => has_greek = true,
            0x0E00..=0x0E7F => has_thai = true,
            0x0900..=0x097F => has_devanagari = true,
            _ => {}
        }
    }

    if has_hiragana_katakana {
        Some(&["ja"])
    } else if has_hangul {
        Some(&["ko"])
    } else if has_han {
        Some(&["zh", "ja"])
    } else if has_cyrillic {
        Some(&["ru", "uk", "bg", "sr", "be", "kk"])
    } else if has_arabic {
        Some(&["ar", "fa", "ur"])
    } else if has_hebrew {
        Some(&["he"])
    } else if has_greek {
        Some(&["el"])
    } else if has_thai {
        Some(&["th"])
    } else if has_devanagari {
        Some(&["hi", "mr", "ne"])
    } else {
        None
    }
}

/// Normalize Unicode digits (Arabic-Indic, Eastern Arabic, Devanagari, Fullwidth) to ASCII 0-9
/// and collapse whitespace/punctuation for fast matching.
pub fn normalize_digits_and_lower(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let mut prev_space = true;
    for ch in input.chars() {
        let mapped = match ch {
            '\u{0660}'..='\u{0669}' => char::from_u32('0' as u32 + (ch as u32 - 0x0660)).unwrap(),
            '\u{06F0}'..='\u{06F9}' => char::from_u32('0' as u32 + (ch as u32 - 0x06F0)).unwrap(),
            '\u{0966}'..='\u{096F}' => char::from_u32('0' as u32 + (ch as u32 - 0x0966)).unwrap(),
            '\u{FF10}'..='\u{FF19}' => char::from_u32('0' as u32 + (ch as u32 - 0xFF10)).unwrap(),
            // Turkish dotted/dotless I normalization to match lowercase tables cleanly
            '\u{0130}' => 'i',
            '\u{00A0}' | '\u{2009}' | '\u{202F}' => ' ',
            other => other,
        };
        if mapped.is_whitespace() {
            if !prev_space {
                out.push(' ');
                prev_space = true;
            }
        } else if mapped == '\u{0307}' {
            continue;
        } else {
            for lc in mapped.to_lowercase() {
                if lc != '\u{0307}' {
                    out.push(lc);
                }
            }
            prev_space = false;
        }
    }
    if out.ends_with(' ') {
        out.pop();
    }
    out
}