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