Skip to main content

native_gui_core/
i18n.rs

1//! Shared localization model (unblocks the `internat` example).
2//!
3//! Decisions frozen here:
4//! - **Fallback chain**: exact tag (`de-at`) → language (`de`) → app default
5//!   (exact → language) → the key itself. Missing keys are recorded, never
6//!   panics.
7//! - **Plural rules** are a deliberately small, deterministic CLDR-lite model:
8//!   English-family `one`/`other`, French zero-as-singular, the Slavic
9//!   `one`/`few`/`many` modulo sets (Polish and East Slavic differ on the
10//!   `one` form), Arabic's six categories, East Asian languages with no
11//!   plural distinction, and `other` for everything else. Catalogs declare
12//!   the forms they use.
13//! - **Number/date formatting** uses per-locale data shipped with this module
14//!   (separators and a few date patterns) — platform resource formats are
15//!   never hard-wired into the shared API, and unknown input passes through
16//!   unchanged.
17//! - **Runtime changes** switch the active locale in place; apps re-render the
18//!   strings they own (`set_locale` returns whether the locale changed).
19
20use std::collections::{HashMap, HashSet};
21use std::fmt;
22
23/// A normalized language tag such as `de-at` or `en`.
24#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
25pub struct Locale {
26    tag: String,
27    language: String,
28}
29
30impl Locale {
31    /// Parses and normalizes a tag: `_` becomes `-`, everything is
32    /// lowercased, and empty input becomes `und` (undetermined).
33    pub fn parse(tag: &str) -> Self {
34        let normalized = tag.trim().replace('_', "-").to_lowercase();
35        let normalized = if normalized.is_empty() {
36            "und".to_owned()
37        } else {
38            normalized
39        };
40        let language = normalized.split('-').next().unwrap_or("und").to_owned();
41        Self {
42            tag: normalized,
43            language,
44        }
45    }
46
47    /// The normalized full tag (`de-at`).
48    pub fn tag(&self) -> &str {
49        &self.tag
50    }
51
52    /// The language subtag (`de`).
53    pub fn language(&self) -> &str {
54        &self.language
55    }
56
57    /// The region subtag (`at`), when present.
58    pub fn region(&self) -> Option<&str> {
59        self.tag.split_once('-').map(|(_, region)| region)
60    }
61}
62
63impl fmt::Display for Locale {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.write_str(&self.tag)
66    }
67}
68
69/// Returns whether a locale conventionally lays out text right-to-left.
70pub fn is_rtl_locale(locale: &Locale) -> bool {
71    matches!(locale.language(), "ar" | "he" | "fa" | "ur")
72}
73
74/// Wraps text in a directional isolate for mixed-direction UI strings.
75pub fn isolate_text(locale: &Locale, text: &str) -> String {
76    let opener = if is_rtl_locale(locale) {
77        '\u{2067}'
78    } else {
79        '\u{2066}'
80    };
81    format!("{opener}{text}\u{2069}")
82}
83
84/// CLDR-lite plural categories.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
86pub enum PluralCategory {
87    Zero,
88    One,
89    Two,
90    Few,
91    Many,
92    Other,
93}
94
95impl PluralCategory {
96    /// Stable lowercase name, used in catalogs and diagnostics.
97    pub fn as_str(&self) -> &'static str {
98        match self {
99            PluralCategory::Zero => "zero",
100            PluralCategory::One => "one",
101            PluralCategory::Two => "two",
102            PluralCategory::Few => "few",
103            PluralCategory::Many => "many",
104            PluralCategory::Other => "other",
105        }
106    }
107}
108
109/// Deterministic CLDR-lite plural selection.
110///
111/// Rules are matched on the language subtag and the absolute count:
112///
113/// - `en`/`de`/`nl`/`es`/`it`/`pt`/`sv`: `one` for 1, `other` otherwise.
114/// - `fr`: `one` for 0 and 1 (French counts zero as a singular), `other` after.
115/// - `pl`: `one` (1), `few` (n mod 10 in 2..=4, excluding n mod 100 in
116///   12..=14), `many` (everything else — 21 and 101 are `many` in Polish).
117/// - `ru`/`uk`: `one` (n mod 10 is 1 and n mod 100 is not 11, so 21 and 101
118///   are `one`), `few` (n mod 10 in 2..=4, excluding n mod 100 in 12..=14),
119///   `many` (everything else).
120/// - `ar`: all six categories — `zero` (0), `one` (1), `two` (2), `few`
121///   (n mod 100 in 3..=10), `many` (n mod 100 in 11..=99), `other`.
122/// - `ja`/`zh`/`ko`/`th`/`vi`: no plural distinction, always `other`.
123/// - Anything else: `other`.
124pub fn plural_category(locale: &Locale, count: i64) -> PluralCategory {
125    let count = count.unsigned_abs();
126    match locale.language() {
127        "en" | "de" | "nl" | "es" | "it" | "pt" | "sv" => {
128            if count == 1 {
129                PluralCategory::One
130            } else {
131                PluralCategory::Other
132            }
133        }
134        "fr" => {
135            if count <= 1 {
136                PluralCategory::One
137            } else {
138                PluralCategory::Other
139            }
140        }
141        "pl" => {
142            let last_two = count % 100;
143            let last = count % 10;
144            if count == 1 {
145                PluralCategory::One
146            } else if (2..=4).contains(&last) && !(12..=14).contains(&last_two) {
147                PluralCategory::Few
148            } else {
149                PluralCategory::Many
150            }
151        }
152        "ru" | "uk" => {
153            let last_two = count % 100;
154            let last = count % 10;
155            if last == 1 && last_two != 11 {
156                PluralCategory::One
157            } else if (2..=4).contains(&last) && !(12..=14).contains(&last_two) {
158                PluralCategory::Few
159            } else {
160                PluralCategory::Many
161            }
162        }
163        "ar" => {
164            let last_two = count % 100;
165            if count == 0 {
166                PluralCategory::Zero
167            } else if count == 1 {
168                PluralCategory::One
169            } else if count == 2 {
170                PluralCategory::Two
171            } else if (3..=10).contains(&last_two) {
172                PluralCategory::Few
173            } else if (11..=99).contains(&last_two) {
174                PluralCategory::Many
175            } else {
176                PluralCategory::Other
177            }
178        }
179        "ja" | "zh" | "ko" | "th" | "vi" => PluralCategory::Other,
180        _ => PluralCategory::Other,
181    }
182}
183
184/// Deterministic CLDR-lite ordinal plural selection.
185///
186/// `en`: `one` (1), `two` (2), `few` (3), `other`.
187/// `fr`: `one` (1), `other`.
188/// `ar`: `one` (1), `two` (2), `few` (n % 100 in 3..=10), `many`
189/// (n % 100 in 11..=99), `other` — note the divergence from the cardinal
190/// rules: ordinals never select `zero`, so 0 is `other` (cardinal 0 is
191/// `zero`) and the category set is five-wide instead of six.
192/// Anything else: `other`.
193pub fn ordinal_category(locale: &Locale, count: i64) -> PluralCategory {
194    let count = count.unsigned_abs();
195    match locale.language() {
196        "en" => match count {
197            1 => PluralCategory::One,
198            2 => PluralCategory::Two,
199            3 => PluralCategory::Few,
200            _ => PluralCategory::Other,
201        },
202        "fr" => {
203            if count == 1 {
204                PluralCategory::One
205            } else {
206                PluralCategory::Other
207            }
208        }
209        "ar" => {
210            let last_two = count % 100;
211            if count == 1 {
212                PluralCategory::One
213            } else if count == 2 {
214                PluralCategory::Two
215            } else if (3..=10).contains(&last_two) {
216                PluralCategory::Few
217            } else if (11..=99).contains(&last_two) {
218                PluralCategory::Many
219            } else {
220                PluralCategory::Other
221            }
222        }
223        _ => PluralCategory::Other,
224    }
225}
226
227/// One catalog message.
228#[derive(Debug, Clone, PartialEq, Eq)]
229pub enum Message {
230    /// A single string; `{n}` substitutes the count when one is supplied.
231    Simple(String),
232    /// Plural forms; the first matching `PluralCategory` for the locale and
233    /// count is rendered, with `{n}` substituted.
234    Plural(Vec<(PluralCategory, String)>),
235}
236
237impl Message {
238    fn render(&self, locale: &Locale, count: Option<i64>) -> String {
239        match self {
240            Message::Simple(text) => match count {
241                Some(count) => text.replace("{n}", &count.to_string()),
242                None => text.clone(),
243            },
244            Message::Plural(forms) => {
245                let count = count.unwrap_or(0);
246                let category = plural_category(locale, count);
247                let template = forms
248                    .iter()
249                    .find(|(form, _)| *form == category)
250                    .or_else(|| {
251                        forms
252                            .iter()
253                            .find(|(form, _)| *form == PluralCategory::Other)
254                    })
255                    .map(|(_, text)| text.as_str())
256                    .unwrap_or("");
257                template.replace("{n}", &count.to_string())
258            }
259        }
260    }
261}
262
263/// Messages for one locale.
264#[derive(Debug, Clone, Default)]
265pub struct MessageCatalog {
266    messages: HashMap<String, Message>,
267}
268
269impl MessageCatalog {
270    /// Creates an empty catalog.
271    pub fn new() -> Self {
272        Self::default()
273    }
274
275    /// Inserts a simple message.
276    pub fn insert(&mut self, key: &str, text: &str) {
277        self.messages
278            .insert(key.to_owned(), Message::Simple(text.to_owned()));
279    }
280
281    /// Inserts a plural message; forms are tried in the given order.
282    pub fn insert_plural(&mut self, key: &str, forms: &[(PluralCategory, &str)]) {
283        self.messages.insert(
284            key.to_owned(),
285            Message::Plural(
286                forms
287                    .iter()
288                    .map(|(category, text)| (*category, (*text).to_owned()))
289                    .collect(),
290            ),
291        );
292    }
293
294    /// Number of stored messages.
295    pub fn len(&self) -> usize {
296        self.messages.len()
297    }
298
299    /// Whether the catalog has no messages.
300    pub fn is_empty(&self) -> bool {
301        self.messages.is_empty()
302    }
303
304    fn get(&self, key: &str) -> Option<&Message> {
305        self.messages.get(key)
306    }
307}
308
309/// Locale-aware lookup and formatting.
310#[derive(Debug)]
311pub struct Localizer {
312    default: Locale,
313    current: Locale,
314    catalogs: HashMap<String, MessageCatalog>,
315    missing: Vec<String>,
316    missing_set: HashSet<String>,
317}
318
319impl Localizer {
320    /// Creates a localizer with a default locale and no catalogs.
321    pub fn new(default: Locale) -> Self {
322        Self {
323            current: default.clone(),
324            default,
325            catalogs: HashMap::new(),
326            missing: Vec::new(),
327            missing_set: HashSet::new(),
328        }
329    }
330
331    /// Registers (or replaces) the catalog for a locale.
332    pub fn add_catalog(&mut self, locale: Locale, catalog: MessageCatalog) {
333        self.catalogs.insert(locale.tag, catalog);
334    }
335
336    /// The active locale.
337    pub fn locale(&self) -> &Locale {
338        &self.current
339    }
340
341    /// The default locale used at the end of the fallback chain.
342    pub fn default_locale(&self) -> &Locale {
343        &self.default
344    }
345
346    /// Switches the active locale; returns `true` when it changed.
347    pub fn set_locale(&mut self, locale: Locale) -> bool {
348        if self.current == locale {
349            false
350        } else {
351            self.current = locale;
352            true
353        }
354    }
355
356    /// Resolves `key` through the fallback chain: exact tag → language →
357    /// default exact → default language → the key itself (recorded as
358    /// missing). The key is returned when nothing matches.
359    pub fn tr(&mut self, key: &str) -> String {
360        if let Some(message) = self.lookup(key, None) {
361            return message;
362        }
363        self.note_missing(key);
364        key.to_owned()
365    }
366
367    /// Like [`Localizer::tr`] but renders the plural form for `count`.
368    pub fn trn(&mut self, key: &str, count: i64) -> String {
369        if let Some(message) = self.lookup(key, Some(count)) {
370            return message;
371        }
372        self.note_missing(key);
373        format!("{key} ({count})")
374    }
375
376    fn lookup(&self, key: &str, count: Option<i64>) -> Option<String> {
377        // Borrow the locale tags: cloning four Strings per lookup dominated
378        // the call and made every translated label allocate.
379        let tags = [
380            self.current.tag.as_str(),
381            self.current.language.as_str(),
382            self.default.tag.as_str(),
383            self.default.language.as_str(),
384        ];
385        for tag in tags {
386            if let Some(catalog) = self.catalogs.get(tag) {
387                if let Some(message) = catalog.get(key) {
388                    return Some(message.render(&self.current, count));
389                }
390            }
391        }
392        None
393    }
394
395    fn note_missing(&mut self, key: &str) {
396        if self.missing_set.insert(key.to_owned()) {
397            self.missing.push(key.to_owned());
398        }
399    }
400
401    /// Missing keys in first-seen order (deduplicated).
402    pub fn missing_keys(&self) -> &[String] {
403        &self.missing
404    }
405
406    /// Clears the missing-key log.
407    pub fn clear_missing_keys(&mut self) {
408        self.missing.clear();
409        self.missing_set.clear();
410    }
411
412    /// Formats a number with the active locale's separators.
413    ///
414    /// Locale data is intentionally small and deterministic: `de`/`es`/`it`/
415    /// `pt`/`ru`/`pl` group with `.` and separate decimals with `,`;
416    /// `fr` groups with a space; English-style locales group with `,` and
417    /// separate decimals with `.`. This is fixture-quality data for tests and
418    /// examples, not a full resource-format implementation.
419    pub fn format_number(&self, value: f64, decimals: usize) -> String {
420        let (group, decimal) = number_separators(self.current.language());
421        let negative = value.is_sign_negative() && value != 0.0;
422        let rendered = format!("{:.*}", decimals, value.abs());
423        let (integer, fraction) = match rendered.split_once('.') {
424            Some((integer, fraction)) => (integer.to_owned(), Some(fraction.to_owned())),
425            None => (rendered, None),
426        };
427
428        let mut grouped = String::new();
429        let digits: Vec<char> = integer.chars().collect();
430        for (index, digit) in digits.iter().enumerate() {
431            if index > 0 && (digits.len() - index).is_multiple_of(3) {
432                grouped.push(group);
433            }
434            grouped.push(*digit);
435        }
436
437        let mut result = String::new();
438        if negative {
439            result.push('-');
440        }
441        result.push_str(&grouped);
442        if let Some(fraction) = fraction {
443            result.push(decimal);
444            result.push_str(&fraction);
445        }
446        result
447    }
448
449    /// Formats an ISO `YYYY-MM-DD` date with the active locale's pattern:
450    /// `en-US` → `MM/DD/YYYY`, other `en` → `DD/MM/YYYY`, `de`/`ru`/`pl` →
451    /// `DD.MM.YYYY`, everything else → `DD/MM/YYYY`. Input that is not a
452    /// valid ISO date passes through unchanged.
453    pub fn format_date(&self, iso_date: &str) -> String {
454        let Some((year, month, day)) = parse_iso_date(iso_date) else {
455            return iso_date.to_owned();
456        };
457        match date_pattern(self.current.language(), self.current.region()) {
458            DatePattern::MonthDayYear => format!("{month:02}/{day:02}/{year:04}"),
459            DatePattern::DayMonthYear => format!("{day:02}/{month:02}/{year:04}"),
460            DatePattern::DayMonthYearDotted => format!("{day:02}.{month:02}.{year:04}"),
461        }
462    }
463}
464
465fn number_separators(language: &str) -> (char, char) {
466    match language {
467        "de" | "es" | "it" | "pt" | "ru" | "pl" => ('.', ','),
468        "fr" => (' ', ','),
469        _ => (',', '.'),
470    }
471}
472
473/// Deterministic CLDR-lite collation for UI sorting.
474///
475/// The default compares case-folded letters by code point, with non-letter
476/// characters after the letters. `sv` places `å ä ö` after `z`, and
477/// `da`/`nb`/`no` place `æ ø å` after `z` — the documented non-code-point
478/// tails this helper exists for. Case-folded equality reports `Equal` so
479/// stable sorts keep the caller's order.
480pub fn collate(locale: &Locale, left: &str, right: &str) -> std::cmp::Ordering {
481    sort_key(locale.language(), left)
482        .cmp(&sort_key(locale.language(), right))
483        .then_with(|| left.to_lowercase().cmp(&right.to_lowercase()))
484}
485
486fn sort_key(language: &str, text: &str) -> Vec<u32> {
487    let tail: &[char] = match language {
488        "sv" => &['å', 'ä', 'ö'],
489        "da" | "nb" | "no" => &['æ', 'ø', 'å'],
490        _ => &[],
491    };
492    text.chars()
493        .map(|ch| {
494            let lower = ch.to_lowercase().next().unwrap_or(ch);
495            if let Some(index) = tail.iter().position(|candidate| *candidate == lower) {
496                return 27 + index as u32;
497            }
498            if lower.is_ascii_lowercase() {
499                return (lower as u32 - 'a' as u32) + 1;
500            }
501            10_000 + lower as u32
502        })
503        .collect()
504}
505
506enum DatePattern {
507    MonthDayYear,
508    DayMonthYear,
509    DayMonthYearDotted,
510}
511
512fn date_pattern(language: &str, region: Option<&str>) -> DatePattern {
513    match language {
514        "en" => match region {
515            Some("us") | None => DatePattern::MonthDayYear,
516            _ => DatePattern::DayMonthYear,
517        },
518        "de" | "ru" | "pl" => DatePattern::DayMonthYearDotted,
519        _ => DatePattern::DayMonthYear,
520    }
521}
522
523fn parse_iso_date(iso_date: &str) -> Option<(u32, u32, u32)> {
524    let mut parts = iso_date.split('-');
525    let year: u32 = parts.next()?.parse().ok()?;
526    let month: u32 = parts.next()?.parse().ok()?;
527    let day: u32 = parts.next()?.parse().ok()?;
528    if parts.next().is_some() || !(1..=12).contains(&month) || !(1..=31).contains(&day) {
529        return None;
530    }
531    Some((year, month, day))
532}
533
534#[cfg(test)]
535mod tests {
536    use super::*;
537
538    #[test]
539    fn rtl_detection_and_isolation_are_deterministic() {
540        let arabic = Locale::parse("ar-EG");
541        let english = Locale::parse("en-US");
542        assert!(is_rtl_locale(&arabic));
543        assert!(!is_rtl_locale(&english));
544        assert_eq!(
545            isolate_text(&arabic, "42 files"),
546            "\u{2067}42 files\u{2069}"
547        );
548        assert_eq!(
549            isolate_text(&english, "42 ملفات"),
550            "\u{2066}42 ملفات\u{2069}"
551        );
552    }
553
554    fn english() -> MessageCatalog {
555        let mut catalog = MessageCatalog::new();
556        catalog.insert("greeting", "Hello");
557        catalog.insert_plural(
558            "files",
559            &[
560                (PluralCategory::One, "{n} file"),
561                (PluralCategory::Other, "{n} files"),
562            ],
563        );
564        catalog
565    }
566
567    fn german() -> MessageCatalog {
568        let mut catalog = MessageCatalog::new();
569        catalog.insert("greeting", "Hallo");
570        catalog
571    }
572
573    fn polish() -> MessageCatalog {
574        let mut catalog = MessageCatalog::new();
575        catalog.insert_plural(
576            "files",
577            &[
578                (PluralCategory::One, "{n} plik"),
579                (PluralCategory::Few, "{n} pliki"),
580                (PluralCategory::Many, "{n} plików"),
581            ],
582        );
583        catalog
584    }
585
586    fn arabic() -> MessageCatalog {
587        let mut catalog = MessageCatalog::new();
588        catalog.insert_plural(
589            "files",
590            &[
591                (PluralCategory::Zero, "لا ملفات"),
592                (PluralCategory::One, "ملف واحد"),
593                (PluralCategory::Two, "ملفان"),
594                (PluralCategory::Few, "{n} ملفات"),
595                (PluralCategory::Many, "{n} ملفًا"),
596                (PluralCategory::Other, "{n} ملف"),
597            ],
598        );
599        catalog
600    }
601
602    #[test]
603    fn locale_parsing_normalizes_tags() {
604        let locale = Locale::parse("  DE_at ");
605        assert_eq!(locale.tag(), "de-at");
606        assert_eq!(locale.language(), "de");
607        assert_eq!(locale.region(), Some("at"));
608        assert_eq!(Locale::parse("").tag(), "und");
609        assert_eq!(Locale::parse("en-US").region(), Some("us"));
610    }
611
612    #[test]
613    fn fallback_chain_prefers_exact_then_language_then_default() {
614        let mut localizer = Localizer::new(Locale::parse("en"));
615        localizer.add_catalog(Locale::parse("en"), english());
616        localizer.add_catalog(Locale::parse("de"), german());
617        localizer.set_locale(Locale::parse("de-AT"));
618
619        // de-AT has no catalog: falls back to the `de` language catalog.
620        assert_eq!(localizer.tr("greeting"), "Hallo");
621        // `files` exists only in the default `en` catalog.
622        assert_eq!(localizer.trn("files", 2), "2 files");
623        assert!(localizer.missing_keys().is_empty());
624    }
625
626    #[test]
627    fn untranslated_keys_are_tracked_not_panicked() {
628        let mut localizer = Localizer::new(Locale::parse("en"));
629        localizer.add_catalog(Locale::parse("en"), english());
630
631        assert_eq!(localizer.tr("missing.key"), "missing.key");
632        assert_eq!(localizer.trn("missing.plural", 3), "missing.plural (3)");
633        // Duplicates are recorded once, in first-seen order.
634        assert_eq!(localizer.tr("missing.key"), "missing.key");
635        assert_eq!(
636            localizer.missing_keys(),
637            &["missing.key".to_owned(), "missing.plural".to_owned()]
638        );
639        localizer.clear_missing_keys();
640        assert!(localizer.missing_keys().is_empty());
641    }
642
643    #[test]
644    fn runtime_locale_switches_report_changes() {
645        let mut localizer = Localizer::new(Locale::parse("en"));
646        localizer.add_catalog(Locale::parse("en"), english());
647        localizer.add_catalog(Locale::parse("de"), german());
648
649        assert!(localizer.set_locale(Locale::parse("de")));
650        assert_eq!(localizer.tr("greeting"), "Hallo");
651        assert!(!localizer.set_locale(Locale::parse("DE")));
652        assert!(localizer.set_locale(Locale::parse("en-gb")));
653        assert_eq!(localizer.tr("greeting"), "Hello");
654    }
655
656    #[test]
657    fn plural_rules_cover_english_and_slavic_families() {
658        let mut localizer = Localizer::new(Locale::parse("en"));
659        localizer.add_catalog(Locale::parse("en"), english());
660        localizer.add_catalog(Locale::parse("pl"), polish());
661
662        assert_eq!(localizer.trn("files", 1), "1 file");
663        assert_eq!(localizer.trn("files", 2), "2 files");
664
665        localizer.set_locale(Locale::parse("pl"));
666        assert_eq!(localizer.trn("files", 1), "1 plik");
667        assert_eq!(localizer.trn("files", 2), "2 pliki");
668        assert_eq!(localizer.trn("files", 5), "5 plików");
669        assert_eq!(localizer.trn("files", 12), "12 plików");
670        assert_eq!(localizer.trn("files", 22), "22 pliki");
671        assert_eq!(
672            plural_category(&Locale::parse("xx"), 1),
673            PluralCategory::Other
674        );
675    }
676
677    /// Arabic selects all six CLDR categories.
678    #[test]
679    fn plural_rules_cover_arabic_six_categories() {
680        let ar = Locale::parse("ar");
681        assert_eq!(plural_category(&ar, 0), PluralCategory::Zero);
682        assert_eq!(plural_category(&ar, 1), PluralCategory::One);
683        assert_eq!(plural_category(&ar, 2), PluralCategory::Two);
684        for count in [3, 10, 103] {
685            assert_eq!(
686                plural_category(&ar, count),
687                PluralCategory::Few,
688                "few: {count}"
689            );
690        }
691        for count in [11, 99, 111] {
692            assert_eq!(
693                plural_category(&ar, count),
694                PluralCategory::Many,
695                "many: {count}"
696            );
697        }
698        for count in [100, 101, 102, 200] {
699            assert_eq!(
700                plural_category(&ar, count),
701                PluralCategory::Other,
702                "other: {count}"
703            );
704        }
705    }
706
707    /// French treats zero as singular; Spanish does not.
708    #[test]
709    fn plural_rules_give_french_zero_the_one_form() {
710        let fr = Locale::parse("fr");
711        assert_eq!(plural_category(&fr, 0), PluralCategory::One);
712        assert_eq!(plural_category(&fr, 1), PluralCategory::One);
713        assert_eq!(plural_category(&fr, 2), PluralCategory::Other);
714
715        let es = Locale::parse("es");
716        assert_eq!(plural_category(&es, 0), PluralCategory::Other);
717        assert_eq!(plural_category(&es, 1), PluralCategory::One);
718    }
719
720    /// East Asian languages have no plural distinction at all.
721    #[test]
722    fn plural_rules_cover_east_asian_no_distinction() {
723        for tag in ["ja", "zh", "ko", "th", "vi"] {
724            let locale = Locale::parse(tag);
725            for count in [0, 1, 2, 5, 100] {
726                assert_eq!(
727                    plural_category(&locale, count),
728                    PluralCategory::Other,
729                    "{tag}:{count}"
730                );
731            }
732        }
733    }
734
735    /// The matcher works on absolute counts, so negative inputs stay sane.
736    #[test]
737    fn plural_rules_use_absolute_counts() {
738        assert_eq!(
739            plural_category(&Locale::parse("ar"), -2),
740            PluralCategory::Two
741        );
742        assert_eq!(
743            plural_category(&Locale::parse("ru"), -3),
744            PluralCategory::Few
745        );
746        assert_eq!(
747            plural_category(&Locale::parse("fr"), -1),
748            PluralCategory::One
749        );
750    }
751
752    /// End to end: an Arabic catalog renders each of the six forms.
753    #[test]
754    fn arabic_plural_rendering_uses_all_six_forms() {
755        let mut localizer = Localizer::new(Locale::parse("ar"));
756        localizer.add_catalog(Locale::parse("ar"), arabic());
757
758        assert_eq!(localizer.trn("files", 0), "لا ملفات");
759        assert_eq!(localizer.trn("files", 1), "ملف واحد");
760        assert_eq!(localizer.trn("files", 2), "ملفان");
761        assert_eq!(localizer.trn("files", 4), "4 ملفات");
762        assert_eq!(localizer.trn("files", 42), "42 ملفًا");
763        assert_eq!(localizer.trn("files", 100), "100 ملف");
764        assert!(localizer.missing_keys().is_empty());
765    }
766
767    #[test]
768    fn number_formatting_uses_locale_separators() {
769        let mut localizer = Localizer::new(Locale::parse("en-us"));
770        assert_eq!(localizer.format_number(1234.5, 2), "1,234.50");
771        assert_eq!(localizer.format_number(-1234567.0, 0), "-1,234,567");
772
773        localizer.set_locale(Locale::parse("de"));
774        assert_eq!(localizer.format_number(1234.5, 2), "1.234,50");
775
776        localizer.set_locale(Locale::parse("fr"));
777        assert_eq!(localizer.format_number(1234.5, 1), "1 234,5");
778    }
779
780    #[test]
781    fn date_formatting_uses_locale_patterns_with_passthrough() {
782        let mut localizer = Localizer::new(Locale::parse("en-us"));
783        assert_eq!(localizer.format_date("2026-09-12"), "09/12/2026");
784
785        localizer.set_locale(Locale::parse("en-gb"));
786        assert_eq!(localizer.format_date("2026-09-12"), "12/09/2026");
787
788        localizer.set_locale(Locale::parse("de"));
789        assert_eq!(localizer.format_date("2026-09-12"), "12.09.2026");
790
791        // Invalid or non-ISO input passes through unchanged.
792        assert_eq!(localizer.format_date("not-a-date"), "not-a-date");
793        assert_eq!(localizer.format_date("2026-13-01"), "2026-13-01");
794    }
795
796    /// Arabic ordinals never select `zero`; every other
797    /// category matches the cardinal classification.
798    #[test]
799    fn ordinal_rules_diverge_from_cardinals_for_arabic_zero() {
800        let ar = Locale::parse("ar_EG");
801        assert_eq!(plural_category(&ar, 0), PluralCategory::Zero);
802        assert_eq!(ordinal_category(&ar, 0), PluralCategory::Other);
803        for (count, cardinal, ordinal) in [
804            (1, PluralCategory::One, PluralCategory::One),
805            (2, PluralCategory::Two, PluralCategory::Two),
806            (3, PluralCategory::Few, PluralCategory::Few),
807            (11, PluralCategory::Many, PluralCategory::Many),
808            (100, PluralCategory::Other, PluralCategory::Other),
809        ] {
810            assert_eq!(plural_category(&ar, count), cardinal, "cardinal {count}");
811            assert_eq!(ordinal_category(&ar, count), ordinal, "ordinal {count}");
812        }
813        // Modulo rules use the absolute count like the cardinal rules.
814        assert_eq!(ordinal_category(&ar, -103), PluralCategory::Few);
815        assert_eq!(
816            ordinal_category(&ar, 111),
817            PluralCategory::Many,
818            "11..=99 modulo 100"
819        );
820
821        let en = Locale::parse("en");
822        assert_eq!(ordinal_category(&en, 2), PluralCategory::Two);
823        assert_eq!(ordinal_category(&en, 3), PluralCategory::Few);
824        assert_eq!(ordinal_category(&en, 4), PluralCategory::Other);
825        assert_eq!(
826            ordinal_category(&Locale::parse("fr"), 1),
827            PluralCategory::One
828        );
829        assert_eq!(
830            ordinal_category(&Locale::parse("fr"), 0),
831            PluralCategory::Other
832        );
833
834        // Rendered ordinals and the bidi helper compose deterministically.
835        let mut localizer = Localizer::new(ar.clone());
836        let mut catalog = MessageCatalog::new();
837        catalog.insert_plural(
838            "place",
839            &[
840                (PluralCategory::Few, "المركز {n}"),
841                (PluralCategory::Many, "المركز {n}"),
842                (PluralCategory::Other, "المركز {n}"),
843            ],
844        );
845        localizer.add_catalog(ar.clone(), catalog);
846        let rendered = localizer.trn("place", 3);
847        assert_eq!(rendered, "المركز 3");
848        let isolated = isolate_text(&ar, &rendered);
849        assert!(
850            isolated.starts_with('\u{2067}') && isolated.ends_with('\u{2069}'),
851            "Arabic UI strings wrap in a right-to-left isolate"
852        );
853    }
854
855    /// French zero-as-singular stays consistent when the count
856    /// is displayed through the locale's decimal formatter.
857    #[test]
858    fn french_decimals_interact_with_zero_as_singular() {
859        let fr = Locale::parse("fr");
860        let mut localizer = Localizer::new(fr.clone());
861        let mut catalog = MessageCatalog::new();
862        catalog.insert_plural(
863            "items",
864            &[
865                (PluralCategory::One, "{n} article"),
866                (PluralCategory::Other, "{n} articles"),
867            ],
868        );
869        localizer.add_catalog(fr, catalog);
870
871        assert_eq!(localizer.trn("items", 0), "0 article", "zero is singular");
872        assert_eq!(localizer.trn("items", 1), "1 article");
873        assert_eq!(localizer.trn("items", 2), "2 articles");
874
875        // A rounded display count and the plural form agree: 0.4 renders as
876        // "0" and therefore selects the singular form.
877        assert_eq!(localizer.format_number(0.4, 0), "0");
878        let displayed: i64 = localizer
879            .format_number(0.4, 0)
880            .parse()
881            .expect("plain digits");
882        assert_eq!(localizer.trn("items", displayed), "0 article");
883
884        // Decimal and grouping separators stay French.
885        assert_eq!(localizer.format_number(1.5, 1), "1,5");
886        assert_eq!(localizer.format_number(1234.5, 1), "1 234,5");
887        assert_eq!(
888            localizer.format_number(1.5, 0),
889            "2",
890            "rounds, not truncates"
891        );
892    }
893
894    /// Nordic collation tails differ from code-point order.
895    #[test]
896    fn collation_tailors_nordic_letters_after_z() {
897        use std::cmp::Ordering;
898
899        let sv = Locale::parse("sv_SE");
900        assert_eq!(collate(&sv, "Zebra", "Ål"), Ordering::Less, "Å after Z");
901        assert_eq!(
902            collate(&sv, "Ål", "Äppel"),
903            Ordering::Less,
904            "sv order is Å < Ä < Ö, not code point order"
905        );
906        assert_eq!(collate(&sv, "Äppel", "Öland"), Ordering::Less);
907        assert_eq!(collate(&sv, "Ö", "Ö"), Ordering::Equal);
908
909        let da = Locale::parse("da_DK");
910        assert_eq!(
911            collate(&da, "Ål", "Æble"),
912            Ordering::Greater,
913            "da/nb order is Æ < Ø < Å"
914        );
915        assert_eq!(collate(&da, "Æble", "Øl"), Ordering::Less);
916
917        // The default keeps a stable code-point order after the ASCII
918        // letters (no Nordic tail), and case variants tie.
919        let en = Locale::parse("en_US");
920        assert_eq!(collate(&en, "Zebra", "Ål"), Ordering::Less);
921        assert_eq!(collate(&en, "apple", "Apple"), Ordering::Equal);
922    }
923
924    /// Polish selects `many` for 21/101 (`one` is exactly
925    /// 1), while East Slavic `one` covers every n mod 10 == 1 outside 11.
926    #[test]
927    fn plural_rules_split_polish_from_east_slavic_one_forms() {
928        let pl = Locale::parse("pl");
929        assert_eq!(plural_category(&pl, 1), PluralCategory::One);
930        for count in [21, 31, 101, 1001] {
931            assert_eq!(
932                plural_category(&pl, count),
933                PluralCategory::Many,
934                "pl: {count} takes the many form"
935            );
936        }
937        assert_eq!(plural_category(&pl, 2), PluralCategory::Few);
938        assert_eq!(plural_category(&pl, 24), PluralCategory::Few);
939        assert_eq!(plural_category(&pl, 12), PluralCategory::Many);
940        assert_eq!(plural_category(&pl, 112), PluralCategory::Many);
941
942        for tag in ["ru", "uk"] {
943            let locale = Locale::parse(tag);
944            for count in [1, 21, 31, 101, 1001] {
945                assert_eq!(
946                    plural_category(&locale, count),
947                    PluralCategory::One,
948                    "{tag}: {count} takes the one form"
949                );
950            }
951            for count in [2, 3, 4, 22, 24, 102] {
952                assert_eq!(
953                    plural_category(&locale, count),
954                    PluralCategory::Few,
955                    "{tag}: {count}"
956                );
957            }
958            for count in [0, 5, 11, 12, 14, 25, 111, 112] {
959                assert_eq!(
960                    plural_category(&locale, count),
961                    PluralCategory::Many,
962                    "{tag}: {count}"
963                );
964            }
965        }
966    }
967
968    /// The Romance family is two-form; only French pulls
969    /// zero into the singular form, and region tags dispatch on the language.
970    #[test]
971    fn plural_rules_match_the_romance_family_matrix() {
972        for tag in ["es", "it", "pt", "pt-br", "it-ch"] {
973            let locale = Locale::parse(tag);
974            assert_eq!(
975                plural_category(&locale, 0),
976                PluralCategory::Other,
977                "{tag}: zero is plural"
978            );
979            assert_eq!(plural_category(&locale, 1), PluralCategory::One, "{tag}");
980            assert_eq!(plural_category(&locale, 2), PluralCategory::Other, "{tag}");
981        }
982        for tag in ["fr", "fr-ca", "fr-ch"] {
983            let locale = Locale::parse(tag);
984            assert_eq!(
985                plural_category(&locale, 0),
986                PluralCategory::One,
987                "{tag}: zero is singular"
988            );
989            assert_eq!(plural_category(&locale, 1), PluralCategory::One, "{tag}");
990            assert_eq!(plural_category(&locale, 2), PluralCategory::Other, "{tag}");
991        }
992
993        // An undetermined tag has no rules of its own, and tags normalize
994        // case and region before dispatch.
995        assert_eq!(
996            plural_category(&Locale::parse("und"), 1),
997            PluralCategory::Other
998        );
999        assert_eq!(
1000            plural_category(&Locale::parse("AR-eg"), 1),
1001            PluralCategory::One,
1002            "region subtags do not change the language rules"
1003        );
1004    }
1005
1006    /// Defensive rendering: a missing category falls back to `other`, and a
1007    /// plural message with neither the selected category nor `other` renders
1008    /// empty; `{n}` fills for simple messages too.
1009    #[test]
1010    fn plural_forms_fall_back_to_other_when_the_category_is_missing() {
1011        let mut localizer = Localizer::new(Locale::parse("ar"));
1012        let mut catalog = MessageCatalog::new();
1013        catalog.insert_plural("files", &[(PluralCategory::Other, "{n} ملف")]);
1014        localizer.add_catalog(Locale::parse("ar"), catalog);
1015        // `few` is not declared: the `other` form renders.
1016        assert_eq!(localizer.trn("files", 3), "3 ملف");
1017
1018        // A simple message substitutes `{n}` when a count is supplied.
1019        let mut simple = MessageCatalog::new();
1020        simple.insert("units", "{n} units of work");
1021        localizer.add_catalog(Locale::parse("en"), simple);
1022        localizer.set_locale(Locale::parse("en"));
1023        assert_eq!(localizer.trn("units", 5), "5 units of work");
1024
1025        // Neither the selected category nor `other`: an empty string, not a
1026        // panic (the key itself is present, so nothing is logged missing).
1027        let mut bare = MessageCatalog::new();
1028        bare.insert_plural("items", &[(PluralCategory::One, "one item")]);
1029        localizer.add_catalog(Locale::parse("ar"), bare);
1030        localizer.set_locale(Locale::parse("ar"));
1031        assert_eq!(localizer.trn("items", 5), "");
1032        assert!(localizer.missing_keys().is_empty());
1033    }
1034
1035    /// Ordinal ladders beyond the existing Arabic divergence test: English
1036    /// stops at 3, French at 1, and unruled locales never leave `other`.
1037    #[test]
1038    fn ordinal_rules_cover_english_and_french_ladders() {
1039        let en = Locale::parse("en");
1040        assert_eq!(ordinal_category(&en, 1), PluralCategory::One);
1041        for count in [0, 4, 11, 21, 101] {
1042            assert_eq!(
1043                ordinal_category(&en, count),
1044                PluralCategory::Other,
1045                "en: {count}"
1046            );
1047        }
1048
1049        let fr = Locale::parse("fr");
1050        assert_eq!(ordinal_category(&fr, 1), PluralCategory::One);
1051        for count in [0, 2, 21] {
1052            assert_eq!(
1053                ordinal_category(&fr, count),
1054                PluralCategory::Other,
1055                "fr: {count}"
1056            );
1057        }
1058
1059        assert_eq!(
1060            ordinal_category(&Locale::parse("de"), 1),
1061            PluralCategory::Other,
1062            "German has no ordinal rules in this model"
1063        );
1064    }
1065
1066    /// Absolute-count selection flows through rendering: negative counts take
1067    /// their positive category and display their sign.
1068    #[test]
1069    fn negative_counts_render_with_their_absolute_category_end_to_end() {
1070        let mut localizer = Localizer::new(Locale::parse("ru"));
1071        let mut russian = MessageCatalog::new();
1072        russian.insert_plural(
1073            "files",
1074            &[
1075                (PluralCategory::One, "{n} файл"),
1076                (PluralCategory::Few, "{n} файла"),
1077                (PluralCategory::Many, "{n} файлов"),
1078            ],
1079        );
1080        localizer.add_catalog(Locale::parse("ru"), russian);
1081        assert_eq!(localizer.trn("files", -21), "-21 файл");
1082        assert_eq!(localizer.trn("files", -3), "-3 файла");
1083        assert_eq!(localizer.trn("files", -11), "-11 файлов");
1084
1085        localizer.add_catalog(Locale::parse("ar"), arabic());
1086        localizer.set_locale(Locale::parse("ar"));
1087        assert_eq!(localizer.trn("files", -2), "ملفان", "dual form");
1088        assert_eq!(localizer.trn("files", -4), "-4 ملفات", "few form");
1089    }
1090}