1use super::decimal::{
5 NegativeZero, NumericNotation, NumericRounding, ResolvedFormat, ResolvedPrecision,
6 TrailingZeros, MAX_FRACTIONAL_DIGITS, MAX_SIGNIFICANT_DIGITS,
7};
8use super::emission::{NumericField, NumericRate, NumericSign, NumericSymbol, Presentation};
9use super::locale::NumericLocale;
10use super::prefixes::{selection::SelectedScale, NumericPrefixes};
11use crate::{Error, Result};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum NumericPrecision {
17 Fractional(u8),
19 Significant(u8),
21 AdaptiveFractional {
23 min: u8,
25 max: u8,
27 },
28 AdaptiveSignificant {
30 min: u8,
32 max: u8,
34 },
35}
36
37impl NumericPrecision {
38 pub(crate) fn bounds(self) -> Result<(u8, u8)> {
39 let (min, max, significant) = match self {
40 Self::Fractional(digits) => (digits, digits, false),
41 Self::Significant(digits) => (digits, digits, true),
42 Self::AdaptiveFractional { min, max } => (min, max, false),
43 Self::AdaptiveSignificant { min, max } => (min, max, true),
44 };
45 let limit = if significant {
46 MAX_SIGNIFICANT_DIGITS
47 } else {
48 MAX_FRACTIONAL_DIGITS
49 };
50 if min > max || max > limit || (significant && min == 0) {
51 return Err(Error::Data(
52 "numeric presentation precision bounds are invalid".into(),
53 ));
54 }
55 Ok((min, max))
56 }
57
58 fn resolved(self, digits: u8) -> Result<ResolvedPrecision> {
59 let (min, max) = self.bounds()?;
60 if !(min..=max).contains(&digits) {
61 return Err(Error::Data(
62 "numeric presentation selected precision is outside its bounds".into(),
63 ));
64 }
65 Ok(match self {
66 Self::Fractional(_) | Self::AdaptiveFractional { .. } => {
67 ResolvedPrecision::Fractional(digits)
68 }
69 Self::Significant(_) | Self::AdaptiveSignificant { .. } => {
70 ResolvedPrecision::Significant(digits)
71 }
72 })
73 }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct NumericFormat {
112 notation: NumericNotation,
113 precision: NumericPrecision,
114 decimal_scale: i16,
115 prefix: Option<String>,
116 suffix: Option<String>,
117 negative_zero: NegativeZero,
118 trailing_zeros: TrailingZeros,
119 rounding: NumericRounding,
120 multiplier_bits: u64,
121 rate: NumericRate,
122 presentation: Presentation,
123 prefixes: NumericPrefixes,
124 pub(super) units: std::sync::Arc<super::unit::UnitPolicy>,
125 pub(super) emitter: super::function::Emitter,
126}
127
128impl Default for NumericFormat {
129 fn default() -> Self {
130 Self {
131 notation: NumericNotation::Decimal,
132 precision: NumericPrecision::Fractional(2),
133 decimal_scale: 0,
134 prefix: None,
135 suffix: None,
136 negative_zero: NegativeZero::Preserve,
137 trailing_zeros: TrailingZeros::Keep,
138 rounding: NumericRounding::NearestEven,
139 multiplier_bits: 1.0_f64.to_bits(),
140 rate: NumericRate::Value,
141 presentation: Presentation::default(),
142 prefixes: NumericPrefixes::none(),
143 units: std::sync::Arc::new(super::unit::UnitPolicy::default()),
144 emitter: super::function::Emitter::default(),
145 }
146 }
147}
148
149impl NumericFormat {
150 pub(crate) fn try_copy(&self) -> Result<Self> {
151 Ok(Self {
152 notation: self.notation,
153 precision: self.precision,
154 decimal_scale: self.decimal_scale,
155 prefix: self
156 .prefix
157 .as_deref()
158 .map(crate::data::source::copy_source_string)
159 .transpose()?,
160 suffix: self
161 .suffix
162 .as_deref()
163 .map(crate::data::source::copy_source_string)
164 .transpose()?,
165 negative_zero: self.negative_zero,
166 trailing_zeros: self.trailing_zeros,
167 rounding: self.rounding,
168 multiplier_bits: self.multiplier_bits,
169 rate: self.rate,
170 presentation: self.presentation.clone(),
171 prefixes: self.prefixes.clone(),
172 units: self.units.clone(),
173 emitter: self.emitter.clone(),
174 })
175 }
176
177 pub fn new(notation: NumericNotation, precision: NumericPrecision) -> Result<Self> {
180 let value = Self {
181 notation,
182 precision,
183 ..Self::default()
184 };
185 value.validate()?;
186 Ok(value)
187 }
188
189 pub const fn get_notation(&self) -> NumericNotation {
191 self.notation
192 }
193 pub const fn get_precision(&self) -> NumericPrecision {
195 self.precision
196 }
197 pub const fn get_decimal_scale(&self) -> i16 {
199 self.decimal_scale
200 }
201 pub fn get_prefix(&self) -> Option<&str> {
203 self.prefix.as_deref()
204 }
205 pub fn get_suffix(&self) -> Option<&str> {
207 self.suffix.as_deref()
208 }
209 pub const fn get_negative_zero(&self) -> NegativeZero {
211 self.negative_zero
212 }
213 pub const fn get_trailing_zeros(&self) -> TrailingZeros {
215 self.trailing_zeros
216 }
217
218 pub fn notation(mut self, value: NumericNotation) -> Result<Self> {
220 self.notation = value;
221 self.validate()?;
222 Ok(self)
223 }
224
225 pub fn precision(mut self, value: NumericPrecision) -> Result<Self> {
228 self.precision = value;
229 self.validate()?;
230 Ok(self)
231 }
232
233 pub fn decimal_scale(mut self, value: i16) -> Result<Self> {
236 self.decimal_scale = value;
237 self.validate()?;
238 Ok(self)
239 }
240
241 pub fn prefix(mut self, value: impl Into<String>) -> Result<Self> {
244 self.prefix = Some(value.into());
245 self.validate()?;
246 Ok(self)
247 }
248
249 pub fn suffix(mut self, value: impl Into<String>) -> Result<Self> {
252 self.suffix = Some(value.into());
253 self.validate()?;
254 Ok(self)
255 }
256
257 pub fn negative_zero(mut self, value: NegativeZero) -> Result<Self> {
259 self.negative_zero = value;
260 self.validate()?;
261 Ok(self)
262 }
263
264 pub fn trailing_zeros(mut self, value: TrailingZeros) -> Result<Self> {
266 self.trailing_zeros = value;
267 self.validate()?;
268 Ok(self)
269 }
270
271 pub fn rounding(mut self, value: NumericRounding) -> Result<Self> {
274 self.rounding = value;
275 self.validate()?;
276 Ok(self)
277 }
278
279 pub fn multiplier(mut self, value: f64) -> Result<Self> {
282 self.multiplier_bits = if value == 0.0 { 0 } else { value.to_bits() };
283 self.validate()?;
284 Ok(self)
285 }
286
287 pub fn locale(mut self, value: NumericLocale) -> Result<Self> {
289 self.presentation.locale = value;
290 self.validate()?;
291 Ok(self)
292 }
293 pub fn grouping(mut self, value: bool) -> Result<Self> {
295 self.presentation.grouping = value;
296 self.validate()?;
297 Ok(self)
298 }
299 pub fn sign(mut self, value: NumericSign) -> Result<Self> {
301 self.presentation.sign = value;
302 self.validate()?;
303 Ok(self)
304 }
305 pub fn symbol(mut self, value: NumericSymbol) -> Result<Self> {
307 self.presentation.symbol = value;
308 self.validate()?;
309 Ok(self)
310 }
311 pub fn field(mut self, value: Option<NumericField>) -> Result<Self> {
313 self.presentation.field = value;
314 self.validate()?;
315 Ok(self)
316 }
317 pub fn rate(mut self, value: NumericRate) -> Result<Self> {
319 self.rate = value;
320 self.validate()?;
321 Ok(self)
322 }
323
324 pub fn prefixes(mut self, value: NumericPrefixes) -> Result<Self> {
326 self.prefixes = value;
327 self.validate()?;
328 Ok(self)
329 }
330
331 pub(crate) fn prefix_policy(&self) -> &NumericPrefixes {
332 &self.prefixes
333 }
334
335 pub(super) fn locale_ref(&self) -> &NumericLocale {
336 &self.presentation.locale
337 }
338 pub(super) fn factor_inputs(&self) -> (f64, i16, NumericRate) {
339 (
340 f64::from_bits(self.multiplier_bits),
341 self.decimal_scale,
342 self.rate,
343 )
344 }
345
346 pub(super) fn present(&self, ascii: &str, scale: &SelectedScale) -> Result<String> {
347 self.presentation.emit(
348 ascii,
349 self.notation,
350 self.rate,
351 super::emission::Affixes {
352 outer_prefix: self.prefix.as_deref().unwrap_or_default(),
353 outer_suffix: self.suffix.as_deref().unwrap_or_default(),
354 prefix: &scale.prefix,
355 suffix: &scale.suffix,
356 },
357 )
358 }
359
360 pub(super) fn validate(&self) -> Result<()> {
361 if let Some(unit) = &self.units.unit {
362 unit.validate()?;
363 }
364 if self.presentation.symbol == NumericSymbol::RadixPrefix
365 && !matches!(self.notation, NumericNotation::Integer(radix) if radix != super::decimal::NumericRadix::Decimal)
366 {
367 return Err(Error::Data(
368 "radix prefix requires nondecimal integer notation".into(),
369 ));
370 }
371 let (min, _) = self.precision.bounds()?;
372 self.resolve_at(min)?.validate()
373 }
374
375 pub(crate) fn resolve_at(&self, digits: u8) -> Result<ResolvedFormat<'_>> {
376 Ok(ResolvedFormat {
377 notation: self.notation,
378 precision: self.precision.resolved(digits)?,
379 decimal_scale: self.decimal_scale,
380 prefix: self.prefix.as_deref(),
381 suffix: self.suffix.as_deref(),
382 negative_zero: self.negative_zero,
383 trailing_zeros: self.trailing_zeros,
384 rounding: self.rounding,
385 multiplier: f64::from_bits(self.multiplier_bits),
386 rate: self.rate,
387 divisor: None,
388 })
389 }
390
391 pub(crate) fn observe_feedback(
392 &self,
393 round: &mut crate::layout::kernel::FeedbackRound,
394 ) -> Result<()> {
395 let (notation, radix) = match self.notation {
396 NumericNotation::Decimal => (0, 0),
397 NumericNotation::Scientific => (1, 0),
398 NumericNotation::Engineering => (2, 0),
399 NumericNotation::General => (3, 0),
400 NumericNotation::Integer(radix) => (4, radix as usize),
401 };
402 round.observe_count(notation)?;
403 round.observe_count(radix)?;
404 let (min, max) = self.precision.bounds()?;
405 round.observe_count(match self.precision {
406 NumericPrecision::Fractional(_) => 0,
407 NumericPrecision::Significant(_) => 1,
408 NumericPrecision::AdaptiveFractional { .. } => 2,
409 NumericPrecision::AdaptiveSignificant { .. } => 3,
410 })?;
411 round.observe_count(usize::from(min))?;
412 round.observe_count(usize::from(max))?;
413 round.observe_number(f64::from(self.decimal_scale))?;
414 round.observe_number(f64::from_bits(self.multiplier_bits))?;
415 round.observe_count(self.rate as usize)?;
416 self.presentation.observe(round)?;
417 self.prefixes.observe(round)?;
418 self.units.observe(round)?;
419 round.observe_numeric_emitter(&self.emitter)?;
420 for affix in [self.get_prefix(), self.get_suffix()] {
421 round.observe_count(usize::from(affix.is_some()))?;
422 if let Some(text) = affix {
423 round.observe_string(text)?;
424 }
425 }
426 round.observe_count(self.negative_zero as usize)?;
427 round.observe_count(self.trailing_zeros as usize)?;
428 round.observe_count(self.rounding as usize)
429 }
430}