use super::decimal::{
NegativeZero, NumericNotation, NumericRounding, ResolvedFormat, ResolvedPrecision,
TrailingZeros, MAX_FRACTIONAL_DIGITS, MAX_SIGNIFICANT_DIGITS,
};
use super::emission::{NumericField, NumericRate, NumericSign, NumericSymbol, Presentation};
use super::locale::NumericLocale;
use super::prefixes::{selection::SelectedScale, NumericPrefixes};
use crate::{Error, Result};
mod recipe;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumericPrecision {
Fractional(u8),
Significant(u8),
AdaptiveFractional {
min: u8,
max: u8,
},
AdaptiveSignificant {
min: u8,
max: u8,
},
}
impl NumericPrecision {
pub(crate) fn bounds(self) -> Result<(u8, u8)> {
let (min, max, significant) = match self {
Self::Fractional(digits) => (digits, digits, false),
Self::Significant(digits) => (digits, digits, true),
Self::AdaptiveFractional { min, max } => (min, max, false),
Self::AdaptiveSignificant { min, max } => (min, max, true),
};
let limit = if significant {
MAX_SIGNIFICANT_DIGITS
} else {
MAX_FRACTIONAL_DIGITS
};
if min > max || max > limit || (significant && min == 0) {
return Err(Error::Data(
"numeric presentation precision bounds are invalid".into(),
));
}
Ok((min, max))
}
fn resolved(self, digits: u8) -> Result<ResolvedPrecision> {
let (min, max) = self.bounds()?;
if !(min..=max).contains(&digits) {
return Err(Error::Data(
"numeric presentation selected precision is outside its bounds".into(),
));
}
Ok(match self {
Self::Fractional(_) | Self::AdaptiveFractional { .. } => {
ResolvedPrecision::Fractional(digits)
}
Self::Significant(_) | Self::AdaptiveSignificant { .. } => {
ResolvedPrecision::Significant(digits)
}
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NumericFormat {
notation: NumericNotation,
precision: NumericPrecision,
decimal_scale: i16,
prefix: Option<String>,
suffix: Option<String>,
negative_zero: NegativeZero,
trailing_zeros: TrailingZeros,
rounding: NumericRounding,
multiplier_bits: u64,
rate: NumericRate,
presentation: Presentation,
prefixes: NumericPrefixes,
pub(super) units: std::sync::Arc<super::unit::UnitPolicy>,
pub(super) emitter: super::function::Emitter,
}
impl Default for NumericFormat {
fn default() -> Self {
Self {
notation: NumericNotation::Decimal,
precision: NumericPrecision::Fractional(2),
decimal_scale: 0,
prefix: None,
suffix: None,
negative_zero: NegativeZero::Preserve,
trailing_zeros: TrailingZeros::Keep,
rounding: NumericRounding::NearestEven,
multiplier_bits: 1.0_f64.to_bits(),
rate: NumericRate::Value,
presentation: Presentation::default(),
prefixes: NumericPrefixes::none(),
units: std::sync::Arc::new(super::unit::UnitPolicy::default()),
emitter: super::function::Emitter::default(),
}
}
}
impl NumericFormat {
pub(crate) fn try_copy(&self) -> Result<Self> {
Ok(Self {
notation: self.notation,
precision: self.precision,
decimal_scale: self.decimal_scale,
prefix: self
.prefix
.as_deref()
.map(crate::data::source::copy_source_string)
.transpose()?,
suffix: self
.suffix
.as_deref()
.map(crate::data::source::copy_source_string)
.transpose()?,
negative_zero: self.negative_zero,
trailing_zeros: self.trailing_zeros,
rounding: self.rounding,
multiplier_bits: self.multiplier_bits,
rate: self.rate,
presentation: self.presentation.clone(),
prefixes: self.prefixes.clone(),
units: self.units.clone(),
emitter: self.emitter.clone(),
})
}
pub fn new(notation: NumericNotation, precision: NumericPrecision) -> Result<Self> {
let value = Self {
notation,
precision,
..Self::default()
};
value.validate()?;
Ok(value)
}
pub const fn get_notation(&self) -> NumericNotation {
self.notation
}
pub const fn get_precision(&self) -> NumericPrecision {
self.precision
}
pub const fn get_decimal_scale(&self) -> i16 {
self.decimal_scale
}
pub fn get_prefix(&self) -> Option<&str> {
self.prefix.as_deref()
}
pub fn get_suffix(&self) -> Option<&str> {
self.suffix.as_deref()
}
pub const fn get_negative_zero(&self) -> NegativeZero {
self.negative_zero
}
pub const fn get_trailing_zeros(&self) -> TrailingZeros {
self.trailing_zeros
}
pub fn notation(mut self, value: NumericNotation) -> Result<Self> {
self.notation = value;
self.validate()?;
Ok(self)
}
pub fn precision(mut self, value: NumericPrecision) -> Result<Self> {
self.precision = value;
self.validate()?;
Ok(self)
}
pub fn decimal_scale(mut self, value: i16) -> Result<Self> {
self.decimal_scale = value;
self.validate()?;
Ok(self)
}
pub fn prefix(mut self, value: impl Into<String>) -> Result<Self> {
self.prefix = Some(value.into());
self.validate()?;
Ok(self)
}
pub fn suffix(mut self, value: impl Into<String>) -> Result<Self> {
self.suffix = Some(value.into());
self.validate()?;
Ok(self)
}
pub fn negative_zero(mut self, value: NegativeZero) -> Result<Self> {
self.negative_zero = value;
self.validate()?;
Ok(self)
}
pub fn trailing_zeros(mut self, value: TrailingZeros) -> Result<Self> {
self.trailing_zeros = value;
self.validate()?;
Ok(self)
}
pub fn rounding(mut self, value: NumericRounding) -> Result<Self> {
self.rounding = value;
self.validate()?;
Ok(self)
}
pub fn multiplier(mut self, value: f64) -> Result<Self> {
self.multiplier_bits = if value == 0.0 { 0 } else { value.to_bits() };
self.validate()?;
Ok(self)
}
pub fn locale(mut self, value: NumericLocale) -> Result<Self> {
self.presentation.locale = value;
self.validate()?;
Ok(self)
}
pub fn grouping(mut self, value: bool) -> Result<Self> {
self.presentation.grouping = value;
self.validate()?;
Ok(self)
}
pub fn sign(mut self, value: NumericSign) -> Result<Self> {
self.presentation.sign = value;
self.validate()?;
Ok(self)
}
pub fn symbol(mut self, value: NumericSymbol) -> Result<Self> {
self.presentation.symbol = value;
self.validate()?;
Ok(self)
}
pub fn field(mut self, value: Option<NumericField>) -> Result<Self> {
self.presentation.field = value;
self.validate()?;
Ok(self)
}
pub fn rate(mut self, value: NumericRate) -> Result<Self> {
self.rate = value;
self.validate()?;
Ok(self)
}
pub fn prefixes(mut self, value: NumericPrefixes) -> Result<Self> {
self.prefixes = value;
self.validate()?;
Ok(self)
}
pub(crate) fn prefix_policy(&self) -> &NumericPrefixes {
&self.prefixes
}
pub(super) fn locale_ref(&self) -> &NumericLocale {
&self.presentation.locale
}
pub(super) fn factor_inputs(&self) -> (f64, i16, NumericRate) {
(
f64::from_bits(self.multiplier_bits),
self.decimal_scale,
self.rate,
)
}
pub(super) fn present(&self, ascii: &str, scale: &SelectedScale) -> Result<String> {
self.presentation.emit(
ascii,
self.notation,
self.rate,
super::emission::Affixes {
outer_prefix: self.prefix.as_deref().unwrap_or_default(),
outer_suffix: self.suffix.as_deref().unwrap_or_default(),
prefix: &scale.prefix,
suffix: &scale.suffix,
},
)
}
pub(super) fn validate(&self) -> Result<()> {
if let Some(unit) = &self.units.unit {
unit.validate()?;
}
if self.presentation.symbol == NumericSymbol::RadixPrefix
&& !matches!(self.notation, NumericNotation::Integer(radix) if radix != super::decimal::NumericRadix::Decimal)
{
return Err(Error::Data(
"radix prefix requires nondecimal integer notation".into(),
));
}
let (min, _) = self.precision.bounds()?;
self.resolve_at(min)?.validate()
}
pub(crate) fn resolve_at(&self, digits: u8) -> Result<ResolvedFormat<'_>> {
Ok(ResolvedFormat {
notation: self.notation,
precision: self.precision.resolved(digits)?,
decimal_scale: self.decimal_scale,
prefix: self.prefix.as_deref(),
suffix: self.suffix.as_deref(),
negative_zero: self.negative_zero,
trailing_zeros: self.trailing_zeros,
rounding: self.rounding,
multiplier: f64::from_bits(self.multiplier_bits),
rate: self.rate,
divisor: None,
})
}
pub(crate) fn observe_feedback(
&self,
round: &mut crate::layout::kernel::FeedbackRound,
) -> Result<()> {
let (notation, radix) = match self.notation {
NumericNotation::Decimal => (0, 0),
NumericNotation::Scientific => (1, 0),
NumericNotation::Engineering => (2, 0),
NumericNotation::General => (3, 0),
NumericNotation::Integer(radix) => (4, radix as usize),
};
round.observe_count(notation)?;
round.observe_count(radix)?;
let (min, max) = self.precision.bounds()?;
round.observe_count(match self.precision {
NumericPrecision::Fractional(_) => 0,
NumericPrecision::Significant(_) => 1,
NumericPrecision::AdaptiveFractional { .. } => 2,
NumericPrecision::AdaptiveSignificant { .. } => 3,
})?;
round.observe_count(usize::from(min))?;
round.observe_count(usize::from(max))?;
round.observe_number(f64::from(self.decimal_scale))?;
round.observe_number(f64::from_bits(self.multiplier_bits))?;
round.observe_count(self.rate as usize)?;
self.presentation.observe(round)?;
self.prefixes.observe(round)?;
self.units.observe(round)?;
round.observe_numeric_emitter(&self.emitter)?;
for affix in [self.get_prefix(), self.get_suffix()] {
round.observe_count(usize::from(affix.is_some()))?;
if let Some(text) = affix {
round.observe_string(text)?;
}
}
round.observe_count(self.negative_zero as usize)?;
round.observe_count(self.trailing_zeros as usize)?;
round.observe_count(self.rounding as usize)
}
}