use super::number_format_data::{
COMPACT_LONG, COMPACT_SHORT, COMPOUND_UNITS, CURRENCIES, Currency, UNITS, Unit,
};
#[path = "localized_number.rs"]
mod localized;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormattedNumberFormat {
#[default]
Decimal,
Currency,
Percent,
Unit,
}
impl FormattedNumberFormat {
pub fn as_str(self) -> &'static str {
match self {
Self::Decimal => "decimal",
Self::Currency => "currency",
Self::Percent => "percent",
Self::Unit => "unit",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormattedNumberNotation {
#[default]
Standard,
Scientific,
Engineering,
Compact,
}
impl FormattedNumberNotation {
pub fn as_str(self) -> &'static str {
match self {
Self::Standard => "standard",
Self::Scientific => "scientific",
Self::Engineering => "engineering",
Self::Compact => "compact",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormattedNumberSignDisplay {
#[default]
Auto,
Always,
ExceptZero,
Never,
}
impl FormattedNumberSignDisplay {
pub fn as_str(self) -> &'static str {
match self {
Self::Auto => "auto",
Self::Always => "always",
Self::ExceptZero => "exceptZero",
Self::Never => "never",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormattedNumberCurrencyDisplay {
#[default]
Symbol,
NarrowSymbol,
Code,
Name,
}
impl FormattedNumberCurrencyDisplay {
pub fn as_str(self) -> &'static str {
match self {
Self::Symbol => "symbol",
Self::NarrowSymbol => "narrowSymbol",
Self::Code => "code",
Self::Name => "name",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormattedNumberCurrencyName {
#[default]
Auto,
Always,
Never,
}
impl FormattedNumberCurrencyName {
pub fn as_str(self) -> &'static str {
match self {
Self::Auto => "auto",
Self::Always => "always",
Self::Never => "never",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormattedNumberUnitDisplay {
#[default]
Short,
Narrow,
Long,
}
impl FormattedNumberUnitDisplay {
pub fn as_str(self) -> &'static str {
match self {
Self::Short => "short",
Self::Narrow => "narrow",
Self::Long => "long",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormattedDateStyle {
Full,
Long,
#[default]
Medium,
Short,
}
impl FormattedDateStyle {
pub fn as_str(self) -> &'static str {
match self {
Self::Full => "full",
Self::Long => "long",
Self::Medium => "medium",
Self::Short => "short",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormattedDateTimeStyle {
Full,
Long,
#[default]
Medium,
Short,
}
impl FormattedDateTimeStyle {
pub fn as_str(self) -> &'static str {
match self {
Self::Full => "full",
Self::Long => "long",
Self::Medium => "medium",
Self::Short => "short",
}
}
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum FormattedNumberValue {
Number(f64),
Text(String),
}
impl From<f64> for FormattedNumberValue {
fn from(value: f64) -> Self {
Self::Number(value)
}
}
impl From<f32> for FormattedNumberValue {
fn from(value: f32) -> Self {
Self::Number(f64::from(value))
}
}
impl From<i32> for FormattedNumberValue {
fn from(value: i32) -> Self {
Self::Number(f64::from(value))
}
}
impl From<u32> for FormattedNumberValue {
fn from(value: u32) -> Self {
Self::Number(f64::from(value))
}
}
impl From<i64> for FormattedNumberValue {
#[allow(
clippy::cast_precision_loss,
reason = "JavaScript numbers are doubles, so large integers round the same way"
)]
fn from(value: i64) -> Self {
Self::Number(value as f64)
}
}
impl From<u64> for FormattedNumberValue {
#[allow(
clippy::cast_precision_loss,
reason = "JavaScript numbers are doubles, so large integers round the same way"
)]
fn from(value: u64) -> Self {
Self::Number(value as f64)
}
}
impl From<usize> for FormattedNumberValue {
#[allow(
clippy::cast_precision_loss,
reason = "JavaScript numbers are doubles, so large integers round the same way"
)]
fn from(value: usize) -> Self {
Self::Number(value as f64)
}
}
impl From<&str> for FormattedNumberValue {
fn from(value: &str) -> Self {
Self::Text(value.to_owned())
}
}
impl From<String> for FormattedNumberValue {
fn from(value: String) -> Self {
Self::Text(value)
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct NumberFormatOptions {
pub(crate) format: FormattedNumberFormat,
pub(crate) notation: FormattedNumberNotation,
pub(crate) sign_display: FormattedNumberSignDisplay,
pub(crate) currency: Option<String>,
pub(crate) currency_display: FormattedNumberCurrencyDisplay,
pub(crate) currency_name: FormattedNumberCurrencyName,
pub(crate) unit: Option<String>,
pub(crate) unit_display: FormattedNumberUnitDisplay,
pub(crate) locale: Option<String>,
pub(crate) minimum_fraction_digits: Option<f64>,
pub(crate) maximum_fraction_digits: Option<f64>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct FormattedNumberText {
pub(crate) text: String,
pub(crate) accessible_text: Option<String>,
pub(crate) valid: bool,
pub(crate) value: Option<String>,
}
pub(crate) const FORMATTED_NUMBER_FALLBACK: &str = "—";
const MAX_TEXT_LENGTH: usize = 64;
const MAX_FRACTION_DIGITS: u8 = 20;
const AMBIGUOUS_CURRENCY_SYMBOLS: [&str; 18] = [
"$", "¥", "¥", "£", "₩", "₨", "kr", "kr.", "Kr", "Kr.", "Rs", "Rs.", "Fr", "Fr.", "L", "R",
"元", "円",
];
pub(crate) fn format_lumen_number(
value: &FormattedNumberValue,
options: &NumberFormatOptions,
fallback: &str,
) -> FormattedNumberText {
let Some(number) = parse_number(value) else {
return FormattedNumberText {
text: fallback.to_owned(),
accessible_text: None,
valid: false,
value: None,
};
};
let decimal = Decimal::from_f64(number);
let negative = number.is_sign_negative();
let used = resolve_spec(options);
let locale = localized::resolve_locale(options.locale.as_deref());
let format = |spec: &Spec| {
locale.as_ref().map_or_else(
|| Some(format_spec(&decimal, negative, spec)),
|locale| localized::format(&decimal, negative, spec, locale),
)
};
let Some(text) = format(&used) else {
return FormattedNumberText {
text: fallback.to_owned(),
accessible_text: None,
valid: false,
value: None,
};
};
let currency_name = match (&used.style, &locale, options.currency_name) {
(Style::Currency(currency), Some(locale), FormattedNumberCurrencyName::Auto)
if currency.display != FormattedNumberCurrencyDisplay::Name =>
{
if localized::currency_is_ambiguous(currency, locale).unwrap_or(true) {
FormattedNumberCurrencyName::Always
} else {
FormattedNumberCurrencyName::Never
}
}
_ => options.currency_name,
};
let accessible = format(&accessible_spec(&used, currency_name)).unwrap_or_else(|| text.clone());
FormattedNumberText {
accessible_text: (accessible != text).then_some(accessible),
text,
valid: true,
value: Some(js_number_to_string(&decimal, negative)),
}
}
fn parse_number(value: &FormattedNumberValue) -> Option<f64> {
match value {
FormattedNumberValue::Number(number) => number.is_finite().then_some(*number),
FormattedNumberValue::Text(text) => parse_number_text(text),
}
}
fn parse_number_text(text: &str) -> Option<f64> {
let trimmed = js_trim(text);
let numeric =
|byte: u8| byte.is_ascii_digit() || matches!(byte, b'+' | b'-' | b'.' | b'e' | b'E');
if trimmed.is_empty() || trimmed.len() > MAX_TEXT_LENGTH || !trimmed.bytes().all(numeric) {
return None;
}
trimmed
.parse::<f64>()
.ok()
.filter(|number| number.is_finite())
}
fn js_trim(text: &str) -> &str {
text.trim_matches(|character: char| {
matches!(
character,
'\u{9}'..='\u{d}'
| ' '
| '\u{a0}'
| '\u{1680}'
| '\u{2000}'..='\u{200a}'
| '\u{2028}'
| '\u{2029}'
| '\u{202f}'
| '\u{205f}'
| '\u{3000}'
| '\u{feff}'
)
})
}
fn resolve_fraction_digits(value: Option<f64>) -> Option<u8> {
let value = value.filter(|value| value.is_finite())?;
Some(
(0..=MAX_FRACTION_DIGITS)
.rev()
.find(|digits| f64::from(*digits) <= value)
.unwrap_or(0),
)
}
fn resolve_currency_code(currency: Option<&str>) -> Option<String> {
let currency = currency?;
(currency.len() == 3 && currency.bytes().all(|byte| byte.is_ascii_alphabetic()))
.then(|| currency.to_ascii_uppercase())
}
#[derive(Clone, Copy)]
enum UnitPatterns {
Stored(&'static [[&'static str; 2]; 3]),
Per(&'static Unit, &'static Unit),
}
enum UnitLookup {
Missing,
Unknown,
Known(UnitPatterns, bool),
}
fn resolve_unit(unit: Option<&str>) -> UnitLookup {
let Some(unit) = unit else {
return UnitLookup::Missing;
};
if unit.encode_utf16().nth(MAX_TEXT_LENGTH).is_some() {
return UnitLookup::Missing;
}
let unit = js_trim(unit);
if unit.is_empty() {
return UnitLookup::Missing;
}
if let Some(simple) = find_unit(unit) {
return UnitLookup::Known(
UnitPatterns::Stored(&simple.patterns),
simple.id == "percent",
);
}
let Some((numerator, denominator)) = unit.split_once("-per-") else {
return UnitLookup::Unknown;
};
let (Some(numerator), Some(denominator)) = (find_unit(numerator), find_unit(denominator))
else {
return UnitLookup::Unknown;
};
let percent = numerator.id == "percent";
match COMPOUND_UNITS.binary_search_by(|compound| compound.id.cmp(unit)) {
Ok(index) => COMPOUND_UNITS
.get(index)
.map_or(UnitLookup::Unknown, |compound| {
UnitLookup::Known(UnitPatterns::Stored(&compound.patterns), percent)
}),
Err(_) => UnitLookup::Known(UnitPatterns::Per(numerator, denominator), percent),
}
}
fn find_unit(id: &str) -> Option<&'static Unit> {
let index = UNITS.binary_search_by(|unit| unit.id.cmp(id)).ok()?;
UNITS.get(index)
}
fn find_currency(code: &str) -> Option<&'static Currency> {
let index = CURRENCIES
.binary_search_by(|currency| currency.code.cmp(code))
.ok()?;
CURRENCIES.get(index)
}
#[derive(Clone)]
struct CurrencyStyle {
code: String,
data: Option<&'static Currency>,
display: FormattedNumberCurrencyDisplay,
}
impl CurrencyStyle {
fn digits(&self) -> u8 {
self.data.map_or(2, |data| data.digits)
}
fn symbol(&self) -> (&str, bool) {
match (self.display, self.data) {
(FormattedNumberCurrencyDisplay::Symbol, Some(data)) => {
(data.symbol, data.symbol_spaced)
}
(FormattedNumberCurrencyDisplay::NarrowSymbol, Some(data)) => {
(data.narrow, data.narrow_spaced)
}
_ => (&self.code, true),
}
}
fn name(&self, one: bool) -> &str {
match self.data {
Some(data) if one => data.one,
Some(data) => data.other,
None => &self.code,
}
}
}
#[derive(Clone)]
enum Style {
Decimal,
Percent,
Currency(CurrencyStyle),
Unit(UnitStyle),
}
#[derive(Clone)]
struct UnitStyle {
id: String,
patterns: UnitPatterns,
display: FormattedNumberUnitDisplay,
percent: bool,
}
#[derive(Clone)]
struct Spec {
style: Style,
notation: FormattedNumberNotation,
compact_long: bool,
sign_display: FormattedNumberSignDisplay,
minimum_fraction_digits: Option<u8>,
maximum_fraction_digits: Option<u8>,
}
fn resolve_spec(options: &NumberFormatOptions) -> Spec {
let minimum_fraction_digits = resolve_fraction_digits(options.minimum_fraction_digits);
let maximum_fraction_digits = resolve_fraction_digits(options.maximum_fraction_digits)
.map(|maximum| maximum.max(minimum_fraction_digits.unwrap_or(0)));
let mut spec = Spec {
style: Style::Decimal,
notation: options.notation,
compact_long: false,
sign_display: options.sign_display,
minimum_fraction_digits,
maximum_fraction_digits,
};
match options.format {
FormattedNumberFormat::Decimal => {}
FormattedNumberFormat::Percent => spec.style = Style::Percent,
FormattedNumberFormat::Currency => {
if let Some(code) = resolve_currency_code(options.currency.as_deref()) {
spec.style = Style::Currency(CurrencyStyle {
data: find_currency(&code),
code,
display: options.currency_display,
});
}
}
FormattedNumberFormat::Unit => match resolve_unit(options.unit.as_deref()) {
UnitLookup::Missing => {}
UnitLookup::Unknown => {
spec.minimum_fraction_digits = None;
spec.maximum_fraction_digits = None;
}
UnitLookup::Known(patterns, percent) => {
spec.style = Style::Unit(UnitStyle {
id: options
.unit
.as_deref()
.map(js_trim)
.unwrap_or_default()
.to_owned(),
patterns,
display: options.unit_display,
percent,
});
}
},
}
spec
}
fn accessible_spec(used: &Spec, currency_name: FormattedNumberCurrencyName) -> Spec {
let mut spec = used.clone();
if spec.notation == FormattedNumberNotation::Compact {
spec.compact_long = true;
}
match &mut spec.style {
Style::Unit(unit) => unit.display = FormattedNumberUnitDisplay::Long,
Style::Currency(currency)
if currency.display != FormattedNumberCurrencyDisplay::Name
&& currency_name != FormattedNumberCurrencyName::Never =>
{
let ambiguous = AMBIGUOUS_CURRENCY_SYMBOLS.contains(&js_trim(currency.symbol().0));
if currency_name == FormattedNumberCurrencyName::Always || ambiguous {
currency.display = FormattedNumberCurrencyDisplay::Name;
}
}
Style::Decimal | Style::Percent | Style::Currency(_) => {}
}
spec
}
#[derive(Clone, Copy, Debug)]
enum Precision {
Fraction {
minimum: u8,
maximum: u8,
},
Compact,
}
impl Precision {
fn of(spec: &Spec) -> Self {
let (minimum_default, maximum_default) = match &spec.style {
Style::Currency(currency) => (currency.digits(), currency.digits()),
Style::Percent => (0, 0),
Style::Decimal | Style::Unit(_) => (0, 3),
};
match (spec.minimum_fraction_digits, spec.maximum_fraction_digits) {
(None, None) if spec.notation == FormattedNumberNotation::Compact => Self::Compact,
(None, None) => Self::Fraction {
minimum: minimum_default,
maximum: maximum_default,
},
(Some(minimum), None) => Self::Fraction {
minimum,
maximum: maximum_default.max(minimum),
},
(None, Some(maximum)) => Self::Fraction {
minimum: minimum_default.min(maximum),
maximum,
},
(Some(minimum), Some(maximum)) => Self::Fraction { minimum, maximum },
}
}
fn apply(self, decimal: &mut Decimal) -> u8 {
match self {
Self::Fraction { minimum, maximum } => {
decimal.round_to(-i32::from(maximum));
minimum
}
Self::Compact => {
if !decimal.is_zero() {
decimal.round_to(0.min(decimal.magnitude() - 1));
}
0
}
}
}
fn apply_with_multiplier(
self,
decimal: &mut Decimal,
multiplier_for: impl Fn(i32) -> i32,
) -> (u8, i32) {
if decimal.is_zero() {
return (self.apply(decimal), 0);
}
let magnitude = decimal.magnitude();
let multiplier = multiplier_for(magnitude);
decimal.shift(multiplier);
let minimum = self.apply(decimal);
if decimal.is_zero() || decimal.magnitude() == magnitude + multiplier {
return (minimum, multiplier);
}
let next = multiplier_for(magnitude + 1);
if next == multiplier {
return (minimum, multiplier);
}
decimal.shift(next - multiplier);
(self.apply(decimal), next)
}
}
fn compact_multiplier(magnitude: i32) -> i32 {
if magnitude < 3 {
0
} else {
let capped = magnitude.min(14);
-(capped - capped % 3)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Decimal {
digits: Vec<u8>,
scale: i32,
}
impl Decimal {
fn from_f64(value: f64) -> Self {
let value = value.abs();
let mut decimal = Self::from_scientific(&format!("{value:e}"));
if decimal.digits.last().is_some_and(|digit| digit % 2 == 1) {
let mut even = decimal.clone();
if let Some(last) = even.digits.last_mut() {
*last -= 1;
}
let mut midpoint = even.clone();
midpoint.digits.push(5);
midpoint.scale -= 1;
if even.to_f64() == Some(value)
&& Self::from_scientific(&format!("{value:.767e}")) == midpoint
{
decimal = even;
}
}
decimal.normalize();
decimal
}
fn from_scientific(text: &str) -> Self {
let (mantissa, exponent) = text.split_once('e').unwrap_or((text, "0"));
let digits: Vec<u8> = mantissa
.bytes()
.filter(u8::is_ascii_digit)
.map(|byte| byte - b'0')
.collect();
let scale = exponent.parse::<i32>().unwrap_or(0) - to_i32(digits.len().saturating_sub(1));
let mut decimal = Self { digits, scale };
decimal.normalize();
decimal
}
fn to_f64(&self) -> Option<f64> {
let digits: String = self.digits.iter().map(|digit| digit_char(*digit)).collect();
format!("{digits}e{}", self.scale).parse().ok()
}
fn normalize(&mut self) {
let leading = self.digits.iter().take_while(|digit| **digit == 0).count();
self.digits.drain(..leading);
while self.digits.last() == Some(&0) {
self.digits.pop();
self.scale += 1;
}
if self.digits.is_empty() {
self.scale = 0;
}
}
fn is_zero(&self) -> bool {
self.digits.is_empty()
}
fn is_one(&self) -> bool {
self.digits == [1] && self.scale == 0
}
fn magnitude(&self) -> i32 {
if self.is_zero() {
0
} else {
self.scale + to_i32(self.digits.len()) - 1
}
}
fn digit_at(&self, magnitude: i32) -> u8 {
usize::try_from(self.magnitude() - magnitude)
.ok()
.and_then(|index| self.digits.get(index))
.copied()
.unwrap_or(0)
}
fn shift(&mut self, shift: i32) {
if !self.is_zero() {
self.scale += shift;
}
}
fn round_to(&mut self, magnitude: i32) {
if self.is_zero() || self.scale >= magnitude {
return;
}
let Ok(keep) = usize::try_from(self.magnitude() - magnitude + 1) else {
self.digits.clear();
self.scale = 0;
return;
};
let round_up = self.digits.get(keep).is_some_and(|digit| *digit >= 5);
self.digits.truncate(keep);
self.scale = magnitude;
if round_up {
let mut carry = true;
for digit in self.digits.iter_mut().rev() {
if *digit == 9 {
*digit = 0;
} else {
*digit += 1;
carry = false;
break;
}
}
if carry {
self.digits.insert(0, 1);
}
}
self.normalize();
}
fn fraction_count(&self, minimum: u8) -> i32 {
(-self.scale).max(i32::from(minimum)).max(0)
}
fn write(&self, out: &mut String, minimum: u8, grouping_threshold: i32) {
let upper = self.magnitude().max(0);
let grouped = upper + 1 >= grouping_threshold;
for magnitude in (0..=upper).rev() {
out.push(digit_char(self.digit_at(magnitude)));
if grouped && magnitude > 0 && magnitude % 3 == 0 {
out.push(',');
}
}
let fraction = self.fraction_count(minimum);
if fraction > 0 {
out.push('.');
for magnitude in (-fraction..0).rev() {
out.push(digit_char(self.digit_at(magnitude)));
}
}
}
}
fn digit_char(digit: u8) -> char {
char::from(b'0' + digit.min(9))
}
fn to_i32(length: usize) -> i32 {
i32::try_from(length).unwrap_or(i32::MAX)
}
struct Rounded {
decimal: Decimal,
minimum: u8,
multiplier: i32,
}
impl Rounded {
fn new(value: &Decimal, spec: &Spec) -> Self {
let precision = Precision::of(spec);
let mut decimal = value.clone();
if matches!(spec.style, Style::Percent) {
decimal.shift(2);
}
let (minimum, multiplier) = match spec.notation {
FormattedNumberNotation::Standard => (precision.apply(&mut decimal), 0),
FormattedNumberNotation::Scientific => {
precision.apply_with_multiplier(&mut decimal, |magnitude| -magnitude)
}
FormattedNumberNotation::Engineering => precision
.apply_with_multiplier(&mut decimal, |magnitude| {
magnitude.rem_euclid(3) - magnitude
}),
FormattedNumberNotation::Compact => {
precision.apply_with_multiplier(&mut decimal, compact_multiplier)
}
};
Self {
decimal,
minimum,
multiplier,
}
}
fn is_one(&self) -> bool {
self.decimal.is_one() && self.minimum == 0 && self.multiplier == 0
}
fn text(&self, spec: &Spec) -> String {
let compact = spec.notation == FormattedNumberNotation::Compact;
let mut text = String::new();
self.decimal
.write(&mut text, self.minimum, if compact { 5 } else { 4 });
match spec.notation {
FormattedNumberNotation::Standard => {}
FormattedNumberNotation::Scientific | FormattedNumberNotation::Engineering => {
text.push('E');
text.push_str(&(-self.multiplier).to_string());
}
FormattedNumberNotation::Compact => {
let magnitude = self.decimal.magnitude() - self.multiplier;
let long = spec.compact_long
&& !matches!(
&spec.style,
Style::Currency(currency)
if currency.display != FormattedNumberCurrencyDisplay::Name
);
let suffixes = if long { COMPACT_LONG } else { COMPACT_SHORT };
let index = usize::try_from(magnitude / 3 - 1)
.ok()
.map(|index| index.min(3));
if let Some(suffix) = index.and_then(|index| suffixes.get(index)) {
text.push_str(suffix);
}
}
}
text
}
}
fn sign_text(display: FormattedNumberSignDisplay, negative: bool, zero: bool) -> &'static str {
match display {
FormattedNumberSignDisplay::Auto => {
if negative {
"-"
} else {
""
}
}
FormattedNumberSignDisplay::Always => {
if negative {
"-"
} else {
"+"
}
}
FormattedNumberSignDisplay::ExceptZero => match (zero, negative) {
(true, _) => "",
(false, true) => "-",
(false, false) => "+",
},
FormattedNumberSignDisplay::Never => "",
}
}
fn format_spec(value: &Decimal, negative: bool, spec: &Spec) -> String {
let rounded = Rounded::new(value, spec);
let sign = sign_text(spec.sign_display, negative, rounded.decimal.is_zero());
let digits = rounded.text(spec);
match &spec.style {
Style::Decimal => format!("{sign}{digits}"),
Style::Percent => format!("{sign}{digits}%"),
Style::Currency(currency) if currency.display == FormattedNumberCurrencyDisplay::Name => {
format!("{sign}{digits} {}", currency.name(rounded.is_one()))
}
Style::Currency(currency) => {
let (symbol, spaced) = currency.symbol();
let space = if spaced { "\u{a0}" } else { "" };
format!("{sign}{symbol}{space}{digits}")
}
Style::Unit(unit)
if unit.percent
&& unit.display != FormattedNumberUnitDisplay::Long
&& spec.notation != FormattedNumberNotation::Compact =>
{
format!("{sign}{digits}%")
}
Style::Unit(unit) => apply_unit_pattern(
unit.patterns,
unit.display,
rounded.is_one(),
&format!("{sign}{digits}"),
),
}
}
fn apply_unit_pattern(
patterns: UnitPatterns,
display: FormattedNumberUnitDisplay,
one: bool,
number: &str,
) -> String {
let width = match display {
FormattedNumberUnitDisplay::Short => 0,
FormattedNumberUnitDisplay::Narrow => 1,
FormattedNumberUnitDisplay::Long => 2,
};
let plural = usize::from(!one);
let split = |pattern: &'static str| pattern.split_once("{0}").unwrap_or((pattern, ""));
let pick = |table: &'static [[&'static str; 2]; 3]| {
table
.get(width)
.and_then(|pair| pair.get(plural))
.copied()
.unwrap_or("{0}")
};
match patterns {
UnitPatterns::Stored(table) => {
let (prefix, suffix) = split(pick(table));
format!("{prefix}{number}{suffix}")
}
UnitPatterns::Per(numerator, denominator) => {
let (prefix, suffix) = split(pick(&numerator.patterns));
let (per_prefix, per_suffix) =
split(denominator.per.get(width).copied().unwrap_or("{0}"));
format!("{per_prefix}{prefix}{number}{suffix}{per_suffix}")
}
}
}
fn js_number_to_string(decimal: &Decimal, negative: bool) -> String {
if decimal.is_zero() {
return "0".to_owned();
}
let digits: String = decimal
.digits
.iter()
.map(|digit| digit_char(*digit))
.collect();
let length = to_i32(digits.len());
let point = decimal.magnitude() + 1;
let mut text = String::from(if negative { "-" } else { "" });
if length <= point && point <= 21 {
text.push_str(&digits);
text.extend((length..point).map(|_| '0'));
} else if 0 < point && point <= 21 {
let (integer, fraction) = digits.split_at(usize::try_from(point).unwrap_or(0));
text.push_str(integer);
text.push('.');
text.push_str(fraction);
} else if -6 < point && point <= 0 {
text.push_str("0.");
text.extend((point..0).map(|_| '0'));
text.push_str(&digits);
} else {
let (first, rest) = digits.split_at(1);
let exponent = point - 1;
text.push_str(first);
if !rest.is_empty() {
text.push('.');
text.push_str(rest);
}
text.push('e');
text.push(if exponent < 0 { '-' } else { '+' });
text.push_str(&exponent.unsigned_abs().to_string());
}
text
}
const MONTHS: [&str; 12] = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const WEEKDAYS: [&str; 7] = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
const MINUTES_PER_DAY: i64 = 1_440;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Moment {
days: i64,
year: i64,
month: i64,
day: i64,
hour: i64,
minute: i64,
second: i64,
}
pub(crate) fn format_lumen_date(
input: &str,
date_style: Option<FormattedDateStyle>,
time_style: Option<FormattedDateTimeStyle>,
) -> Option<String> {
let moment = parse_moment(input)?;
let date_style = match (date_style, time_style) {
(None, None) => Some(FormattedDateStyle::Medium),
(style, _) => style,
};
let date = date_style.map(|style| format_date(&moment, style));
let time = time_style.map(|style| format_time(&moment, style));
match (date, time) {
(Some(date), Some(time)) => {
let glue = match date_style {
Some(FormattedDateStyle::Full | FormattedDateStyle::Long) => " at ",
_ => ", ",
};
Some(format!("{date}{glue}{time}"))
}
(date, time) => date.or(time),
}
}
struct Cursor<'a> {
bytes: &'a [u8],
}
impl Cursor<'_> {
fn number(&mut self, count: usize) -> Option<i64> {
let (field, rest) = self.bytes.split_at_checked(count)?;
if !field.iter().all(u8::is_ascii_digit) {
return None;
}
self.bytes = rest;
Some(
field
.iter()
.fold(0, |total, digit| total * 10 + i64::from(digit - b'0')),
)
}
fn eat(&mut self, byte: u8) -> bool {
match self.bytes.split_first() {
Some((first, rest)) if *first == byte => {
self.bytes = rest;
true
}
_ => false,
}
}
fn expect(&mut self, byte: u8) -> Option<()> {
self.eat(byte).then_some(())
}
fn fraction(&mut self) -> Option<bool> {
let count = self
.bytes
.iter()
.take_while(|byte| byte.is_ascii_digit())
.count();
let (digits, rest) = self.bytes.split_at_checked(count)?;
self.bytes = rest;
(count > 0).then(|| digits.iter().all(|digit| *digit == b'0'))
}
}
fn parse_moment(input: &str) -> Option<Moment> {
if input.len() > MAX_TEXT_LENGTH {
return None;
}
let mut cursor = Cursor {
bytes: input.as_bytes(),
};
let year = cursor.number(4)?;
cursor.expect(b'-')?;
let month = cursor.number(2)?;
cursor.expect(b'-')?;
let day = cursor.number(2)?;
if !(1..=9999).contains(&year) || !(1..=days_in_month(year, month)).contains(&day) {
return None;
}
let (mut hour, mut minute, mut second, mut offset) = (0, 0, 0, 0);
if !cursor.bytes.is_empty() {
cursor.expect(b'T')?;
hour = cursor.number(2)?;
cursor.expect(b':')?;
minute = cursor.number(2)?;
let mut whole_second = true;
if cursor.eat(b':') {
second = cursor.number(2)?;
if cursor.eat(b'.') {
whole_second = cursor.fraction()?;
}
}
if !cursor.eat(b'Z') && !cursor.bytes.is_empty() {
let sign = if cursor.eat(b'+') {
1
} else {
cursor.expect(b'-')?;
-1
};
let offset_hour = cursor.number(2)?;
cursor.expect(b':')?;
let offset_minute = cursor.number(2)?;
if offset_hour > 23 || offset_minute > 59 {
return None;
}
offset = sign * (offset_hour * 60 + offset_minute);
}
if !cursor.bytes.is_empty() {
return None;
}
let end_of_day = hour == 24 && minute == 0 && second == 0 && whole_second;
if (hour > 23 && !end_of_day) || minute > 59 || second > 59 {
return None;
}
}
let minutes = days_from_civil(year, month, day) * MINUTES_PER_DAY + hour * 60 + minute - offset;
let days = minutes.div_euclid(MINUTES_PER_DAY);
let minute_of_day = minutes.rem_euclid(MINUTES_PER_DAY);
let (year, month, day) = civil_from_days(days);
(1..=9999).contains(&year).then_some(Moment {
days,
year,
month,
day,
hour: minute_of_day / 60,
minute: minute_of_day % 60,
second,
})
}
fn days_in_month(year: i64, month: i64) -> i64 {
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) => 29,
2 => 28,
_ => 0,
}
}
fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
let year = if month <= 2 { year - 1 } else { year };
let era = year.div_euclid(400);
let year_of_era = year - era * 400;
let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 1;
let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
era * 146_097 + day_of_era - 719_468
}
fn civil_from_days(days: i64) -> (i64, i64, i64) {
let days = days + 719_468;
let era = days.div_euclid(146_097);
let day_of_era = days - era * 146_097;
let year_of_era =
(day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let shifted_month = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
let month = if shifted_month < 10 {
shifted_month + 3
} else {
shifted_month - 9
};
let year = year_of_era + era * 400 + i64::from(month <= 2);
(year, month, day)
}
fn name_at(names: &'static [&'static str], index: i64) -> &'static str {
usize::try_from(index)
.ok()
.and_then(|index| names.get(index))
.copied()
.unwrap_or_default()
}
fn format_date(moment: &Moment, style: FormattedDateStyle) -> String {
let Moment {
year, month, day, ..
} = *moment;
let month_name = name_at(&MONTHS, month - 1);
match style {
FormattedDateStyle::Full => {
let weekday = name_at(&WEEKDAYS, (moment.days + 4).rem_euclid(7));
format!("{weekday}, {month_name} {day}, {year}")
}
FormattedDateStyle::Long => format!("{month_name} {day}, {year}"),
FormattedDateStyle::Medium => {
format!(
"{} {day}, {year}",
month_name.get(..3).unwrap_or(month_name)
)
}
FormattedDateStyle::Short => format!("{month}/{day}/{:02}", year % 100),
}
}
fn format_time(moment: &Moment, style: FormattedDateTimeStyle) -> String {
let Moment {
hour,
minute,
second,
..
} = *moment;
let hour12 = if hour % 12 == 0 { 12 } else { hour % 12 };
let period = if hour < 12 { "AM" } else { "PM" };
match style {
FormattedDateTimeStyle::Full => {
format!("{hour12}:{minute:02}:{second:02} {period} Coordinated Universal Time")
}
FormattedDateTimeStyle::Long => format!("{hour12}:{minute:02}:{second:02} {period} UTC"),
FormattedDateTimeStyle::Medium => format!("{hour12}:{minute:02}:{second:02} {period}"),
FormattedDateTimeStyle::Short => format!("{hour12}:{minute:02} {period}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use FormattedNumberCurrencyDisplay as Display;
use FormattedNumberCurrencyName as CurrencyName;
use FormattedNumberNotation as Notation;
use FormattedNumberSignDisplay as Sign;
use FormattedNumberUnitDisplay as UnitDisplay;
fn check(
value: impl Into<FormattedNumberValue>,
options: &NumberFormatOptions,
text: &str,
accessible_text: Option<&str>,
js_value: &str,
) {
let expected = FormattedNumberText {
text: text.to_owned(),
accessible_text: accessible_text.map(str::to_owned),
valid: true,
value: Some(js_value.to_owned()),
};
assert_eq!(
format_lumen_number(&value.into(), options, FORMATTED_NUMBER_FALLBACK),
expected,
"{options:?}"
);
}
fn check_invalid(value: impl Into<FormattedNumberValue>) {
let value = value.into();
let expected = FormattedNumberText {
text: FORMATTED_NUMBER_FALLBACK.to_owned(),
accessible_text: None,
valid: false,
value: None,
};
assert_eq!(
format_lumen_number(&value, &decimal(), FORMATTED_NUMBER_FALLBACK),
expected,
"{value:?}"
);
}
fn decimal() -> NumberFormatOptions {
NumberFormatOptions::default()
}
fn fraction(minimum: Option<f64>, maximum: Option<f64>) -> NumberFormatOptions {
NumberFormatOptions {
minimum_fraction_digits: minimum,
maximum_fraction_digits: maximum,
..decimal()
}
}
fn sign(sign_display: Sign) -> NumberFormatOptions {
NumberFormatOptions {
sign_display,
..decimal()
}
}
fn notation(notation: Notation) -> NumberFormatOptions {
NumberFormatOptions {
notation,
..decimal()
}
}
fn compact() -> NumberFormatOptions {
notation(Notation::Compact)
}
fn percent() -> NumberFormatOptions {
NumberFormatOptions {
format: FormattedNumberFormat::Percent,
..decimal()
}
}
fn currency(code: &str, currency_display: Display) -> NumberFormatOptions {
NumberFormatOptions {
format: FormattedNumberFormat::Currency,
currency: Some(code.to_owned()),
currency_display,
..decimal()
}
}
fn unit(id: &str, unit_display: UnitDisplay) -> NumberFormatOptions {
NumberFormatOptions {
format: FormattedNumberFormat::Unit,
unit: Some(id.to_owned()),
unit_display,
..decimal()
}
}
#[test]
fn formats_decimal_numbers() {
check(1234.5678, &decimal(), "1,234.568", None, "1234.5678");
check(0.0, &decimal(), "0", None, "0");
check(-0.0, &decimal(), "-0", None, "0");
check(
1e21,
&decimal(),
"1,000,000,000,000,000,000,000",
None,
"1e+21",
);
check(1e-7, &decimal(), "0", None, "1e-7");
check(
f64::MIN_POSITIVE,
&decimal(),
"0",
None,
"2.2250738585072014e-308",
);
check(5e-324, &decimal(), "0", None, "5e-324");
check(
2f64.powi(60),
&decimal(),
"1,152,921,504,606,847,000",
None,
"1152921504606847000",
);
check(
256_079_881_684_854.0 + 0.625,
&decimal(),
"256,079,881,684,854.62",
None,
"256079881684854.62",
);
check(
0.1 + 0.2,
&fraction(None, Some(20.0)),
"0.30000000000000004",
None,
"0.30000000000000004",
);
check(1e-7, &fraction(None, Some(20.0)), "0.0000001", None, "1e-7");
}
#[test]
fn rounds_half_away_from_zero_on_the_shortest_decimal() {
check(1.005, &fraction(None, Some(2.0)), "1.01", None, "1.005");
check(2.675, &fraction(None, Some(2.0)), "2.68", None, "2.675");
check(-2.5, &fraction(None, Some(0.0)), "-3", None, "-2.5");
check(0.5, &fraction(None, Some(0.0)), "1", None, "0.5");
check(9.9995, &decimal(), "10", None, "9.9995");
check(-0.0001, &decimal(), "-0", None, "-0.0001");
}
#[test]
fn clamps_fraction_digits() {
check(1.5, &fraction(Some(-2.0), None), "1.5", None, "1.5");
check(
1.0 / 3.0,
&fraction(None, Some(25.0)),
"0.3333333333333333",
None,
"0.3333333333333333",
);
check(1.5, &fraction(Some(2.0), Some(1.0)), "1.50", None, "1.5");
check(
1.23456,
&fraction(Some(f64::NAN), Some(2.9)),
"1.23",
None,
"1.23456",
);
check(
1.23456,
&fraction(Some(f64::INFINITY), None),
"1.235",
None,
"1.23456",
);
check(
2.0,
&fraction(Some(21.0), None),
"2.00000000000000000000",
None,
"2",
);
}
#[test]
fn shows_signs() {
check(5.0, &sign(Sign::Always), "+5", None, "5");
check(0.0, &sign(Sign::Always), "+0", None, "0");
check(-0.0, &sign(Sign::Always), "-0", None, "0");
check(0.0, &sign(Sign::ExceptZero), "0", None, "0");
check(-0.0001, &sign(Sign::ExceptZero), "0", None, "-0.0001");
check(5.0, &sign(Sign::ExceptZero), "+5", None, "5");
check(-5.0, &sign(Sign::ExceptZero), "-5", None, "-5");
check(-5.0, &sign(Sign::Never), "5", None, "-5");
}
#[test]
fn formats_percentages() {
check(0.145, &percent(), "15%", None, "0.145");
check(-0.001, &percent(), "-0%", None, "-0.001");
check(
12.34,
&NumberFormatOptions {
notation: Notation::Compact,
..percent()
},
"1.2K%",
Some("1.2 thousand%"),
"12.34",
);
}
#[test]
fn formats_currencies() {
check(
1.0,
¤cy("USD", Display::Symbol),
"$1.00",
Some("1.00 US dollars"),
"1",
);
check(
1.0,
¤cy("USD", Display::Name),
"1.00 US dollars",
None,
"1",
);
check(
1.0,
¤cy("JPY", Display::Name),
"1 Japanese yen",
None,
"1",
);
check(
1234.5,
¤cy("JPY", Display::Symbol),
"¥1,235",
Some("1,235 Japanese yen"),
"1234.5",
);
check(
1.0,
¤cy("KWD", Display::Symbol),
"KWD\u{a0}1.000",
None,
"1",
);
check(
-1.0,
¤cy("EUR", Display::Symbol),
"-€1.00",
None,
"-1",
);
check(
1.0,
¤cy("GBP", Display::Symbol),
"£1.00",
Some("1.00 British pounds"),
"1",
);
check(1.0, ¤cy("CAD", Display::Symbol), "CA$1.00", None, "1");
check(
1.0,
¤cy("CAD", Display::NarrowSymbol),
"$1.00",
Some("1.00 Canadian dollars"),
"1",
);
check(
1.0,
¤cy("CHF", Display::Symbol),
"CHF\u{a0}1.00",
None,
"1",
);
check(
1.0,
¤cy("USD", Display::Code),
"USD\u{a0}1.00",
None,
"1",
);
check(
1.0,
¤cy("usd", Display::Symbol),
"$1.00",
Some("1.00 US dollars"),
"1",
);
check(
1.0,
¤cy("XYZ", Display::Symbol),
"XYZ\u{a0}1.00",
None,
"1",
);
check(1.0, ¤cy("XYZ", Display::Name), "1.00 XYZ", None, "1");
}
#[test]
fn formats_currencies_with_other_options() {
check(1.0, ¤cy("US", Display::Symbol), "1", None, "1");
check(
1.0,
&NumberFormatOptions {
currency: None,
..currency("USD", Display::Symbol)
},
"1",
None,
"1",
);
check(
1.0,
&NumberFormatOptions {
maximum_fraction_digits: Some(0.0),
..currency("USD", Display::Symbol)
},
"$1",
Some("1 US dollar"),
"1",
);
check(
1234.0,
&NumberFormatOptions {
notation: Notation::Compact,
..currency("USD", Display::Symbol)
},
"$1.2K",
Some("1.2 thousand US dollars"),
"1234",
);
check(
1000.0,
&NumberFormatOptions {
notation: Notation::Compact,
maximum_fraction_digits: Some(1.0),
..currency("USD", Display::Symbol)
},
"$1.0K",
Some("1.0 thousand US dollars"),
"1000",
);
check(
1234.5,
&NumberFormatOptions {
notation: Notation::Scientific,
..currency("USD", Display::Symbol)
},
"$1.23E3",
Some("1.23E3 US dollars"),
"1234.5",
);
check(
-1.0,
&NumberFormatOptions {
sign_display: Sign::Always,
..currency("XOF", Display::Symbol)
},
"-F\u{202f}CFA\u{a0}1",
None,
"-1",
);
}
#[test]
fn names_currencies_for_assistive_technology() {
check(
1.0,
&NumberFormatOptions {
currency_name: CurrencyName::Never,
..currency("USD", Display::Symbol)
},
"$1.00",
None,
"1",
);
check(
1.0,
&NumberFormatOptions {
currency_name: CurrencyName::Always,
..currency("EUR", Display::Symbol)
},
"€1.00",
Some("1.00 euros"),
"1",
);
check(
1.0,
&NumberFormatOptions {
currency_name: CurrencyName::Always,
..currency("KWD", Display::Code)
},
"KWD\u{a0}1.000",
Some("1.000 Kuwaiti dinars"),
"1",
);
check(
1.0,
¤cy("DKK", Display::NarrowSymbol),
"kr\u{a0}1.00",
Some("1.00 Danish kroner"),
"1",
);
check(
1.0,
¤cy("DKK", Display::Symbol),
"DKK\u{a0}1.00",
None,
"1",
);
}
#[test]
fn formats_units() {
check(
1.0,
&unit("kilobyte", UnitDisplay::Short),
"1 kB",
Some("1 kilobyte"),
"1",
);
check(
2.0,
&unit("kilobyte", UnitDisplay::Long),
"2 kilobytes",
None,
"2",
);
check(
16.0,
&unit("kilometer-per-hour", UnitDisplay::Narrow),
"16km/h",
Some("16 kilometers per hour"),
"16",
);
check(
-5.0,
&unit("celsius", UnitDisplay::Short),
"-5°C",
Some("-5 degrees Celsius"),
"-5",
);
check(1.0, &unit("day", UnitDisplay::Long), "1 day", None, "1");
check(
1.5,
&unit("day", UnitDisplay::Short),
"1.5 days",
None,
"1.5",
);
check(
0.0,
&unit("byte", UnitDisplay::Narrow),
"0B",
Some("0 bytes"),
"0",
);
check(
50.0,
&unit("percent", UnitDisplay::Short),
"50%",
Some("50 percent"),
"50",
);
check(
5.0,
&unit("percent-per-hour", UnitDisplay::Short),
"5%",
Some("5 percent per hour"),
"5",
);
check(
1.0,
&unit("byte-per-day", UnitDisplay::Long),
"1 byte per day",
None,
"1",
);
check(
30.0,
&unit("mile-per-gallon", UnitDisplay::Short),
"30 mpg",
Some("30 miles per gallon"),
"30",
);
check(
1.0,
&unit(" meter ", UnitDisplay::Short),
"1 m",
Some("1 meter"),
"1",
);
check(
1.0,
&NumberFormatOptions {
minimum_fraction_digits: Some(1.0),
..unit("day", UnitDisplay::Long)
},
"1.0 days",
None,
"1",
);
}
#[test]
fn falls_back_for_unusable_units() {
check(
1.23456,
&NumberFormatOptions {
maximum_fraction_digits: Some(1.0),
..unit("parsec", UnitDisplay::Short)
},
"1.235",
None,
"1.23456",
);
check(
1.23456,
&NumberFormatOptions {
maximum_fraction_digits: Some(1.0),
..unit("Meter", UnitDisplay::Short)
},
"1.235",
None,
"1.23456",
);
check(
1.23456,
&NumberFormatOptions {
maximum_fraction_digits: Some(1.0),
..unit(" ", UnitDisplay::Short)
},
"1.2",
None,
"1.23456",
);
check(
1.23456,
&NumberFormatOptions {
maximum_fraction_digits: Some(1.0),
..unit(&"x".repeat(65), UnitDisplay::Short)
},
"1.2",
None,
"1.23456",
);
check(
1234.0,
&NumberFormatOptions {
notation: Notation::Compact,
..unit("meter-per-second-per-hour", UnitDisplay::Short)
},
"1.2K",
Some("1.2 thousand"),
"1234",
);
}
#[test]
fn formats_compact_numbers() {
check(1234.0, &compact(), "1.2K", Some("1.2 thousand"), "1234");
check(12345.0, &compact(), "12K", Some("12 thousand"), "12345");
check(999_999.0, &compact(), "1M", Some("1 million"), "999999");
check(
1e15,
&compact(),
"1000T",
Some("1000 trillion"),
"1000000000000000",
);
check(
1e16,
&compact(),
"10,000T",
Some("10,000 trillion"),
"10000000000000000",
);
check(-1234.0, &compact(), "-1.2K", Some("-1.2 thousand"), "-1234");
check(1249.5, &compact(), "1.2K", Some("1.2 thousand"), "1249.5");
check(0.001_234_5, &compact(), "0.0012", None, "0.0012345");
check(
1234.0,
&NumberFormatOptions {
maximum_fraction_digits: Some(2.0),
..compact()
},
"1.23K",
Some("1.23 thousand"),
"1234",
);
check(
1000.0,
&NumberFormatOptions {
minimum_fraction_digits: Some(2.0),
..compact()
},
"1.00K",
Some("1.00 thousand"),
"1000",
);
check(
1000.0,
&NumberFormatOptions {
notation: Notation::Compact,
..unit("day", UnitDisplay::Long)
},
"1K days",
Some("1 thousand days"),
"1000",
);
check(
1234.5,
&NumberFormatOptions {
notation: Notation::Compact,
..unit("percent-per-acre", UnitDisplay::Short)
},
"1.2K%/ac",
Some("1.2 thousand percent per acre"),
"1234.5",
);
}
#[test]
fn formats_scientific_and_engineering_numbers() {
check(
1234.5,
¬ation(Notation::Scientific),
"1.235E3",
None,
"1234.5",
);
check(
0.000_123_45,
¬ation(Notation::Scientific),
"1.235E-4",
None,
"0.00012345",
);
check(0.0, ¬ation(Notation::Scientific), "0E0", None, "0");
check(
-9.9996,
¬ation(Notation::Scientific),
"-1E1",
None,
"-9.9996",
);
check(
f64::MAX,
¬ation(Notation::Scientific),
"1.798E308",
None,
"1.7976931348623157e+308",
);
check(
123_456.0,
¬ation(Notation::Engineering),
"123.456E3",
None,
"123456",
);
check(
0.000_123_45,
¬ation(Notation::Engineering),
"123.45E-6",
None,
"0.00012345",
);
check(
5e-324,
¬ation(Notation::Engineering),
"5E-324",
None,
"5e-324",
);
check(
1.0,
&NumberFormatOptions {
notation: Notation::Scientific,
..unit("day", UnitDisplay::Long)
},
"1E0 day",
None,
"1",
);
check(
0.5,
&NumberFormatOptions {
notation: Notation::Scientific,
..percent()
},
"5E1%",
None,
"0.5",
);
}
#[test]
fn reads_numeric_text() {
check("1234.5", &decimal(), "1,234.5", None, "1234.5");
check(" 2e3 ", &decimal(), "2,000", None, "2000");
check("+.5", &decimal(), "0.5", None, "0.5");
check("5.", &decimal(), "5", None, "5");
check("\u{a0}1\u{feff}", &decimal(), "1", None, "1");
check("\u{2028}7\u{3000}", &decimal(), "7", None, "7");
check("-1e-400", &decimal(), "-0", None, "0");
check("00012", &decimal(), "12", None, "12");
}
#[test]
fn rejects_values_that_are_not_finite_numbers() {
check_invalid(f64::NAN);
check_invalid(f64::INFINITY);
check_invalid(f64::NEG_INFINITY);
for text in [
"0x10",
"Infinity",
"-Infinity",
"",
" ",
".",
"+",
"1e",
"1e400",
"1,000",
"1 2",
"1_000",
"\u{85}1",
"\u{180e}1",
"NaN",
"1",
"٣",
] {
check_invalid(text);
}
check_invalid("1".repeat(65));
check(
"1".repeat(64),
&decimal(),
"1,111,111,111,111,111,200,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000",
None,
"1.1111111111111112e+63",
);
}
#[test]
fn renders_a_custom_fallback() {
let result = format_lumen_number(&"n/a".into(), &decimal(), "Not available");
assert_eq!(result.text, "Not available");
assert!(!result.valid);
}
#[test]
fn writes_values_like_javascript() {
for (number, expected) in [
(1e21, "1e+21"),
(1e-7, "1e-7"),
(1.23e-18, "1.23e-18"),
(0.000_001, "0.000001"),
(-0.0, "0"),
(1.5, "1.5"),
(100.0, "100"),
(2f64.powi(60), "1152921504606847000"),
(-f64::MAX, "-1.7976931348623157e+308"),
(5e-324, "5e-324"),
(0.1 + 0.2, "0.30000000000000004"),
(123_456_789_012_345_680_000.0, "123456789012345680000"),
(9.499_999_999_999_999e-7, "9.499999999999999e-7"),
(256_079_881_684_854.0 + 0.625, "256079881684854.62"),
] {
assert_eq!(
js_number_to_string(&Decimal::from_f64(number), number.is_sign_negative()),
expected,
"{number:e}"
);
}
}
#[test]
fn converts_rust_numbers_like_javascript() {
let value = |value: FormattedNumberValue| format_lumen_number(&value, &decimal(), "").value;
assert_eq!(
value(i64::MAX.into()),
Some("9223372036854776000".to_owned())
);
assert_eq!(
value(u64::MAX.into()),
Some("18446744073709552000".to_owned())
);
assert_eq!(value(42_usize.into()), Some("42".to_owned()));
assert_eq!(value((-7_i32).into()), Some("-7".to_owned()));
assert_eq!(value(7_u32.into()), Some("7".to_owned()));
assert_eq!(
value(0.1_f32.into()),
Some("0.10000000149011612".to_owned())
);
assert_eq!(value(String::from("8").into()), Some("8".to_owned()));
}
#[test]
fn formats_german_currency_in_its_requested_locale() {
let german = NumberFormatOptions {
locale: Some("de".to_owned()),
..currency("EUR", Display::Symbol)
};
assert_eq!(
format_lumen_number(&1234.5.into(), &german, "").text,
"1.234,50\u{a0}€"
);
}
#[test]
fn exposes_javascript_option_names() {
assert_eq!(FormattedNumberFormat::Unit.as_str(), "unit");
assert_eq!(Notation::Engineering.as_str(), "engineering");
assert_eq!(Sign::ExceptZero.as_str(), "exceptZero");
assert_eq!(Display::NarrowSymbol.as_str(), "narrowSymbol");
assert_eq!(CurrencyName::Always.as_str(), "always");
assert_eq!(UnitDisplay::Narrow.as_str(), "narrow");
assert_eq!(FormattedDateStyle::default().as_str(), "medium");
assert_eq!(FormattedDateTimeStyle::Full.as_str(), "full");
}
#[test]
fn stays_linear_on_adversarial_input() {
let long_number = format!("{}1{}", " ".repeat(1_000_000), "\u{3000}".repeat(100_000));
check(long_number, &decimal(), "1", None, "1");
check_invalid("1".repeat(1_000_000));
check_invalid("-".repeat(1_000_000));
check(
1.5,
&unit(&"-per-".repeat(200_000), UnitDisplay::Long),
"1.5",
None,
"1.5",
);
check(
1.5,
&unit(&"a".repeat(1_000_000), UnitDisplay::Long),
"1.5",
None,
"1.5",
);
check(
1.5,
¤cy(&"USD".repeat(300_000), Display::Name),
"1.5",
None,
"1.5",
);
let huge = format_lumen_number(
&f64::MAX.into(),
&NumberFormatOptions {
minimum_fraction_digits: Some(1e300),
..percent()
},
"",
);
assert_eq!(huge.text.len(), 436);
assert!(huge.text.starts_with("17,976,931,348,623,157,000,000"));
assert!(huge.text.ends_with(",000,000.00000000000000000000%"));
assert_eq!(format_lumen_date(&"2".repeat(1_000_000), None, None), None);
assert_eq!(
format_lumen_date(
&format!("2020-01-01T12:00:00.{}Z", "0".repeat(1_000_000)),
None,
None
),
None
);
}
#[test]
fn formats_dates_in_every_style() {
use FormattedDateStyle as Date;
use FormattedDateTimeStyle as Time;
let cases = [
(
None,
Some(Time::Full),
"3:04:05 PM Coordinated Universal Time",
),
(None, Some(Time::Long), "3:04:05 PM UTC"),
(None, Some(Time::Medium), "3:04:05 PM"),
(None, Some(Time::Short), "3:04 PM"),
(Some(Date::Full), None, "Tuesday, December 1, 2026"),
(Some(Date::Long), None, "December 1, 2026"),
(Some(Date::Medium), None, "Dec 1, 2026"),
(None, None, "Dec 1, 2026"),
(Some(Date::Short), None, "12/1/26"),
(
Some(Date::Full),
Some(Time::Full),
"Tuesday, December 1, 2026 at 3:04:05 PM Coordinated Universal Time",
),
(
Some(Date::Long),
Some(Time::Long),
"December 1, 2026 at 3:04:05 PM UTC",
),
(
Some(Date::Long),
Some(Time::Short),
"December 1, 2026 at 3:04 PM",
),
(
Some(Date::Medium),
Some(Time::Full),
"Dec 1, 2026, 3:04:05 PM Coordinated Universal Time",
),
(
Some(Date::Medium),
Some(Time::Medium),
"Dec 1, 2026, 3:04:05 PM",
),
(
Some(Date::Short),
Some(Time::Long),
"12/1/26, 3:04:05 PM UTC",
),
(Some(Date::Short), Some(Time::Short), "12/1/26, 3:04 PM"),
];
for (date_style, time_style, expected) in cases {
assert_eq!(
format_lumen_date("2026-12-01T15:04:05Z", date_style, time_style).as_deref(),
Some(expected),
"{date_style:?} {time_style:?}"
);
}
}
#[test]
fn converts_dates_to_utc() {
let full = |input: &str| {
format_lumen_date(
input,
Some(FormattedDateStyle::Full),
Some(FormattedDateTimeStyle::Medium),
)
};
let short = |input: &str| format_lumen_date(input, Some(FormattedDateStyle::Short), None);
for (input, expected) in [
(
"2026-12-31T23:30:00-05:00",
"Friday, January 1, 2027 at 4:30:00 AM",
),
("2024-02-29", "Thursday, February 29, 2024 at 12:00:00 AM"),
(
"2000-02-29T00:00:00.5+00:00",
"Tuesday, February 29, 2000 at 12:00:00 AM",
),
(
"2020-01-01T24:00Z",
"Thursday, January 2, 2020 at 12:00:00 AM",
),
("0001-01-01", "Monday, January 1, 1 at 12:00:00 AM"),
("1970-01-01", "Thursday, January 1, 1970 at 12:00:00 AM"),
(
"2026-01-01T00:00:00+14:00",
"Wednesday, December 31, 2025 at 10:00:00 AM",
),
(
"9999-12-31T23:59:59.999Z",
"Friday, December 31, 9999 at 11:59:59 PM",
),
(
"2026-12-01T15:04",
"Tuesday, December 1, 2026 at 3:04:00 PM",
),
] {
assert_eq!(full(input).as_deref(), Some(expected), "{input}");
}
assert_eq!(short("0001-01-01").as_deref(), Some("1/1/01"));
assert_eq!(short("9999-12-31").as_deref(), Some("12/31/99"));
}
#[test]
fn rejects_invalid_dates() {
for input in [
"2023-02-29",
"1900-02-29",
"2021-04-31",
"2021-13-01",
"2021-00-10",
"2021-01-00",
"0000-01-01",
"10000-01-01",
"+002020-01-01",
"2020-1-01",
"2020-01-01T",
"2020-01-01T12",
"2020-01-01T12Z",
"2020-01-01T24:00:01Z",
"2020-01-01T24:00:00.001Z",
"2020-01-01T23:60Z",
"2020-01-01T12:00:60Z",
"2020-01-01T12:00:00.Z",
"2020-01-01T12:00+24:00",
"2020-01-01T12:00+0530",
"2020-01-01t12:00Z",
"2020-01-01 12:00Z",
"2020-01-01T12:00Z ",
"2020-01-01Z",
"9999-12-31T23:30-05:00",
"0001-01-01T00:00+01:00",
"",
"garbage",
"2020-01-01",
] {
assert_eq!(format_lumen_date(input, None, None), None, "{input}");
}
let overlong = format!("2020-01-01T12:00:00.{}Z", "0".repeat(44));
assert_eq!(overlong.len(), 65);
assert_eq!(format_lumen_date(&overlong, None, None), None);
assert!(format_lumen_date(&overlong[..63], None, None).is_some());
assert!(format_lumen_date(&format!("{}Z", &overlong[..63]), None, None).is_some());
}
#[test]
fn counts_days_like_the_gregorian_calendar() {
let mut days = days_from_civil(1, 1, 1);
assert_eq!(days, -719_162);
assert_eq!(days_from_civil(1970, 1, 1), 0);
for year in 1..=9999 {
for month in 1..=12 {
for day in 1..=days_in_month(year, month) {
assert_eq!(civil_from_days(days), (year, month, day));
assert_eq!(days_from_civil(year, month, day), days);
days += 1;
}
}
}
}
}