Skip to main content

lichtung_plot/numeric/
format.rs

1//! The sole owned normalized scientific presentation policy. Exact resolved
2//! views borrow its affixes; adaptive precision is selected by a semantic set.
3
4use 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/// Exact precision or one uniformly selected precision for a complete numeric set.
16/// Construction through [`NumericFormat`] validates all bounds.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum NumericPrecision {
19    /// Exactly this many fractional digits, from zero through twenty.
20    Fractional(u8),
21    /// Exactly this many significant digits, from one through twenty-one.
22    Significant(u8),
23    /// The smallest common fractional precision distinguishing the complete set.
24    AdaptiveFractional {
25        /// Inclusive lower bound, from zero through twenty.
26        min: u8,
27        /// Inclusive upper bound, at least `min` and at most twenty.
28        max: u8,
29    },
30    /// The smallest common significant precision distinguishing the complete set.
31    AdaptiveSignificant {
32        /// Inclusive lower bound, from one through twenty-one.
33        min: u8,
34        /// Inclusive upper bound, at least `min` and at most twenty-one.
35        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/// Immutable scientific numeric presentation with explicitly selected locale.
79///
80/// Rounding defaults to nearest with ties to even, after exact decimal scaling.
81/// Affixes are literal: a percent suffix alone does not scale the scientific value.
82/// Adaptive precision is selected uniformly for each complete semantic set,
83/// independently of geometric fit. The default is Decimal/Fractional(2), scale
84/// zero, absent affixes, preserved negative zero and retained trailing zeros.
85///
86/// ```
87/// use lichtung_plot::{NumericFormat, NumericValues, Plot, formatting::{NumericNotation, NumericPrecision}};
88/// let percent = NumericFormat::new(NumericNotation::Decimal, NumericPrecision::Fractional(1))?
89///     .decimal_scale(2)?
90///     .suffix("%")?;
91/// assert_eq!(percent.get_decimal_scale(), 2);
92/// let plot = Plot::scatter(NumericValues::new("x", [1.0, 2.0]),
93///                          NumericValues::new("rate", [0.125, 0.875]))
94///     .y_tick_format(percent);
95/// # let _ = plot;
96/// # Ok::<(), lichtung_plot::Error>(())
97/// ```
98///
99/// Fields and the implementation module stay private:
100/// ```compile_fail
101/// use lichtung_plot::NumericFormat;
102/// let _ = NumericFormat::default().decimal_scale;
103/// ```
104/// ```compile_fail
105/// use lichtung_plot::numeric::format::NumericFormat;
106/// ```
107/// Precision edits take an explicit precision policy:
108/// ```compile_fail
109/// use lichtung_plot::NumericFormat;
110/// let _ = NumericFormat::default().precision(2);
111/// ```
112#[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    /// Construct a validated format with scale zero, no affixes, Preserve, Keep
180    /// and NearestEven rounding.
181    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    /// The selected decimal/exponent notation.
192    pub const fn get_notation(&self) -> NumericNotation {
193        self.notation
194    }
195    /// The exact precision or complete adaptive bounds.
196    pub const fn get_precision(&self) -> NumericPrecision {
197        self.precision
198    }
199    /// The exact signed decimal display shift, from -324 through 324.
200    pub const fn get_decimal_scale(&self) -> i16 {
201        self.decimal_scale
202    }
203    /// Literal text before the sign and number, or absence.
204    pub fn get_prefix(&self) -> Option<&str> {
205        self.prefix.as_deref()
206    }
207    /// Literal text immediately after the number, or absence.
208    pub fn get_suffix(&self) -> Option<&str> {
209        self.suffix.as_deref()
210    }
211    /// Actual and rounded negative-zero handling.
212    pub const fn get_negative_zero(&self) -> NegativeZero {
213        self.negative_zero
214    }
215    /// Fractional trailing-zero handling.
216    pub const fn get_trailing_zeros(&self) -> TrailingZeros {
217        self.trailing_zeros
218    }
219
220    /// Replace notation while retaining and validating every other field.
221    pub fn notation(mut self, value: NumericNotation) -> Result<Self> {
222        self.notation = value;
223        self.validate()?;
224        Ok(self)
225    }
226
227    /// Replace precision; fractional bounds are 0..=20 and significant bounds 1..=21.
228    /// Adaptive `min` must not exceed `max`.
229    pub fn precision(mut self, value: NumericPrecision) -> Result<Self> {
230        self.precision = value;
231        self.validate()?;
232        Ok(self)
233    }
234
235    /// Replace the exact decimal display shift within -324..=324.
236    /// This never changes scientific coordinates or color mapping.
237    pub fn decimal_scale(mut self, value: i16) -> Result<Self> {
238        self.decimal_scale = value;
239        self.validate()?;
240        Ok(self)
241    }
242
243    /// Replace the literal prefix with nonempty, control-free text.
244    /// Spaces and combining marks are preserved exactly.
245    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    /// Replace the literal suffix with nonempty, control-free text.
252    /// No scaling or spacing is inferred from its contents.
253    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    /// Replace handling of actual or rounded negative zero.
260    pub fn negative_zero(mut self, value: NegativeZero) -> Result<Self> {
261        self.negative_zero = value;
262        self.validate()?;
263        Ok(self)
264    }
265
266    /// Replace fractional zero trimming; integral place-value zeros are retained.
267    pub fn trailing_zeros(mut self, value: TrailingZeros) -> Result<Self> {
268        self.trailing_zeros = value;
269        self.validate()?;
270        Ok(self)
271    }
272
273    /// Replace exact rounding at the selected decimal quantum.
274    /// Signed floor/ceiling and tie handling apply before negative-zero normalization.
275    pub fn rounding(mut self, value: NumericRounding) -> Result<Self> {
276        self.rounding = value;
277        self.validate()?;
278        Ok(self)
279    }
280
281    /// Multiply by the exact represented finite factor before the one rounding.
282    /// Negative factors reverse display signs; either signed zero selects zero.
283    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    /// Select complete explicit locale tokens, without host inference.
290    pub fn locale(mut self, value: NumericLocale) -> Result<Self> {
291        self.presentation.locale = value;
292        self.validate()?;
293        Ok(self)
294    }
295    /// Enable integer grouping using the selected locale's optional pattern.
296    pub fn grouping(mut self, value: bool) -> Result<Self> {
297        self.presentation.grouping = value;
298        self.validate()?;
299        Ok(self)
300    }
301    /// Select sign presentation, after numeric rounding and zero normalization.
302    pub fn sign(mut self, value: NumericSign) -> Result<Self> {
303        self.presentation.sign = value;
304        self.validate()?;
305        Ok(self)
306    }
307    /// Select currency or an applicable nondecimal integer-radix prefix.
308    pub fn symbol(mut self, value: NumericSymbol) -> Result<Self> {
309        self.presentation.symbol = value;
310        self.validate()?;
311        Ok(self)
312    }
313    /// Set or clear minimum Unicode-scalar field width.
314    pub fn field(mut self, value: Option<NumericField>) -> Result<Self> {
315        self.presentation.field = value;
316        self.validate()?;
317        Ok(self)
318    }
319    /// Select an exact rate factor and the locale's automatic suffix.
320    pub fn rate(mut self, value: NumericRate) -> Result<Self> {
321        self.rate = value;
322        self.validate()?;
323        Ok(self)
324    }
325
326    /// Replace the sole SI, compact or common exact-divisor policy.
327    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}