Skip to main content

lumen_dioxus/content/
number_format.rs

1//! Display formatting for `FormattedNumber` and `FormattedDate` without `Intl`.
2//!
3//! [`format_lumen_number`] ports Lumen's `formatLumenNumber`, which wraps `Intl.NumberFormat`, for
4//! English. It validates options the same way, rounds the shortest round-trip decimal of the value
5//! half away from zero the way ICU does, and reads currency, unit, and compact text from the
6//! generated `number_format_data` tables for `en` and `en-US`. Other locales and Unicode
7//! numbering-system extensions use ICU4X and generated CLDR patterns in `localized`.
8//!
9//! [`format_lumen_date`] renders an ISO 8601 date or date-time as
10//! `Intl.DateTimeFormat("en-US", { timeZone: "UTC" })` does.
11
12// cspell:words CLDR feff
13
14use super::number_format_data::{
15    COMPACT_LONG, COMPACT_SHORT, COMPOUND_UNITS, CURRENCIES, Currency, UNITS, Unit,
16};
17
18#[path = "localized_number.rs"]
19mod localized;
20
21/// Number style for `FormattedNumber`: the `Intl.NumberFormat` `style` option.
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23#[non_exhaustive]
24pub enum FormattedNumberFormat {
25    /// A plain number, such as "1,234.5".
26    #[default]
27    Decimal,
28    /// Money in the given currency, such as "$1,234.50". Formats as `Decimal` without a valid code.
29    Currency,
30    /// A ratio shown as a percentage, so `0.25` reads "25%".
31    Percent,
32    /// A measurement in the given unit, such as "16 km/h". Formats as `Decimal` without a unit.
33    Unit,
34}
35
36impl FormattedNumberFormat {
37    /// The `Intl.NumberFormat` `style` value, such as `"currency"`.
38    pub fn as_str(self) -> &'static str {
39        match self {
40            Self::Decimal => "decimal",
41            Self::Currency => "currency",
42            Self::Percent => "percent",
43            Self::Unit => "unit",
44        }
45    }
46}
47
48/// How `FormattedNumber` writes the magnitude: the `Intl.NumberFormat` `notation` option.
49#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
50#[non_exhaustive]
51pub enum FormattedNumberNotation {
52    /// Every digit, such as "1,234,567".
53    #[default]
54    Standard,
55    /// One integer digit and a power of ten, such as "1.235E6".
56    Scientific,
57    /// A power of ten that is a multiple of three, such as "1.235E6" or "12.346E3".
58    Engineering,
59    /// Rounded with a magnitude word, such as "1.2M", with "1.2 million" for assistive technology.
60    Compact,
61}
62
63impl FormattedNumberNotation {
64    /// The `Intl.NumberFormat` `notation` value, such as `"compact"`.
65    pub fn as_str(self) -> &'static str {
66        match self {
67            Self::Standard => "standard",
68            Self::Scientific => "scientific",
69            Self::Engineering => "engineering",
70            Self::Compact => "compact",
71        }
72    }
73}
74
75/// When `FormattedNumber` shows a sign: the `Intl.NumberFormat` `signDisplay` option.
76#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
77#[non_exhaustive]
78pub enum FormattedNumberSignDisplay {
79    /// A minus sign for negative values, including negative zero.
80    #[default]
81    Auto,
82    /// A plus or minus sign on every value, including zero.
83    Always,
84    /// A plus or minus sign on every value except zero.
85    ExceptZero,
86    /// No sign at all.
87    Never,
88}
89
90impl FormattedNumberSignDisplay {
91    /// The `Intl.NumberFormat` `signDisplay` value, such as `"exceptZero"`.
92    pub fn as_str(self) -> &'static str {
93        match self {
94            Self::Auto => "auto",
95            Self::Always => "always",
96            Self::ExceptZero => "exceptZero",
97            Self::Never => "never",
98        }
99    }
100}
101
102/// How `FormattedNumber` names a currency: the `Intl.NumberFormat` `currencyDisplay` option.
103#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
104#[non_exhaustive]
105pub enum FormattedNumberCurrencyDisplay {
106    /// The locale's symbol, such as "$" for CAD in en-CA and "CA$" in en-US.
107    #[default]
108    Symbol,
109    /// The shortest symbol, such as "$" for both USD and CAD.
110    NarrowSymbol,
111    /// The ISO 4217 code, such as "USD".
112    Code,
113    /// The full name, such as "US dollars".
114    Name,
115}
116
117impl FormattedNumberCurrencyDisplay {
118    /// The `Intl.NumberFormat` `currencyDisplay` value, such as `"narrowSymbol"`.
119    pub fn as_str(self) -> &'static str {
120        match self {
121            Self::Symbol => "symbol",
122            Self::NarrowSymbol => "narrowSymbol",
123            Self::Code => "code",
124            Self::Name => "name",
125        }
126    }
127}
128
129/// When `FormattedNumber` reads the full currency name to assistive technology.
130#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
131#[non_exhaustive]
132pub enum FormattedNumberCurrencyName {
133    /// Only for symbols that several currencies share, such as "$", "¥", "£", or "kr".
134    #[default]
135    Auto,
136    /// For every currency symbol and code.
137    Always,
138    /// Never; assistive technology reads the visible symbol.
139    Never,
140}
141
142impl FormattedNumberCurrencyName {
143    /// The Lumen `currencyName` value, such as `"auto"`.
144    pub fn as_str(self) -> &'static str {
145        match self {
146            Self::Auto => "auto",
147            Self::Always => "always",
148            Self::Never => "never",
149        }
150    }
151}
152
153/// How `FormattedNumber` writes a unit: the `Intl.NumberFormat` `unitDisplay` option.
154#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
155#[non_exhaustive]
156pub enum FormattedNumberUnitDisplay {
157    /// An abbreviation, such as "16 km/h".
158    #[default]
159    Short,
160    /// The tightest abbreviation, such as "16km/h".
161    Narrow,
162    /// The full name, such as "16 kilometers per hour".
163    Long,
164}
165
166impl FormattedNumberUnitDisplay {
167    /// The `Intl.NumberFormat` `unitDisplay` value, such as `"long"`.
168    pub fn as_str(self) -> &'static str {
169        match self {
170            Self::Short => "short",
171            Self::Narrow => "narrow",
172            Self::Long => "long",
173        }
174    }
175}
176
177/// Date length for `FormattedDate`: the `Intl.DateTimeFormat` `dateStyle` option.
178#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
179#[non_exhaustive]
180pub enum FormattedDateStyle {
181    /// Weekday and full month, such as "Tuesday, December 1, 2026".
182    Full,
183    /// Full month, such as "December 1, 2026".
184    Long,
185    /// Abbreviated month, such as "Dec 1, 2026".
186    #[default]
187    Medium,
188    /// Numeric, such as "12/1/26".
189    Short,
190}
191
192impl FormattedDateStyle {
193    /// The `Intl.DateTimeFormat` `dateStyle` value, such as `"medium"`.
194    pub fn as_str(self) -> &'static str {
195        match self {
196            Self::Full => "full",
197            Self::Long => "long",
198            Self::Medium => "medium",
199            Self::Short => "short",
200        }
201    }
202}
203
204/// Time length for `FormattedDate`: the `Intl.DateTimeFormat` `timeStyle` option. Times are UTC.
205#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
206#[non_exhaustive]
207pub enum FormattedDateTimeStyle {
208    /// Seconds and the zone name, such as "3:04:05 PM Coordinated Universal Time".
209    Full,
210    /// Seconds and the zone abbreviation, such as "3:04:05 PM UTC".
211    Long,
212    /// Seconds, such as "3:04:05 PM".
213    #[default]
214    Medium,
215    /// Hours and minutes, such as "3:04 PM".
216    Short,
217}
218
219impl FormattedDateTimeStyle {
220    /// The `Intl.DateTimeFormat` `timeStyle` value, such as `"short"`.
221    pub fn as_str(self) -> &'static str {
222        match self {
223            Self::Full => "full",
224            Self::Long => "long",
225            Self::Medium => "medium",
226            Self::Short => "short",
227        }
228    }
229}
230
231/// The value `FormattedNumber` formats: a number, or text read the way Lumen's `parseLumenNumber`
232/// reads it.
233#[derive(Clone, Debug, PartialEq)]
234#[non_exhaustive]
235pub enum FormattedNumberValue {
236    /// A double, like a JavaScript number. NaN and infinities render the fallback text.
237    Number(f64),
238    /// Plain decimal text such as `"-1234.5"` or `" 2e3 "`. Surrounding whitespace is ignored;
239    /// hexadecimal, `"Infinity"`, empty text, and text longer than 64 characters render the
240    /// fallback text.
241    Text(String),
242}
243
244/// Formats a double as is.
245impl From<f64> for FormattedNumberValue {
246    fn from(value: f64) -> Self {
247        Self::Number(value)
248    }
249}
250
251/// Widens a single-precision float without loss.
252impl From<f32> for FormattedNumberValue {
253    fn from(value: f32) -> Self {
254        Self::Number(f64::from(value))
255    }
256}
257
258/// Converts the integer without loss.
259impl From<i32> for FormattedNumberValue {
260    fn from(value: i32) -> Self {
261        Self::Number(f64::from(value))
262    }
263}
264
265/// Converts the integer without loss.
266impl From<u32> for FormattedNumberValue {
267    fn from(value: u32) -> Self {
268        Self::Number(f64::from(value))
269    }
270}
271
272/// Rounds integers beyond 2^53 to the nearest double, as JavaScript's `Number(bigint)` does.
273impl From<i64> for FormattedNumberValue {
274    #[allow(
275        clippy::cast_precision_loss,
276        reason = "JavaScript numbers are doubles, so large integers round the same way"
277    )]
278    fn from(value: i64) -> Self {
279        Self::Number(value as f64)
280    }
281}
282
283/// Rounds integers beyond 2^53 to the nearest double, as JavaScript's `Number(bigint)` does.
284impl From<u64> for FormattedNumberValue {
285    #[allow(
286        clippy::cast_precision_loss,
287        reason = "JavaScript numbers are doubles, so large integers round the same way"
288    )]
289    fn from(value: u64) -> Self {
290        Self::Number(value as f64)
291    }
292}
293
294/// Rounds integers beyond 2^53 to the nearest double, as JavaScript's `Number(bigint)` does.
295impl From<usize> for FormattedNumberValue {
296    #[allow(
297        clippy::cast_precision_loss,
298        reason = "JavaScript numbers are doubles, so large integers round the same way"
299    )]
300    fn from(value: usize) -> Self {
301        Self::Number(value as f64)
302    }
303}
304
305/// Parses the text when formatting, like `parseLumenNumber`.
306impl From<&str> for FormattedNumberValue {
307    fn from(value: &str) -> Self {
308        Self::Text(value.to_owned())
309    }
310}
311
312/// Parses the text when formatting, like `parseLumenNumber`.
313impl From<String> for FormattedNumberValue {
314    fn from(value: String) -> Self {
315        Self::Text(value)
316    }
317}
318
319/// `formatLumenNumber` options. Invalid currency codes, units, and fraction digits fall back the way
320/// Lumen's `resolveLumenNumberFormatOptions` does.
321#[derive(Clone, Debug, Default, PartialEq)]
322pub(crate) struct NumberFormatOptions {
323    /// Number style.
324    pub(crate) format: FormattedNumberFormat,
325    /// Magnitude notation.
326    pub(crate) notation: FormattedNumberNotation,
327    /// Sign display.
328    pub(crate) sign_display: FormattedNumberSignDisplay,
329    /// ISO 4217 code, such as `"USD"`, in any letter case. Required for the currency format.
330    pub(crate) currency: Option<String>,
331    /// Currency display.
332    pub(crate) currency_display: FormattedNumberCurrencyDisplay,
333    /// When to read the full currency name to assistive technology.
334    pub(crate) currency_name: FormattedNumberCurrencyName,
335    /// Sanctioned unit, such as `"kilobyte"` or `"kilometer-per-hour"`. Required for the unit format.
336    pub(crate) unit: Option<String>,
337    /// Unit display.
338    pub(crate) unit_display: FormattedNumberUnitDisplay,
339    /// BCP 47 locale. Omitted, invalid, or unsupported locales use English.
340    pub(crate) locale: Option<String>,
341    /// Minimum fraction digits, floored and clamped to 0 through 20.
342    pub(crate) minimum_fraction_digits: Option<f64>,
343    /// Maximum fraction digits, floored and clamped to 0 through 20, and never below the minimum.
344    pub(crate) maximum_fraction_digits: Option<f64>,
345}
346
347/// The result of [`format_lumen_number`], like Lumen's `LumenFormattedNumber`.
348#[derive(Clone, Debug, PartialEq, Eq)]
349pub(crate) struct FormattedNumberText {
350    /// Visible text.
351    pub(crate) text: String,
352    /// Fuller reading for assistive technology, present only when it differs from `text`.
353    pub(crate) accessible_text: Option<String>,
354    /// False when the input was not a finite number and `text` is the fallback.
355    pub(crate) valid: bool,
356    /// Machine-readable value, as JavaScript's `String(number)` writes it, or `None` when invalid.
357    pub(crate) value: Option<String>,
358}
359
360/// Text `FormattedNumber` shows when its value is not a finite number.
361pub(crate) const FORMATTED_NUMBER_FALLBACK: &str = "—";
362
363/// Longest numeric text, unit, or date accepted, like `maxNumericTextLength`.
364const MAX_TEXT_LENGTH: usize = 64;
365
366/// Largest fraction digit count, like `maxFractionDigits`.
367const MAX_FRACTION_DIGITS: u8 = 20;
368
369/// Currency symbols that several currencies display the same way in at least one locale.
370const AMBIGUOUS_CURRENCY_SYMBOLS: [&str; 18] = [
371    "$", "¥", "¥", "£", "₩", "₨", "kr", "kr.", "Kr", "Kr.", "Rs", "Rs.", "Fr", "Fr.", "L", "R",
372    "元", "円",
373];
374
375/// Formats a display-only number like Lumen's `formatLumenNumber` in the requested locale.
376///
377/// Invalid input renders `fallback`. For compact notation, units, and ambiguous currency symbols
378/// it also returns the long reading for assistive technology, such as "1.2 thousand US dollars"
379/// for a visible "$1.2K".
380pub(crate) fn format_lumen_number(
381    value: &FormattedNumberValue,
382    options: &NumberFormatOptions,
383    fallback: &str,
384) -> FormattedNumberText {
385    let Some(number) = parse_number(value) else {
386        return FormattedNumberText {
387            text: fallback.to_owned(),
388            accessible_text: None,
389            valid: false,
390            value: None,
391        };
392    };
393    let decimal = Decimal::from_f64(number);
394    let negative = number.is_sign_negative();
395    let used = resolve_spec(options);
396    let locale = localized::resolve_locale(options.locale.as_deref());
397    let format = |spec: &Spec| {
398        locale.as_ref().map_or_else(
399            || Some(format_spec(&decimal, negative, spec)),
400            |locale| localized::format(&decimal, negative, spec, locale),
401        )
402    };
403    let Some(text) = format(&used) else {
404        return FormattedNumberText {
405            text: fallback.to_owned(),
406            accessible_text: None,
407            valid: false,
408            value: None,
409        };
410    };
411    let currency_name = match (&used.style, &locale, options.currency_name) {
412        (Style::Currency(currency), Some(locale), FormattedNumberCurrencyName::Auto)
413            if currency.display != FormattedNumberCurrencyDisplay::Name =>
414        {
415            if localized::currency_is_ambiguous(currency, locale).unwrap_or(true) {
416                FormattedNumberCurrencyName::Always
417            } else {
418                FormattedNumberCurrencyName::Never
419            }
420        }
421        _ => options.currency_name,
422    };
423    let accessible = format(&accessible_spec(&used, currency_name)).unwrap_or_else(|| text.clone());
424
425    FormattedNumberText {
426        accessible_text: (accessible != text).then_some(accessible),
427        text,
428        valid: true,
429        value: Some(js_number_to_string(&decimal, negative)),
430    }
431}
432
433/// Reads a finite number like `parseLumenNumber`.
434fn parse_number(value: &FormattedNumberValue) -> Option<f64> {
435    match value {
436        FormattedNumberValue::Number(number) => number.is_finite().then_some(*number),
437        FormattedNumberValue::Text(text) => parse_number_text(text),
438    }
439}
440
441/// Reads plain decimal text. After the character check, Rust's float grammar is the same as
442/// JavaScript's `StrDecimalLiteral` without `Infinity`, and both round correctly.
443fn parse_number_text(text: &str) -> Option<f64> {
444    let trimmed = js_trim(text);
445    let numeric =
446        |byte: u8| byte.is_ascii_digit() || matches!(byte, b'+' | b'-' | b'.' | b'e' | b'E');
447
448    if trimmed.is_empty() || trimmed.len() > MAX_TEXT_LENGTH || !trimmed.bytes().all(numeric) {
449        return None;
450    }
451
452    trimmed
453        .parse::<f64>()
454        .ok()
455        .filter(|number| number.is_finite())
456}
457
458/// Trims the characters JavaScript's `String.prototype.trim` removes.
459fn js_trim(text: &str) -> &str {
460    text.trim_matches(|character: char| {
461        matches!(
462            character,
463            '\u{9}'..='\u{d}'
464                | ' '
465                | '\u{a0}'
466                | '\u{1680}'
467                | '\u{2000}'..='\u{200a}'
468                | '\u{2028}'
469                | '\u{2029}'
470                | '\u{202f}'
471                | '\u{205f}'
472                | '\u{3000}'
473                | '\u{feff}'
474        )
475    })
476}
477
478/// Floors a fraction digit count and clamps it to 0 through 20; non-finite counts are ignored.
479fn resolve_fraction_digits(value: Option<f64>) -> Option<u8> {
480    let value = value.filter(|value| value.is_finite())?;
481
482    Some(
483        (0..=MAX_FRACTION_DIGITS)
484            .rev()
485            .find(|digits| f64::from(*digits) <= value)
486            .unwrap_or(0),
487    )
488}
489
490/// Validates a three-letter ASCII currency code and converts it to uppercase.
491fn resolve_currency_code(currency: Option<&str>) -> Option<String> {
492    let currency = currency?;
493
494    (currency.len() == 3 && currency.bytes().all(|byte| byte.is_ascii_alphabetic()))
495        .then(|| currency.to_ascii_uppercase())
496}
497
498/// Patterns of a unit `Intl.NumberFormat` accepts.
499#[derive(Clone, Copy)]
500enum UnitPatterns {
501    /// A simple unit or an `X-per-Y` unit with its own CLDR patterns.
502    Stored(&'static [[&'static str; 2]; 3]),
503    /// An `X-per-Y` unit composed from the patterns of `X` and the `per` pattern of `Y`.
504    Per(&'static Unit, &'static Unit),
505}
506
507/// The unit option after validation.
508enum UnitLookup {
509    /// No usable unit text, so the format falls back to decimal.
510    Missing,
511    /// Text `Intl.NumberFormat` rejects, so `createFormatter` falls back to a plain decimal.
512    Unknown,
513    /// A sanctioned unit, and whether its numerator is `percent`.
514    Known(UnitPatterns, bool),
515}
516
517/// Validates a unit like `resolveUnit`, then looks it up like `Intl.NumberFormat`.
518fn resolve_unit(unit: Option<&str>) -> UnitLookup {
519    let Some(unit) = unit else {
520        return UnitLookup::Missing;
521    };
522
523    if unit.encode_utf16().nth(MAX_TEXT_LENGTH).is_some() {
524        return UnitLookup::Missing;
525    }
526
527    let unit = js_trim(unit);
528
529    if unit.is_empty() {
530        return UnitLookup::Missing;
531    }
532
533    if let Some(simple) = find_unit(unit) {
534        return UnitLookup::Known(
535            UnitPatterns::Stored(&simple.patterns),
536            simple.id == "percent",
537        );
538    }
539
540    let Some((numerator, denominator)) = unit.split_once("-per-") else {
541        return UnitLookup::Unknown;
542    };
543    let (Some(numerator), Some(denominator)) = (find_unit(numerator), find_unit(denominator))
544    else {
545        return UnitLookup::Unknown;
546    };
547
548    let percent = numerator.id == "percent";
549
550    match COMPOUND_UNITS.binary_search_by(|compound| compound.id.cmp(unit)) {
551        Ok(index) => COMPOUND_UNITS
552            .get(index)
553            .map_or(UnitLookup::Unknown, |compound| {
554                UnitLookup::Known(UnitPatterns::Stored(&compound.patterns), percent)
555            }),
556        Err(_) => UnitLookup::Known(UnitPatterns::Per(numerator, denominator), percent),
557    }
558}
559
560/// Finds a sanctioned simple unit.
561fn find_unit(id: &str) -> Option<&'static Unit> {
562    let index = UNITS.binary_search_by(|unit| unit.id.cmp(id)).ok()?;
563
564    UNITS.get(index)
565}
566
567/// Finds the display data of a currency code ICU knows.
568fn find_currency(code: &str) -> Option<&'static Currency> {
569    let index = CURRENCIES
570        .binary_search_by(|currency| currency.code.cmp(code))
571        .ok()?;
572
573    CURRENCIES.get(index)
574}
575
576/// A validated currency.
577#[derive(Clone)]
578struct CurrencyStyle {
579    /// Uppercase code.
580    code: String,
581    /// ICU display data, or `None` for a code that displays as itself.
582    data: Option<&'static Currency>,
583    /// Requested display.
584    display: FormattedNumberCurrencyDisplay,
585}
586
587impl CurrencyStyle {
588    /// Default fraction digits.
589    fn digits(&self) -> u8 {
590        self.data.map_or(2, |data| data.digits)
591    }
592
593    /// Prefix text and whether a no-break space follows it, for every display except `Name`.
594    fn symbol(&self) -> (&str, bool) {
595        match (self.display, self.data) {
596            (FormattedNumberCurrencyDisplay::Symbol, Some(data)) => {
597                (data.symbol, data.symbol_spaced)
598            }
599            (FormattedNumberCurrencyDisplay::NarrowSymbol, Some(data)) => {
600                (data.narrow, data.narrow_spaced)
601            }
602            _ => (&self.code, true),
603        }
604    }
605
606    /// Full name for the plural category `one` or `other`.
607    fn name(&self, one: bool) -> &str {
608        match self.data {
609            Some(data) if one => data.one,
610            Some(data) => data.other,
611            None => &self.code,
612        }
613    }
614}
615
616/// Number style after validation.
617#[derive(Clone)]
618enum Style {
619    /// Plain number.
620    Decimal,
621    /// Percentage of a ratio.
622    Percent,
623    /// Money.
624    Currency(CurrencyStyle),
625    /// Measurement.
626    Unit(UnitStyle),
627}
628
629/// A validated unit.
630#[derive(Clone)]
631struct UnitStyle {
632    /// Validated ECMA-402 unit identifier, retained for locale-specific patterns.
633    id: String,
634    /// Patterns for every display.
635    patterns: UnitPatterns,
636    /// Requested display.
637    display: FormattedNumberUnitDisplay,
638    /// Whether the numerator is `percent`, which ICU formats with the percent pattern unless the
639    /// display is long or the notation is compact; any `-per-` denominator is then dropped.
640    percent: bool,
641}
642
643/// Options a formatter was built with, like the `Intl.NumberFormatOptions` `createFormatter` used.
644#[derive(Clone)]
645struct Spec {
646    /// Number style.
647    style: Style,
648    /// Magnitude notation.
649    notation: FormattedNumberNotation,
650    /// Whether compact notation uses long words, like `compactDisplay: "long"`.
651    compact_long: bool,
652    /// Sign display.
653    sign_display: FormattedNumberSignDisplay,
654    /// Requested minimum fraction digits.
655    minimum_fraction_digits: Option<u8>,
656    /// Requested maximum fraction digits, never below the minimum.
657    maximum_fraction_digits: Option<u8>,
658}
659
660/// Resolves options like `resolveLumenNumberFormatOptions` followed by `createFormatter`.
661fn resolve_spec(options: &NumberFormatOptions) -> Spec {
662    let minimum_fraction_digits = resolve_fraction_digits(options.minimum_fraction_digits);
663    let maximum_fraction_digits = resolve_fraction_digits(options.maximum_fraction_digits)
664        .map(|maximum| maximum.max(minimum_fraction_digits.unwrap_or(0)));
665    let mut spec = Spec {
666        style: Style::Decimal,
667        notation: options.notation,
668        compact_long: false,
669        sign_display: options.sign_display,
670        minimum_fraction_digits,
671        maximum_fraction_digits,
672    };
673
674    match options.format {
675        FormattedNumberFormat::Decimal => {}
676        FormattedNumberFormat::Percent => spec.style = Style::Percent,
677        FormattedNumberFormat::Currency => {
678            if let Some(code) = resolve_currency_code(options.currency.as_deref()) {
679                spec.style = Style::Currency(CurrencyStyle {
680                    data: find_currency(&code),
681                    code,
682                    display: options.currency_display,
683                });
684            }
685        }
686        FormattedNumberFormat::Unit => match resolve_unit(options.unit.as_deref()) {
687            UnitLookup::Missing => {}
688            // `Intl.NumberFormat` throws for the unit with and without fraction limits, so
689            // `createFormatter` keeps only the notation and sign display.
690            UnitLookup::Unknown => {
691                spec.minimum_fraction_digits = None;
692                spec.maximum_fraction_digits = None;
693            }
694            UnitLookup::Known(patterns, percent) => {
695                spec.style = Style::Unit(UnitStyle {
696                    id: options
697                        .unit
698                        .as_deref()
699                        .map(js_trim)
700                        .unwrap_or_default()
701                        .to_owned(),
702                    patterns,
703                    display: options.unit_display,
704                    percent,
705                });
706            }
707        },
708    }
709
710    spec
711}
712
713/// Options for the long reading, like `resolveAccessibleOptions`.
714fn accessible_spec(used: &Spec, currency_name: FormattedNumberCurrencyName) -> Spec {
715    let mut spec = used.clone();
716
717    if spec.notation == FormattedNumberNotation::Compact {
718        spec.compact_long = true;
719    }
720
721    match &mut spec.style {
722        Style::Unit(unit) => unit.display = FormattedNumberUnitDisplay::Long,
723        Style::Currency(currency)
724            if currency.display != FormattedNumberCurrencyDisplay::Name
725                && currency_name != FormattedNumberCurrencyName::Never =>
726        {
727            let ambiguous = AMBIGUOUS_CURRENCY_SYMBOLS.contains(&js_trim(currency.symbol().0));
728
729            if currency_name == FormattedNumberCurrencyName::Always || ambiguous {
730                currency.display = FormattedNumberCurrencyDisplay::Name;
731            }
732        }
733        Style::Decimal | Style::Percent | Style::Currency(_) => {}
734    }
735
736    spec
737}
738
739/// Rounding the way `Intl.NumberFormat` resolves its digit options.
740#[derive(Clone, Copy, Debug)]
741enum Precision {
742    /// Round to `maximum` fraction digits and show at least `minimum`.
743    Fraction {
744        /// Fraction digits always shown.
745        minimum: u8,
746        /// Fraction digits kept when rounding.
747        maximum: u8,
748    },
749    /// Compact default: round to an integer, keeping at least two significant digits.
750    Compact,
751}
752
753impl Precision {
754    /// Resolves the digit options for a spec, like ECMA-402 `SetNumberFormatDigitOptions` in V8,
755    /// which uses the currency digits as defaults in every notation.
756    fn of(spec: &Spec) -> Self {
757        let (minimum_default, maximum_default) = match &spec.style {
758            Style::Currency(currency) => (currency.digits(), currency.digits()),
759            Style::Percent => (0, 0),
760            Style::Decimal | Style::Unit(_) => (0, 3),
761        };
762
763        match (spec.minimum_fraction_digits, spec.maximum_fraction_digits) {
764            (None, None) if spec.notation == FormattedNumberNotation::Compact => Self::Compact,
765            (None, None) => Self::Fraction {
766                minimum: minimum_default,
767                maximum: maximum_default,
768            },
769            (Some(minimum), None) => Self::Fraction {
770                minimum,
771                maximum: maximum_default.max(minimum),
772            },
773            (None, Some(maximum)) => Self::Fraction {
774                minimum: minimum_default.min(maximum),
775                maximum,
776            },
777            (Some(minimum), Some(maximum)) => Self::Fraction { minimum, maximum },
778        }
779    }
780
781    /// Rounds `decimal` and returns the fraction digits that must be shown.
782    fn apply(self, decimal: &mut Decimal) -> u8 {
783        match self {
784            Self::Fraction { minimum, maximum } => {
785                decimal.round_to(-i32::from(maximum));
786                minimum
787            }
788            Self::Compact => {
789                if !decimal.is_zero() {
790                    decimal.round_to(0.min(decimal.magnitude() - 1));
791                }
792                0
793            }
794        }
795    }
796
797    /// Scales `decimal` by the multiplier for its magnitude and rounds it, moving to the next
798    /// multiplier when rounding carries into a new magnitude, like ICU's
799    /// `chooseMultiplierAndApply`. Returns the shown fraction digits and the multiplier.
800    fn apply_with_multiplier(
801        self,
802        decimal: &mut Decimal,
803        multiplier_for: impl Fn(i32) -> i32,
804    ) -> (u8, i32) {
805        if decimal.is_zero() {
806            return (self.apply(decimal), 0);
807        }
808
809        let magnitude = decimal.magnitude();
810        let multiplier = multiplier_for(magnitude);
811
812        decimal.shift(multiplier);
813
814        let minimum = self.apply(decimal);
815
816        if decimal.is_zero() || decimal.magnitude() == magnitude + multiplier {
817            return (minimum, multiplier);
818        }
819
820        let next = multiplier_for(magnitude + 1);
821
822        if next == multiplier {
823            return (minimum, multiplier);
824        }
825
826        decimal.shift(next - multiplier);
827
828        (self.apply(decimal), next)
829    }
830}
831
832/// Power-of-ten shift that turns a number of `magnitude` into its compact mantissa.
833fn compact_multiplier(magnitude: i32) -> i32 {
834    if magnitude < 3 {
835        0
836    } else {
837        let capped = magnitude.min(14);
838
839        -(capped - capped % 3)
840    }
841}
842
843/// A non-negative decimal `digits × 10^scale` with no leading or trailing zero digits; zero has
844/// no digits.
845#[derive(Clone, Debug, PartialEq, Eq)]
846struct Decimal {
847    /// Decimal digits, most significant first.
848    digits: Vec<u8>,
849    /// Power of ten of the last digit.
850    scale: i32,
851}
852
853impl Decimal {
854    /// The shortest decimal that round-trips to `|value|`, which ICU rounds and JavaScript's
855    /// `String(number)` writes. When two shortest decimals are equally close, both pick the one
856    /// with an even last digit, while Rust's `{:e}` picks the larger one.
857    fn from_f64(value: f64) -> Self {
858        let value = value.abs();
859        let mut decimal = Self::from_scientific(&format!("{value:e}"));
860
861        if decimal.digits.last().is_some_and(|digit| digit % 2 == 1) {
862            let mut even = decimal.clone();
863
864            if let Some(last) = even.digits.last_mut() {
865                *last -= 1;
866            }
867
868            // A tie means the exact binary value ends with a 5 right after the shorter digits.
869            let mut midpoint = even.clone();
870
871            midpoint.digits.push(5);
872            midpoint.scale -= 1;
873
874            if even.to_f64() == Some(value)
875                && Self::from_scientific(&format!("{value:.767e}")) == midpoint
876            {
877                decimal = even;
878            }
879        }
880
881        decimal.normalize();
882        decimal
883    }
884
885    /// Reads Rust's `{:e}` output, such as `1.2345e-3`.
886    fn from_scientific(text: &str) -> Self {
887        let (mantissa, exponent) = text.split_once('e').unwrap_or((text, "0"));
888        let digits: Vec<u8> = mantissa
889            .bytes()
890            .filter(u8::is_ascii_digit)
891            .map(|byte| byte - b'0')
892            .collect();
893        let scale = exponent.parse::<i32>().unwrap_or(0) - to_i32(digits.len().saturating_sub(1));
894        let mut decimal = Self { digits, scale };
895
896        decimal.normalize();
897        decimal
898    }
899
900    /// The nearest double, for the round-trip check.
901    fn to_f64(&self) -> Option<f64> {
902        let digits: String = self.digits.iter().map(|digit| digit_char(*digit)).collect();
903
904        format!("{digits}e{}", self.scale).parse().ok()
905    }
906
907    /// Removes leading and trailing zero digits.
908    fn normalize(&mut self) {
909        let leading = self.digits.iter().take_while(|digit| **digit == 0).count();
910
911        self.digits.drain(..leading);
912
913        while self.digits.last() == Some(&0) {
914            self.digits.pop();
915            self.scale += 1;
916        }
917
918        if self.digits.is_empty() {
919            self.scale = 0;
920        }
921    }
922
923    /// Whether the value is zero.
924    fn is_zero(&self) -> bool {
925        self.digits.is_empty()
926    }
927
928    /// Whether the value is exactly one.
929    fn is_one(&self) -> bool {
930        self.digits == [1] && self.scale == 0
931    }
932
933    /// Power of ten of the first digit, or zero for zero.
934    fn magnitude(&self) -> i32 {
935        if self.is_zero() {
936            0
937        } else {
938            self.scale + to_i32(self.digits.len()) - 1
939        }
940    }
941
942    /// Digit at a power of ten.
943    fn digit_at(&self, magnitude: i32) -> u8 {
944        usize::try_from(self.magnitude() - magnitude)
945            .ok()
946            .and_then(|index| self.digits.get(index))
947            .copied()
948            .unwrap_or(0)
949    }
950
951    /// Multiplies by `10^shift`.
952    fn shift(&mut self, shift: i32) {
953        if !self.is_zero() {
954            self.scale += shift;
955        }
956    }
957
958    /// Rounds half away from zero to a multiple of `10^magnitude`.
959    fn round_to(&mut self, magnitude: i32) {
960        if self.is_zero() || self.scale >= magnitude {
961            return;
962        }
963
964        let Ok(keep) = usize::try_from(self.magnitude() - magnitude + 1) else {
965            self.digits.clear();
966            self.scale = 0;
967            return;
968        };
969        let round_up = self.digits.get(keep).is_some_and(|digit| *digit >= 5);
970
971        self.digits.truncate(keep);
972        self.scale = magnitude;
973
974        if round_up {
975            let mut carry = true;
976
977            for digit in self.digits.iter_mut().rev() {
978                if *digit == 9 {
979                    *digit = 0;
980                } else {
981                    *digit += 1;
982                    carry = false;
983                    break;
984                }
985            }
986
987            if carry {
988                self.digits.insert(0, 1);
989            }
990        }
991
992        self.normalize();
993    }
994
995    /// Fraction digits shown with at least `minimum` of them.
996    fn fraction_count(&self, minimum: u8) -> i32 {
997        (-self.scale).max(i32::from(minimum)).max(0)
998    }
999
1000    /// Writes the digits with English grouping when the integer part has at least
1001    /// `grouping_threshold` digits, and at least `minimum` fraction digits.
1002    fn write(&self, out: &mut String, minimum: u8, grouping_threshold: i32) {
1003        let upper = self.magnitude().max(0);
1004        let grouped = upper + 1 >= grouping_threshold;
1005
1006        for magnitude in (0..=upper).rev() {
1007            out.push(digit_char(self.digit_at(magnitude)));
1008
1009            if grouped && magnitude > 0 && magnitude % 3 == 0 {
1010                out.push(',');
1011            }
1012        }
1013
1014        let fraction = self.fraction_count(minimum);
1015
1016        if fraction > 0 {
1017            out.push('.');
1018
1019            for magnitude in (-fraction..0).rev() {
1020                out.push(digit_char(self.digit_at(magnitude)));
1021            }
1022        }
1023    }
1024}
1025
1026/// ASCII character of a decimal digit.
1027fn digit_char(digit: u8) -> char {
1028    char::from(b'0' + digit.min(9))
1029}
1030
1031/// Converts a small length to `i32`, saturating.
1032fn to_i32(length: usize) -> i32 {
1033    i32::try_from(length).unwrap_or(i32::MAX)
1034}
1035
1036/// A number after notation scaling and rounding.
1037struct Rounded {
1038    /// Rounded mantissa.
1039    decimal: Decimal,
1040    /// Fraction digits that must be shown.
1041    minimum: u8,
1042    /// Power of ten applied by scientific or compact notation.
1043    multiplier: i32,
1044}
1045
1046impl Rounded {
1047    /// Scales and rounds an absolute value for a spec.
1048    fn new(value: &Decimal, spec: &Spec) -> Self {
1049        let precision = Precision::of(spec);
1050        let mut decimal = value.clone();
1051
1052        if matches!(spec.style, Style::Percent) {
1053            decimal.shift(2);
1054        }
1055
1056        let (minimum, multiplier) = match spec.notation {
1057            FormattedNumberNotation::Standard => (precision.apply(&mut decimal), 0),
1058            FormattedNumberNotation::Scientific => {
1059                precision.apply_with_multiplier(&mut decimal, |magnitude| -magnitude)
1060            }
1061            FormattedNumberNotation::Engineering => precision
1062                .apply_with_multiplier(&mut decimal, |magnitude| {
1063                    magnitude.rem_euclid(3) - magnitude
1064                }),
1065            FormattedNumberNotation::Compact => {
1066                precision.apply_with_multiplier(&mut decimal, compact_multiplier)
1067            }
1068        };
1069
1070        Self {
1071            decimal,
1072            minimum,
1073            multiplier,
1074        }
1075    }
1076
1077    /// English plural category `one`: exactly 1 with no visible fraction digits or scaling.
1078    fn is_one(&self) -> bool {
1079        self.decimal.is_one() && self.minimum == 0 && self.multiplier == 0
1080    }
1081
1082    /// Digits, exponent, and compact suffix, without the sign.
1083    fn text(&self, spec: &Spec) -> String {
1084        let compact = spec.notation == FormattedNumberNotation::Compact;
1085        let mut text = String::new();
1086
1087        self.decimal
1088            .write(&mut text, self.minimum, if compact { 5 } else { 4 });
1089
1090        match spec.notation {
1091            FormattedNumberNotation::Standard => {}
1092            FormattedNumberNotation::Scientific | FormattedNumberNotation::Engineering => {
1093                text.push('E');
1094                text.push_str(&(-self.multiplier).to_string());
1095            }
1096            FormattedNumberNotation::Compact => {
1097                let magnitude = self.decimal.magnitude() - self.multiplier;
1098                // English currency patterns have no long form.
1099                let long = spec.compact_long
1100                    && !matches!(
1101                        &spec.style,
1102                        Style::Currency(currency)
1103                            if currency.display != FormattedNumberCurrencyDisplay::Name
1104                    );
1105                let suffixes = if long { COMPACT_LONG } else { COMPACT_SHORT };
1106                let index = usize::try_from(magnitude / 3 - 1)
1107                    .ok()
1108                    .map(|index| index.min(3));
1109
1110                if let Some(suffix) = index.and_then(|index| suffixes.get(index)) {
1111                    text.push_str(suffix);
1112                }
1113            }
1114        }
1115
1116        text
1117    }
1118}
1119
1120/// Sign for a value, after rounding decides whether it is zero.
1121fn sign_text(display: FormattedNumberSignDisplay, negative: bool, zero: bool) -> &'static str {
1122    match display {
1123        FormattedNumberSignDisplay::Auto => {
1124            if negative {
1125                "-"
1126            } else {
1127                ""
1128            }
1129        }
1130        FormattedNumberSignDisplay::Always => {
1131            if negative {
1132                "-"
1133            } else {
1134                "+"
1135            }
1136        }
1137        FormattedNumberSignDisplay::ExceptZero => match (zero, negative) {
1138            (true, _) => "",
1139            (false, true) => "-",
1140            (false, false) => "+",
1141        },
1142        FormattedNumberSignDisplay::Never => "",
1143    }
1144}
1145
1146/// Formats the absolute value `value` and its sign with resolved options, like
1147/// `Intl.NumberFormat.prototype.format`.
1148fn format_spec(value: &Decimal, negative: bool, spec: &Spec) -> String {
1149    let rounded = Rounded::new(value, spec);
1150    let sign = sign_text(spec.sign_display, negative, rounded.decimal.is_zero());
1151    let digits = rounded.text(spec);
1152
1153    match &spec.style {
1154        Style::Decimal => format!("{sign}{digits}"),
1155        Style::Percent => format!("{sign}{digits}%"),
1156        Style::Currency(currency) if currency.display == FormattedNumberCurrencyDisplay::Name => {
1157            format!("{sign}{digits} {}", currency.name(rounded.is_one()))
1158        }
1159        Style::Currency(currency) => {
1160            let (symbol, spaced) = currency.symbol();
1161            let space = if spaced { "\u{a0}" } else { "" };
1162
1163            format!("{sign}{symbol}{space}{digits}")
1164        }
1165        Style::Unit(unit)
1166            if unit.percent
1167                && unit.display != FormattedNumberUnitDisplay::Long
1168                && spec.notation != FormattedNumberNotation::Compact =>
1169        {
1170            format!("{sign}{digits}%")
1171        }
1172        Style::Unit(unit) => apply_unit_pattern(
1173            unit.patterns,
1174            unit.display,
1175            rounded.is_one(),
1176            &format!("{sign}{digits}"),
1177        ),
1178    }
1179}
1180
1181/// Puts the formatted number into the unit pattern for a display and plural category.
1182fn apply_unit_pattern(
1183    patterns: UnitPatterns,
1184    display: FormattedNumberUnitDisplay,
1185    one: bool,
1186    number: &str,
1187) -> String {
1188    let width = match display {
1189        FormattedNumberUnitDisplay::Short => 0,
1190        FormattedNumberUnitDisplay::Narrow => 1,
1191        FormattedNumberUnitDisplay::Long => 2,
1192    };
1193    let plural = usize::from(!one);
1194    let split = |pattern: &'static str| pattern.split_once("{0}").unwrap_or((pattern, ""));
1195    let pick = |table: &'static [[&'static str; 2]; 3]| {
1196        table
1197            .get(width)
1198            .and_then(|pair| pair.get(plural))
1199            .copied()
1200            .unwrap_or("{0}")
1201    };
1202
1203    match patterns {
1204        UnitPatterns::Stored(table) => {
1205            let (prefix, suffix) = split(pick(table));
1206
1207            format!("{prefix}{number}{suffix}")
1208        }
1209        UnitPatterns::Per(numerator, denominator) => {
1210            let (prefix, suffix) = split(pick(&numerator.patterns));
1211            let (per_prefix, per_suffix) =
1212                split(denominator.per.get(width).copied().unwrap_or("{0}"));
1213
1214            format!("{per_prefix}{prefix}{number}{suffix}{per_suffix}")
1215        }
1216    }
1217}
1218
1219/// Writes a finite number, given as its absolute value and sign, like JavaScript's
1220/// `String(number)`.
1221fn js_number_to_string(decimal: &Decimal, negative: bool) -> String {
1222    if decimal.is_zero() {
1223        return "0".to_owned();
1224    }
1225
1226    let digits: String = decimal
1227        .digits
1228        .iter()
1229        .map(|digit| digit_char(*digit))
1230        .collect();
1231    let length = to_i32(digits.len());
1232    let point = decimal.magnitude() + 1;
1233    let mut text = String::from(if negative { "-" } else { "" });
1234
1235    if length <= point && point <= 21 {
1236        text.push_str(&digits);
1237        text.extend((length..point).map(|_| '0'));
1238    } else if 0 < point && point <= 21 {
1239        let (integer, fraction) = digits.split_at(usize::try_from(point).unwrap_or(0));
1240
1241        text.push_str(integer);
1242        text.push('.');
1243        text.push_str(fraction);
1244    } else if -6 < point && point <= 0 {
1245        text.push_str("0.");
1246        text.extend((point..0).map(|_| '0'));
1247        text.push_str(&digits);
1248    } else {
1249        let (first, rest) = digits.split_at(1);
1250        let exponent = point - 1;
1251
1252        text.push_str(first);
1253
1254        if !rest.is_empty() {
1255            text.push('.');
1256            text.push_str(rest);
1257        }
1258
1259        text.push('e');
1260        text.push(if exponent < 0 { '-' } else { '+' });
1261        text.push_str(&exponent.unsigned_abs().to_string());
1262    }
1263
1264    text
1265}
1266
1267/// English month names.
1268const MONTHS: [&str; 12] = [
1269    "January",
1270    "February",
1271    "March",
1272    "April",
1273    "May",
1274    "June",
1275    "July",
1276    "August",
1277    "September",
1278    "October",
1279    "November",
1280    "December",
1281];
1282
1283/// English weekday names, starting on Sunday.
1284const WEEKDAYS: [&str; 7] = [
1285    "Sunday",
1286    "Monday",
1287    "Tuesday",
1288    "Wednesday",
1289    "Thursday",
1290    "Friday",
1291    "Saturday",
1292];
1293
1294/// Minutes in a day.
1295const MINUTES_PER_DAY: i64 = 1_440;
1296
1297/// A UTC moment between 0001-01-01 and 9999-12-31.
1298#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1299struct Moment {
1300    /// Days since 1970-01-01.
1301    days: i64,
1302    /// Year, 1 through 9999.
1303    year: i64,
1304    /// Month, 1 through 12.
1305    month: i64,
1306    /// Day of the month.
1307    day: i64,
1308    /// Hour, 0 through 23.
1309    hour: i64,
1310    /// Minute.
1311    minute: i64,
1312    /// Second.
1313    second: i64,
1314}
1315
1316/// Formats an ISO 8601 date like
1317/// `new Intl.DateTimeFormat("en-US", { dateStyle, timeStyle, timeZone: "UTC" }).format(new Date(input))`.
1318///
1319/// Accepts `YYYY-MM-DD` and `YYYY-MM-DDTHH:MM`, optionally with `:SS` and a fraction of a second,
1320/// followed by `Z`, a `±HH:MM` offset, or nothing. A date-time without an offset is read as UTC,
1321/// where JavaScript reads it as local time. Returns `None` for any other text, an impossible date
1322/// such as February 29 of a common year (JavaScript rolls it over), text longer than 64 characters,
1323/// and moments outside the years 1 through 9999 in UTC. Without either style it formats like
1324/// `dateStyle: "medium"`.
1325pub(crate) fn format_lumen_date(
1326    input: &str,
1327    date_style: Option<FormattedDateStyle>,
1328    time_style: Option<FormattedDateTimeStyle>,
1329) -> Option<String> {
1330    let moment = parse_moment(input)?;
1331    let date_style = match (date_style, time_style) {
1332        (None, None) => Some(FormattedDateStyle::Medium),
1333        (style, _) => style,
1334    };
1335    let date = date_style.map(|style| format_date(&moment, style));
1336    let time = time_style.map(|style| format_time(&moment, style));
1337
1338    match (date, time) {
1339        (Some(date), Some(time)) => {
1340            let glue = match date_style {
1341                Some(FormattedDateStyle::Full | FormattedDateStyle::Long) => " at ",
1342                _ => ", ",
1343            };
1344
1345            Some(format!("{date}{glue}{time}"))
1346        }
1347        (date, time) => date.or(time),
1348    }
1349}
1350
1351/// Reads fixed-width ASCII fields from the date text.
1352struct Cursor<'a> {
1353    /// Remaining bytes.
1354    bytes: &'a [u8],
1355}
1356
1357impl Cursor<'_> {
1358    /// Reads exactly `count` digits as a number.
1359    fn number(&mut self, count: usize) -> Option<i64> {
1360        let (field, rest) = self.bytes.split_at_checked(count)?;
1361
1362        if !field.iter().all(u8::is_ascii_digit) {
1363            return None;
1364        }
1365
1366        self.bytes = rest;
1367
1368        Some(
1369            field
1370                .iter()
1371                .fold(0, |total, digit| total * 10 + i64::from(digit - b'0')),
1372        )
1373    }
1374
1375    /// Consumes `byte` when it comes next.
1376    fn eat(&mut self, byte: u8) -> bool {
1377        match self.bytes.split_first() {
1378            Some((first, rest)) if *first == byte => {
1379                self.bytes = rest;
1380                true
1381            }
1382            _ => false,
1383        }
1384    }
1385
1386    /// Requires `byte` next.
1387    fn expect(&mut self, byte: u8) -> Option<()> {
1388        self.eat(byte).then_some(())
1389    }
1390
1391    /// Consumes one or more digits and returns whether they are all zero.
1392    fn fraction(&mut self) -> Option<bool> {
1393        let count = self
1394            .bytes
1395            .iter()
1396            .take_while(|byte| byte.is_ascii_digit())
1397            .count();
1398        let (digits, rest) = self.bytes.split_at_checked(count)?;
1399
1400        self.bytes = rest;
1401
1402        (count > 0).then(|| digits.iter().all(|digit| *digit == b'0'))
1403    }
1404}
1405
1406/// Parses the accepted ISO 8601 forms into a UTC moment.
1407fn parse_moment(input: &str) -> Option<Moment> {
1408    if input.len() > MAX_TEXT_LENGTH {
1409        return None;
1410    }
1411
1412    let mut cursor = Cursor {
1413        bytes: input.as_bytes(),
1414    };
1415    let year = cursor.number(4)?;
1416
1417    cursor.expect(b'-')?;
1418
1419    let month = cursor.number(2)?;
1420
1421    cursor.expect(b'-')?;
1422
1423    let day = cursor.number(2)?;
1424
1425    if !(1..=9999).contains(&year) || !(1..=days_in_month(year, month)).contains(&day) {
1426        return None;
1427    }
1428
1429    let (mut hour, mut minute, mut second, mut offset) = (0, 0, 0, 0);
1430
1431    if !cursor.bytes.is_empty() {
1432        cursor.expect(b'T')?;
1433        hour = cursor.number(2)?;
1434        cursor.expect(b':')?;
1435        minute = cursor.number(2)?;
1436
1437        let mut whole_second = true;
1438
1439        if cursor.eat(b':') {
1440            second = cursor.number(2)?;
1441
1442            if cursor.eat(b'.') {
1443                whole_second = cursor.fraction()?;
1444            }
1445        }
1446
1447        // Nothing after the time means no offset: read as UTC.
1448        if !cursor.eat(b'Z') && !cursor.bytes.is_empty() {
1449            let sign = if cursor.eat(b'+') {
1450                1
1451            } else {
1452                cursor.expect(b'-')?;
1453                -1
1454            };
1455            let offset_hour = cursor.number(2)?;
1456
1457            cursor.expect(b':')?;
1458
1459            let offset_minute = cursor.number(2)?;
1460
1461            if offset_hour > 23 || offset_minute > 59 {
1462                return None;
1463            }
1464
1465            offset = sign * (offset_hour * 60 + offset_minute);
1466        }
1467
1468        if !cursor.bytes.is_empty() {
1469            return None;
1470        }
1471
1472        let end_of_day = hour == 24 && minute == 0 && second == 0 && whole_second;
1473
1474        if (hour > 23 && !end_of_day) || minute > 59 || second > 59 {
1475            return None;
1476        }
1477    }
1478
1479    let minutes = days_from_civil(year, month, day) * MINUTES_PER_DAY + hour * 60 + minute - offset;
1480    let days = minutes.div_euclid(MINUTES_PER_DAY);
1481    let minute_of_day = minutes.rem_euclid(MINUTES_PER_DAY);
1482    let (year, month, day) = civil_from_days(days);
1483
1484    (1..=9999).contains(&year).then_some(Moment {
1485        days,
1486        year,
1487        month,
1488        day,
1489        hour: minute_of_day / 60,
1490        minute: minute_of_day % 60,
1491        second,
1492    })
1493}
1494
1495/// Days in a proleptic Gregorian month, or zero for an invalid month.
1496fn days_in_month(year: i64, month: i64) -> i64 {
1497    match month {
1498        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
1499        4 | 6 | 9 | 11 => 30,
1500        2 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) => 29,
1501        2 => 28,
1502        _ => 0,
1503    }
1504}
1505
1506/// Days from 1970-01-01 to a proleptic Gregorian date.
1507fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
1508    let year = if month <= 2 { year - 1 } else { year };
1509    let era = year.div_euclid(400);
1510    let year_of_era = year - era * 400;
1511    let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 1;
1512    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
1513
1514    era * 146_097 + day_of_era - 719_468
1515}
1516
1517/// Proleptic Gregorian `(year, month, day)` of a day count from 1970-01-01.
1518fn civil_from_days(days: i64) -> (i64, i64, i64) {
1519    let days = days + 719_468;
1520    let era = days.div_euclid(146_097);
1521    let day_of_era = days - era * 146_097;
1522    let year_of_era =
1523        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
1524    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
1525    let shifted_month = (5 * day_of_year + 2) / 153;
1526    let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
1527    let month = if shifted_month < 10 {
1528        shifted_month + 3
1529    } else {
1530        shifted_month - 9
1531    };
1532    let year = year_of_era + era * 400 + i64::from(month <= 2);
1533
1534    (year, month, day)
1535}
1536
1537/// Reads an English name from a table, by a validated index.
1538fn name_at(names: &'static [&'static str], index: i64) -> &'static str {
1539    usize::try_from(index)
1540        .ok()
1541        .and_then(|index| names.get(index))
1542        .copied()
1543        .unwrap_or_default()
1544}
1545
1546/// Writes the date part.
1547fn format_date(moment: &Moment, style: FormattedDateStyle) -> String {
1548    let Moment {
1549        year, month, day, ..
1550    } = *moment;
1551    let month_name = name_at(&MONTHS, month - 1);
1552
1553    match style {
1554        FormattedDateStyle::Full => {
1555            let weekday = name_at(&WEEKDAYS, (moment.days + 4).rem_euclid(7));
1556
1557            format!("{weekday}, {month_name} {day}, {year}")
1558        }
1559        FormattedDateStyle::Long => format!("{month_name} {day}, {year}"),
1560        FormattedDateStyle::Medium => {
1561            format!(
1562                "{} {day}, {year}",
1563                month_name.get(..3).unwrap_or(month_name)
1564            )
1565        }
1566        FormattedDateStyle::Short => format!("{month}/{day}/{:02}", year % 100),
1567    }
1568}
1569
1570/// Writes the time part in UTC.
1571fn format_time(moment: &Moment, style: FormattedDateTimeStyle) -> String {
1572    let Moment {
1573        hour,
1574        minute,
1575        second,
1576        ..
1577    } = *moment;
1578    let hour12 = if hour % 12 == 0 { 12 } else { hour % 12 };
1579    let period = if hour < 12 { "AM" } else { "PM" };
1580
1581    match style {
1582        FormattedDateTimeStyle::Full => {
1583            format!("{hour12}:{minute:02}:{second:02} {period} Coordinated Universal Time")
1584        }
1585        FormattedDateTimeStyle::Long => format!("{hour12}:{minute:02}:{second:02} {period} UTC"),
1586        FormattedDateTimeStyle::Medium => format!("{hour12}:{minute:02}:{second:02} {period}"),
1587        FormattedDateTimeStyle::Short => format!("{hour12}:{minute:02} {period}"),
1588    }
1589}
1590
1591#[cfg(test)]
1592mod tests {
1593    // Expected text comes from Node 22 (ICU 78, CLDR 48) running Lumen's `formatLumenNumber`.
1594    use super::*;
1595    use FormattedNumberCurrencyDisplay as Display;
1596    use FormattedNumberCurrencyName as CurrencyName;
1597    use FormattedNumberNotation as Notation;
1598    use FormattedNumberSignDisplay as Sign;
1599    use FormattedNumberUnitDisplay as UnitDisplay;
1600
1601    /// Formats a valid number and compares every field.
1602    fn check(
1603        value: impl Into<FormattedNumberValue>,
1604        options: &NumberFormatOptions,
1605        text: &str,
1606        accessible_text: Option<&str>,
1607        js_value: &str,
1608    ) {
1609        let expected = FormattedNumberText {
1610            text: text.to_owned(),
1611            accessible_text: accessible_text.map(str::to_owned),
1612            valid: true,
1613            value: Some(js_value.to_owned()),
1614        };
1615
1616        assert_eq!(
1617            format_lumen_number(&value.into(), options, FORMATTED_NUMBER_FALLBACK),
1618            expected,
1619            "{options:?}"
1620        );
1621    }
1622
1623    /// Formats a value that must render the fallback.
1624    fn check_invalid(value: impl Into<FormattedNumberValue>) {
1625        let value = value.into();
1626        let expected = FormattedNumberText {
1627            text: FORMATTED_NUMBER_FALLBACK.to_owned(),
1628            accessible_text: None,
1629            valid: false,
1630            value: None,
1631        };
1632
1633        assert_eq!(
1634            format_lumen_number(&value, &decimal(), FORMATTED_NUMBER_FALLBACK),
1635            expected,
1636            "{value:?}"
1637        );
1638    }
1639
1640    fn decimal() -> NumberFormatOptions {
1641        NumberFormatOptions::default()
1642    }
1643
1644    fn fraction(minimum: Option<f64>, maximum: Option<f64>) -> NumberFormatOptions {
1645        NumberFormatOptions {
1646            minimum_fraction_digits: minimum,
1647            maximum_fraction_digits: maximum,
1648            ..decimal()
1649        }
1650    }
1651
1652    fn sign(sign_display: Sign) -> NumberFormatOptions {
1653        NumberFormatOptions {
1654            sign_display,
1655            ..decimal()
1656        }
1657    }
1658
1659    fn notation(notation: Notation) -> NumberFormatOptions {
1660        NumberFormatOptions {
1661            notation,
1662            ..decimal()
1663        }
1664    }
1665
1666    fn compact() -> NumberFormatOptions {
1667        notation(Notation::Compact)
1668    }
1669
1670    fn percent() -> NumberFormatOptions {
1671        NumberFormatOptions {
1672            format: FormattedNumberFormat::Percent,
1673            ..decimal()
1674        }
1675    }
1676
1677    fn currency(code: &str, currency_display: Display) -> NumberFormatOptions {
1678        NumberFormatOptions {
1679            format: FormattedNumberFormat::Currency,
1680            currency: Some(code.to_owned()),
1681            currency_display,
1682            ..decimal()
1683        }
1684    }
1685
1686    fn unit(id: &str, unit_display: UnitDisplay) -> NumberFormatOptions {
1687        NumberFormatOptions {
1688            format: FormattedNumberFormat::Unit,
1689            unit: Some(id.to_owned()),
1690            unit_display,
1691            ..decimal()
1692        }
1693    }
1694
1695    #[test]
1696    fn formats_decimal_numbers() {
1697        check(1234.5678, &decimal(), "1,234.568", None, "1234.5678");
1698        check(0.0, &decimal(), "0", None, "0");
1699        check(-0.0, &decimal(), "-0", None, "0");
1700        check(
1701            1e21,
1702            &decimal(),
1703            "1,000,000,000,000,000,000,000",
1704            None,
1705            "1e+21",
1706        );
1707        check(1e-7, &decimal(), "0", None, "1e-7");
1708        check(
1709            f64::MIN_POSITIVE,
1710            &decimal(),
1711            "0",
1712            None,
1713            "2.2250738585072014e-308",
1714        );
1715        check(5e-324, &decimal(), "0", None, "5e-324");
1716        check(
1717            2f64.powi(60),
1718            &decimal(),
1719            "1,152,921,504,606,847,000",
1720            None,
1721            "1152921504606847000",
1722        );
1723        check(
1724            256_079_881_684_854.0 + 0.625,
1725            &decimal(),
1726            "256,079,881,684,854.62",
1727            None,
1728            "256079881684854.62",
1729        );
1730        check(
1731            0.1 + 0.2,
1732            &fraction(None, Some(20.0)),
1733            "0.30000000000000004",
1734            None,
1735            "0.30000000000000004",
1736        );
1737        check(1e-7, &fraction(None, Some(20.0)), "0.0000001", None, "1e-7");
1738    }
1739
1740    #[test]
1741    fn rounds_half_away_from_zero_on_the_shortest_decimal() {
1742        check(1.005, &fraction(None, Some(2.0)), "1.01", None, "1.005");
1743        check(2.675, &fraction(None, Some(2.0)), "2.68", None, "2.675");
1744        check(-2.5, &fraction(None, Some(0.0)), "-3", None, "-2.5");
1745        check(0.5, &fraction(None, Some(0.0)), "1", None, "0.5");
1746        check(9.9995, &decimal(), "10", None, "9.9995");
1747        check(-0.0001, &decimal(), "-0", None, "-0.0001");
1748    }
1749
1750    #[test]
1751    fn clamps_fraction_digits() {
1752        check(1.5, &fraction(Some(-2.0), None), "1.5", None, "1.5");
1753        check(
1754            1.0 / 3.0,
1755            &fraction(None, Some(25.0)),
1756            "0.3333333333333333",
1757            None,
1758            "0.3333333333333333",
1759        );
1760        check(1.5, &fraction(Some(2.0), Some(1.0)), "1.50", None, "1.5");
1761        check(
1762            1.23456,
1763            &fraction(Some(f64::NAN), Some(2.9)),
1764            "1.23",
1765            None,
1766            "1.23456",
1767        );
1768        check(
1769            1.23456,
1770            &fraction(Some(f64::INFINITY), None),
1771            "1.235",
1772            None,
1773            "1.23456",
1774        );
1775        check(
1776            2.0,
1777            &fraction(Some(21.0), None),
1778            "2.00000000000000000000",
1779            None,
1780            "2",
1781        );
1782    }
1783
1784    #[test]
1785    fn shows_signs() {
1786        check(5.0, &sign(Sign::Always), "+5", None, "5");
1787        check(0.0, &sign(Sign::Always), "+0", None, "0");
1788        check(-0.0, &sign(Sign::Always), "-0", None, "0");
1789        check(0.0, &sign(Sign::ExceptZero), "0", None, "0");
1790        check(-0.0001, &sign(Sign::ExceptZero), "0", None, "-0.0001");
1791        check(5.0, &sign(Sign::ExceptZero), "+5", None, "5");
1792        check(-5.0, &sign(Sign::ExceptZero), "-5", None, "-5");
1793        check(-5.0, &sign(Sign::Never), "5", None, "-5");
1794    }
1795
1796    #[test]
1797    fn formats_percentages() {
1798        check(0.145, &percent(), "15%", None, "0.145");
1799        check(-0.001, &percent(), "-0%", None, "-0.001");
1800        check(
1801            12.34,
1802            &NumberFormatOptions {
1803                notation: Notation::Compact,
1804                ..percent()
1805            },
1806            "1.2K%",
1807            Some("1.2 thousand%"),
1808            "12.34",
1809        );
1810    }
1811
1812    #[test]
1813    fn formats_currencies() {
1814        check(
1815            1.0,
1816            &currency("USD", Display::Symbol),
1817            "$1.00",
1818            Some("1.00 US dollars"),
1819            "1",
1820        );
1821        check(
1822            1.0,
1823            &currency("USD", Display::Name),
1824            "1.00 US dollars",
1825            None,
1826            "1",
1827        );
1828        check(
1829            1.0,
1830            &currency("JPY", Display::Name),
1831            "1 Japanese yen",
1832            None,
1833            "1",
1834        );
1835        check(
1836            1234.5,
1837            &currency("JPY", Display::Symbol),
1838            "¥1,235",
1839            Some("1,235 Japanese yen"),
1840            "1234.5",
1841        );
1842        check(
1843            1.0,
1844            &currency("KWD", Display::Symbol),
1845            "KWD\u{a0}1.000",
1846            None,
1847            "1",
1848        );
1849        check(
1850            -1.0,
1851            &currency("EUR", Display::Symbol),
1852            "-€1.00",
1853            None,
1854            "-1",
1855        );
1856        check(
1857            1.0,
1858            &currency("GBP", Display::Symbol),
1859            "£1.00",
1860            Some("1.00 British pounds"),
1861            "1",
1862        );
1863        check(1.0, &currency("CAD", Display::Symbol), "CA$1.00", None, "1");
1864        check(
1865            1.0,
1866            &currency("CAD", Display::NarrowSymbol),
1867            "$1.00",
1868            Some("1.00 Canadian dollars"),
1869            "1",
1870        );
1871        check(
1872            1.0,
1873            &currency("CHF", Display::Symbol),
1874            "CHF\u{a0}1.00",
1875            None,
1876            "1",
1877        );
1878        check(
1879            1.0,
1880            &currency("USD", Display::Code),
1881            "USD\u{a0}1.00",
1882            None,
1883            "1",
1884        );
1885        check(
1886            1.0,
1887            &currency("usd", Display::Symbol),
1888            "$1.00",
1889            Some("1.00 US dollars"),
1890            "1",
1891        );
1892        check(
1893            1.0,
1894            &currency("XYZ", Display::Symbol),
1895            "XYZ\u{a0}1.00",
1896            None,
1897            "1",
1898        );
1899        check(1.0, &currency("XYZ", Display::Name), "1.00 XYZ", None, "1");
1900    }
1901
1902    #[test]
1903    fn formats_currencies_with_other_options() {
1904        check(1.0, &currency("US", Display::Symbol), "1", None, "1");
1905        check(
1906            1.0,
1907            &NumberFormatOptions {
1908                currency: None,
1909                ..currency("USD", Display::Symbol)
1910            },
1911            "1",
1912            None,
1913            "1",
1914        );
1915        check(
1916            1.0,
1917            &NumberFormatOptions {
1918                maximum_fraction_digits: Some(0.0),
1919                ..currency("USD", Display::Symbol)
1920            },
1921            "$1",
1922            Some("1 US dollar"),
1923            "1",
1924        );
1925        check(
1926            1234.0,
1927            &NumberFormatOptions {
1928                notation: Notation::Compact,
1929                ..currency("USD", Display::Symbol)
1930            },
1931            "$1.2K",
1932            Some("1.2 thousand US dollars"),
1933            "1234",
1934        );
1935        check(
1936            1000.0,
1937            &NumberFormatOptions {
1938                notation: Notation::Compact,
1939                maximum_fraction_digits: Some(1.0),
1940                ..currency("USD", Display::Symbol)
1941            },
1942            "$1.0K",
1943            Some("1.0 thousand US dollars"),
1944            "1000",
1945        );
1946        check(
1947            1234.5,
1948            &NumberFormatOptions {
1949                notation: Notation::Scientific,
1950                ..currency("USD", Display::Symbol)
1951            },
1952            "$1.23E3",
1953            Some("1.23E3 US dollars"),
1954            "1234.5",
1955        );
1956        check(
1957            -1.0,
1958            &NumberFormatOptions {
1959                sign_display: Sign::Always,
1960                ..currency("XOF", Display::Symbol)
1961            },
1962            "-F\u{202f}CFA\u{a0}1",
1963            None,
1964            "-1",
1965        );
1966    }
1967
1968    #[test]
1969    fn names_currencies_for_assistive_technology() {
1970        check(
1971            1.0,
1972            &NumberFormatOptions {
1973                currency_name: CurrencyName::Never,
1974                ..currency("USD", Display::Symbol)
1975            },
1976            "$1.00",
1977            None,
1978            "1",
1979        );
1980        check(
1981            1.0,
1982            &NumberFormatOptions {
1983                currency_name: CurrencyName::Always,
1984                ..currency("EUR", Display::Symbol)
1985            },
1986            "€1.00",
1987            Some("1.00 euros"),
1988            "1",
1989        );
1990        check(
1991            1.0,
1992            &NumberFormatOptions {
1993                currency_name: CurrencyName::Always,
1994                ..currency("KWD", Display::Code)
1995            },
1996            "KWD\u{a0}1.000",
1997            Some("1.000 Kuwaiti dinars"),
1998            "1",
1999        );
2000        check(
2001            1.0,
2002            &currency("DKK", Display::NarrowSymbol),
2003            "kr\u{a0}1.00",
2004            Some("1.00 Danish kroner"),
2005            "1",
2006        );
2007        check(
2008            1.0,
2009            &currency("DKK", Display::Symbol),
2010            "DKK\u{a0}1.00",
2011            None,
2012            "1",
2013        );
2014    }
2015
2016    #[test]
2017    fn formats_units() {
2018        check(
2019            1.0,
2020            &unit("kilobyte", UnitDisplay::Short),
2021            "1 kB",
2022            Some("1 kilobyte"),
2023            "1",
2024        );
2025        check(
2026            2.0,
2027            &unit("kilobyte", UnitDisplay::Long),
2028            "2 kilobytes",
2029            None,
2030            "2",
2031        );
2032        check(
2033            16.0,
2034            &unit("kilometer-per-hour", UnitDisplay::Narrow),
2035            "16km/h",
2036            Some("16 kilometers per hour"),
2037            "16",
2038        );
2039        check(
2040            -5.0,
2041            &unit("celsius", UnitDisplay::Short),
2042            "-5°C",
2043            Some("-5 degrees Celsius"),
2044            "-5",
2045        );
2046        check(1.0, &unit("day", UnitDisplay::Long), "1 day", None, "1");
2047        check(
2048            1.5,
2049            &unit("day", UnitDisplay::Short),
2050            "1.5 days",
2051            None,
2052            "1.5",
2053        );
2054        check(
2055            0.0,
2056            &unit("byte", UnitDisplay::Narrow),
2057            "0B",
2058            Some("0 bytes"),
2059            "0",
2060        );
2061        check(
2062            50.0,
2063            &unit("percent", UnitDisplay::Short),
2064            "50%",
2065            Some("50 percent"),
2066            "50",
2067        );
2068        check(
2069            5.0,
2070            &unit("percent-per-hour", UnitDisplay::Short),
2071            "5%",
2072            Some("5 percent per hour"),
2073            "5",
2074        );
2075        check(
2076            1.0,
2077            &unit("byte-per-day", UnitDisplay::Long),
2078            "1 byte per day",
2079            None,
2080            "1",
2081        );
2082        check(
2083            30.0,
2084            &unit("mile-per-gallon", UnitDisplay::Short),
2085            "30 mpg",
2086            Some("30 miles per gallon"),
2087            "30",
2088        );
2089        check(
2090            1.0,
2091            &unit(" meter ", UnitDisplay::Short),
2092            "1 m",
2093            Some("1 meter"),
2094            "1",
2095        );
2096        check(
2097            1.0,
2098            &NumberFormatOptions {
2099                minimum_fraction_digits: Some(1.0),
2100                ..unit("day", UnitDisplay::Long)
2101            },
2102            "1.0 days",
2103            None,
2104            "1",
2105        );
2106    }
2107
2108    #[test]
2109    fn falls_back_for_unusable_units() {
2110        check(
2111            1.23456,
2112            &NumberFormatOptions {
2113                maximum_fraction_digits: Some(1.0),
2114                ..unit("parsec", UnitDisplay::Short)
2115            },
2116            "1.235",
2117            None,
2118            "1.23456",
2119        );
2120        check(
2121            1.23456,
2122            &NumberFormatOptions {
2123                maximum_fraction_digits: Some(1.0),
2124                ..unit("Meter", UnitDisplay::Short)
2125            },
2126            "1.235",
2127            None,
2128            "1.23456",
2129        );
2130        check(
2131            1.23456,
2132            &NumberFormatOptions {
2133                maximum_fraction_digits: Some(1.0),
2134                ..unit("  ", UnitDisplay::Short)
2135            },
2136            "1.2",
2137            None,
2138            "1.23456",
2139        );
2140        check(
2141            1.23456,
2142            &NumberFormatOptions {
2143                maximum_fraction_digits: Some(1.0),
2144                ..unit(&"x".repeat(65), UnitDisplay::Short)
2145            },
2146            "1.2",
2147            None,
2148            "1.23456",
2149        );
2150        check(
2151            1234.0,
2152            &NumberFormatOptions {
2153                notation: Notation::Compact,
2154                ..unit("meter-per-second-per-hour", UnitDisplay::Short)
2155            },
2156            "1.2K",
2157            Some("1.2 thousand"),
2158            "1234",
2159        );
2160    }
2161
2162    #[test]
2163    fn formats_compact_numbers() {
2164        check(1234.0, &compact(), "1.2K", Some("1.2 thousand"), "1234");
2165        check(12345.0, &compact(), "12K", Some("12 thousand"), "12345");
2166        check(999_999.0, &compact(), "1M", Some("1 million"), "999999");
2167        check(
2168            1e15,
2169            &compact(),
2170            "1000T",
2171            Some("1000 trillion"),
2172            "1000000000000000",
2173        );
2174        check(
2175            1e16,
2176            &compact(),
2177            "10,000T",
2178            Some("10,000 trillion"),
2179            "10000000000000000",
2180        );
2181        check(-1234.0, &compact(), "-1.2K", Some("-1.2 thousand"), "-1234");
2182        check(1249.5, &compact(), "1.2K", Some("1.2 thousand"), "1249.5");
2183        check(0.001_234_5, &compact(), "0.0012", None, "0.0012345");
2184        check(
2185            1234.0,
2186            &NumberFormatOptions {
2187                maximum_fraction_digits: Some(2.0),
2188                ..compact()
2189            },
2190            "1.23K",
2191            Some("1.23 thousand"),
2192            "1234",
2193        );
2194        check(
2195            1000.0,
2196            &NumberFormatOptions {
2197                minimum_fraction_digits: Some(2.0),
2198                ..compact()
2199            },
2200            "1.00K",
2201            Some("1.00 thousand"),
2202            "1000",
2203        );
2204        check(
2205            1000.0,
2206            &NumberFormatOptions {
2207                notation: Notation::Compact,
2208                ..unit("day", UnitDisplay::Long)
2209            },
2210            "1K days",
2211            Some("1 thousand days"),
2212            "1000",
2213        );
2214        check(
2215            1234.5,
2216            &NumberFormatOptions {
2217                notation: Notation::Compact,
2218                ..unit("percent-per-acre", UnitDisplay::Short)
2219            },
2220            "1.2K%/ac",
2221            Some("1.2 thousand percent per acre"),
2222            "1234.5",
2223        );
2224    }
2225
2226    #[test]
2227    fn formats_scientific_and_engineering_numbers() {
2228        check(
2229            1234.5,
2230            &notation(Notation::Scientific),
2231            "1.235E3",
2232            None,
2233            "1234.5",
2234        );
2235        check(
2236            0.000_123_45,
2237            &notation(Notation::Scientific),
2238            "1.235E-4",
2239            None,
2240            "0.00012345",
2241        );
2242        check(0.0, &notation(Notation::Scientific), "0E0", None, "0");
2243        check(
2244            -9.9996,
2245            &notation(Notation::Scientific),
2246            "-1E1",
2247            None,
2248            "-9.9996",
2249        );
2250        check(
2251            f64::MAX,
2252            &notation(Notation::Scientific),
2253            "1.798E308",
2254            None,
2255            "1.7976931348623157e+308",
2256        );
2257        check(
2258            123_456.0,
2259            &notation(Notation::Engineering),
2260            "123.456E3",
2261            None,
2262            "123456",
2263        );
2264        check(
2265            0.000_123_45,
2266            &notation(Notation::Engineering),
2267            "123.45E-6",
2268            None,
2269            "0.00012345",
2270        );
2271        check(
2272            5e-324,
2273            &notation(Notation::Engineering),
2274            "5E-324",
2275            None,
2276            "5e-324",
2277        );
2278        check(
2279            1.0,
2280            &NumberFormatOptions {
2281                notation: Notation::Scientific,
2282                ..unit("day", UnitDisplay::Long)
2283            },
2284            "1E0 day",
2285            None,
2286            "1",
2287        );
2288        check(
2289            0.5,
2290            &NumberFormatOptions {
2291                notation: Notation::Scientific,
2292                ..percent()
2293            },
2294            "5E1%",
2295            None,
2296            "0.5",
2297        );
2298    }
2299
2300    #[test]
2301    fn reads_numeric_text() {
2302        check("1234.5", &decimal(), "1,234.5", None, "1234.5");
2303        check(" 2e3 ", &decimal(), "2,000", None, "2000");
2304        check("+.5", &decimal(), "0.5", None, "0.5");
2305        check("5.", &decimal(), "5", None, "5");
2306        check("\u{a0}1\u{feff}", &decimal(), "1", None, "1");
2307        check("\u{2028}7\u{3000}", &decimal(), "7", None, "7");
2308        check("-1e-400", &decimal(), "-0", None, "0");
2309        check("00012", &decimal(), "12", None, "12");
2310    }
2311
2312    #[test]
2313    fn rejects_values_that_are_not_finite_numbers() {
2314        check_invalid(f64::NAN);
2315        check_invalid(f64::INFINITY);
2316        check_invalid(f64::NEG_INFINITY);
2317
2318        for text in [
2319            "0x10",
2320            "Infinity",
2321            "-Infinity",
2322            "",
2323            "   ",
2324            ".",
2325            "+",
2326            "1e",
2327            "1e400",
2328            "1,000",
2329            "1 2",
2330            "1_000",
2331            "\u{85}1",
2332            "\u{180e}1",
2333            "NaN",
2334            "1",
2335            "٣",
2336        ] {
2337            check_invalid(text);
2338        }
2339
2340        check_invalid("1".repeat(65));
2341        check(
2342            "1".repeat(64),
2343            &decimal(),
2344            "1,111,111,111,111,111,200,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000",
2345            None,
2346            "1.1111111111111112e+63",
2347        );
2348    }
2349
2350    #[test]
2351    fn renders_a_custom_fallback() {
2352        let result = format_lumen_number(&"n/a".into(), &decimal(), "Not available");
2353
2354        assert_eq!(result.text, "Not available");
2355        assert!(!result.valid);
2356    }
2357
2358    #[test]
2359    fn writes_values_like_javascript() {
2360        for (number, expected) in [
2361            (1e21, "1e+21"),
2362            (1e-7, "1e-7"),
2363            (1.23e-18, "1.23e-18"),
2364            (0.000_001, "0.000001"),
2365            (-0.0, "0"),
2366            (1.5, "1.5"),
2367            (100.0, "100"),
2368            (2f64.powi(60), "1152921504606847000"),
2369            (-f64::MAX, "-1.7976931348623157e+308"),
2370            (5e-324, "5e-324"),
2371            (0.1 + 0.2, "0.30000000000000004"),
2372            (123_456_789_012_345_680_000.0, "123456789012345680000"),
2373            (9.499_999_999_999_999e-7, "9.499999999999999e-7"),
2374            (256_079_881_684_854.0 + 0.625, "256079881684854.62"),
2375        ] {
2376            assert_eq!(
2377                js_number_to_string(&Decimal::from_f64(number), number.is_sign_negative()),
2378                expected,
2379                "{number:e}"
2380            );
2381        }
2382    }
2383
2384    #[test]
2385    fn converts_rust_numbers_like_javascript() {
2386        let value = |value: FormattedNumberValue| format_lumen_number(&value, &decimal(), "").value;
2387
2388        assert_eq!(
2389            value(i64::MAX.into()),
2390            Some("9223372036854776000".to_owned())
2391        );
2392        assert_eq!(
2393            value(u64::MAX.into()),
2394            Some("18446744073709552000".to_owned())
2395        );
2396        assert_eq!(value(42_usize.into()), Some("42".to_owned()));
2397        assert_eq!(value((-7_i32).into()), Some("-7".to_owned()));
2398        assert_eq!(value(7_u32.into()), Some("7".to_owned()));
2399        assert_eq!(
2400            value(0.1_f32.into()),
2401            Some("0.10000000149011612".to_owned())
2402        );
2403        assert_eq!(value(String::from("8").into()), Some("8".to_owned()));
2404    }
2405
2406    #[test]
2407    fn formats_german_currency_in_its_requested_locale() {
2408        let german = NumberFormatOptions {
2409            locale: Some("de".to_owned()),
2410            ..currency("EUR", Display::Symbol)
2411        };
2412
2413        assert_eq!(
2414            format_lumen_number(&1234.5.into(), &german, "").text,
2415            "1.234,50\u{a0}€"
2416        );
2417    }
2418
2419    #[test]
2420    fn exposes_javascript_option_names() {
2421        assert_eq!(FormattedNumberFormat::Unit.as_str(), "unit");
2422        assert_eq!(Notation::Engineering.as_str(), "engineering");
2423        assert_eq!(Sign::ExceptZero.as_str(), "exceptZero");
2424        assert_eq!(Display::NarrowSymbol.as_str(), "narrowSymbol");
2425        assert_eq!(CurrencyName::Always.as_str(), "always");
2426        assert_eq!(UnitDisplay::Narrow.as_str(), "narrow");
2427        assert_eq!(FormattedDateStyle::default().as_str(), "medium");
2428        assert_eq!(FormattedDateTimeStyle::Full.as_str(), "full");
2429    }
2430
2431    #[test]
2432    fn stays_linear_on_adversarial_input() {
2433        let long_number = format!("{}1{}", " ".repeat(1_000_000), "\u{3000}".repeat(100_000));
2434
2435        check(long_number, &decimal(), "1", None, "1");
2436        check_invalid("1".repeat(1_000_000));
2437        check_invalid("-".repeat(1_000_000));
2438        check(
2439            1.5,
2440            &unit(&"-per-".repeat(200_000), UnitDisplay::Long),
2441            "1.5",
2442            None,
2443            "1.5",
2444        );
2445        check(
2446            1.5,
2447            &unit(&"a".repeat(1_000_000), UnitDisplay::Long),
2448            "1.5",
2449            None,
2450            "1.5",
2451        );
2452        check(
2453            1.5,
2454            &currency(&"USD".repeat(300_000), Display::Name),
2455            "1.5",
2456            None,
2457            "1.5",
2458        );
2459
2460        let huge = format_lumen_number(
2461            &f64::MAX.into(),
2462            &NumberFormatOptions {
2463                minimum_fraction_digits: Some(1e300),
2464                ..percent()
2465            },
2466            "",
2467        );
2468
2469        // Node: 311 integer digits with grouping, 20 fraction digits, and the percent sign.
2470        assert_eq!(huge.text.len(), 436);
2471        assert!(huge.text.starts_with("17,976,931,348,623,157,000,000"));
2472        assert!(huge.text.ends_with(",000,000.00000000000000000000%"));
2473        assert_eq!(format_lumen_date(&"2".repeat(1_000_000), None, None), None);
2474        assert_eq!(
2475            format_lumen_date(
2476                &format!("2020-01-01T12:00:00.{}Z", "0".repeat(1_000_000)),
2477                None,
2478                None
2479            ),
2480            None
2481        );
2482    }
2483
2484    #[test]
2485    fn formats_dates_in_every_style() {
2486        use FormattedDateStyle as Date;
2487        use FormattedDateTimeStyle as Time;
2488
2489        let cases = [
2490            (
2491                None,
2492                Some(Time::Full),
2493                "3:04:05 PM Coordinated Universal Time",
2494            ),
2495            (None, Some(Time::Long), "3:04:05 PM UTC"),
2496            (None, Some(Time::Medium), "3:04:05 PM"),
2497            (None, Some(Time::Short), "3:04 PM"),
2498            (Some(Date::Full), None, "Tuesday, December 1, 2026"),
2499            (Some(Date::Long), None, "December 1, 2026"),
2500            (Some(Date::Medium), None, "Dec 1, 2026"),
2501            (None, None, "Dec 1, 2026"),
2502            (Some(Date::Short), None, "12/1/26"),
2503            (
2504                Some(Date::Full),
2505                Some(Time::Full),
2506                "Tuesday, December 1, 2026 at 3:04:05 PM Coordinated Universal Time",
2507            ),
2508            (
2509                Some(Date::Long),
2510                Some(Time::Long),
2511                "December 1, 2026 at 3:04:05 PM UTC",
2512            ),
2513            (
2514                Some(Date::Long),
2515                Some(Time::Short),
2516                "December 1, 2026 at 3:04 PM",
2517            ),
2518            (
2519                Some(Date::Medium),
2520                Some(Time::Full),
2521                "Dec 1, 2026, 3:04:05 PM Coordinated Universal Time",
2522            ),
2523            (
2524                Some(Date::Medium),
2525                Some(Time::Medium),
2526                "Dec 1, 2026, 3:04:05 PM",
2527            ),
2528            (
2529                Some(Date::Short),
2530                Some(Time::Long),
2531                "12/1/26, 3:04:05 PM UTC",
2532            ),
2533            (Some(Date::Short), Some(Time::Short), "12/1/26, 3:04 PM"),
2534        ];
2535
2536        for (date_style, time_style, expected) in cases {
2537            assert_eq!(
2538                format_lumen_date("2026-12-01T15:04:05Z", date_style, time_style).as_deref(),
2539                Some(expected),
2540                "{date_style:?} {time_style:?}"
2541            );
2542        }
2543    }
2544
2545    #[test]
2546    fn converts_dates_to_utc() {
2547        let full = |input: &str| {
2548            format_lumen_date(
2549                input,
2550                Some(FormattedDateStyle::Full),
2551                Some(FormattedDateTimeStyle::Medium),
2552            )
2553        };
2554        let short = |input: &str| format_lumen_date(input, Some(FormattedDateStyle::Short), None);
2555
2556        for (input, expected) in [
2557            (
2558                "2026-12-31T23:30:00-05:00",
2559                "Friday, January 1, 2027 at 4:30:00 AM",
2560            ),
2561            ("2024-02-29", "Thursday, February 29, 2024 at 12:00:00 AM"),
2562            (
2563                "2000-02-29T00:00:00.5+00:00",
2564                "Tuesday, February 29, 2000 at 12:00:00 AM",
2565            ),
2566            (
2567                "2020-01-01T24:00Z",
2568                "Thursday, January 2, 2020 at 12:00:00 AM",
2569            ),
2570            ("0001-01-01", "Monday, January 1, 1 at 12:00:00 AM"),
2571            ("1970-01-01", "Thursday, January 1, 1970 at 12:00:00 AM"),
2572            (
2573                "2026-01-01T00:00:00+14:00",
2574                "Wednesday, December 31, 2025 at 10:00:00 AM",
2575            ),
2576            (
2577                "9999-12-31T23:59:59.999Z",
2578                "Friday, December 31, 9999 at 11:59:59 PM",
2579            ),
2580            // Without an offset the time is UTC, not local time as in JavaScript.
2581            (
2582                "2026-12-01T15:04",
2583                "Tuesday, December 1, 2026 at 3:04:00 PM",
2584            ),
2585        ] {
2586            assert_eq!(full(input).as_deref(), Some(expected), "{input}");
2587        }
2588
2589        assert_eq!(short("0001-01-01").as_deref(), Some("1/1/01"));
2590        assert_eq!(short("9999-12-31").as_deref(), Some("12/31/99"));
2591    }
2592
2593    #[test]
2594    fn rejects_invalid_dates() {
2595        for input in [
2596            "2023-02-29",
2597            "1900-02-29",
2598            "2021-04-31",
2599            "2021-13-01",
2600            "2021-00-10",
2601            "2021-01-00",
2602            "0000-01-01",
2603            "10000-01-01",
2604            "+002020-01-01",
2605            "2020-1-01",
2606            "2020-01-01T",
2607            "2020-01-01T12",
2608            "2020-01-01T12Z",
2609            "2020-01-01T24:00:01Z",
2610            "2020-01-01T24:00:00.001Z",
2611            "2020-01-01T23:60Z",
2612            "2020-01-01T12:00:60Z",
2613            "2020-01-01T12:00:00.Z",
2614            "2020-01-01T12:00+24:00",
2615            "2020-01-01T12:00+0530",
2616            "2020-01-01t12:00Z",
2617            "2020-01-01 12:00Z",
2618            "2020-01-01T12:00Z ",
2619            "2020-01-01Z",
2620            "9999-12-31T23:30-05:00",
2621            "0001-01-01T00:00+01:00",
2622            "",
2623            "garbage",
2624            "2020-01-01",
2625        ] {
2626            assert_eq!(format_lumen_date(input, None, None), None, "{input}");
2627        }
2628
2629        let overlong = format!("2020-01-01T12:00:00.{}Z", "0".repeat(44));
2630
2631        assert_eq!(overlong.len(), 65);
2632        assert_eq!(format_lumen_date(&overlong, None, None), None);
2633        assert!(format_lumen_date(&overlong[..63], None, None).is_some());
2634        assert!(format_lumen_date(&format!("{}Z", &overlong[..63]), None, None).is_some());
2635    }
2636
2637    #[test]
2638    fn counts_days_like_the_gregorian_calendar() {
2639        let mut days = days_from_civil(1, 1, 1);
2640
2641        assert_eq!(days, -719_162);
2642        assert_eq!(days_from_civil(1970, 1, 1), 0);
2643
2644        for year in 1..=9999 {
2645            for month in 1..=12 {
2646                for day in 1..=days_in_month(year, month) {
2647                    assert_eq!(civil_from_days(days), (year, month, day));
2648                    assert_eq!(days_from_civil(year, month, day), days);
2649                    days += 1;
2650                }
2651            }
2652        }
2653    }
2654}