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