Skip to main content

lichtung_plot/numeric/
prefixes.rs

1//! One normalized scale/prefix request for exact numeric operands.
2
3use std::sync::Arc;
4
5use super::locale::validate_token;
6use crate::{Error, Result};
7use num_bigint::BigInt;
8
9pub(crate) mod selection;
10#[cfg(test)]
11mod tests;
12
13/// Whether a scale is chosen separately, for the complete set, or explicitly.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum NumericSelection<T> {
16    /// Choose separately for each member.
17    PerValue,
18    /// Choose one common factor from the entire semantic set.
19    WholeSet,
20    /// Retain a caller-selected factor or rule.
21    Fixed(T),
22}
23
24/// Handling of a rounding carry into the next automatic prefix threshold.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum NumericPromotion {
27    /// Select only from the original unrounded magnitude.
28    KeepThreshold,
29    /// Resolve the final threshold from the original signed rounding cell.
30    PromoteOnRounding,
31}
32
33/// A standard SI prefix, including neutral, deci/centi/deca/hecto and 2022 additions.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct SiPrefix(i8);
36
37const SI: &[(i8, &str)] = &[
38    (-30, "q"),
39    (-27, "r"),
40    (-24, "y"),
41    (-21, "z"),
42    (-18, "a"),
43    (-15, "f"),
44    (-12, "p"),
45    (-9, "n"),
46    (-6, "ยต"),
47    (-3, "m"),
48    (-2, "c"),
49    (-1, "d"),
50    (0, ""),
51    (1, "da"),
52    (2, "h"),
53    (3, "k"),
54    (6, "M"),
55    (9, "G"),
56    (12, "T"),
57    (15, "P"),
58    (18, "E"),
59    (21, "Z"),
60    (24, "Y"),
61    (27, "R"),
62    (30, "Q"),
63];
64
65impl SiPrefix {
66    /// Validate a standard decimal exponent.
67    pub fn from_exponent(exponent: i8) -> Result<Self> {
68        if SI.iter().any(|(e, _)| *e == exponent) {
69            Ok(Self(exponent))
70        } else {
71            Err(Error::Data("unsupported SI prefix exponent".into()))
72        }
73    }
74    /// Exact decimal exponent.
75    pub const fn exponent(&self) -> i8 {
76        self.0
77    }
78    /// Standard symbol; micro is U+00B5.
79    pub fn symbol(&self) -> &str {
80        SI.iter()
81            .find(|(e, _)| *e == self.0)
82            .expect("validated SI prefix")
83            .1
84    }
85}
86
87/// An exact divisor or an automatic common decimal-power request.
88#[derive(Debug, Clone)]
89pub enum NumericFactor {
90    /// Use the decade of the greatest nonzero magnitude in the whole set.
91    AutomaticDecimal,
92    /// The exact represented nonzero finite divisor.
93    Value(f64),
94    /// A mathematical power with an arbitrary-size signed ASCII integral exponent.
95    PowerOfTen(String),
96}
97
98impl PartialEq for NumericFactor {
99    fn eq(&self, other: &Self) -> bool {
100        match (self, other) {
101            (Self::AutomaticDecimal, Self::AutomaticDecimal) => true,
102            (Self::Value(a), Self::Value(b)) => a.to_bits() == b.to_bits(),
103            (Self::PowerOfTen(a), Self::PowerOfTen(b)) => a == b,
104            _ => false,
105        }
106    }
107}
108impl Eq for NumericFactor {}
109
110impl NumericFactor {
111    pub(super) fn try_copy(&self) -> Result<Self> {
112        Ok(match self {
113            Self::AutomaticDecimal => Self::AutomaticDecimal,
114            Self::Value(value) => Self::Value(*value),
115            Self::PowerOfTen(value) => {
116                Self::PowerOfTen(crate::data::source::copy_source_string(value)?)
117            }
118        })
119    }
120
121    fn observe(&self, round: &mut crate::layout::kernel::FeedbackRound) -> Result<()> {
122        match self {
123            Self::AutomaticDecimal => round.observe_count(0),
124            Self::Value(value) => {
125                round.observe_count(1)?;
126                round.observe_number(*value)
127            }
128            Self::PowerOfTen(value) => {
129                round.observe_count(2)?;
130                round.observe_string(value)
131            }
132        }
133    }
134    fn normalize(self) -> Result<Self> {
135        match self {
136            Self::Value(value) if !value.is_finite() || value == 0.0 => Err(Error::Data(
137                "numeric divisor must be nonzero and finite".into(),
138            )),
139            Self::PowerOfTen(source) => {
140                let digits = source.strip_prefix(['+', '-']).unwrap_or(&source);
141                if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
142                    return Err(Error::Data(
143                        "decimal factor exponent must be a signed ASCII integer".into(),
144                    ));
145                }
146                let exponent = BigInt::parse_bytes(source.as_bytes(), 10)
147                    .ok_or_else(|| Error::Data("invalid decimal factor exponent".into()))?;
148                Ok(Self::PowerOfTen(exponent.to_string()))
149            }
150            _ => Ok(self),
151        }
152    }
153}
154
155/// An unrounded threshold, exact divisor and literal compact affixes.
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct NumericCompactRule(Arc<CompactRule>);
158
159#[derive(Debug, PartialEq, Eq)]
160struct CompactRule {
161    threshold: u64,
162    divisor: u64,
163    prefix: String,
164    suffix: String,
165}
166
167impl NumericCompactRule {
168    /// Construct a finite threshold, positive finite divisor and single-line affixes.
169    pub fn new(
170        threshold: f64,
171        divisor: f64,
172        prefix: impl Into<String>,
173        suffix: impl Into<String>,
174    ) -> Result<Self> {
175        if !threshold.is_finite() || !divisor.is_finite() || divisor <= 0.0 {
176            return Err(Error::Data(
177                "compact thresholds must be finite and divisors positive finite".into(),
178            ));
179        }
180        let (prefix, suffix) = (prefix.into(), suffix.into());
181        validate_token(&prefix, true)?;
182        validate_token(&suffix, true)?;
183        Ok(Self(Arc::new(CompactRule {
184            threshold: if threshold == 0.0 {
185                0
186            } else {
187                threshold.to_bits()
188            },
189            divisor: divisor.to_bits(),
190            prefix,
191            suffix,
192        })))
193    }
194    /// Unrounded magnitude threshold.
195    pub fn threshold(&self) -> f64 {
196        f64::from_bits(self.0.threshold)
197    }
198    /// Exact represented divisor.
199    pub fn divisor(&self) -> f64 {
200        f64::from_bits(self.0.divisor)
201    }
202    /// Literal prefix inside the format's outer prefix.
203    pub fn prefix(&self) -> &str {
204        &self.0.prefix
205    }
206    /// Literal suffix inside the format's outer suffix.
207    pub fn suffix(&self) -> &str {
208        &self.0.suffix
209    }
210}
211
212#[derive(Debug, Clone, PartialEq, Eq)]
213pub(super) enum PrefixMode {
214    None,
215    Si(NumericSelection<SiPrefix>, NumericPromotion),
216    Compact(
217        Arc<Vec<NumericCompactRule>>,
218        NumericSelection<usize>,
219        NumericPromotion,
220    ),
221    Factor(NumericFactor),
222}
223
224/// The sole selected SI, compact or exact factor policy.
225#[derive(Debug, Clone, PartialEq, Eq)]
226pub struct NumericPrefixes(pub(super) Arc<PrefixMode>);
227
228impl NumericPrefixes {
229    pub(super) fn observe(&self, round: &mut crate::layout::kernel::FeedbackRound) -> Result<()> {
230        match self.0.as_ref() {
231            PrefixMode::None => round.observe_count(0),
232            PrefixMode::Si(selection, promotion) => {
233                round.observe_count(1)?;
234                observe_selection(
235                    *selection,
236                    |prefix| usize::from(prefix.0.unsigned_abs()) * 2 + usize::from(prefix.0 < 0),
237                    round,
238                )?;
239                round.observe_count(*promotion as usize)
240            }
241            PrefixMode::Compact(rules, selection, promotion) => {
242                round.observe_count(2)?;
243                observe_selection(*selection, |index| index, round)?;
244                round.observe_count(*promotion as usize)?;
245                round.observe_count(rules.len())?;
246                for rule in rules.iter() {
247                    round.observe_number(rule.threshold())?;
248                    round.observe_number(rule.divisor())?;
249                    round.observe_string(rule.prefix())?;
250                    round.observe_string(rule.suffix())?;
251                }
252                Ok(())
253            }
254            PrefixMode::Factor(factor) => {
255                round.observe_count(3)?;
256                factor.observe(round)
257            }
258        }
259    }
260    /// No scale selection.
261    pub fn none() -> Self {
262        Self(Arc::new(PrefixMode::None))
263    }
264    /// Standard SI selection, saturating automatic engineering prefixes at -30/30.
265    pub fn si(selection: NumericSelection<SiPrefix>, promotion: NumericPromotion) -> Result<Self> {
266        fixed_promotion(matches!(selection, NumericSelection::Fixed(_)), promotion)?;
267        Ok(Self(Arc::new(PrefixMode::Si(selection, promotion))))
268    }
269    /// The scales 1.4.0 short-scale K/M/B/T rules, normalized to custom rules.
270    pub fn decimal_compact(
271        selection: NumericSelection<usize>,
272        promotion: NumericPromotion,
273    ) -> Result<Self> {
274        let rules = crate::data::source::collect_source(
275            [(1e3, "K"), (1e6, "M"), (1e9, "B"), (1e12, "T")]
276                .into_iter()
277                .map(|(threshold, suffix)| {
278                    NumericCompactRule::new(threshold, threshold, "", suffix)
279                }),
280        )?;
281        Self::compact(rules, selection, promotion)
282    }
283    /// Strictly increasing thresholds with one explicit selection/promotion policy.
284    pub fn compact(
285        rules: Vec<NumericCompactRule>,
286        selection: NumericSelection<usize>,
287        promotion: NumericPromotion,
288    ) -> Result<Self> {
289        fixed_promotion(matches!(selection, NumericSelection::Fixed(_)), promotion)?;
290        if rules
291            .windows(2)
292            .any(|pair| pair[0].threshold() >= pair[1].threshold())
293        {
294            return Err(Error::Data(
295                "compact thresholds must be strictly increasing".into(),
296            ));
297        }
298        if let NumericSelection::Fixed(index) = selection {
299            if index >= rules.len() {
300                return Err(Error::Data(
301                    "fixed compact rule index is out of range".into(),
302                ));
303            }
304        }
305        if rules.is_empty() {
306            Ok(Self::none())
307        } else {
308            Ok(Self(Arc::new(PrefixMode::Compact(
309                Arc::new(rules),
310                selection,
311                promotion,
312            ))))
313        }
314    }
315    /// Choose one exact or automatic common divisor, replacing SI/compact selection.
316    pub fn factor(value: NumericFactor) -> Result<Self> {
317        Ok(Self(Arc::new(PrefixMode::Factor(value.normalize()?))))
318    }
319}
320
321fn observe_selection<T>(
322    selection: NumericSelection<T>,
323    index: impl FnOnce(T) -> usize,
324    round: &mut crate::layout::kernel::FeedbackRound,
325) -> Result<()> {
326    match selection {
327        NumericSelection::PerValue => round.observe_count(0),
328        NumericSelection::WholeSet => round.observe_count(1),
329        NumericSelection::Fixed(value) => {
330            round.observe_count(2)?;
331            round.observe_count(index(value))
332        }
333    }
334}
335
336fn fixed_promotion(fixed: bool, promotion: NumericPromotion) -> Result<()> {
337    if fixed && promotion != NumericPromotion::KeepThreshold {
338        Err(Error::Data(
339            "fixed prefix selection requires KeepThreshold".into(),
340        ))
341    } else {
342        Ok(())
343    }
344}