Skip to main content

egui_pop_i18n/
format.rs

1//! Locale-aware numbers and dates, for Rust code and for catalogues.
2//!
3//! In a catalogue, numbers go through Fluent's `NUMBER` function (or are
4//! placed as they are) and are written with the locale's separators;
5//! plurals select on them by the locale's rules. Dates go through
6//! `DATETIME`, which takes an ISO date (`2026-10-12`), date and time
7//! (`2026-10-12T14:05`) or a number of seconds since 1970 (UTC):
8//!
9//! ```ftl
10//! files = { $count ->
11//!     [one] { $count } file
12//!    *[other] { $count } files
13//! }
14//! size = { NUMBER($mib, maximumFractionDigits: 1) } MiB
15//! saved = Saved on { DATETIME($when, dateStyle: "long") }
16//! ```
17//!
18//! `dateStyle` is `short`, `medium` (the default), `long` or `full`;
19//! `timeStyle` is `short` or `medium`. Month and weekday names are known
20//! for English and French; other languages get numeric dates
21//! (`2026-10-12`).
22//!
23//! ```
24//! use egui_pop_i18n::format::{self, DateStyle};
25//!
26//! assert_eq!(format::number("fr", 1234.5, Some(1)), "1\u{202f}234,5");
27//! assert_eq!(format::number("en", 1234.5, Some(1)), "1,234.5");
28//! let d = format::Date::parse("2026-10-12").unwrap();
29//! assert_eq!(format::date("fr", &d, DateStyle::Long), "12 octobre 2026");
30//! assert_eq!(format::date("en", &d, DateStyle::Medium), "Oct 12, 2026");
31//! ```
32
33use fluent_bundle::types::{FluentNumber, FluentNumberOptions, FluentNumberStyle};
34use fluent_bundle::{FluentArgs, FluentValue};
35
36use crate::locale::language;
37
38/// How a locale writes numbers.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub struct Separators {
41    pub decimal: &'static str,
42    pub group: &'static str,
43    /// What goes between a number and `%`.
44    pub percent: &'static str,
45    /// What goes between a number and its unit (`1,5 EV`, `12 px`, a
46    /// slider's `50 %`).
47    pub unit: &'static str,
48}
49
50/// The separators of a locale (English's for a language not known).
51pub fn separators(locale: &str) -> Separators {
52    const NNBSP: &str = "\u{202f}";
53    const NBSP: &str = "\u{a0}";
54    let (decimal, group, percent) = match locale {
55        "de-CH" | "it-CH" => (".", "’", ""),
56        "pt-PT" => (",", NBSP, ""),
57        _ => match language(locale) {
58            "fr" => (",", NNBSP, NNBSP),
59            "de" | "nl" | "it" | "es" | "pt" | "da" | "id" | "el" | "ro" | "tr" | "sl" | "hr" => {
60                (",", ".", "")
61            }
62            "ru" | "uk" | "pl" | "cs" | "sk" | "sv" | "nb" | "fi" | "hu" | "bg" | "lt" | "lv"
63            | "et" => (",", NBSP, NBSP),
64            _ => (".", ",", ""),
65        },
66    };
67    // French typography puts a narrow no-break space before a unit;
68    // other languages keep a plain space.
69    let unit = if language(locale) == "fr" { NNBSP } else { " " };
70    Separators {
71        decimal,
72        group,
73        percent,
74        unit,
75    }
76}
77
78/// A number written for a locale: at most `max_fraction` digits after
79/// the separator (3 when `None`), trailing zeros dropped, grouped by
80/// thousands.
81pub fn number(locale: &str, value: f64, max_fraction: Option<usize>) -> String {
82    let options = FluentNumberOptions {
83        maximum_fraction_digits: max_fraction,
84        ..FluentNumberOptions::default()
85    };
86    number_with(locale, value, &options)
87}
88
89/// A number written for a locale with Fluent's options
90/// (`minimumFractionDigits`, `maximumFractionDigits`,
91/// `minimumIntegerDigits`, `useGrouping`, `style: "percent"`).
92pub fn number_with(locale: &str, value: f64, options: &FluentNumberOptions) -> String {
93    let sep = separators(locale);
94    if !value.is_finite() {
95        return value.to_string();
96    }
97    let percent = options.style == FluentNumberStyle::Percent;
98    let value = if percent { value * 100.0 } else { value };
99    let min = options.minimum_fraction_digits.unwrap_or(0);
100    let max = options
101        .maximum_fraction_digits
102        .unwrap_or(if percent { 0 } else { 3 })
103        .max(min);
104    let fixed = format!("{:.*}", max, value.abs());
105    let (int, frac) = fixed.split_once('.').unwrap_or((&fixed, ""));
106    let mut frac = frac.trim_end_matches('0').to_string();
107    while frac.len() < min {
108        frac.push('0');
109    }
110    let mut int = int.to_string();
111    if let Some(digits) = options.minimum_integer_digits {
112        while int.len() < digits {
113            int.insert(0, '0');
114        }
115    }
116    let int = if options.use_grouping && int.len() > 3 {
117        let mut out = String::new();
118        for (i, c) in int.chars().enumerate() {
119            if i > 0 && (int.len() - i) % 3 == 0 {
120                out.push_str(sep.group);
121            }
122            out.push(c);
123        }
124        out
125    } else {
126        int
127    };
128    let negative =
129        value < 0.0 && (int.chars().any(|c| c.is_ascii_digit() && c != '0') || !frac.is_empty());
130    let mut out = String::new();
131    if negative {
132        out.push('-');
133    }
134    out.push_str(&int);
135    if !frac.is_empty() {
136        out.push_str(sep.decimal);
137        out.push_str(&frac);
138    }
139    if percent {
140        out.push_str(sep.percent);
141        out.push('%');
142    }
143    out
144}
145
146/// A number already written followed by its unit, with the locale's
147/// space between them (the number alone when `unit` is empty).
148///
149/// ```
150/// use egui_pop_i18n::format;
151///
152/// assert_eq!(format::quantity("fr", "1,5", "EV"), "1,5\u{202f}EV");
153/// assert_eq!(format::quantity("en", "50", "%"), "50 %");
154/// ```
155pub fn quantity(locale: &str, number: &str, unit: &str) -> String {
156    if unit.is_empty() {
157        number.to_string()
158    } else {
159        format!("{number}{}{unit}", separators(locale).unit)
160    }
161}
162
163/// A calendar date, with an optional time of day.
164#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165pub struct Date {
166    pub year: i32,
167    pub month: u32,
168    pub day: u32,
169    pub time: Option<(u32, u32, u32)>,
170}
171
172impl Date {
173    /// From `YYYY-MM-DD`, optionally followed by `THH:MM[:SS]` (a
174    /// trailing zone or fraction is ignored).
175    pub fn parse(s: &str) -> Option<Self> {
176        let s = s.trim();
177        let (date, time) = match s.split_once(['T', ' ']) {
178            Some((d, t)) => (d, Some(t)),
179            None => (s, None),
180        };
181        let mut parts = date.splitn(3, '-');
182        let year = parts.next()?.parse().ok()?;
183        let month: u32 = parts.next()?.parse().ok()?;
184        let day: u32 = parts.next()?.parse().ok()?;
185        if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
186            return None;
187        }
188        let time = match time {
189            None => None,
190            Some(t) => {
191                let t: String = t
192                    .chars()
193                    .take_while(|c| c.is_ascii_digit() || *c == ':')
194                    .collect();
195                let mut p = t.split(':');
196                let h: u32 = p.next()?.parse().ok()?;
197                let m: u32 = p.next()?.parse().ok()?;
198                let sec: u32 = p.next().map_or(Some(0), |x| x.parse().ok())?;
199                (h < 24 && m < 60 && sec < 61).then_some((h, m, sec))?;
200                Some((h, m, sec))
201            }
202        };
203        Some(Self {
204            year,
205            month,
206            day,
207            time,
208        })
209    }
210
211    /// From seconds since 1970-01-01 (UTC).
212    pub fn from_unix(seconds: i64) -> Self {
213        let days = seconds.div_euclid(86_400);
214        let secs = seconds.rem_euclid(86_400) as u32;
215        // Howard Hinnant's days-to-civil.
216        let z = days + 719_468;
217        let era = z.div_euclid(146_097);
218        let doe = z.rem_euclid(146_097);
219        let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
220        let y = yoe + era * 400;
221        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
222        let mp = (5 * doy + 2) / 153;
223        let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
224        let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
225        let year = (if month <= 2 { y + 1 } else { y }) as i32;
226        Self {
227            year,
228            month,
229            day,
230            time: Some((secs / 3600, secs / 60 % 60, secs % 60)),
231        }
232    }
233
234    /// The day of the week, 0 for Monday.
235    pub fn weekday(&self) -> u32 {
236        // Days since 1970-01-01 (a Thursday), by civil-to-days.
237        let (y, m) = if self.month <= 2 {
238            (i64::from(self.year) - 1, i64::from(self.month) + 9)
239        } else {
240            (i64::from(self.year), i64::from(self.month) - 3)
241        };
242        let era = y.div_euclid(400);
243        let yoe = y.rem_euclid(400);
244        let doy = (153 * m + 2) / 5 + i64::from(self.day) - 1;
245        let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
246        let days = era * 146_097 + doe - 719_468;
247        (days + 3).rem_euclid(7) as u32
248    }
249}
250
251/// How long a date is written.
252#[derive(Clone, Copy, Debug, PartialEq, Eq)]
253pub enum DateStyle {
254    Short,
255    Medium,
256    Long,
257    Full,
258}
259
260impl DateStyle {
261    fn parse(s: &str) -> Option<Self> {
262        Some(match s {
263            "short" => Self::Short,
264            "medium" => Self::Medium,
265            "long" => Self::Long,
266            "full" => Self::Full,
267            _ => return None,
268        })
269    }
270}
271
272const EN_MONTHS: [&str; 12] = [
273    "January",
274    "February",
275    "March",
276    "April",
277    "May",
278    "June",
279    "July",
280    "August",
281    "September",
282    "October",
283    "November",
284    "December",
285];
286const EN_DAYS: [&str; 7] = [
287    "Monday",
288    "Tuesday",
289    "Wednesday",
290    "Thursday",
291    "Friday",
292    "Saturday",
293    "Sunday",
294];
295const FR_MONTHS: [&str; 12] = [
296    "janvier",
297    "février",
298    "mars",
299    "avril",
300    "mai",
301    "juin",
302    "juillet",
303    "août",
304    "septembre",
305    "octobre",
306    "novembre",
307    "décembre",
308];
309const FR_SHORT_MONTHS: [&str; 12] = [
310    "janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.",
311    "déc.",
312];
313const FR_DAYS: [&str; 7] = [
314    "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche",
315];
316
317/// English written month first (the United States, or no region).
318fn month_first(locale: &str) -> bool {
319    let region = locale.split('-').skip(1).find(|p| p.len() == 2);
320    matches!(region, None | Some("US" | "PH"))
321}
322
323/// A date written for a locale.
324pub fn date(locale: &str, d: &Date, style: DateStyle) -> String {
325    let m = (d.month as usize).saturating_sub(1).min(11);
326    let (y, day) = (d.year, d.day);
327    match language(locale) {
328        "en" => {
329            let month = EN_MONTHS[m];
330            let us = month_first(locale);
331            match style {
332                DateStyle::Short if us => format!("{}/{day}/{}", d.month, y.rem_euclid(100)),
333                DateStyle::Short => format!("{day:02}/{:02}/{y}", d.month),
334                DateStyle::Medium if us => format!("{} {day}, {y}", &month[..3]),
335                DateStyle::Medium => format!("{day} {} {y}", &month[..3]),
336                DateStyle::Long if us => format!("{month} {day}, {y}"),
337                DateStyle::Long => format!("{day} {month} {y}"),
338                DateStyle::Full if us => {
339                    format!("{}, {month} {day}, {y}", EN_DAYS[d.weekday() as usize])
340                }
341                DateStyle::Full => format!("{}, {day} {month} {y}", EN_DAYS[d.weekday() as usize]),
342            }
343        }
344        "fr" => match style {
345            DateStyle::Short => format!("{day:02}/{:02}/{y}", d.month),
346            DateStyle::Medium => format!("{day} {} {y}", FR_SHORT_MONTHS[m]),
347            DateStyle::Long => format!("{day} {} {y}", FR_MONTHS[m]),
348            DateStyle::Full => format!(
349                "{} {day} {} {y}",
350                FR_DAYS[d.weekday() as usize],
351                FR_MONTHS[m]
352            ),
353        },
354        _ => format!("{y:04}-{:02}-{day:02}", d.month),
355    }
356}
357
358/// A time of day written for a locale; `seconds` for the medium style.
359pub fn time(locale: &str, hour: u32, minute: u32, second: Option<u32>) -> String {
360    let secs = second.map(|s| format!(":{s:02}")).unwrap_or_default();
361    if language(locale) == "en" && month_first(locale) {
362        let h12 = match hour % 12 {
363            0 => 12,
364            h => h,
365        };
366        let half = if hour < 12 { "AM" } else { "PM" };
367        format!("{h12}:{minute:02}{secs}\u{202f}{half}")
368    } else {
369        format!("{hour:02}:{minute:02}{secs}")
370    }
371}
372
373/// Number formatting as Fluent's custom formatter: called by every
374/// bundle for every number it writes, with the bundle's locale.
375pub(crate) fn fluent_formatter(
376    value: &FluentValue,
377    intls: &intl_memoizer::concurrent::IntlLangMemoizer,
378) -> Option<String> {
379    use fluent_bundle::memoizer::MemoizerKind;
380    let FluentValue::Number(n) = value else {
381        return None;
382    };
383    intls
384        .with_try_get_threadsafe::<LocaleOf, _, _>((), |l| number_with(&l.0, n.value, &n.options))
385        .ok()
386}
387
388/// The locale a memoizer is for.
389struct LocaleOf(String);
390
391impl intl_memoizer::Memoizable for LocaleOf {
392    type Args = ();
393    type Error = ();
394
395    fn construct(lang: unic_langid::LanguageIdentifier, _: ()) -> Result<Self, ()> {
396        Ok(Self(lang.to_string()))
397    }
398}
399
400/// The `DATETIME` function of a bundle in `locale`.
401pub(crate) fn datetime_function(
402    locale: String,
403) -> impl for<'a> Fn(&[FluentValue<'a>], &FluentArgs) -> FluentValue<'a> + Send + Sync + 'static {
404    move |positional, named| {
405        let d = match positional.first() {
406            Some(FluentValue::String(s)) => Date::parse(s),
407            Some(FluentValue::Number(n)) => Some(Date::from_unix(n.value as i64)),
408            _ => None,
409        };
410        let Some(d) = d else {
411            return FluentValue::Error;
412        };
413        let option = |name: &str| match named.get(name) {
414            Some(FluentValue::String(s)) => Some(s.to_string()),
415            _ => None,
416        };
417        let date_style = option("dateStyle").and_then(|s| DateStyle::parse(&s));
418        let time_style = option("timeStyle");
419        let mut parts = Vec::new();
420        if date_style.is_some() || time_style.is_none() {
421            parts.push(date(&locale, &d, date_style.unwrap_or(DateStyle::Medium)));
422        }
423        if let (Some(ts), Some((h, m, s))) = (time_style, d.time) {
424            parts.push(time(&locale, h, m, (ts == "medium").then_some(s)));
425        }
426        FluentValue::String(parts.join(" ").into())
427    }
428}
429
430/// A Fluent number from Rust, for arguments.
431pub fn fluent_number(value: f64) -> FluentValue<'static> {
432    FluentValue::Number(FluentNumber::new(value, FluentNumberOptions::default()))
433}
434
435#[cfg(test)]
436mod tests {
437    use super::*;
438
439    #[test]
440    fn numbers_follow_the_locale() {
441        assert_eq!(number("en", 1_234_567.891, None), "1,234,567.891");
442        assert_eq!(
443            number("fr", 1_234_567.891, Some(2)),
444            "1\u{202f}234\u{202f}567,89"
445        );
446        assert_eq!(number("de", 1234.0, None), "1.234");
447        assert_eq!(number("en", 3.0, None), "3");
448        assert_eq!(number("en", -0.0001, Some(2)), "0");
449        assert_eq!(number("en", -2.5, None), "-2.5");
450        let pct = FluentNumberOptions {
451            style: FluentNumberStyle::Percent,
452            ..Default::default()
453        };
454        assert_eq!(number_with("fr", 0.25, &pct), "25\u{202f}%");
455        assert_eq!(number_with("en", 0.25, &pct), "25%");
456        let min = FluentNumberOptions {
457            minimum_fraction_digits: Some(2),
458            use_grouping: false,
459            ..Default::default()
460        };
461        assert_eq!(number_with("en", 1234.5, &min), "1234.50");
462    }
463
464    #[test]
465    fn a_unit_is_spaced_as_the_locale_does() {
466        assert_eq!(quantity("fr", "1,50", "EV"), "1,50\u{202f}EV");
467        assert_eq!(quantity("fr-CA", "50", "%"), "50\u{202f}%");
468        assert_eq!(quantity("en", "1.50", "EV"), "1.50 EV");
469        assert_eq!(quantity("en-US", "50", "%"), "50 %");
470        assert_eq!(quantity("de", "12", "px"), "12 px");
471        assert_eq!(quantity("fr", "3", ""), "3");
472    }
473
474    #[test]
475    fn dates_parse_and_print() {
476        let d = Date::parse("2026-10-12T14:05:09Z").unwrap();
477        assert_eq!(d.time, Some((14, 5, 9)));
478        assert_eq!(d.weekday(), 0, "a Monday");
479        assert_eq!(
480            Date::from_unix(0),
481            Date::parse("1970-01-01T00:00:00").unwrap()
482        );
483        assert_eq!(
484            Date::from_unix(1_791_806_752),
485            Date::parse("2026-10-12T12:05:52").unwrap()
486        );
487        assert_eq!(date("en", &d, DateStyle::Full), "Monday, October 12, 2026");
488        assert_eq!(date("en-GB", &d, DateStyle::Medium), "12 Oct 2026");
489        assert_eq!(date("en", &d, DateStyle::Short), "10/12/26");
490        assert_eq!(date("fr", &d, DateStyle::Full), "lundi 12 octobre 2026");
491        assert_eq!(date("fr", &d, DateStyle::Short), "12/10/2026");
492        assert_eq!(date("ja", &d, DateStyle::Long), "2026-10-12");
493        assert_eq!(time("en", 14, 5, None), "2:05\u{202f}PM");
494        assert_eq!(time("fr", 14, 5, Some(9)), "14:05:09");
495        assert!(Date::parse("2026-13-01").is_none());
496    }
497}