Skip to main content

lichtung_plot/numeric/
emission.rs

1//! Presentation of the exact engine's private ASCII digit runs, never caller text.
2
3use super::decimal::{NumericNotation, NumericRadix};
4use super::locale::{validate_token, NumericGroupRepeat, NumericGrouping, NumericLocale};
5use crate::{Error, Result};
6
7/// Positive and negative sign presentation.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum NumericSign {
10    /// Only negative values have a sign.
11    NegativeOnly,
12    /// Emit a positive or negative sign for every value.
13    Always,
14    /// Positive values have one ordinary space.
15    Space,
16    /// Negative values are enclosed in parentheses.
17    Accounting,
18}
19
20/// A locale currency or integer-radix affix.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum NumericSymbol {
23    /// No symbol.
24    None,
25    /// Use the locale's currency prefix and suffix.
26    Currency,
27    /// Emit 0b, 0o or 0x for a nondecimal integer notation.
28    RadixPrefix,
29}
30
31/// Placement of field fill around a complete numeric presentation.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum NumericAlignment {
34    /// Fill after the number.
35    Left,
36    /// Fill before the number.
37    Right,
38    /// Fill on both sides, with an odd extra scalar on the right.
39    Center,
40    /// Fill after sign and currency/radix prefix.
41    AfterSign,
42}
43
44/// Minimum scalar width, independent of CSS geometry and numeric precision.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct NumericField {
47    pub(super) width: usize,
48    pub(super) fill: char,
49    pub(super) alignment: NumericAlignment,
50}
51
52impl NumericField {
53    /// Construct a field with one single-line fill scalar; zero width adds no fill.
54    pub fn new(width: usize, fill: char, alignment: NumericAlignment) -> Result<Self> {
55        let mut bytes = [0; 4];
56        validate_token(fill.encode_utf8(&mut bytes), false)?;
57        Ok(Self {
58            width,
59            fill,
60            alignment,
61        })
62    }
63}
64
65/// Exact rate scaling, independent of a literal suffix.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum NumericRate {
68    /// No rate scaling.
69    Value,
70    /// Multiply exactly by 100 and use the locale percent suffix.
71    Percent,
72    /// Multiply exactly by 1000 and use the locale per-mille suffix.
73    PerMille,
74}
75
76impl NumericRate {
77    pub(super) const fn shift(self) -> i16 {
78        match self {
79            Self::Value => 0,
80            Self::Percent => 2,
81            Self::PerMille => 3,
82        }
83    }
84}
85
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub(super) struct Presentation {
88    pub(super) locale: NumericLocale,
89    pub(super) grouping: bool,
90    pub(super) sign: NumericSign,
91    pub(super) symbol: NumericSymbol,
92    pub(super) field: Option<NumericField>,
93}
94
95#[derive(Clone, Copy)]
96pub(super) struct Affixes<'a> {
97    pub(super) outer_prefix: &'a str,
98    pub(super) outer_suffix: &'a str,
99    pub(super) prefix: &'a str,
100    pub(super) suffix: &'a str,
101}
102
103impl Default for Presentation {
104    fn default() -> Self {
105        Self {
106            locale: NumericLocale::invariant(),
107            grouping: false,
108            sign: NumericSign::NegativeOnly,
109            symbol: NumericSymbol::None,
110            field: None,
111        }
112    }
113}
114
115pub(super) fn append(out: &mut String, text: &str) -> Result<()> {
116    crate::operation::check()?;
117    out.try_reserve_exact(text.len())
118        .map_err(|e| Error::Render(format!("numeric text allocation: {e}").into()))?;
119    out.push_str(text);
120    Ok(())
121}
122
123fn fill(out: &mut String, scalar: char, count: usize) -> Result<()> {
124    let bytes = count
125        .checked_mul(scalar.len_utf8())
126        .ok_or_else(length_error)?;
127    crate::operation::check()?;
128    out.try_reserve_exact(bytes)
129        .map_err(|e| Error::Render(format!("numeric field allocation: {e}").into()))?;
130    out.extend(std::iter::repeat_n(scalar, count));
131    Ok(())
132}
133
134fn length_error() -> Error {
135    Error::Render("numeric field or token length overflow".into())
136}
137
138fn digit(out: &mut String, byte: u8, locale: &NumericLocale) -> Result<()> {
139    if byte.is_ascii_digit() {
140        append(out, &locale.digits()[usize::from(byte - b'0')])
141    } else {
142        let mut bytes = [0; 4];
143        append(out, char::from(byte).encode_utf8(&mut bytes))
144    }
145}
146
147fn separators(count: usize, grouping: &NumericGrouping) -> Result<usize> {
148    if count == 0 {
149        return Ok(0);
150    }
151    let mut remaining = count;
152    let mut groups = 0_usize;
153    for &size in grouping.sizes() {
154        if remaining <= size {
155            return Ok(groups);
156        }
157        remaining -= size;
158        groups = groups.checked_add(1).ok_or_else(length_error)?;
159    }
160    match grouping.repeat() {
161        NumericGroupRepeat::Stop => Ok(groups),
162        NumericGroupRepeat::Last => groups
163            .checked_add((remaining - 1) / grouping.sizes()[grouping.sizes().len() - 1])
164            .ok_or_else(length_error),
165        NumericGroupRepeat::Cycle => {
166            let cycle = grouping
167                .sizes()
168                .iter()
169                .try_fold(0_usize, |n, &s| n.checked_add(s))
170                .ok_or_else(length_error)?;
171            let full = (remaining - 1) / cycle;
172            groups = groups
173                .checked_add(
174                    full.checked_mul(grouping.sizes().len())
175                        .ok_or_else(length_error)?,
176                )
177                .ok_or_else(length_error)?;
178            remaining -= full * cycle;
179            for &size in grouping.sizes() {
180                if remaining <= size {
181                    break;
182                }
183                remaining -= size;
184                groups = groups.checked_add(1).ok_or_else(length_error)?;
185            }
186            Ok(groups)
187        }
188    }
189}
190
191fn integer_scalars(
192    integer: &str,
193    zeros: usize,
194    locale: &NumericLocale,
195    grouping: Option<&NumericGrouping>,
196) -> Result<usize> {
197    let mut count = zeros
198        .checked_mul(locale.digits()[0].chars().count())
199        .ok_or_else(length_error)?;
200    for byte in integer.bytes() {
201        count = count
202            .checked_add(if byte.is_ascii_digit() {
203                locale.digits()[usize::from(byte - b'0')].chars().count()
204            } else {
205                1
206            })
207            .ok_or_else(length_error)?;
208    }
209    if let Some(grouping) = grouping {
210        count = count
211            .checked_add(
212                separators(
213                    integer.len().checked_add(zeros).ok_or_else(length_error)?,
214                    grouping,
215                )?
216                .checked_mul(grouping.separator().chars().count())
217                .ok_or_else(length_error)?,
218            )
219            .ok_or_else(length_error)?;
220    }
221    Ok(count)
222}
223
224fn integer_text(
225    integer: &str,
226    zeros: usize,
227    locale: &NumericLocale,
228    grouping: Option<&NumericGrouping>,
229) -> Result<String> {
230    let total = integer.len().checked_add(zeros).ok_or_else(length_error)?;
231    let mut cuts = Vec::new();
232    let count = grouping.map_or(Ok(0), |g| separators(total, g))?;
233    crate::data::source::reserve_source(&mut cuts, count)?;
234    let mut remaining = total;
235    if let Some(grouping) = grouping {
236        for index in 0..count {
237            remaining -= grouping.size(index).ok_or_else(length_error)?;
238            cuts.push(remaining);
239        }
240    }
241    let mut output = String::new();
242    // Reserve before visiting a possibly large zero field, including multibyte tokens.
243    let max_digit = locale.digits().iter().map(String::len).max().unwrap_or(1);
244    let bytes = total
245        .checked_mul(max_digit)
246        .and_then(|n| {
247            n.checked_add(count.checked_mul(grouping.map_or(0, |g| g.separator().len()))?)
248        })
249        .ok_or_else(length_error)?;
250    crate::operation::check()?;
251    output
252        .try_reserve_exact(bytes)
253        .map_err(|e| Error::Render(format!("numeric integer tokens: {e}").into()))?;
254    for index in 0..total {
255        if cuts.last() == Some(&index) {
256            append(&mut output, grouping.expect("grouped cut").separator())?;
257            cuts.pop();
258        }
259        digit(
260            &mut output,
261            if index < zeros {
262                b'0'
263            } else {
264                integer.as_bytes()[index - zeros]
265            },
266            locale,
267        )?;
268    }
269    Ok(output)
270}
271
272impl Presentation {
273    pub(super) fn observe(&self, round: &mut crate::layout::kernel::FeedbackRound) -> Result<()> {
274        self.locale.observe(round)?;
275        round.observe_count(usize::from(self.grouping))?;
276        round.observe_count(self.sign as usize)?;
277        round.observe_count(self.symbol as usize)?;
278        round.observe_count(usize::from(self.field.is_some()))?;
279        if let Some(field) = &self.field {
280            round.observe_count(field.width)?;
281            round.observe_count(field.fill as usize)?;
282            round.observe_count(field.alignment as usize)?;
283        }
284        Ok(())
285    }
286    #[expect(
287        clippy::too_many_lines,
288        reason = "one normalized emission order owns sign, grouping, locale tokens and final scalar padding"
289    )]
290    pub(super) fn emit(
291        &self,
292        ascii: &str,
293        notation: NumericNotation,
294        rate: NumericRate,
295        affixes: Affixes<'_>,
296    ) -> Result<String> {
297        let negative = ascii.starts_with('-');
298        let magnitude = ascii.strip_prefix('-').unwrap_or(ascii);
299        let (mantissa, exponent) = if matches!(notation, NumericNotation::Integer(_)) {
300            (magnitude, None)
301        } else {
302            magnitude
303                .split_once('e')
304                .map_or((magnitude, None), |(m, e)| (m, Some(e)))
305        };
306        let (integer, fraction) = mantissa
307            .split_once('.')
308            .map_or((mantissa, None), |(i, f)| (i, Some(f)));
309        let mut leading = String::new();
310        append(&mut leading, affixes.outer_prefix)?;
311        append(&mut leading, affixes.prefix)?;
312        append(
313            &mut leading,
314            match (negative, self.sign) {
315                (true, NumericSign::Accounting) => "(",
316                (true, _) => self.locale.symbols().negative(),
317                (false, NumericSign::Always) => self.locale.symbols().positive(),
318                (false, NumericSign::Space) => " ",
319                _ => "",
320            },
321        )?;
322        let radix = match (self.symbol, notation) {
323            (NumericSymbol::RadixPrefix, NumericNotation::Integer(NumericRadix::Binary)) => "0b",
324            (NumericSymbol::RadixPrefix, NumericNotation::Integer(NumericRadix::Octal)) => "0o",
325            (
326                NumericSymbol::RadixPrefix,
327                NumericNotation::Integer(NumericRadix::HexLower | NumericRadix::HexUpper),
328            ) => "0x",
329            _ => "",
330        };
331        append(
332            &mut leading,
333            if self.symbol == NumericSymbol::Currency {
334                self.locale.currency().prefix()
335            } else {
336                radix
337            },
338        )?;
339        let mut trailing = String::new();
340        if let Some(fraction) = fraction {
341            append(&mut trailing, self.locale.decimal())?;
342            for byte in fraction.bytes() {
343                digit(&mut trailing, byte, &self.locale)?;
344            }
345        }
346        if let Some(exponent) = exponent {
347            append(&mut trailing, "e")?;
348            for byte in exponent.bytes() {
349                if byte == b'-' {
350                    append(&mut trailing, self.locale.symbols().negative())?;
351                } else {
352                    digit(&mut trailing, byte, &self.locale)?;
353                }
354            }
355        }
356        append(
357            &mut trailing,
358            if self.symbol == NumericSymbol::Currency {
359                self.locale.currency().suffix()
360            } else {
361                match rate {
362                    NumericRate::Value => "",
363                    NumericRate::Percent => self.locale.symbols().percent(),
364                    NumericRate::PerMille => self.locale.symbols().per_mille(),
365                }
366            },
367        )?;
368        if negative && self.sign == NumericSign::Accounting {
369            append(&mut trailing, ")")?;
370        }
371        append(&mut trailing, affixes.suffix)?;
372        append(&mut trailing, affixes.outer_suffix)?;
373        let grouping = self.grouping.then(|| self.locale.grouping()).flatten();
374        let fixed = leading
375            .chars()
376            .count()
377            .checked_add(trailing.chars().count())
378            .ok_or_else(length_error)?;
379        let mut zeros = 0;
380        if let Some(field) = &self.field {
381            if field.fill == '0' && field.alignment == NumericAlignment::AfterSign {
382                let (mut low, mut high) = (0_usize, field.width);
383                while low < high {
384                    let middle = low + (high - low) / 2;
385                    if fixed
386                        .checked_add(integer_scalars(integer, middle, &self.locale, grouping)?)
387                        .ok_or_else(length_error)?
388                        < field.width
389                    {
390                        low = middle + 1;
391                    } else {
392                        high = middle;
393                    }
394                }
395                zeros = low;
396            }
397        }
398        let numeric = integer_text(integer, zeros, &self.locale, grouping)?;
399        let length = fixed
400            .checked_add(numeric.chars().count())
401            .ok_or_else(length_error)?;
402        let mut output = String::new();
403        let padding = self
404            .field
405            .as_ref()
406            .map_or(0, |field| field.width.saturating_sub(length));
407        let (before, after, inside, scalar) =
408            self.field
409                .as_ref()
410                .map_or((0, 0, 0, ' '), |field| match field.alignment {
411                    NumericAlignment::Left => (0, padding, 0, field.fill),
412                    NumericAlignment::Right => (padding, 0, 0, field.fill),
413                    NumericAlignment::Center => (padding / 2, padding - padding / 2, 0, field.fill),
414                    NumericAlignment::AfterSign => (0, 0, padding, field.fill),
415                });
416        fill(&mut output, scalar, before)?;
417        append(&mut output, &leading)?;
418        fill(&mut output, scalar, inside)?;
419        append(&mut output, &numeric)?;
420        append(&mut output, &trailing)?;
421        fill(&mut output, scalar, after)?;
422        Ok(output)
423    }
424}
425
426#[cfg(test)]
427mod tests {
428    use super::*;
429    use crate::{formatting::NumericPrecision, NumericFormat};
430
431    #[test]
432    fn locale_signs_rates_currency_and_literal_affixes_follow_one_emission_order() {
433        let format = NumericFormat::new(NumericNotation::Decimal, NumericPrecision::Fractional(1))
434            .unwrap()
435            .locale(NumericLocale::named("fr-FR").unwrap())
436            .unwrap()
437            .grouping(true)
438            .unwrap()
439            .rate(NumericRate::Percent)
440            .unwrap()
441            .symbol(NumericSymbol::Currency)
442            .unwrap()
443            .sign(NumericSign::Accounting)
444            .unwrap()
445            .prefix("[")
446            .unwrap()
447            .suffix(" 00]")
448            .unwrap();
449        assert_eq!(
450            format.format_singleton(-12.5, false).unwrap(),
451            "[(1\u{a0}250,0\u{a0}€) 00]"
452        );
453        let rate = format
454            .clone()
455            .symbol(NumericSymbol::None)
456            .unwrap()
457            .sign(NumericSign::Always)
458            .unwrap();
459        assert_eq!(
460            rate.format_singleton(0.125, false).unwrap(),
461            "[+12,5\u{202f}% 00]"
462        );
463        let per_mille = NumericFormat::default()
464            .rate(NumericRate::PerMille)
465            .unwrap();
466        assert_eq!(per_mille.format_singleton(0.125, false).unwrap(), "125.00‰");
467        assert_eq!(per_mille.format_singleton(0.0, true).unwrap(), "1000.00‰");
468        let arabic = NumericFormat::default()
469            .locale(NumericLocale::named("ar-001").unwrap())
470            .unwrap()
471            .notation(NumericNotation::Scientific)
472            .unwrap()
473            .prefix("ID 012: ")
474            .unwrap();
475        assert_eq!(
476            arabic.format_singleton(-0.125, false).unwrap(),
477            "ID 012: −١٫٢٥e−١"
478        );
479    }
480}