use std::sync::Arc;
use toml_edit::{InlineTable, Item, Value};
use crate::{
numeric::{
decimal::{NegativeZero, NumericNotation, NumericRadix, NumericRounding, TrailingZeros},
emission::{
NumericAlignment, NumericField, NumericRate, NumericSign, NumericSymbol, Presentation,
},
locale::{
NumericCurrency, NumericGroupRepeat, NumericGrouping, NumericLocale, NumericSymbols,
},
prefixes::{
NumericCompactRule, NumericFactor, NumericPrefixes, NumericPromotion, NumericSelection,
PrefixMode, SiPrefix,
},
unit::{NumericExplanation, NumericUnit, NumericUnitPlacement, UnitPolicy},
},
recipe::codec::{choice, field, invalid, table, Codec},
Result,
};
use super::{NumericFormat, NumericPrecision};
use crate::recipe::schema::{self as grammar, Schema};
choice!(NumericRadix {Decimal=>"decimal",Binary=>"binary",Octal=>"octal",HexLower=>"hex_lower",HexUpper=>"hex_upper"});
choice!(NumericRounding {NearestEven=>"nearest_even",NearestAway=>"nearest_away",NearestTowardZero=>"nearest_toward_zero",TowardZero=>"toward_zero",AwayFromZero=>"away_from_zero",Floor=>"floor",Ceiling=>"ceiling"});
choice!(NegativeZero {Preserve=>"preserve",Normalize=>"normalize"});
choice!(TrailingZeros {Keep=>"keep",Trim=>"trim"});
choice!(NumericSign {NegativeOnly=>"negative_only",Always=>"always",Space=>"space",Accounting=>"accounting"});
choice!(NumericSymbol {None=>"none",Currency=>"currency",RadixPrefix=>"radix_prefix"});
choice!(NumericAlignment {Left=>"left",Right=>"right",Center=>"center",AfterSign=>"after_sign"});
choice!(NumericRate {Value=>"value",Percent=>"percent",PerMille=>"per_mille"});
choice!(NumericGroupRepeat {Cycle=>"cycle",Last=>"last",Stop=>"stop"});
choice!(NumericPromotion {KeepThreshold=>"keep_threshold",PromoteOnRounding=>"promote_on_rounding"});
choice!(NumericUnitPlacement {PerLabel=>"per_label",Shared=>"shared"});
const FORMAT_FIELDS: &[grammar::Field] = &[
grammar::optional::<NumericNotation>("notation"),
grammar::optional::<NumericPrecision>("precision"),
grammar::optional::<i16>("decimal_scale"),
grammar::optional::<Option<String>>("prefix"),
grammar::optional::<Option<String>>("suffix"),
grammar::optional::<NegativeZero>("negative_zero"),
grammar::optional::<TrailingZeros>("trailing_zeros"),
grammar::optional::<NumericRounding>("rounding"),
grammar::optional::<f64>("multiplier"),
grammar::optional::<NumericRate>("rate"),
grammar::optional::<NumericLocale>("locale"),
grammar::optional::<bool>("grouping"),
grammar::optional::<NumericSign>("sign"),
grammar::optional::<NumericSymbol>("symbol"),
grammar::optional::<Option<NumericField>>("field"),
grammar::optional::<NumericPrefixes>("prefixes"),
grammar::optional::<Option<NumericUnit>>("unit"),
grammar::optional::<NumericExplanation>("explanation"),
];
impl NumericFormat {
pub(crate) fn schema(ctx: &mut Schema) -> serde_json::Value {
ctx.named("NumericFormat", |ctx| grammar::record(ctx, FORMAT_FIELDS))
}
pub(crate) fn style_schema(ctx: &mut Schema) -> serde_json::Value {
ctx.named("NumericFormatStyle", |ctx| {
let mut shape = grammar::record(ctx, FORMAT_FIELDS);
grammar::declare_property(
&mut shape,
"explanation",
crate::recipe::style::text_schema(ctx),
);
shape
})
}
pub(crate) fn style_recipe_value(&self, retain_unit_reference: bool) -> Result<Value> {
let mut style = self.clone();
let units = Arc::make_mut(&mut style.units);
if !retain_unit_reference {
units.unit = None;
}
units.explanation = units.explanation.appearance_only();
style.recipe_value()
}
pub(crate) fn from_style_value(item: &Item) -> Result<Self> {
if let Some(explanation) = item.get("explanation") {
crate::recipe::style::read_text(explanation)?;
}
Self::from_recipe_value(item)
}
pub(crate) fn unit_reference(&self) -> Option<&str> {
self.units.unit.as_ref().map(NumericUnit::text)
}
pub(crate) fn apply_recipe_style(
style: Option<Self>,
target: Option<&Self>,
) -> Result<Option<Self>> {
let Some(mut style) = style else {
if target.is_some_and(|format| {
format.units.unit.is_some() || format.units.explanation.has_authored_content()
}) {
return Err(invalid(
"omitted numeric format cannot retain the target's explicit unit or explanation",
));
}
return Ok(None);
};
let appearance = style.units.explanation.clone();
let mut units = target.map_or_else(UnitPolicy::default, |value| (*value.units).clone());
units.explanation.apply_appearance(&appearance);
style.units = Arc::new(units);
style.validate()?;
Ok(Some(style))
}
pub(crate) fn recipe_value(&self) -> Result<Value> {
if !self.emitter.is_builtin() {
return Err(invalid(
"numeric formatting callback cannot be represented as a recipe",
));
}
let mut fields = InlineTable::new();
fields.insert("notation", self.notation.encode());
fields.insert("precision", self.precision.encode());
fields.insert("decimal_scale", self.decimal_scale.encode());
if let Some(prefix) = &self.prefix {
fields.insert("prefix", prefix.encode());
}
if let Some(suffix) = &self.suffix {
fields.insert("suffix", suffix.encode());
}
fields.insert("negative_zero", self.negative_zero.encode());
fields.insert("trailing_zeros", self.trailing_zeros.encode());
fields.insert("rounding", self.rounding.encode());
fields.insert("multiplier", f64::from_bits(self.multiplier_bits).encode());
fields.insert("rate", self.rate.encode());
fields.insert("locale", self.presentation.locale.encode());
fields.insert("grouping", self.presentation.grouping.encode());
fields.insert("sign", self.presentation.sign.encode());
fields.insert("symbol", self.presentation.symbol.encode());
if let Some(field) = &self.presentation.field {
fields.insert("field", field.encode());
}
fields.insert("prefixes", self.prefixes.encode());
if let Some(unit) = &self.units.unit {
fields.insert("unit", unit.encode());
}
if self.units.explanation != NumericExplanation::automatic() {
fields.insert("explanation", self.units.explanation.encode());
}
Ok(fields.into())
}
pub(crate) fn from_recipe_value(item: &Item) -> Result<Self> {
let fields = grammar::record_fields(item, FORMAT_FIELDS)?;
let default = Self::default();
let multiplier: f64 = field(fields, "multiplier", Some(1.0))?;
let value = Self {
notation: field(fields, "notation", Some(default.notation))?,
precision: field(fields, "precision", Some(default.precision))?,
decimal_scale: field(fields, "decimal_scale", Some(default.decimal_scale))?,
prefix: field(fields, "prefix", Some(None))?,
suffix: field(fields, "suffix", Some(None))?,
negative_zero: field(fields, "negative_zero", Some(default.negative_zero))?,
trailing_zeros: field(fields, "trailing_zeros", Some(default.trailing_zeros))?,
rounding: field(fields, "rounding", Some(default.rounding))?,
multiplier_bits: if multiplier == 0.0 {
0
} else {
multiplier.to_bits()
},
rate: field(fields, "rate", Some(default.rate))?,
presentation: Presentation {
locale: field(fields, "locale", Some(default.presentation.locale))?,
grouping: field(fields, "grouping", Some(default.presentation.grouping))?,
sign: field(fields, "sign", Some(default.presentation.sign))?,
symbol: field(fields, "symbol", Some(default.presentation.symbol))?,
field: field(fields, "field", Some(None))?,
},
prefixes: field(fields, "prefixes", Some(default.prefixes))?,
units: Arc::new(UnitPolicy {
unit: field(fields, "unit", Some(None))?,
explanation: field(fields, "explanation", Some(NumericExplanation::automatic()))?,
}),
emitter: default.emitter,
};
value.validate()?;
Ok(value)
}
}
const NOTATION_INTEGER: &[grammar::Field] = &[grammar::mandatory::<NumericRadix>("integer")];
impl Codec for NumericNotation {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::any_of([
grammar::choices(&["decimal", "scientific", "engineering", "general"]),
grammar::record(ctx, NOTATION_INTEGER),
])
}
fn encode(&self) -> Value {
let kind = match self {
Self::Decimal => "decimal",
Self::Scientific => "scientific",
Self::Engineering => "engineering",
Self::General => "general",
Self::Integer(radix) => {
let mut fields = InlineTable::new();
fields.insert("integer", radix.encode());
return fields.into();
}
};
kind.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
match item.as_str() {
Some("decimal") => Ok(Self::Decimal),
Some("scientific") => Ok(Self::Scientific),
Some("engineering") => Ok(Self::Engineering),
Some("general") => Ok(Self::General),
Some(_) => Err(invalid("unknown numeric notation")),
None => field(
grammar::record_fields(item, NOTATION_INTEGER)?,
"integer",
None,
)
.map(Self::Integer),
}
}
}
const PRECISION_FIELDS: &[grammar::Field] = &[
grammar::optional::<u8>("fractional"),
grammar::optional::<u8>("significant"),
grammar::custom("adaptive_fractional", false, |ctx| {
grammar::pair(ctx.reference::<u8>())
}),
grammar::custom("adaptive_significant", false, |ctx| {
grammar::pair(ctx.reference::<u8>())
}),
];
impl Codec for NumericPrecision {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::with(
grammar::record(ctx, PRECISION_FIELDS),
grammar::exclusive(&[
"fractional",
"significant",
"adaptive_fractional",
"adaptive_significant",
]),
)
}
fn encode(&self) -> Value {
let mut fields = InlineTable::new();
match *self {
Self::Fractional(value) => fields.insert("fractional", value.encode()),
Self::Significant(value) => fields.insert("significant", value.encode()),
Self::AdaptiveFractional { min, max } => {
fields.insert("adaptive_fractional", vec![min, max].encode())
}
Self::AdaptiveSignificant { min, max } => {
fields.insert("adaptive_significant", vec![min, max].encode())
}
};
fields.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
let fields = grammar::record_fields(item, PRECISION_FIELDS)?;
if fields.len() != 1 {
return Err(invalid("numeric precision requires one policy"));
}
let (kind, value) = fields.iter().next().expect("one precision policy");
let result = match kind {
"fractional" => Self::Fractional(u8::decode(value, None)?),
"significant" => Self::Significant(u8::decode(value, None)?),
"adaptive_fractional" | "adaptive_significant" => {
let bounds = Vec::<u8>::decode(value, None)?;
let [min, max] = bounds.as_slice() else {
return Err(invalid("adaptive precision requires two bounds"));
};
if kind == "adaptive_fractional" {
Self::AdaptiveFractional {
min: *min,
max: *max,
}
} else {
Self::AdaptiveSignificant {
min: *min,
max: *max,
}
}
}
_ => unreachable!("validated precision policy"),
};
result.bounds()?;
Ok(result)
}
}
const NUMERIC_FIELD_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<usize>("width"),
grammar::optional::<String>("fill"),
grammar::optional::<NumericAlignment>("alignment"),
];
impl Codec for NumericField {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::record(ctx, NUMERIC_FIELD_FIELDS)
}
fn encode(&self) -> Value {
let mut fields = InlineTable::new();
fields.insert("width", self.width.encode());
fields.insert("fill", self.fill.to_string().encode());
fields.insert("alignment", self.alignment.encode());
fields.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
let fields = grammar::record_fields(item, NUMERIC_FIELD_FIELDS)?;
let fill = field::<String>(fields, "fill", Some(" ".to_owned()))?;
let mut chars = fill.chars();
let scalar = chars
.next()
.filter(|_| chars.next().is_none())
.ok_or_else(|| invalid("numeric fill must be one Unicode scalar"))?;
Self::new(
field(fields, "width", None)?,
scalar,
field(fields, "alignment", Some(NumericAlignment::Right))?,
)
}
}
const GROUPING_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<String>("separator"),
grammar::mandatory::<Vec<usize>>("sizes"),
grammar::optional::<NumericGroupRepeat>("repeat"),
];
impl Codec for NumericGrouping {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::record(ctx, GROUPING_FIELDS)
}
fn encode(&self) -> Value {
let mut fields = InlineTable::new();
fields.insert("separator", Value::from(self.separator()));
fields.insert("sizes", crate::recipe::codec::array(self.sizes()));
fields.insert("repeat", self.repeat().encode());
fields.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
let fields = grammar::record_fields(item, GROUPING_FIELDS)?;
Self::new(
field::<String>(fields, "separator", None)?,
field(fields, "sizes", None)?,
field(fields, "repeat", Some(NumericGroupRepeat::Cycle))?,
)
}
}
const SYMBOL_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<String>("positive"),
grammar::mandatory::<String>("negative"),
grammar::mandatory::<String>("percent"),
grammar::mandatory::<String>("per_mille"),
];
impl Codec for NumericSymbols {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::record(ctx, SYMBOL_FIELDS)
}
fn encode(&self) -> Value {
let mut fields = InlineTable::new();
fields.insert("positive", Value::from(self.positive()));
fields.insert("negative", Value::from(self.negative()));
fields.insert("percent", Value::from(self.percent()));
fields.insert("per_mille", Value::from(self.per_mille()));
fields.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
let fields = grammar::record_fields(item, SYMBOL_FIELDS)?;
Self::new(
field::<String>(fields, "positive", None)?,
field::<String>(fields, "negative", None)?,
field::<String>(fields, "percent", None)?,
field::<String>(fields, "per_mille", None)?,
)
}
}
const CURRENCY_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<String>("prefix"),
grammar::mandatory::<String>("suffix"),
];
impl Codec for NumericCurrency {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::record(ctx, CURRENCY_FIELDS)
}
fn encode(&self) -> Value {
let mut fields = InlineTable::new();
fields.insert("prefix", Value::from(self.prefix()));
fields.insert("suffix", Value::from(self.suffix()));
fields.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
let fields = grammar::record_fields(item, CURRENCY_FIELDS)?;
Self::new(
field::<String>(fields, "prefix", None)?,
field::<String>(fields, "suffix", None)?,
)
}
}
const LOCALE_FIELDS: &[grammar::Field] = &[
grammar::optional::<String>("decimal"),
grammar::custom(
"digits",
false,
|ctx| serde_json::json!({"type":"array","minItems":10,"maxItems":10,"uniqueItems":true,"items":ctx.reference::<String>()}),
),
grammar::optional::<Option<NumericGrouping>>("grouping"),
grammar::optional::<NumericSymbols>("symbols"),
grammar::optional::<NumericCurrency>("currency"),
];
impl Codec for NumericLocale {
fn schema(ctx: &mut Schema) -> serde_json::Value {
{
let mut names = NumericLocale::named_ids().to_vec();
names.push("invariant");
grammar::any_of([
grammar::choices(&names),
grammar::record(ctx, LOCALE_FIELDS),
])
}
}
fn encode(&self) -> Value {
let mut fields = InlineTable::new();
fields.insert("decimal", Value::from(self.decimal()));
fields.insert("digits", crate::recipe::codec::array(self.digits()));
fields.insert("grouping", self.grouping().cloned().encode());
fields.insert("symbols", self.symbols().encode());
fields.insert("currency", self.currency().encode());
fields.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
if let Some(name) = item.as_str() {
return if name == "invariant" {
Ok(Self::invariant())
} else {
Self::named(name)
};
}
let fields = grammar::record_fields(item, LOCALE_FIELDS)?;
let base = Self::invariant();
let digits: Vec<String> = field(fields, "digits", Some(base.digits().to_vec()))?;
Self::custom(
field::<String>(fields, "decimal", Some(base.decimal().to_owned()))?,
digits
.try_into()
.map_err(|_| invalid("numeric locale requires exactly ten digit tokens"))?,
field(fields, "grouping", Some(base.grouping().cloned()))?,
field(fields, "symbols", Some(base.symbols().clone()))?,
field(fields, "currency", Some(base.currency().clone()))?,
)
}
}
impl Codec for SiPrefix {
fn schema(ctx: &mut Schema) -> serde_json::Value {
ctx.reference::<i8>()
}
fn encode(&self) -> Value {
self.exponent().encode()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
Self::from_exponent(i8::decode(item, None)?)
}
}
impl<T: Codec> Codec for NumericSelection<T> {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::any_of([
grammar::choices(&["per_value", "whole_set"]),
grammar::object([("fixed", ctx.reference::<T>())], &["fixed"]),
])
}
fn encode(&self) -> Value {
match self {
Self::PerValue => Value::from("per_value"),
Self::WholeSet => Value::from("whole_set"),
Self::Fixed(value) => {
let mut fields = InlineTable::new();
fields.insert("fixed", value.encode());
fields.into()
}
}
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
match item.as_str() {
Some("per_value") => Ok(Self::PerValue),
Some("whole_set") => Ok(Self::WholeSet),
_ => field(table(item, &["fixed"])?, "fixed", None).map(Self::Fixed),
}
}
}
const COMPACT_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<f64>("threshold"),
grammar::mandatory::<f64>("divisor"),
grammar::optional::<String>("prefix"),
grammar::optional::<String>("suffix"),
];
impl Codec for NumericCompactRule {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::record(ctx, COMPACT_FIELDS)
}
fn encode(&self) -> Value {
let mut fields = InlineTable::new();
fields.insert("threshold", self.threshold().encode());
fields.insert("divisor", self.divisor().encode());
fields.insert("prefix", Value::from(self.prefix()));
fields.insert("suffix", Value::from(self.suffix()));
fields.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
let fields = grammar::record_fields(item, COMPACT_FIELDS)?;
Self::new(
field(fields, "threshold", None)?,
field(fields, "divisor", None)?,
field::<String>(fields, "prefix", Some(String::new()))?,
field::<String>(fields, "suffix", Some(String::new()))?,
)
}
}
const FACTOR_FIELDS: &[grammar::Field] = &[grammar::mandatory::<String>("power_of_ten")];
impl Codec for NumericFactor {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::any_of([
grammar::literal("automatic_decimal"),
ctx.reference::<f64>(),
grammar::record(ctx, FACTOR_FIELDS),
])
}
fn encode(&self) -> Value {
match self {
Self::AutomaticDecimal => Value::from("automatic_decimal"),
Self::Value(value) => value.encode(),
Self::PowerOfTen(exponent) => {
let mut fields = InlineTable::new();
fields.insert("power_of_ten", exponent.encode());
fields.into()
}
}
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
if item.as_str() == Some("automatic_decimal") {
return Ok(Self::AutomaticDecimal);
}
if item.as_integer().is_some() || item.as_float().is_some() {
return f64::decode(item, None).map(Self::Value);
}
field(
grammar::record_fields(item, FACTOR_FIELDS)?,
"power_of_ten",
None,
)
.map(Self::PowerOfTen)
}
}
const PREFIX_SI: &[grammar::Field] = &[
grammar::custom("kind", true, |_| grammar::literal("si")),
grammar::mandatory::<NumericSelection<SiPrefix>>("selection"),
grammar::optional::<NumericPromotion>("promotion"),
];
const PREFIX_COMPACT: &[grammar::Field] = &[
grammar::custom("kind", true, |_| grammar::literal("compact")),
grammar::mandatory::<Vec<NumericCompactRule>>("rules"),
grammar::mandatory::<NumericSelection<usize>>("selection"),
grammar::optional::<NumericPromotion>("promotion"),
];
const PREFIX_FACTOR: &[grammar::Field] = &[
grammar::custom("kind", true, |_| grammar::literal("factor")),
grammar::mandatory::<NumericFactor>("factor"),
];
impl Codec for NumericPrefixes {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::one_of([
grammar::literal("none"),
grammar::record(ctx, PREFIX_SI),
grammar::record(ctx, PREFIX_COMPACT),
grammar::record(ctx, PREFIX_FACTOR),
])
}
fn encode(&self) -> Value {
let mut fields = InlineTable::new();
match self.0.as_ref() {
PrefixMode::None => return Value::from("none"),
PrefixMode::Si(selection, promotion) => {
fields.insert("kind", Value::from("si"));
fields.insert("selection", selection.encode());
fields.insert("promotion", promotion.encode());
}
PrefixMode::Compact(rules, selection, promotion) => {
fields.insert("kind", Value::from("compact"));
fields.insert("rules", crate::recipe::codec::array(rules));
fields.insert("selection", selection.encode());
fields.insert("promotion", promotion.encode());
}
PrefixMode::Factor(factor) => {
fields.insert("kind", Value::from("factor"));
fields.insert("factor", factor.encode());
}
}
fields.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
if item.as_str() == Some("none") {
return Ok(Self::none());
}
let fields = table(item, &["kind", "selection", "promotion", "rules", "factor"])?;
match field::<String>(fields, "kind", None)?.as_str() {
"si" => {
grammar::record_fields(item, PREFIX_SI)?;
Self::si(
field(fields, "selection", None)?,
field(fields, "promotion", Some(NumericPromotion::KeepThreshold))?,
)
}
"compact" => {
grammar::record_fields(item, PREFIX_COMPACT)?;
Self::compact(
field(fields, "rules", None)?,
field(fields, "selection", None)?,
field(fields, "promotion", Some(NumericPromotion::KeepThreshold))?,
)
}
"factor" => {
grammar::record_fields(item, PREFIX_FACTOR)?;
Self::factor(field(fields, "factor", None)?)
}
_ => Err(invalid("unknown numeric prefix policy")),
}
}
}
const UNIT_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<String>("text"),
grammar::optional::<NumericUnitPlacement>("placement"),
grammar::optional::<String>("separator"),
];
impl Codec for NumericUnit {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::record(ctx, UNIT_FIELDS)
}
fn encode(&self) -> Value {
let mut fields = InlineTable::new();
fields.insert("text", Value::from(self.text()));
fields.insert("placement", self.placement().encode());
fields.insert("separator", Value::from(self.get_separator()));
fields.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
let fields = grammar::record_fields(item, UNIT_FIELDS)?;
let value = Self::new(
field::<String>(fields, "text", None)?,
field(fields, "placement", Some(NumericUnitPlacement::PerLabel))?,
)
.separator(field::<String>(fields, "separator", Some(" ".to_owned()))?);
value.validate()?;
Ok(value)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn native_numeric_declaration_round_trips_complete_normalized_policies() {
use crate::Text;
let locale = NumericLocale::named("fr-FR").unwrap();
let radix = NumericFormat::new(
NumericNotation::Integer(NumericRadix::HexUpper),
NumericPrecision::Fractional(0),
)
.unwrap()
.locale(locale.clone())
.unwrap()
.symbol(NumericSymbol::RadixPrefix)
.unwrap()
.field(Some(
NumericField::new(12, '·', NumericAlignment::AfterSign).unwrap(),
))
.unwrap()
.sign(NumericSign::Always)
.unwrap()
.negative_zero(NegativeZero::Normalize)
.unwrap()
.rounding(NumericRounding::NearestTowardZero)
.unwrap()
.prefix("[")
.unwrap()
.suffix("]")
.unwrap();
let common = NumericFormat::new(
NumericNotation::General,
NumericPrecision::AdaptiveSignificant { min: 2, max: 9 },
)
.unwrap()
.locale(locale)
.unwrap()
.grouping(true)
.unwrap()
.decimal_scale(-2)
.unwrap()
.multiplier(-0.125)
.unwrap()
.rate(NumericRate::PerMille)
.unwrap()
.trailing_zeros(TrailingZeros::Trim)
.unwrap()
.unit(Some(
NumericUnit::new("m", NumericUnitPlacement::Shared).separator(" "),
))
.unwrap()
.explanation(NumericExplanation::text(
Text::new("Adjusted scale").layout(
crate::text::TextLayout::default().alignment(crate::text::TextAlignment::End),
),
));
let policies = [
NumericPrefixes::none(),
NumericPrefixes::si(
NumericSelection::Fixed(SiPrefix::from_exponent(-6).unwrap()),
NumericPromotion::KeepThreshold,
)
.unwrap(),
NumericPrefixes::decimal_compact(
NumericSelection::WholeSet,
NumericPromotion::PromoteOnRounding,
)
.unwrap(),
NumericPrefixes::compact(
vec![NumericCompactRule::new(2., 3., "about ", " units").unwrap()],
NumericSelection::PerValue,
NumericPromotion::KeepThreshold,
)
.unwrap(),
NumericPrefixes::factor(NumericFactor::PowerOfTen("500".into())).unwrap(),
NumericPrefixes::factor(NumericFactor::AutomaticDecimal).unwrap(),
NumericPrefixes::factor(NumericFactor::Value(-2.)).unwrap(),
];
let mut formats = vec![NumericFormat::default(), radix];
formats.extend(
policies
.into_iter()
.map(|prefixes| common.clone().prefixes(prefixes).unwrap()),
);
for format in formats {
let encoded = format.recipe_value().unwrap();
assert_eq!(
NumericFormat::from_recipe_value(&Item::Value(encoded)).unwrap(),
format
);
}
}
}