Skip to main content

mobiler_core/
format.rs

1//! Locale-aware number, currency, and date formatting — pure, synchronous, dependency-light.
2//!
3//! `view()` builds the `Widget` tree synchronously, but device capabilities/plugins are async, so
4//! locale formatting can't be delegated to the platform's `NumberFormatter`/`Intl` at render time —
5//! it has to run in the core. This module hand-rolls the conventions for the locales Mobiler apps
6//! actually target (Swiss de/fr/it, the common Western locales, Ukrainian, Serbian, Polish, Spanish),
7//! following the platform's CLDR conventions, instead of pulling in a full ICU
8//! data bundle, keeping the wasm web shell small.
9//!
10//! ```
11//! use mobiler_core::format::{format_currency, Currency, Locale};
12//! assert_eq!(format_currency(1234.5, Currency::Chf, Locale::DeCh), "CHF 1'234.50");
13//! assert_eq!(format_currency(1234.5, Currency::Eur, Locale::DeDe), "1.234,50 €");
14//! ```
15
16use serde::{Deserialize, Serialize};
17
18/// A formatting locale — drives digit grouping, the decimal mark, currency placement, and the
19/// date order + month names. Map a device language tag (e.g. from a `locale` plugin) to one with
20/// [`Locale::from_tag`].
21#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
22pub enum Locale {
23    #[default]
24    EnUs,
25    EnGb,
26    /// Swiss German — `1'234.50`, `31.12.2026`.
27    DeCh,
28    /// Swiss French — `1'234.50`, `31.12.2026`.
29    FrCh,
30    /// Swiss Italian — `1'234.50`, `31.12.2026`.
31    ItCh,
32    DeDe,
33    FrFr,
34    ItIt,
35    /// Ukrainian — `1 234,50` (no-break space grouping), `31.12.2026`, `січень`.
36    UkUa,
37    /// Serbian, Latin script — `1.234,50`, `31.12.2026.`, `januar`.
38    SrLatn,
39    /// Serbian, Cyrillic script — `1.234,50`, `31.12.2026.`, `јануар`.
40    SrCyrl,
41    /// Polish — `1234,50` and `12 345,50` (no-break space grouping from five digits, as the platform does),
42    /// `31.12.2026`, `styczeń`.
43    PlPl,
44    /// Spanish (Spain; every `es` tag maps here) — `1234,50` and `12.345,50` (grouping from five digits, as
45    /// the platform does), `31/12/2026`, `enero`.
46    EsEs,
47}
48
49/// A currency. Placement (symbol leading vs trailing) follows the [`Locale`].
50#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
51pub enum Currency {
52    Chf,
53    #[default]
54    Eur,
55    Usd,
56    Gbp,
57    /// Ukrainian hryvnia — trails the amount (`1 234,50 ₴`).
58    Uah,
59    /// Serbian dinar — trails (`din.` in Latin, `дин.` in Cyrillic, else `RSD`).
60    Rsd,
61    /// Polish złoty — trails the amount in every locale (`1234,50 zł`).
62    Pln,
63}
64
65/// A day of the week — the first column of a localized calendar ([`Locale::week_start`]).
66#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
67pub enum Weekday {
68    Sunday,
69    Monday,
70    Tuesday,
71    Wednesday,
72    Thursday,
73    Friday,
74    Saturday,
75}
76
77impl Weekday {
78    /// 0 = Sunday … 6 = Saturday (the index `weekday_short` and the calendar layout use).
79    #[must_use]
80    pub const fn sun0(self) -> u8 {
81        self as u8
82    }
83}
84
85#[derive(Clone, Copy, PartialEq, Eq)]
86enum Lang {
87    En,
88    De,
89    Fr,
90    It,
91    Uk,
92    SrLatn,
93    SrCyrl,
94    Pl,
95    Es,
96}
97
98impl Locale {
99    /// `(group separator, decimal separator)`.
100    const fn seps(self) -> (&'static str, &'static str) {
101        match self {
102            Locale::EnUs | Locale::EnGb => (",", "."),
103            // Swiss: apostrophe grouping, period decimal (e.g. SSM's "CHF 80'000").
104            Locale::DeCh | Locale::FrCh | Locale::ItCh => ("'", "."),
105            Locale::DeDe | Locale::ItIt | Locale::SrLatn | Locale::SrCyrl | Locale::EsEs => (".", ","),
106            // French: narrow no-break space grouping, comma decimal.
107            Locale::FrFr => ("\u{202f}", ","),
108            // Ukrainian and Polish: no-break space grouping, comma decimal.
109            Locale::UkUa | Locale::PlPl => ("\u{a0}", ","),
110        }
111    }
112
113    /// CLDR's minimum grouping digits: with 2, an integer part of four digits stays ungrouped
114    /// (`1234`) and grouping starts at five (`12 345`), as Android, iOS and browsers print Polish and
115    /// Spanish.
116    const fn min_grouping(self) -> usize {
117        match self {
118            Locale::PlPl | Locale::EsEs => 2,
119            _ => 1,
120        }
121    }
122
123    const fn lang(self) -> Lang {
124        match self {
125            Locale::EnUs | Locale::EnGb => Lang::En,
126            Locale::DeCh | Locale::DeDe => Lang::De,
127            Locale::FrCh | Locale::FrFr => Lang::Fr,
128            Locale::ItCh | Locale::ItIt => Lang::It,
129            Locale::UkUa => Lang::Uk,
130            Locale::SrLatn => Lang::SrLatn,
131            Locale::SrCyrl => Lang::SrCyrl,
132            Locale::PlPl => Lang::Pl,
133            Locale::EsEs => Lang::Es,
134        }
135    }
136
137    /// Best-effort map of a BCP-47 language tag (case-insensitive, e.g. `"de-CH"`, `"fr"`,
138    /// `"en-US"`) to a supported [`Locale`]. Region wins when known; otherwise the language's
139    /// most common locale is used. Returns `None` for unrecognized languages.
140    #[must_use]
141    pub fn from_tag(tag: &str) -> Option<Locale> {
142        let t = tag.to_ascii_lowercase().replace('_', "-");
143        let mut parts = t.split('-');
144        let lang = parts.next().unwrap_or("");
145        let region = parts.next().unwrap_or("");
146        Some(match (lang, region) {
147            ("en", "gb") => Locale::EnGb,
148            ("en", _) => Locale::EnUs,
149            ("de", "ch") => Locale::DeCh,
150            ("de", _) => Locale::DeDe,
151            ("fr", "ch") => Locale::FrCh,
152            ("fr", _) => Locale::FrFr,
153            ("it", "ch") => Locale::ItCh,
154            ("it", _) => Locale::ItIt,
155            ("uk", _) => Locale::UkUa,
156            // Serbian: script wins; default to Cyrillic (the official script) when unspecified.
157            ("sr", "latn") => Locale::SrLatn,
158            ("sr", _) => Locale::SrCyrl,
159            ("pl", _) => Locale::PlPl,
160            // Every Spanish region gets Spain's conventions (the only Spanish locale).
161            ("es", _) => Locale::EsEs,
162            _ => return None,
163        })
164    }
165}
166
167/// Group an unsigned integer's digit string with `sep` every three digits from the right, unless it
168/// is shorter than `3 + min_grouping` digits (CLDR minimum grouping digits).
169fn group_digits(digits: &str, sep: &str, min_grouping: usize) -> String {
170    let len = digits.len();
171    if len < 3 + min_grouping {
172        return digits.to_string();
173    }
174    let mut out = String::with_capacity(len + len / 3 * sep.len());
175    for (i, ch) in digits.chars().enumerate() {
176        if i > 0 && (len - i).is_multiple_of(3) {
177            out.push_str(sep);
178        }
179        out.push(ch);
180    }
181    out
182}
183
184/// Format a floating-point number with a fixed number of decimal places, grouped per `locale`.
185///
186/// ```
187/// use mobiler_core::format::{format_number, Locale};
188/// assert_eq!(format_number(1234567.5, 2, Locale::DeCh), "1'234'567.50");
189/// assert_eq!(format_number(1234567.5, 2, Locale::DeDe), "1.234.567,50");
190/// ```
191#[must_use]
192pub fn format_number(value: f64, decimals: usize, locale: Locale) -> String {
193    let (group, dec) = locale.seps();
194    let s = format!("{:.*}", decimals, value.abs());
195    let (int_part, frac_part) = match s.split_once('.') {
196        Some((i, f)) => (i, Some(f)),
197        None => (s.as_str(), None),
198    };
199    // Determine sign from the rounded result so -0.00 reads as "0.00".
200    let negative = value < 0.0 && s.bytes().any(|b| b != b'0' && b != b'.');
201    let mut out = String::new();
202    if negative {
203        out.push('-');
204    }
205    out.push_str(&group_digits(int_part, group, locale.min_grouping()));
206    if let Some(f) = frac_part {
207        out.push_str(dec);
208        out.push_str(f);
209    }
210    out
211}
212
213/// Format an integer, grouped per `locale`.
214///
215/// ```
216/// use mobiler_core::format::{format_int, Locale};
217/// assert_eq!(format_int(80000, Locale::DeCh), "80'000");
218/// assert_eq!(format_int(-1234, Locale::EnUs), "-1,234");
219/// ```
220#[must_use]
221pub fn format_int(value: i64, locale: Locale) -> String {
222    let (group, _) = locale.seps();
223    let digits = value.unsigned_abs().to_string();
224    let mut out = String::new();
225    if value < 0 {
226        out.push('-');
227    }
228    out.push_str(&group_digits(&digits, group, locale.min_grouping()));
229    out
230}
231
232/// Format a monetary amount (always two fraction digits). Symbol placement follows `locale`:
233/// CHF/USD/GBP lead; EUR trails in de-DE/fr-FR/it-IT/pl-PL/es-ES and leads elsewhere; UAH, RSD and
234/// PLN trail.
235///
236/// ```
237/// use mobiler_core::format::{format_currency, Currency, Locale};
238/// assert_eq!(format_currency(1234.5, Currency::Chf, Locale::FrCh), "CHF 1'234.50");
239/// assert_eq!(format_currency(1234.5, Currency::Usd, Locale::EnUs), "$1,234.50");
240/// ```
241#[must_use]
242pub fn format_currency(value: f64, currency: Currency, locale: Locale) -> String {
243    let num = format_number(value, 2, locale);
244    match currency {
245        Currency::Chf => format!("CHF {num}"),
246        Currency::Usd => format!("${num}"),
247        Currency::Gbp => format!("£{num}"),
248        Currency::Eur => match locale {
249            Locale::DeDe | Locale::FrFr | Locale::ItIt | Locale::PlPl | Locale::EsEs => format!("{num} €"),
250            _ => format!("€{num}"),
251        },
252        Currency::Uah => format!("{num} ₴"),
253        Currency::Rsd => match locale {
254            Locale::SrLatn => format!("{num} din."),
255            Locale::SrCyrl => format!("{num} дин."),
256            _ => format!("{num} RSD"),
257        },
258        Currency::Pln => format!("{num} zł"),
259    }
260}
261
262const MONTHS_EN: [&str; 12] = [
263    "January", "February", "March", "April", "May", "June", "July", "August", "September",
264    "October", "November", "December",
265];
266const MONTHS_DE: [&str; 12] = [
267    "Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober",
268    "November", "Dezember",
269];
270const MONTHS_FR: [&str; 12] = [
271    "janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre",
272    "octobre", "novembre", "décembre",
273];
274const MONTHS_IT: [&str; 12] = [
275    "gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre",
276    "ottobre", "novembre", "dicembre",
277];
278// Ukrainian standalone (nominative) month names.
279const MONTHS_UK: [&str; 12] = [
280    "січень", "лютий", "березень", "квітень", "травень", "червень", "липень", "серпень",
281    "вересень", "жовтень", "листопад", "грудень",
282];
283const MONTHS_SR_LATN: [&str; 12] = [
284    "januar", "februar", "mart", "april", "maj", "jun", "jul", "avgust", "septembar", "oktobar",
285    "novembar", "decembar",
286];
287const MONTHS_SR_CYRL: [&str; 12] = [
288    "јануар", "фебруар", "март", "април", "мај", "јун", "јул", "август", "септембар", "октобар",
289    "новембар", "децембар",
290];
291
292// Polish standalone (nominative) month names.
293const MONTHS_PL: [&str; 12] = [
294    "styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień",
295    "październik", "listopad", "grudzień",
296];
297const MONTHS_ES: [&str; 12] = [
298    "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre",
299    "octubre", "noviembre", "diciembre",
300];
301
302// Genitive month names for "day month year" dates, where Polish and Ukrainian decline the month
303// ("31 grudnia", "5 травня"). Only `format_date_long` uses them.
304const MONTHS_PL_GEN: [&str; 12] = [
305    "stycznia", "lutego", "marca", "kwietnia", "maja", "czerwca", "lipca", "sierpnia", "września",
306    "października", "listopada", "grudnia",
307];
308const MONTHS_UK_GEN: [&str; 12] = [
309    "січня", "лютого", "березня", "квітня", "травня", "червня", "липня", "серпня", "вересня",
310    "жовтня", "листопада", "грудня",
311];
312
313/// The month as it reads after a day number: genitive in Polish and Ukrainian, else [`month_name`].
314fn month_in_date(month: u32, locale: Locale) -> &'static str {
315    let idx = (month.clamp(1, 12) - 1) as usize;
316    match locale.lang() {
317        Lang::Pl => MONTHS_PL_GEN[idx],
318        Lang::Uk => MONTHS_UK_GEN[idx],
319        _ => month_name(month, locale),
320    }
321}
322
323/// The localized full month name (`month` is 1–12, clamped).
324#[must_use]
325pub fn month_name(month: u32, locale: Locale) -> &'static str {
326    let idx = (month.clamp(1, 12) - 1) as usize;
327    match locale.lang() {
328        Lang::En => MONTHS_EN[idx],
329        Lang::De => MONTHS_DE[idx],
330        Lang::Fr => MONTHS_FR[idx],
331        Lang::It => MONTHS_IT[idx],
332        Lang::Uk => MONTHS_UK[idx],
333        Lang::SrLatn => MONTHS_SR_LATN[idx],
334        Lang::SrCyrl => MONTHS_SR_CYRL[idx],
335        Lang::Pl => MONTHS_PL[idx],
336        Lang::Es => MONTHS_ES[idx],
337    }
338}
339
340impl Locale {
341    /// The first day of the week: Sunday for US English, Monday for every other supported locale.
342    #[must_use]
343    pub const fn week_start(self) -> Weekday {
344        match self {
345            Locale::EnUs => Weekday::Sunday,
346            _ => Weekday::Monday,
347        }
348    }
349}
350
351// Narrow weekday labels for a calendar header, Sunday-first (index = `Weekday::sun0`).
352const WEEKDAYS_EN: [&str; 7] = ["S", "M", "T", "W", "T", "F", "S"];
353const WEEKDAYS_DE: [&str; 7] = ["S", "M", "D", "M", "D", "F", "S"];
354const WEEKDAYS_FR: [&str; 7] = ["D", "L", "M", "M", "J", "V", "S"];
355const WEEKDAYS_IT: [&str; 7] = ["D", "L", "M", "M", "G", "V", "S"];
356// Ukrainian calendars use the two-letter forms (single letters are ambiguous).
357const WEEKDAYS_UK: [&str; 7] = ["Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"];
358const WEEKDAYS_SR_LATN: [&str; 7] = ["N", "P", "U", "S", "Č", "P", "S"];
359const WEEKDAYS_SR_CYRL: [&str; 7] = ["Н", "П", "У", "С", "Ч", "П", "С"];
360const WEEKDAYS_PL: [&str; 7] = ["N", "P", "W", "Ś", "C", "P", "S"];
361// Spanish uses X for miércoles so it differs from martes.
362const WEEKDAYS_ES: [&str; 7] = ["D", "L", "M", "X", "J", "V", "S"];
363
364/// The localized narrow weekday label for a calendar header. `sun0` is 0 = Sunday … 6 = Saturday
365/// and wraps, so `weekday_short(start + i, …)` walks a week from any start day.
366#[must_use]
367pub fn weekday_short(sun0: u8, locale: Locale) -> &'static str {
368    let idx = usize::from(sun0 % 7);
369    match locale.lang() {
370        Lang::En => WEEKDAYS_EN[idx],
371        Lang::De => WEEKDAYS_DE[idx],
372        Lang::Fr => WEEKDAYS_FR[idx],
373        Lang::It => WEEKDAYS_IT[idx],
374        Lang::Uk => WEEKDAYS_UK[idx],
375        Lang::SrLatn => WEEKDAYS_SR_LATN[idx],
376        Lang::SrCyrl => WEEKDAYS_SR_CYRL[idx],
377        Lang::Pl => WEEKDAYS_PL[idx],
378        Lang::Es => WEEKDAYS_ES[idx],
379    }
380}
381
382/// A calendar title: the localized month name, capitalized, then the year (`"Septembar 2026"`;
383/// Spanish puts "de" between them, as the platform does: `"Diciembre de 2026"`).
384#[must_use]
385pub fn month_year(year: u32, month: u32, locale: Locale) -> String {
386    let name = month_name(month, locale);
387    let mut chars = name.chars();
388    let capitalized: String = chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default();
389    match locale.lang() {
390        Lang::Es => format!("{capitalized} de {year}"),
391        _ => format!("{capitalized} {year}"),
392    }
393}
394
395/// Numeric date in the locale's conventional order/separator.
396///
397/// ```
398/// use mobiler_core::format::{format_date, Locale};
399/// assert_eq!(format_date(2026, 1, 5, Locale::DeCh), "05.01.2026");
400/// assert_eq!(format_date(2026, 1, 5, Locale::EnUs), "01/05/2026");
401/// ```
402#[must_use]
403pub fn format_date(year: i32, month: u32, day: u32, locale: Locale) -> String {
404    match locale {
405        Locale::EnUs => format!("{month:02}/{day:02}/{year}"),
406        Locale::EnGb | Locale::FrFr | Locale::ItIt | Locale::EsEs => format!("{day:02}/{month:02}/{year}"),
407        Locale::DeCh | Locale::FrCh | Locale::ItCh | Locale::DeDe | Locale::UkUa | Locale::PlPl => {
408            format!("{day:02}.{month:02}.{year}")
409        }
410        // Serbian uses a trailing dot: "31.12.2026."
411        Locale::SrLatn | Locale::SrCyrl => format!("{day:02}.{month:02}.{year}."),
412    }
413}
414
415/// Long date with the localized month name (e.g. `"5. Januar 2026"`, `"January 5, 2026"`). Polish and
416/// Ukrainian use the genitive month (`"31 grudnia 2026"`, `"5 травня 2026 р."`), as the platform does.
417///
418/// ```
419/// use mobiler_core::format::{format_date_long, Locale};
420/// assert_eq!(format_date_long(2026, 1, 5, Locale::DeCh), "5. Januar 2026");
421/// assert_eq!(format_date_long(2026, 1, 5, Locale::EnUs), "January 5, 2026");
422/// ```
423#[must_use]
424pub fn format_date_long(year: i32, month: u32, day: u32, locale: Locale) -> String {
425    let m = month_in_date(month, locale);
426    match locale.lang() {
427        Lang::En => match locale {
428            Locale::EnUs => format!("{m} {day}, {year}"),
429            _ => format!("{day} {m} {year}"),
430        },
431        // German + Serbian use the ordinal dot after the day; French/Italian/Polish/Ukrainian do not.
432        Lang::De | Lang::SrLatn | Lang::SrCyrl => format!("{day}. {m} {year}"),
433        Lang::Fr | Lang::It | Lang::Pl => format!("{day} {m} {year}"),
434        // Ukrainian closes the year with "р." (рік), as the platform does.
435        Lang::Uk => format!("{day} {m} {year} р."),
436        Lang::Es => format!("{day} de {m} de {year}"),
437    }
438}
439
440#[cfg(test)]
441mod tests {
442    use super::*;
443
444    #[test]
445    fn swiss_grouping_uses_apostrophe() {
446        assert_eq!(format_int(80000, Locale::DeCh), "80'000");
447        assert_eq!(format_int(1234567, Locale::FrCh), "1'234'567");
448        assert_eq!(format_number(1234567.5, 2, Locale::ItCh), "1'234'567.50");
449    }
450
451    #[test]
452    fn western_number_conventions() {
453        assert_eq!(format_number(1234567.5, 2, Locale::EnUs), "1,234,567.50");
454        assert_eq!(format_number(1234567.5, 2, Locale::DeDe), "1.234.567,50");
455        assert_eq!(format_number(1234.5, 2, Locale::FrFr), "1\u{202f}234,50");
456        assert_eq!(format_number(12.0, 0, Locale::EnUs), "12");
457        assert_eq!(format_number(999.999, 2, Locale::EnUs), "1,000.00"); // rounds up + regroups
458    }
459
460    #[test]
461    fn negatives_and_zero() {
462        assert_eq!(format_int(-1234, Locale::EnUs), "-1,234");
463        assert_eq!(format_number(-0.001, 2, Locale::EnUs), "0.00"); // rounds to zero → no sign
464        assert_eq!(format_number(-12.5, 1, Locale::DeCh), "-12.5");
465    }
466
467    #[test]
468    fn currency_placement() {
469        assert_eq!(format_currency(1234.5, Currency::Chf, Locale::DeCh), "CHF 1'234.50");
470        assert_eq!(format_currency(1234.5, Currency::Usd, Locale::EnUs), "$1,234.50");
471        assert_eq!(format_currency(1234.5, Currency::Gbp, Locale::EnGb), "£1,234.50");
472        assert_eq!(format_currency(1234.5, Currency::Eur, Locale::DeDe), "1.234,50 €");
473        assert_eq!(format_currency(1234.5, Currency::Eur, Locale::EnUs), "€1,234.50");
474    }
475
476    #[test]
477    fn dates() {
478        assert_eq!(format_date(2026, 1, 5, Locale::DeCh), "05.01.2026");
479        assert_eq!(format_date(2026, 1, 5, Locale::EnUs), "01/05/2026");
480        assert_eq!(format_date(2026, 12, 31, Locale::ItIt), "31/12/2026");
481        assert_eq!(format_date_long(2026, 1, 5, Locale::DeCh), "5. Januar 2026");
482        assert_eq!(format_date_long(2026, 3, 5, Locale::FrCh), "5 mars 2026");
483        assert_eq!(format_date_long(2026, 1, 5, Locale::EnUs), "January 5, 2026");
484    }
485
486    #[test]
487    fn serbian() {
488        // Latin + Cyrillic share number/date conventions (".", ",", trailing-dot date).
489        assert_eq!(format_int(1234567, Locale::SrLatn), "1.234.567");
490        assert_eq!(format_number(1234.5, 2, Locale::SrCyrl), "1.234,50");
491        assert_eq!(format_date(2026, 12, 31, Locale::SrLatn), "31.12.2026.");
492        assert_eq!(format_currency(1234.5, Currency::Rsd, Locale::SrLatn), "1.234,50 din.");
493        assert_eq!(format_currency(1234.5, Currency::Rsd, Locale::SrCyrl), "1.234,50 дин.");
494        assert_eq!(format_currency(1234.5, Currency::Rsd, Locale::EnUs), "1,234.50 RSD");
495        // Month names differ by script.
496        assert_eq!(format_date_long(2026, 1, 5, Locale::SrLatn), "5. januar 2026");
497        assert_eq!(format_date_long(2026, 1, 5, Locale::SrCyrl), "5. јануар 2026");
498    }
499
500    #[test]
501    fn ukrainian() {
502        // No-break space grouping, comma decimal, trailing ₴.
503        assert_eq!(format_int(1234567, Locale::UkUa), "1\u{a0}234\u{a0}567");
504        assert_eq!(format_number(1234.5, 2, Locale::UkUa), "1\u{a0}234,50");
505        assert_eq!(format_currency(1234.5, Currency::Uah, Locale::UkUa), "1\u{a0}234,50 ₴");
506        // dd.MM.yyyy (no trailing dot), nominative month name, day-month-year long form.
507        assert_eq!(format_date(2026, 12, 31, Locale::UkUa), "31.12.2026");
508        assert_eq!(month_name(1, Locale::UkUa), "січень");
509        assert_eq!(format_date_long(2026, 5, 5, Locale::UkUa), "5 травня 2026 р.");
510        assert_eq!(format_date_long(2026, 11, 30, Locale::UkUa), "30 листопада 2026 р.");
511        assert_eq!(month_name(5, Locale::UkUa), "травень");
512        assert_eq!(month_year(2026, 5, Locale::UkUa), "Травень 2026");
513    }
514
515    #[test]
516    fn polish() {
517        assert_eq!(format_int(1234, Locale::PlPl), "1234");
518        assert_eq!(format_int(12345, Locale::PlPl), "12\u{a0}345");
519        assert_eq!(format_int(-1234, Locale::PlPl), "-1234");
520        assert_eq!(format_int(-12345, Locale::PlPl), "-12\u{a0}345");
521        assert_eq!(format_number(1234.5, 2, Locale::PlPl), "1234,50");
522        assert_eq!(format_number(-1234.5, 2, Locale::PlPl), "-1234,50");
523        assert_eq!(format_number(9999.999, 2, Locale::PlPl), "10\u{a0}000,00");
524        assert_eq!(format_number(1234567.5, 2, Locale::PlPl), "1\u{a0}234\u{a0}567,50");
525        assert_eq!(format_currency(1234.5, Currency::Eur, Locale::PlPl), "1234,50 €");
526        assert_eq!(format_date(2026, 12, 31, Locale::PlPl), "31.12.2026");
527        // Long dates take the genitive ("31 grudnia"); the month name alone stays nominative.
528        assert_eq!(format_date_long(2026, 12, 31, Locale::PlPl), "31 grudnia 2026");
529        assert_eq!(format_date_long(2026, 9, 1, Locale::PlPl), "1 września 2026");
530        assert_eq!(month_name(12, Locale::PlPl), "grudzień");
531        assert_eq!(month_name(10, Locale::PlPl), "październik");
532        assert_eq!(month_year(2026, 12, Locale::PlPl), "Grudzień 2026");
533        let pl: Vec<&str> = (0..7).map(|i| weekday_short(i, Locale::PlPl)).collect();
534        assert_eq!(pl, ["N", "P", "W", "Ś", "C", "P", "S"]);
535        assert_eq!(Locale::PlPl.week_start(), Weekday::Monday);
536    }
537
538    #[test]
539    fn polish_zloty() {
540        assert_eq!(format_currency(1234.5, Currency::Pln, Locale::PlPl), "1234,50 zł");
541        assert_eq!(format_currency(12345.5, Currency::Pln, Locale::PlPl), "12\u{a0}345,50 zł");
542        assert_eq!(format_currency(1234.5, Currency::Pln, Locale::EnUs), "1,234.50 zł");
543    }
544
545    #[test]
546    fn spanish() {
547        assert_eq!(format_int(1234, Locale::EsEs), "1234");
548        assert_eq!(format_int(12345, Locale::EsEs), "12.345");
549        assert_eq!(format_number(1234.5, 2, Locale::EsEs), "1234,50");
550        assert_eq!(format_number(12345.5, 2, Locale::EsEs), "12.345,50");
551        assert_eq!(format_currency(1234.5, Currency::Eur, Locale::EsEs), "1234,50 €");
552        assert_eq!(format_date(2026, 1, 5, Locale::EsEs), "05/01/2026");
553        assert_eq!(format_date_long(2026, 1, 5, Locale::EsEs), "5 de enero de 2026");
554        assert_eq!(month_name(1, Locale::EsEs), "enero");
555        assert_eq!(month_year(2026, 12, Locale::EsEs), "Diciembre de 2026");
556        let es: Vec<&str> = (0..7).map(|i| weekday_short(i, Locale::EsEs)).collect();
557        assert_eq!(es, ["D", "L", "M", "X", "J", "V", "S"]);
558        assert_eq!(Locale::EsEs.week_start(), Weekday::Monday);
559    }
560
561    #[test]
562    fn existing_locales_still_group_four_digits() {
563        assert_eq!(format_int(1234, Locale::DeDe), "1.234");
564        assert_eq!(format_int(1234, Locale::UkUa), "1\u{a0}234");
565        assert_eq!(format_int(1234, Locale::EnUs), "1,234");
566        assert_eq!(format_number(1234.5, 2, Locale::FrFr), "1\u{202f}234,50");
567    }
568
569    #[test]
570    fn defaults() {
571        assert_eq!(Locale::default(), Locale::EnUs);
572        assert_eq!(Currency::default(), Currency::Eur);
573    }
574
575    #[test]
576    fn tag_parsing() {
577        assert_eq!(Locale::from_tag("de-CH"), Some(Locale::DeCh));
578        assert_eq!(Locale::from_tag("uk"), Some(Locale::UkUa));
579        assert_eq!(Locale::from_tag("uk-UA"), Some(Locale::UkUa));
580        assert_eq!(Locale::from_tag("fr_FR"), Some(Locale::FrFr));
581        assert_eq!(Locale::from_tag("EN-us"), Some(Locale::EnUs));
582        assert_eq!(Locale::from_tag("it"), Some(Locale::ItIt));
583        assert_eq!(Locale::from_tag("sr-Latn-RS"), Some(Locale::SrLatn));
584        assert_eq!(Locale::from_tag("sr"), Some(Locale::SrCyrl));
585        assert_eq!(Locale::from_tag("sr-RS"), Some(Locale::SrCyrl));
586        assert_eq!(Locale::from_tag("pl"), Some(Locale::PlPl));
587        assert_eq!(Locale::from_tag("pl_PL"), Some(Locale::PlPl));
588        assert_eq!(Locale::from_tag("es"), Some(Locale::EsEs));
589        assert_eq!(Locale::from_tag("ES"), Some(Locale::EsEs));
590        assert_eq!(Locale::from_tag("es-MX"), Some(Locale::EsEs));
591        assert_eq!(Locale::from_tag("es-419"), Some(Locale::EsEs));
592        assert_eq!(Locale::from_tag("ja-JP"), None);
593    }
594
595    #[test]
596    fn week_start_and_weekday_labels() {
597        assert_eq!(Locale::EnUs.week_start(), Weekday::Sunday);
598        assert_eq!(Locale::EnGb.week_start(), Weekday::Monday);
599        assert_eq!(Locale::SrLatn.week_start(), Weekday::Monday);
600        assert_eq!(Weekday::Tuesday.sun0(), 2);
601        let sr: Vec<&str> = (1..8).map(|i| weekday_short(i, Locale::SrLatn)).collect();
602        assert_eq!(sr, ["P", "U", "S", "Č", "P", "S", "N"], "Monday-first Serbian, wraps past Saturday");
603        let en: Vec<&str> = (0..7).map(|i| weekday_short(i, Locale::EnUs)).collect();
604        assert_eq!(en, ["S", "M", "T", "W", "T", "F", "S"]);
605        assert_eq!(weekday_short(1, Locale::SrCyrl), "П");
606        assert_eq!(weekday_short(1, Locale::UkUa), "Пн");
607        assert_eq!(weekday_short(4, Locale::ItIt), "G");
608    }
609
610    #[test]
611    fn month_year_capitalizes() {
612        assert_eq!(month_year(2026, 6, Locale::EnUs), "June 2026");
613        assert_eq!(month_year(2026, 9, Locale::SrLatn), "Septembar 2026");
614        assert_eq!(month_year(2026, 9, Locale::SrCyrl), "Септембар 2026");
615        assert_eq!(month_year(2026, 6, Locale::UkUa), "Червень 2026");
616    }
617}