Skip to main content

lichtung_plot/numeric/
specifier.rs

1//! D3 numeric syntax compiled into the sole normalized typed policy.
2
3use super::decimal::{NumericNotation, NumericRadix, TrailingZeros};
4use super::emission::{NumericAlignment, NumericField, NumericRate, NumericSign, NumericSymbol};
5use super::format::{NumericFormat, NumericPrecision};
6use super::prefixes::{NumericPrefixes, NumericPromotion, NumericSelection};
7use crate::{Error, Result};
8
9impl NumericFormat {
10    /// Compile `[[fill]align][sign][symbol][0][width][,][.precision][~][type]`.
11    /// Numeric types are f/e/g/r/s/%/p/d/b/o/x/X/n or omitted; unknown types and
12    /// text coercion reject. Exact renderer rounding is not JavaScript arithmetic.
13    pub fn from_specifier(specifier: &str) -> Result<Self> {
14        parse(specifier)
15    }
16}
17
18fn alignment(value: char) -> Option<NumericAlignment> {
19    match value {
20        '<' => Some(NumericAlignment::Left),
21        '>' => Some(NumericAlignment::Right),
22        '^' => Some(NumericAlignment::Center),
23        '=' => Some(NumericAlignment::AfterSign),
24        _ => None,
25    }
26}
27
28fn take(source: &mut &str) -> Option<char> {
29    let value = source.chars().next()?;
30    *source = &source[value.len_utf8()..];
31    Some(value)
32}
33
34fn digits<'a>(source: &mut &'a str) -> &'a str {
35    let count = source.bytes().take_while(u8::is_ascii_digit).count();
36    let (number, rest) = source.split_at(count);
37    *source = rest;
38    number
39}
40
41fn flag(source: &mut &str, value: char) -> bool {
42    if source.starts_with(value) {
43        take(source);
44        true
45    } else {
46        false
47    }
48}
49
50#[expect(
51    clippy::too_many_lines,
52    reason = "the pinned grammar and its explicit irrelevant-field normalizations compile once into typed edits"
53)]
54fn parse(mut source: &str) -> Result<NumericFormat> {
55    let (mut fill, mut align) = (' ', NumericAlignment::Right);
56    if let Some(value) = source.chars().nth(1).and_then(alignment) {
57        fill = take(&mut source).expect("fill before alignment");
58        take(&mut source);
59        align = value;
60    } else if let Some(value) = source.chars().next().and_then(alignment) {
61        take(&mut source);
62        align = value;
63    }
64    let sign = match source.chars().next() {
65        Some('-') => Some(NumericSign::NegativeOnly),
66        Some('+') => Some(NumericSign::Always),
67        Some(' ') => Some(NumericSign::Space),
68        Some('(') => Some(NumericSign::Accounting),
69        _ => None,
70    };
71    if sign.is_some() {
72        take(&mut source);
73    }
74    let symbol = match source.chars().next() {
75        Some('$') => Some(NumericSymbol::Currency),
76        Some('#') => Some(NumericSymbol::RadixPrefix),
77        _ => None,
78    };
79    if symbol.is_some() {
80        take(&mut source);
81    }
82    if flag(&mut source, '0') || (fill == '0' && align == NumericAlignment::AfterSign) {
83        fill = '0';
84        align = NumericAlignment::AfterSign;
85    }
86    let width = digits(&mut source);
87    let width = if width.is_empty() {
88        None
89    } else {
90        Some(width.parse::<usize>().map_err(|_| invalid())?)
91    };
92    let grouping = flag(&mut source, ',');
93    let precision = if flag(&mut source, '.') {
94        let precision = digits(&mut source);
95        if precision.is_empty() {
96            return Err(invalid());
97        }
98        Some(precision)
99    } else {
100        None
101    };
102    let trim = flag(&mut source, '~');
103    let kind = take(&mut source);
104    if !source.is_empty() {
105        return Err(invalid());
106    }
107    let notation = match kind {
108        Some('f' | 'r' | 's' | '%' | 'p') => NumericNotation::Decimal,
109        Some('e') => NumericNotation::Scientific,
110        Some('g' | 'n') | None => NumericNotation::General,
111        Some('d') => NumericNotation::Integer(NumericRadix::Decimal),
112        Some('b') => NumericNotation::Integer(NumericRadix::Binary),
113        Some('o') => NumericNotation::Integer(NumericRadix::Octal),
114        Some('x') => NumericNotation::Integer(NumericRadix::HexLower),
115        Some('X') => NumericNotation::Integer(NumericRadix::HexUpper),
116        _ => return Err(invalid()),
117    };
118    let precision = if matches!(notation, NumericNotation::Integer(_)) {
119        // The reference integer grammar discards precision, including values
120        // larger than u8/usize. Only the decimal syntax above matters here.
121        NumericPrecision::Fractional(0)
122    } else {
123        let count = precision.map_or(Ok(if kind.is_none() { 12 } else { 6 }), |value| {
124            value.parse::<u8>().map_err(|_| invalid())
125        })?;
126        if matches!(kind, Some('f' | 'e' | '%')) {
127            NumericPrecision::Fractional(count)
128        } else {
129            NumericPrecision::Significant(count)
130        }
131    };
132    let symbol = match (symbol, notation) {
133        (Some(NumericSymbol::RadixPrefix), NumericNotation::Integer(radix))
134            if radix != NumericRadix::Decimal =>
135        {
136            NumericSymbol::RadixPrefix
137        }
138        (Some(NumericSymbol::Currency), _) => NumericSymbol::Currency,
139        _ => NumericSymbol::None,
140    };
141    let field = NumericField::new(width.unwrap_or(0), fill, align)?;
142    let mut format = NumericFormat::new(notation, precision)?
143        .sign(sign.unwrap_or(NumericSign::NegativeOnly))?
144        .symbol(symbol)?
145        .grouping(grouping || kind == Some('n'))?
146        .field(width.map(|_| field))?
147        .trailing_zeros(if trim || kind.is_none() {
148            TrailingZeros::Trim
149        } else {
150            TrailingZeros::Keep
151        })?;
152    if matches!(kind, Some('%' | 'p')) {
153        format = format.rate(NumericRate::Percent)?;
154    }
155    if kind == Some('s') {
156        format = format.prefixes(NumericPrefixes::si(
157            NumericSelection::PerValue,
158            NumericPromotion::PromoteOnRounding,
159        )?)?;
160    }
161    Ok(format)
162}
163
164fn invalid() -> Error {
165    Error::Data("invalid numeric format specifier".into())
166}