use super::data::{self, Loc};
use super::date::{Cycle, DateOptions, NO_STYLE, Shape, zone_named};
use super::number::currency_digits;
use crate::catalog::is_js_space;
use crate::error::Error;
use crate::hash::FastMap;
use crate::json::{Event, Reader, push_js_number};
use std::borrow::Cow;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Style {
Decimal,
Percent,
Currency,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Display {
Symbol,
Narrow,
Code,
#[cfg_attr(not(feature = "currency-names"), allow(dead_code))]
Name,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Grouping {
Auto,
Min2,
Always,
Off,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct NumberOptions {
pub(crate) style: Style,
pub(crate) currency: [u8; 3],
pub(crate) display: Display,
pub(crate) min_frac: u8,
pub(crate) max_frac: u8,
pub(crate) min_int: u8,
pub(crate) grouping: Grouping,
pub(crate) compact: bool,
pub(crate) frac_given: bool,
}
impl NumberOptions {
pub(crate) const DEFAULT: NumberOptions = NumberOptions {
style: Style::Decimal,
currency: *b"XXX",
display: Display::Symbol,
min_frac: 0,
max_frac: 3,
min_int: 1,
grouping: Grouping::Auto,
compact: false,
frac_given: false,
};
}
enum Val<'a> {
Str(Cow<'a, str>),
Num(f64),
Bool(bool),
Null,
Arr(String),
Obj,
}
impl Val<'_> {
fn string(&self) -> Cow<'_, str> {
match self {
Val::Str(s) => Cow::Borrowed(&**s),
Val::Num(n) => {
let mut out = String::new();
push_js_number(&mut out, *n);
Cow::Owned(out)
}
Val::Bool(b) => Cow::Borrowed(if *b { "true" } else { "false" }),
Val::Null => Cow::Borrowed("null"),
Val::Arr(s) => Cow::Borrowed(s),
Val::Obj => Cow::Borrowed("[object Object]"),
}
}
fn number(&self) -> f64 {
match self {
Val::Num(n) => *n,
Val::Str(s) => js_number(s),
Val::Arr(s) => js_number(s),
Val::Bool(b) => f64::from(u8::from(*b)),
Val::Null => 0.0,
Val::Obj => f64::NAN,
}
}
fn truthy(&self) -> bool {
match self {
Val::Str(s) => !s.is_empty(),
Val::Num(n) => *n != 0.0 && !n.is_nan(),
Val::Bool(b) => *b,
Val::Null => false,
Val::Arr(_) | Val::Obj => true,
}
}
}
fn js_number(s: &str) -> f64 {
let t = s.trim_matches(is_js_space);
if t.is_empty() {
return 0.0;
}
let radix = match t.get(..2) {
Some("0x" | "0X") => 16,
Some("0o" | "0O") => 8,
Some("0b" | "0B") => 2,
_ => 10,
};
if radix != 10 {
let digits = t.get(2..).unwrap_or("");
if digits.is_empty() {
return f64::NAN;
}
let mut v = 0.0;
for c in digits.chars() {
match c.to_digit(radix) {
Some(d) => v = v * f64::from(radix) + f64::from(d),
None => return f64::NAN,
}
}
return v;
}
let body = t.strip_prefix(['+', '-']).unwrap_or(t);
if body == "Infinity" {
return if t.starts_with('-') {
f64::NEG_INFINITY
} else {
f64::INFINITY
};
}
if !body.starts_with(|c: char| c.is_ascii_digit() || c == '.')
|| !body
.bytes()
.all(|b| b.is_ascii_digit() || matches!(b, b'.' | b'e' | b'E' | b'+' | b'-'))
{
return f64::NAN;
}
t.parse().unwrap_or(f64::NAN)
}
fn array_string<'a>(r: &mut Reader<'a>, path: &str) -> Result<String, Error> {
let mut out = String::new();
let mut first = true;
loop {
let e = next_event(r, path)?;
if matches!(e, Event::ArrayEnd) {
return Ok(out);
}
if !first {
out.push(',');
}
first = false;
match e {
Event::Str(s) => out.push_str(&s),
Event::Num(n) => push_js_number(&mut out, n.parse().unwrap_or(f64::NAN)),
Event::Bool(b) => out.push_str(if b { "true" } else { "false" }),
Event::ArrayStart => out.push_str(&array_string(r, path)?),
Event::ObjectStart => {
skip_object(r, path)?;
out.push_str("[object Object]");
}
_ => {}
}
}
}
fn skip_object(r: &mut Reader<'_>, path: &str) -> Result<(), Error> {
let mut depth = 1;
while depth > 0 {
match next_event(r, path)? {
Event::ObjectStart | Event::ArrayStart => depth += 1,
Event::ObjectEnd | Event::ArrayEnd => depth -= 1,
_ => {}
}
}
Ok(())
}
pub(crate) type Formats = FastMap<Box<str>, FastMap<Box<str>, NumberOptions>>;
pub(crate) type DateFormats = FastMap<Box<str>, FastMap<Box<str>, DateOptions>>;
pub(crate) type Numbering = Vec<(Box<str>, Box<str>, [u8; 8])>;
type Raw<'a> = [(Box<str>, Val<'a>)];
pub(crate) fn parse_formats(
json: &str,
path: &str,
into: &mut Formats,
numbering: &mut Numbering,
) -> Result<(), Error> {
parse_named(json, path, NUMBER_SHAPES, &mut |locale, name, raw| {
store(locale, name, resolve(raw), into, numbering)
})
}
pub(crate) fn parse_date_formats(
json: &str,
path: &str,
into: &mut DateFormats,
numbering: &mut Numbering,
) -> Result<(), Error> {
parse_named(json, path, DATE_SHAPES, &mut |locale, name, raw| {
store(locale, name, resolve_date(raw), into, numbering)
})
}
const NUMBER_SHAPES: [&str; 3] = [
"numberFormats must be an object",
"numberFormats.<locale> must be an object",
"numberFormats.<locale>.<name> must be an object",
];
const DATE_SHAPES: [&str; 3] = [
"datetimeFormats must be an object",
"datetimeFormats.<locale> must be an object",
"datetimeFormats.<locale>.<name> must be an object",
];
fn store<T>(
locale: &str,
name: &str,
resolved: Result<(T, Option<[u8; 8]>), &'static str>,
into: &mut FastMap<Box<str>, FastMap<Box<str>, T>>,
numbering: &mut Numbering,
) -> Result<(), Error> {
let (options, nu) = resolved.map_err(|option| Error::UnsupportedFormat {
locale: locale.to_owned(),
name: name.to_owned(),
option: option.to_owned(),
})?;
if name != "__proto__" && locale != "__proto__" {
numbering.retain(|(l, n, _)| (&**l, &**n) != (locale, name));
if let Some(nu) = nu {
numbering.push((Box::from(locale), Box::from(name), nu));
}
into.entry(Box::from(locale))
.or_default()
.insert(Box::from(name), options);
}
Ok(())
}
fn parse_named<'a>(
json: &'a str,
path: &str,
shapes: [&'static str; 3],
each: &mut dyn FnMut(&str, &str, &Raw<'_>) -> Result<(), Error>,
) -> Result<(), Error> {
let mut r = Reader::new(json.as_bytes());
let shape = |reason| Error::Config {
path: path.to_owned(),
reason,
};
let next = |r: &mut Reader<'a>| next_event(r, path);
if !matches!(next(&mut r)?, Event::ObjectStart) {
return Err(shape(shapes[0]));
}
while let Event::Key(locale) = next(&mut r)? {
if !matches!(next(&mut r)?, Event::ObjectStart) {
return Err(shape(shapes[1]));
}
while let Event::Key(name) = next(&mut r)? {
if !matches!(next(&mut r)?, Event::ObjectStart) {
return Err(shape(shapes[2]));
}
let mut raw: Vec<(Box<str>, Val<'_>)> = Vec::new();
while let Event::Key(key) = next(&mut r)? {
let v = match next(&mut r)? {
Event::Str(s) => Val::Str(s),
Event::Num(n) => Val::Num(n.parse().unwrap_or(f64::NAN)),
Event::Bool(b) => Val::Bool(b),
Event::ArrayStart => Val::Arr(array_string(&mut r, path)?),
Event::ObjectStart => {
skip_object(&mut r, path)?;
Val::Obj
}
_ => Val::Null,
};
raw.retain(|(k, _)| **k != *key);
raw.push((Box::from(&*key), v));
}
each(&locale, &name, &raw)?;
}
}
match r.next() {
Ok(_) => Ok(()),
Err(e) => Err(Error::Json {
path: path.to_owned(),
offset: e.offset,
kind: e.kind.as_str(),
}),
}
}
pub(crate) fn check_numbering(
numbering: &Numbering,
loc: impl Fn(&str) -> &'static Loc,
) -> Result<(), Error> {
let mut refused: Option<(&str, &str)> = None;
for (locale, name, nu) in numbering {
let given = nu.split(|&b| b == 0).next().unwrap_or(&[]);
if given == data::numbering(loc(locale).digits).as_bytes() {
continue;
}
if refused.is_none_or(|r| (&**locale, &**name) < r) {
refused = Some((locale, name));
}
}
match refused {
Some((locale, name)) => Err(Error::UnsupportedFormat {
locale: locale.to_owned(),
name: name.to_owned(),
option: "numberingSystem".to_owned(),
}),
None => Ok(()),
}
}
fn next_event<'a>(r: &mut Reader<'a>, path: &str) -> Result<Event<'a>, Error> {
match r.next() {
Ok(Some(e)) => Ok(e),
Ok(None) => Err(Error::Config {
path: path.to_owned(),
reason: "unexpected end",
}),
Err(e) => Err(Error::Json {
path: path.to_owned(),
offset: e.offset,
kind: e.kind.as_str(),
}),
}
}
fn number(v: &Val<'_>, lo: u8, hi: u8) -> Option<u8> {
let n = v.number();
(n >= f64::from(lo) && n <= f64::from(hi)).then(|| n.floor() as u8)
}
fn numbering_system(nu: Option<&str>) -> Result<Option<[u8; 8]>, &'static str> {
let Some(nu) = nu else { return Ok(None) };
let b = nu.as_bytes();
if !(3..=8).contains(&b.len()) || !b.iter().all(u8::is_ascii_alphanumeric) {
return Err("numberingSystem");
}
let mut given = [0u8; 8];
for (slot, c) in given.iter_mut().zip(b) {
*slot = c.to_ascii_lowercase();
}
Ok(Some(given))
}
fn resolve(raw: &Raw<'_>) -> Result<(NumberOptions, Option<[u8; 8]>), &'static str> {
let get = |k: &str| raw.iter().find(|(key, _)| &**key == k).map(|(_, v)| v);
let string = |k: &str| get(k).map(Val::string);
const DEFAULTS: [(&str, &[&str]); 7] = [
("signDisplay", &["auto"]),
("currencySign", &["standard"]),
("localeMatcher", &["best fit", "lookup"]),
("roundingMode", &["halfExpand"]),
("roundingPriority", &["auto"]),
("trailingZeroDisplay", &["auto"]),
("notation", &["standard", "compact"]),
];
for (key, v) in raw {
let key = &**key;
if let Some((name, ok)) = DEFAULTS.iter().find(|(k, _)| *k == key) {
if !ok.contains(&&*v.string()) {
return Err(name);
}
continue;
}
match key {
"roundingIncrement" if (1.0..2.0).contains(&v.number()) => {}
"roundingIncrement" => return Err("roundingIncrement"),
"unit" => return Err("unit"),
"unitDisplay" => return Err("unitDisplay"),
"minimumSignificantDigits" => return Err("minimumSignificantDigits"),
"maximumSignificantDigits" => return Err("maximumSignificantDigits"),
_ => {}
}
}
let mut o = NumberOptions::DEFAULT;
o.style = match string("style").as_deref() {
None | Some("decimal") => Style::Decimal,
Some("percent") => Style::Percent,
Some("currency") => Style::Currency,
Some(_) => return Err("style"),
};
o.compact = string("notation").as_deref() == Some("compact");
if o.compact && o.style != Style::Decimal {
return Err("notation");
}
match string("compactDisplay").as_deref() {
None | Some("short") => {}
Some("long") if !o.compact => {}
Some(_) => return Err("compactDisplay"),
}
let numbering = numbering_system(string("numberingSystem").as_deref())?;
if let Some(c) = string("currency") {
let b = c.as_bytes();
if b.len() != 3 || !b.iter().all(u8::is_ascii_alphabetic) {
return Err("currency");
}
o.currency = [
b[0].to_ascii_uppercase(),
b[1].to_ascii_uppercase(),
b[2].to_ascii_uppercase(),
];
} else if o.style == Style::Currency {
return Err("currency");
}
o.display = match string("currencyDisplay").as_deref() {
None | Some("symbol") => Display::Symbol,
Some("narrowSymbol") => Display::Narrow,
Some("code") => Display::Code,
#[cfg(feature = "currency-names")]
Some("name") => Display::Name,
Some(_) => return Err("currencyDisplay"),
};
if let Some(v) = get("minimumIntegerDigits") {
o.min_int = number(v, 1, 21).ok_or("minimumIntegerDigits")?;
}
let (min_default, max_default) = match o.style {
Style::Decimal => (0, 3),
Style::Percent => (0, 0),
Style::Currency => {
let d = currency_digits(o.currency);
(d, d)
}
};
let min = get("minimumFractionDigits")
.map(|v| number(v, 0, 100).ok_or("minimumFractionDigits"))
.transpose()?;
let max = get("maximumFractionDigits")
.map(|v| number(v, 0, 100).ok_or("maximumFractionDigits"))
.transpose()?;
o.frac_given = min.is_some() || max.is_some();
(o.min_frac, o.max_frac) = match (min, max) {
(None, None) => (min_default, max_default),
(None, Some(max)) => (min_default.min(max), max),
(Some(min), None) => (min, max_default.max(min)),
(Some(min), Some(max)) if min > max => return Err("maximumFractionDigits"),
(Some(min), Some(max)) => (min, max),
};
let fallback = if o.compact {
Grouping::Min2
} else {
Grouping::Auto
};
o.grouping = match get("useGrouping") {
None => fallback,
Some(Val::Bool(true)) => Grouping::Always,
Some(v) if !v.truthy() => Grouping::Off,
Some(v) => match &*v.string() {
"always" => Grouping::Always,
"auto" => Grouping::Auto,
"min2" => Grouping::Min2,
"true" | "false" => fallback,
_ => return Err("useGrouping"),
},
};
if o.compact && o.grouping == Grouping::Auto {
o.grouping = Grouping::Min2;
}
Ok((o, numbering))
}
fn resolve_date(raw: &Raw<'_>) -> Result<(DateOptions, Option<[u8; 8]>), &'static str> {
let get = |k: &str| raw.iter().find(|(key, _)| &**key == k).map(|(_, v)| v);
let string = |k: &str| get(k).map(Val::string);
let pick = |k: &'static str, values: &[&str]| -> Result<u8, &'static str> {
match string(k) {
None => Ok(0),
Some(v) => values
.iter()
.position(|x| *x == v)
.map(|i| i as u8 + 1)
.ok_or(k),
}
};
for (key, v) in raw {
match &**key {
"era" | "timeZoneName" | "dayPeriod" | "fractionalSecondDigits" => {
return Err(match &**key {
"era" => "era",
"timeZoneName" => "timeZoneName",
"dayPeriod" => "dayPeriod",
_ => "fractionalSecondDigits",
});
}
"calendar" if v.string().eq_ignore_ascii_case("gregory") => {}
"calendar" => return Err("calendar"),
"localeMatcher" if matches!(&*v.string(), "best fit" | "lookup") => {}
"localeMatcher" => return Err("localeMatcher"),
"formatMatcher" if matches!(&*v.string(), "best fit" | "basic") => {}
"formatMatcher" => return Err("formatMatcher"),
_ => {}
}
}
let numeric = ["numeric", "2-digit"];
let weekday = pick("weekday", &["long", "short", "narrow"])?;
let year = pick("year", &numeric)?;
let month = pick("month", &["numeric", "2-digit", "long", "short", "narrow"])?;
let day = pick("day", &numeric)?;
let hour = pick("hour", &numeric)?;
let minute = pick("minute", &numeric)?;
let second = pick("second", &numeric)?;
let styles = ["full", "long", "medium", "short"];
let date_style = pick("dateStyle", &styles)?;
let time_style = pick("timeStyle", &styles)?;
let hour12 = get("hour12").map(Val::truthy);
let cycle = match (hour12, pick("hourCycle", &["h11", "h12", "h23", "h24"])?) {
(Some(h), _) => Cycle::Hour12(h),
(None, 1) => Cycle::H11,
(None, 2) => Cycle::H12,
(None, 3) => Cycle::H23,
(None, 4) => Cycle::H24,
_ => Cycle::Locale,
};
let zone = match string("timeZone") {
Some(name) => Some(zone_named(&name).ok_or("timeZone")?),
None => None,
};
let components = weekday | year | month | day | hour | minute | second != 0;
let shape = if date_style != 0 || time_style != 0 {
if components {
return Err(if date_style != 0 {
"dateStyle"
} else {
"timeStyle"
});
}
if matches!(time_style, 1 | 2) {
return Err("timeStyle");
}
Shape::Styles {
date: date_style.checked_sub(1).unwrap_or(NO_STYLE),
time: time_style.checked_sub(1).unwrap_or(NO_STYLE),
}
} else if components {
Shape::Components {
date: ((year * 6 + month) * 3 + day) * 4 + weekday,
time: (hour * 3 + minute) * 3 + second,
}
} else {
DateOptions::DEFAULT.shape
};
let numbering = numbering_system(string("numberingSystem").as_deref())?;
Ok((DateOptions { shape, cycle, zone }, numbering))
}