Skip to main content

mitsuami_core/l10n/
format.rs

1//! Numbers and dates, written the user's way: by the platform's own
2//! formatters, which follow the region settings (decimal and grouping
3//! separators, date order, 12 or 24 hours).
4
5use std::borrow::Cow;
6use std::time::{SystemTime, UNIX_EPOCH};
7
8use fluent_bundle::types::{FluentNumberCurrencyDisplayStyle, FluentNumberOptions, FluentNumberStyle, FluentType};
9use fluent_bundle::{FluentArgs, FluentValue};
10
11/// The user's languages and how they write numbers and dates, as the
12/// platform has them. Each backend gives one ([`Backend::locale`]).
13///
14/// [`Backend::locale`]: crate::Backend::locale
15pub trait PlatformLocale {
16    /// The languages the user prefers, most preferred first, as BCP 47
17    /// tags (`"pt-BR"`, `"zh-Hant-TW"`).
18    fn languages(&self) -> Vec<String>;
19
20    /// `value` written as the user's region writes numbers, or `None` to
21    /// have mitsuami write it.
22    fn format_number(&self, value: f64, format: &NumberFormat) -> Option<String>;
23
24    /// `time` written as the user's region writes dates and times, in the
25    /// user's time zone, or `None` to have mitsuami write it.
26    fn format_date_time(&self, time: SystemTime, format: &DateTimeFormat) -> Option<String>;
27}
28
29/// How a number is written: Fluent's `NUMBER()` options, which are
30/// ECMAScript `Intl.NumberFormat`'s. Each platform does what its own
31/// formatter can of them.
32#[derive(Clone, Debug, PartialEq)]
33pub struct NumberFormat {
34    pub style: NumberStyle,
35    /// Separators between groups of digits, where the region has them.
36    pub grouping: bool,
37    pub minimum_integer_digits: Option<usize>,
38    pub minimum_fraction_digits: Option<usize>,
39    pub maximum_fraction_digits: Option<usize>,
40    /// Significant digits, in place of the fraction digits when set.
41    pub minimum_significant_digits: Option<usize>,
42    pub maximum_significant_digits: Option<usize>,
43}
44
45impl Default for NumberFormat {
46    fn default() -> NumberFormat {
47        NumberFormat {
48            style: NumberStyle::Decimal,
49            grouping: true,
50            minimum_integer_digits: None,
51            minimum_fraction_digits: None,
52            maximum_fraction_digits: None,
53            minimum_significant_digits: None,
54            maximum_significant_digits: None,
55        }
56    }
57}
58
59#[derive(Clone, Debug, Default, PartialEq)]
60pub enum NumberStyle {
61    #[default]
62    Decimal,
63    /// The value times 100, with the region's percent sign.
64    Percent,
65    /// An amount of this currency (ISO 4217, `"EUR"`).
66    Currency { code: String, display: CurrencyDisplay },
67}
68
69/// How a currency is named next to its amount.
70#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
71pub enum CurrencyDisplay {
72    /// Its symbol (€), where the region has one.
73    #[default]
74    Symbol,
75    /// Its code (EUR).
76    Code,
77    /// Its name (euros), where the platform has one.
78    Name,
79}
80
81impl NumberFormat {
82    /// The fraction digits the style has when the format gives none, as
83    /// `Intl.NumberFormat` has them.
84    pub fn fraction_digits(&self) -> (usize, usize) {
85        let (min, max) = match &self.style {
86            NumberStyle::Decimal => (0, 3),
87            NumberStyle::Percent => (0, 0),
88            NumberStyle::Currency { code, .. } => {
89                let digits = currency_digits(code);
90                (digits, digits)
91            }
92        };
93        // A maximum below the style's minimum lowers it, as Intl's does.
94        let min = self.minimum_fraction_digits.unwrap_or(match self.maximum_fraction_digits {
95            Some(max) => min.min(max),
96            None => min,
97        });
98        let max = self.maximum_fraction_digits.unwrap_or(max).max(min);
99        (min, max)
100    }
101
102    pub(crate) fn from_fluent(options: &FluentNumberOptions) -> NumberFormat {
103        NumberFormat {
104            style: match options.style {
105                FluentNumberStyle::Decimal => NumberStyle::Decimal,
106                FluentNumberStyle::Percent => NumberStyle::Percent,
107                FluentNumberStyle::Currency => NumberStyle::Currency {
108                    code: options.currency.clone().unwrap_or_default(),
109                    display: match options.currency_display {
110                        FluentNumberCurrencyDisplayStyle::Symbol => CurrencyDisplay::Symbol,
111                        FluentNumberCurrencyDisplayStyle::Code => CurrencyDisplay::Code,
112                        FluentNumberCurrencyDisplayStyle::Name => CurrencyDisplay::Name,
113                    },
114                },
115            },
116            grouping: options.use_grouping,
117            // In the ranges `Intl.NumberFormat` takes, so a translation
118            // can't ask for a billion digits.
119            minimum_integer_digits: options.minimum_integer_digits.map(|n| n.clamp(1, 21)),
120            minimum_fraction_digits: options.minimum_fraction_digits.map(|n| n.min(100)),
121            maximum_fraction_digits: options.maximum_fraction_digits.map(|n| n.min(100)),
122            minimum_significant_digits: options.minimum_significant_digits.map(|n| n.clamp(1, 21)),
123            maximum_significant_digits: options.maximum_significant_digits.map(|n| n.clamp(1, 21)),
124        }
125    }
126}
127
128/// How a date and time are written: Fluent's `DATETIME()` `dateStyle`
129/// and `timeStyle`, `Intl.DateTimeFormat`'s. Each platform maps them to
130/// the styles it has. Neither: the date, short.
131#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
132pub struct DateTimeFormat {
133    pub date: Option<DateTimeStyle>,
134    pub time: Option<DateTimeStyle>,
135}
136
137impl DateTimeFormat {
138    /// What's shown: the date short when the format says nothing.
139    pub fn resolved(self) -> (Option<DateTimeStyle>, Option<DateTimeStyle>) {
140        match (self.date, self.time) {
141            (None, None) => (Some(DateTimeStyle::Short), None),
142            styles => styles,
143        }
144    }
145
146    fn merge(&mut self, args: &FluentArgs) {
147        for (key, value) in args.iter() {
148            let FluentValue::String(style) = value else { continue };
149            let style = match style.as_ref() {
150                "short" => DateTimeStyle::Short,
151                "medium" => DateTimeStyle::Medium,
152                "long" => DateTimeStyle::Long,
153                "full" => DateTimeStyle::Full,
154                _ => continue,
155            };
156            match key {
157                "dateStyle" => self.date = Some(style),
158                "timeStyle" => self.time = Some(style),
159                _ => {}
160            }
161        }
162    }
163}
164
165/// From the shortest (`9/29/26`, `3:04 PM`) to the longest (`Tuesday,
166/// September 29, 2026`, `3:04:05 PM Brasília Standard Time`).
167#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
168pub enum DateTimeStyle {
169    Short,
170    Medium,
171    Long,
172    Full,
173}
174
175/// A date and time passed to a message: a [`SystemTime`], with the
176/// format `DATETIME()` gives it.
177#[derive(Clone, Debug, PartialEq)]
178pub(crate) struct DateTimeArg {
179    pub time: SystemTime,
180    pub format: DateTimeFormat,
181}
182
183impl FluentType for DateTimeArg {
184    fn duplicate(&self) -> Box<dyn FluentType + Send> {
185        Box::new(self.clone())
186    }
187
188    fn as_string(&self, _: &intl_memoizer::IntlLangMemoizer) -> Cow<'static, str> {
189        format_date_time(self.time, &self.format).into()
190    }
191
192    fn as_string_threadsafe(&self, _: &intl_memoizer::concurrent::IntlLangMemoizer) -> Cow<'static, str> {
193        basic_date_time(self.time, &self.format).into()
194    }
195}
196
197/// Fluent's `DATETIME($date, dateStyle: "long", timeStyle: "short")`.
198#[allow(non_snake_case)]
199pub(crate) fn DATETIME<'a>(positional: &[FluentValue<'a>], named: &FluentArgs) -> FluentValue<'a> {
200    let Some(FluentValue::Custom(value)) = positional.first() else { return FluentValue::Error };
201    let Some(date) = value.as_any().downcast_ref::<DateTimeArg>() else { return FluentValue::Error };
202    let mut date = date.clone();
203    // Given styles replace the default, so a time alone is a time alone.
204    date.format = DateTimeFormat::default();
205    date.format.merge(named);
206    FluentValue::Custom(Box::new(date))
207}
208
209/// Every value a message shows goes through here: numbers and dates are
210/// the platform's to write.
211pub(crate) fn format_value(value: &FluentValue, _: &intl_memoizer::IntlLangMemoizer) -> Option<String> {
212    match value {
213        FluentValue::Number(n) => Some(format_number(n.value, &NumberFormat::from_fluent(&n.options))),
214        FluentValue::Custom(custom) => {
215            custom.as_any().downcast_ref::<DateTimeArg>().map(|d| format_date_time(d.time, &d.format))
216        }
217        _ => None,
218    }
219}
220
221/// `value` written the user's way, as messages write numbers: by the
222/// platform, or else in the style of US English.
223pub fn format_number(value: f64, format: &NumberFormat) -> String {
224    super::platform_locale()
225        .and_then(|platform| platform.format_number(value, format))
226        .unwrap_or_else(|| basic_number(value, format))
227}
228
229/// `time` written the user's way, as messages write dates: by the
230/// platform, or else in the style of US English, in UTC.
231pub fn format_date_time(time: SystemTime, format: &DateTimeFormat) -> String {
232    super::platform_locale()
233        .and_then(|platform| platform.format_date_time(time, format))
234        .unwrap_or_else(|| basic_date_time(time, format))
235}
236
237/// How a region writes numbers, for backends whose platform gives only
238/// its symbols (glibc's `localeconv`), not a formatter.
239#[derive(Clone, Debug, PartialEq)]
240pub struct NumberSymbols {
241    pub decimal: String,
242    pub group: String,
243    /// The sizes of the digit groups, from the decimal point out; the last
244    /// repeats.
245    pub grouping: Vec<usize>,
246    /// Where a currency's symbol goes, and whether a space parts it from
247    /// the amount.
248    pub currency_before: bool,
249    pub currency_space: bool,
250    /// The percent sign, with any space the region puts beside it, and
251    /// whether it goes before the number.
252    pub percent: String,
253    pub percent_before: bool,
254}
255
256impl NumberSymbols {
257    /// US English's.
258    pub fn us_english() -> NumberSymbols {
259        NumberSymbols {
260            decimal: ".".into(),
261            group: ",".into(),
262            grouping: vec![3],
263            currency_before: true,
264            currency_space: false,
265            percent: "%".into(),
266            percent_before: false,
267        }
268    }
269}
270
271/// US English, the way `Intl.NumberFormat("en-US")` writes it: what the
272/// headless backend shows, so tests don't depend on the machine.
273pub fn basic_number(value: f64, format: &NumberFormat) -> String {
274    format_number_with(value, format, &NumberSymbols::us_english())
275}
276
277/// `value` written with a region's symbols, the digits as
278/// `Intl.NumberFormat` rounds them.
279pub fn format_number_with(value: f64, format: &NumberFormat, symbols: &NumberSymbols) -> String {
280    if !value.is_finite() {
281        return if value.is_nan() {
282            "NaN".into()
283        } else if value > 0.0 {
284            "∞".into()
285        } else {
286            "-∞".into()
287        };
288    }
289    let scaled = if format.style == NumberStyle::Percent { value * 100.0 } else { value };
290    let digits = digits(scaled.abs(), format);
291    let (int, frac) = match digits.split_once('.') {
292        Some((i, f)) => (i.to_string(), Some(f.to_string())),
293        None => (digits, None),
294    };
295    let int = format!("{int:0>width$}", width = format.minimum_integer_digits.unwrap_or(1));
296    let mut out = if format.grouping { group(&int, symbols) } else { int };
297    if let Some(frac) = frac {
298        out.push_str(&symbols.decimal);
299        out.push_str(&frac);
300    }
301    let negative = scaled < 0.0 && out.chars().any(|c| c.is_ascii_digit() && c != '0');
302    let sign = if negative { "-" } else { "" };
303    match &format.style {
304        NumberStyle::Decimal => format!("{sign}{out}"),
305        NumberStyle::Percent if symbols.percent_before => format!("{sign}{}{out}", symbols.percent),
306        NumberStyle::Percent => format!("{sign}{out}{}", symbols.percent),
307        NumberStyle::Currency { code, display } => {
308            let symbol = match (display, currency_symbol(code)) {
309                (CurrencyDisplay::Symbol, Some(symbol)) => symbol.to_owned(),
310                _ => code.clone(),
311            };
312            // A code is always parted from the amount.
313            let space = if symbols.currency_space || symbol == *code { "\u{a0}" } else { "" };
314            if symbols.currency_before {
315                format!("{sign}{symbol}{space}{out}")
316            } else {
317                format!("{sign}{out}{space}{symbol}")
318            }
319        }
320    }
321}
322
323/// What a format shows of `value` (times 100 for a percentage), rounded
324/// as `Intl.NumberFormat` rounds it, and how many fraction digits it
325/// shows: for platforms whose formatter takes a number of digits (Qt's).
326pub fn rounded(value: f64, format: &NumberFormat) -> (f64, usize) {
327    let scaled = if format.style == NumberStyle::Percent { value * 100.0 } else { value };
328    if !scaled.is_finite() {
329        return (scaled, 0);
330    }
331    let digits = digits(scaled.abs(), format);
332    let decimals = digits.split_once('.').map_or(0, |(_, fraction)| fraction.len());
333    (digits.parse::<f64>().unwrap_or(scaled.abs()).copysign(scaled), decimals)
334}
335
336/// The digits of `abs`, with a `.` before its fraction.
337fn digits(abs: f64, format: &NumberFormat) -> String {
338    match (format.minimum_significant_digits, format.maximum_significant_digits) {
339        (None, None) => {
340            let (min, max) = format.fraction_digits();
341            trim_fraction(round_to(abs, max as i32), min)
342        }
343        (min, max) => {
344            let max = max.unwrap_or(21).max(1);
345            let min = min.unwrap_or(1).min(max);
346            significant(abs, min, max)
347        }
348    }
349}
350
351/// `abs` rounded to `decimals` fraction digits (negative: to tens,
352/// hundreds…), half away from zero as `Intl.NumberFormat` rounds, from its
353/// shortest decimal form: `{:.N}` would round ties to even, and show the
354/// binary value's digits past the 17th.
355fn round_to(abs: f64, decimals: i32) -> String {
356    let text = format!("{abs}");
357    let (int, fraction) = text.split_once('.').unwrap_or((&text, ""));
358    let mut digits: Vec<u8> = int.bytes().chain(fraction.bytes()).map(|b| b - b'0').collect();
359    let mut point = int.len() as i32;
360    let keep = point + decimals;
361    if keep < 0 {
362        digits.clear();
363    } else if (keep as usize) < digits.len() {
364        let up = digits[keep as usize] >= 5;
365        digits.truncate(keep as usize);
366        if up {
367            match digits.iter().rposition(|d| *d < 9) {
368                Some(i) => {
369                    digits[i] += 1;
370                    digits.truncate(i + 1);
371                }
372                None => {
373                    digits.clear();
374                    digits.push(1);
375                    point += 1;
376                }
377            }
378        }
379    }
380    let digit =
381        |i: i32| if i >= 0 && (i as usize) < digits.len() { char::from(b'0' + digits[i as usize]) } else { '0' };
382    let int: String = (0..point).map(digit).collect();
383    let int = match int.trim_start_matches('0') {
384        "" => "0".to_owned(),
385        trimmed => trimmed.to_owned(),
386    };
387    if decimals <= 0 {
388        return int;
389    }
390    let fraction: String = (point..point + decimals).map(digit).collect();
391    format!("{int}.{fraction}")
392}
393
394/// Drops trailing zeros past `min` fraction digits.
395fn trim_fraction(mut digits: String, min: usize) -> String {
396    if let Some(dot) = digits.find('.') {
397        let keep = dot + 1 + min;
398        while digits.len() > keep && digits.ends_with('0') {
399            digits.pop();
400        }
401        if digits.ends_with('.') {
402            digits.pop();
403        }
404    }
405    digits
406}
407
408fn significant(value: f64, min: usize, max: usize) -> String {
409    if value == 0.0 {
410        return trim_fraction(round_to(0.0, max as i32 - 1), min.saturating_sub(1));
411    }
412    let exponent = value.log10().floor() as i32;
413    let min_decimals = (min as i32 - 1 - exponent).max(0) as usize;
414    trim_fraction(round_to(value, max as i32 - 1 - exponent), min_decimals)
415}
416
417/// A currency's minor unit, as ISO 4217 and Intl have it.
418fn currency_digits(code: &str) -> usize {
419    match code {
420        "BIF" | "CLP" | "DJF" | "GNF" | "ISK" | "JPY" | "KMF" | "KRW" | "PYG" | "RWF" | "UGX" | "VND" | "VUV"
421        | "XAF" | "XOF" | "XPF" => 0,
422        "BHD" | "IQD" | "JOD" | "KWD" | "LYD" | "OMR" | "TND" => 3,
423        _ => 2,
424    }
425}
426
427fn group(int: &str, symbols: &NumberSymbols) -> String {
428    let Some(&last) = symbols.grouping.last().filter(|size| **size > 0) else { return int.to_owned() };
429    // Where groups start, counted from the right.
430    let mut cuts = Vec::new();
431    let mut at = 0;
432    for i in 0.. {
433        at += symbols.grouping.get(i).copied().unwrap_or(last);
434        if at >= int.len() {
435            break;
436        }
437        cuts.push(int.len() - at);
438    }
439    let mut out = String::with_capacity(int.len() + cuts.len() * symbols.group.len());
440    for (i, c) in int.chars().enumerate() {
441        if cuts.contains(&i) {
442            out.push_str(&symbols.group);
443        }
444        out.push(c);
445    }
446    out
447}
448
449fn currency_symbol(code: &str) -> Option<&'static str> {
450    Some(match code {
451        "USD" => "$",
452        "EUR" => "€",
453        "GBP" => "£",
454        "JPY" => "¥",
455        "BRL" => "R$",
456        "INR" => "₹",
457        _ => return None,
458    })
459}
460
461const MONTHS: [&str; 12] = [
462    "January",
463    "February",
464    "March",
465    "April",
466    "May",
467    "June",
468    "July",
469    "August",
470    "September",
471    "October",
472    "November",
473    "December",
474];
475const WEEKDAYS: [&str; 7] = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
476
477/// US English in UTC, as `Intl.DateTimeFormat("en-US", { timeZone: "UTC" })`
478/// writes it: what the headless backend shows.
479pub fn basic_date_time(time: SystemTime, format: &DateTimeFormat) -> String {
480    let seconds = match time.duration_since(UNIX_EPOCH) {
481        Ok(d) => d.as_secs() as i64,
482        Err(e) => -(e.duration().as_secs_f64().ceil() as i64),
483    };
484    let days = seconds.div_euclid(86_400);
485    let of_day = seconds.rem_euclid(86_400);
486    let (year, month, day) = civil_from_days(days);
487    let weekday = WEEKDAYS[(days + 4).rem_euclid(7) as usize];
488    let month_name = MONTHS[month as usize - 1];
489    let (date_style, time_style) = format.resolved();
490    let date = date_style.map(|style| match style {
491        DateTimeStyle::Short => format!("{month}/{day}/{:02}", year.rem_euclid(100)),
492        DateTimeStyle::Medium => format!("{} {day}, {year}", &month_name[..3]),
493        DateTimeStyle::Long => format!("{month_name} {day}, {year}"),
494        DateTimeStyle::Full => format!("{weekday}, {month_name} {day}, {year}"),
495    });
496    let time = time_style.map(|style| {
497        let (hour, minute, second) = (of_day / 3600, of_day / 60 % 60, of_day % 60);
498        let (hour12, half) = (if hour % 12 == 0 { 12 } else { hour % 12 }, if hour < 12 { "AM" } else { "PM" });
499        match style {
500            DateTimeStyle::Short => format!("{hour12}:{minute:02}\u{202f}{half}"),
501            DateTimeStyle::Medium => format!("{hour12}:{minute:02}:{second:02}\u{202f}{half}"),
502            DateTimeStyle::Long | DateTimeStyle::Full => {
503                format!("{hour12}:{minute:02}:{second:02}\u{202f}{half} UTC")
504            }
505        }
506    });
507    match (date, time) {
508        (Some(date), Some(time)) => format!("{date}, {time}"),
509        (Some(one), None) | (None, Some(one)) => one,
510        (None, None) => String::new(),
511    }
512}
513
514/// Howard Hinnant's `civil_from_days`: the proleptic Gregorian date of a
515/// day counted from 1970-01-01.
516fn civil_from_days(days: i64) -> (i64, u32, u32) {
517    let z = days + 719_468;
518    let era = z.div_euclid(146_097);
519    let doe = z.rem_euclid(146_097);
520    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
521    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
522    let mp = (5 * doy + 2) / 153;
523    let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
524    let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
525    let year = yoe + era * 400 + i64::from(month <= 2);
526    (year, month, day)
527}