Skip to main content

lichtung_plot/numeric/
decimal.rs

1//! Exact finite-binary64 decimal conversion and one-round decimal emission.
2//!
3//! A finite dyadic m*2^e is an integer when e>=0, otherwise
4//! (m*5^-e)*10^e. Decimal scaling shifts that exponent exactly. Quantization
5//! divides by a power of ten and uses the exact remainder and quotient parity.
6//! Notation changes only the quantum and final decimal-point/exponent placement;
7//! carry normalization never rounds again. No floating arithmetic is used here.
8
9use super::emission::NumericRate;
10use super::prefixes::NumericFactor;
11use num_bigint::{BigInt, BigUint, Sign};
12
13use crate::{Error, Result};
14
15pub(super) const MAX_FRACTIONAL_DIGITS: u8 = 20;
16pub(super) const MAX_SIGNIFICANT_DIGITS: u8 = 21;
17
18/// Decimal-point and exponent spelling for numeric presentation.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum NumericNotation {
21    /// Plain decimal notation, without an exponent.
22    Decimal,
23    /// One leading integral digit and a decimal exponent.
24    Scientific,
25    /// One to three integral digits and an exponent divisible by three.
26    Engineering,
27    /// Significant digits, switching between decimal and scientific after rounding.
28    General,
29    /// An exact rounded mathematical integer in the selected radix.
30    Integer(NumericRadix),
31}
32
33/// Digit alphabet for integer numeric presentation.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum NumericRadix {
36    /// Base ten.
37    Decimal,
38    /// Base two.
39    Binary,
40    /// Base eight.
41    Octal,
42    /// Base sixteen with lowercase letters.
43    HexLower,
44    /// Base sixteen with uppercase letters.
45    HexUpper,
46}
47
48/// Exact rounding at the selected decimal quantum, before numeric emission.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum NumericRounding {
51    /// Round to the nearest value; an exact tie chooses the even coefficient.
52    NearestEven,
53    /// Round to the nearest value; an exact tie rounds away from zero.
54    NearestAway,
55    /// Round to the nearest value; an exact tie rounds toward zero.
56    NearestTowardZero,
57    /// Discard the fractional remainder toward zero.
58    TowardZero,
59    /// Round every nonzero fractional remainder away from zero.
60    AwayFromZero,
61    /// Round toward negative infinity.
62    Floor,
63    /// Round toward positive infinity.
64    Ceiling,
65}
66
67/// One precision already selected by its semantic owner, never by geometry.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub(crate) enum ResolvedPrecision {
70    Fractional(u8),
71    Significant(u8),
72}
73
74/// Whether actual or rounded negative zero retains its minus sign.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum NegativeZero {
77    /// Preserve the source sign, including when rounding produces zero.
78    Preserve,
79    /// Display every zero without a minus sign.
80    Normalize,
81}
82
83/// Fractional trailing-zero handling after numeric rounding.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum TrailingZeros {
86    /// Retain the digits required by the selected precision.
87    Keep,
88    /// Remove fractional trailing zeros and an empty decimal point.
89    /// Integral place-value zeros are never removed.
90    Trim,
91}
92
93/// Borrowed effective inputs to the one emitter; not a second public policy.
94#[derive(Debug, Clone, Copy, PartialEq)]
95pub(crate) struct ResolvedFormat<'a> {
96    pub(crate) notation: NumericNotation,
97    pub(crate) precision: ResolvedPrecision,
98    pub(crate) decimal_scale: i16,
99    pub(crate) prefix: Option<&'a str>,
100    pub(crate) suffix: Option<&'a str>,
101    pub(crate) negative_zero: NegativeZero,
102    pub(crate) trailing_zeros: TrailingZeros,
103    pub(crate) rounding: NumericRounding,
104    pub(crate) multiplier: f64,
105    pub(crate) rate: NumericRate,
106    pub(crate) divisor: Option<&'a NumericFactor>,
107}
108
109impl Default for ResolvedFormat<'_> {
110    fn default() -> Self {
111        Self {
112            notation: NumericNotation::Decimal,
113            precision: ResolvedPrecision::Fractional(2),
114            decimal_scale: 0,
115            prefix: None,
116            suffix: None,
117            negative_zero: NegativeZero::Preserve,
118            trailing_zeros: TrailingZeros::Keep,
119            rounding: NumericRounding::NearestEven,
120            multiplier: 1.0,
121            rate: NumericRate::Value,
122            divisor: None,
123        }
124    }
125}
126
127impl ResolvedFormat<'_> {
128    pub(crate) fn validate(&self) -> Result<()> {
129        let valid = match self.precision {
130            ResolvedPrecision::Fractional(digits) => digits <= MAX_FRACTIONAL_DIGITS,
131            ResolvedPrecision::Significant(digits) => {
132                (1..=MAX_SIGNIFICANT_DIGITS).contains(&digits)
133            }
134        };
135        if !valid || !(-324..=324).contains(&self.decimal_scale) || !self.multiplier.is_finite() {
136            return Err(Error::Data(
137                "numeric presentation precision or decimal scale is outside its admitted range"
138                    .into(),
139            ));
140        }
141        if (self.notation == NumericNotation::General
142            && !matches!(self.precision, ResolvedPrecision::Significant(_)))
143            || (matches!(self.notation, NumericNotation::Integer(_))
144                && self.precision != ResolvedPrecision::Fractional(0))
145        {
146            return Err(Error::Data(
147                "numeric notation and precision are incompatible".into(),
148            ));
149        }
150        if [self.prefix, self.suffix]
151            .into_iter()
152            .flatten()
153            .any(|text| text.is_empty() || text.chars().any(char::is_control))
154        {
155            return Err(Error::Data(
156                "numeric presentation affixes must be nonempty and contain no control characters"
157                    .into(),
158            ));
159        }
160        Ok(())
161    }
162}
163
164/// A rounded magnitude at one exact decimal quantum, plus the source sign.
165/// Arbitrary-size exponents also admit the later symbolic Forest operand.
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub(crate) struct RoundedDecimal {
168    pub(crate) negative: bool,
169    pub(crate) coefficient: BigUint,
170    pub(crate) exponent: BigInt,
171}
172
173/// One output allocation and a reusable, fallible base-10^9 conversion buffer.
174#[derive(Debug, Default)]
175pub(crate) struct DecimalBuffer {
176    text: String,
177    chunks: Vec<u32>,
178}
179
180impl DecimalBuffer {
181    pub(crate) fn reserve(output_bytes: usize, integer_bits: usize) -> Result<Self> {
182        let mut buffer = Self::default();
183        buffer.reserve_chunks(u64::try_from(integer_bits).map_err(|_| arithmetic_error())?)?;
184        buffer
185            .text
186            .try_reserve_exact(output_bytes)
187            .map_err(|error| Error::Render(format!("numeric presentation output: {error}")))?;
188        Ok(buffer)
189    }
190
191    fn reserve_chunks(&mut self, bits: u64) -> Result<()> {
192        // 2^29 < 10^9, so ceil(bits/29) bounds the exact division count.
193        let count = usize::try_from(bits.div_ceil(29).max(1)).map_err(|_| arithmetic_error())?;
194        let additional = count.saturating_sub(self.chunks.len());
195        crate::data::source::reserve_source(&mut self.chunks, additional)
196    }
197
198    fn convert(&mut self, value: &BigUint) -> Result<()> {
199        self.chunks.clear();
200        self.reserve_chunks(value.bits())?;
201        let mut remaining = value.clone();
202        loop {
203            let quotient = &remaining / 1_000_000_000_u32;
204            let remainder =
205                u32::try_from(&remaining % 1_000_000_000_u32).expect("decimal chunk below 10^9");
206            if self.chunks.len() == self.chunks.capacity() {
207                return Err(arithmetic_error());
208            }
209            self.chunks.push(remainder);
210            if quotient.bits() == 0 {
211                break;
212            }
213            remaining = quotient;
214        }
215        Ok(())
216    }
217
218    fn digit_count(&self) -> Result<usize> {
219        let leading = *self.chunks.last().ok_or_else(arithmetic_error)?;
220        (self.chunks.len() - 1)
221            .checked_mul(9)
222            .and_then(|length| length.checked_add(chunk_width(leading)))
223            .ok_or_else(arithmetic_error)
224    }
225
226    fn append_exponent(&mut self, exponent: &BigInt) -> Result<()> {
227        self.convert(exponent.magnitude())?;
228        self.text.push('e');
229        if exponent.sign() == Sign::Minus {
230            self.text.push('-');
231        }
232        visit_digits(&self.chunks, 0..self.digit_count()?, |digits| {
233            self.text
234                .push_str(std::str::from_utf8(digits).expect("ASCII decimal digits"));
235        });
236        Ok(())
237    }
238}
239
240pub(super) struct ExactDecimal {
241    pub(super) negative: bool,
242    pub(super) coefficient: BigUint,
243    pub(super) denominator: BigUint,
244    pub(super) exponent: BigInt,
245    pub(super) decade: BigInt,
246}
247
248impl ExactDecimal {
249    pub(super) fn new(negative: bool, coefficient: BigUint, exponent: BigInt) -> Result<Self> {
250        Self::ratio(negative, coefficient, BigUint::from(1_u8), exponent)
251    }
252
253    pub(super) fn ratio(
254        negative: bool,
255        coefficient: BigUint,
256        denominator: BigUint,
257        exponent: BigInt,
258    ) -> Result<Self> {
259        let decade = if coefficient.bits() == 0 {
260            BigInt::ZERO
261        } else {
262            let mut digits = DecimalBuffer::default();
263            digits.convert(&coefficient)?;
264            let top = digits.digit_count()?;
265            digits.convert(&denominator)?;
266            let bottom = digits.digit_count()?;
267            let mut power = i64::try_from(top).map_err(|_| arithmetic_error())?
268                - i64::try_from(bottom).map_err(|_| arithmetic_error())?;
269            let lower = if power >= 0 {
270                coefficient < &denominator * decimal_power(power.unsigned_abs())?
271            } else {
272                &coefficient * decimal_power(power.unsigned_abs())? < denominator
273            };
274            power -= i64::from(lower);
275            &exponent + power
276        };
277        Ok(Self {
278            negative,
279            coefficient,
280            denominator,
281            exponent,
282            decade,
283        })
284    }
285
286    pub(super) fn decode(value: f64, scale: i16) -> Result<Self> {
287        if !value.is_finite() {
288            return Err(Error::Data(
289                "numeric presentation operand must be finite".into(),
290            ));
291        }
292        let bits = value.to_bits();
293        let stored = i32::try_from((bits >> 52) & 0x7ff).expect("11 exponent bits");
294        let mut significand = bits & ((1_u64 << 52) - 1);
295        let mut exponent = if stored == 0 {
296            -1074
297        } else {
298            significand |= 1_u64 << 52;
299            stored - 1023 - 52
300        };
301        if significand == 0 {
302            return Ok(Self {
303                negative: value.is_sign_negative(),
304                coefficient: BigUint::ZERO,
305                denominator: BigUint::from(1_u8),
306                exponent: BigInt::ZERO,
307                decade: BigInt::ZERO,
308            });
309        }
310        let common = significand.trailing_zeros();
311        significand >>= common;
312        exponent += i32::try_from(common).expect("at most 52 common bits");
313
314        // Binary64 bounds these powers/shifts by 1074/1023 and the exact
315        // decimal coefficient by 767 digits. No scratch quota is involved.
316        let (coefficient, decimal_exponent) = if exponent >= 0 {
317            (
318                BigUint::from(significand) << exponent.unsigned_abs() as usize,
319                0,
320            )
321        } else {
322            (
323                BigUint::from(significand) * BigUint::from(5_u8).pow(exponent.unsigned_abs()),
324                exponent,
325            )
326        };
327        let exponent = decimal_exponent + i32::from(scale);
328        Self::new(value.is_sign_negative(), coefficient, exponent.into())
329    }
330
331    fn multiply(self, multiplier: f64, shift: i16) -> Result<Self> {
332        let other = Self::decode(multiplier, shift)?;
333        Self::new(
334            self.negative ^ other.negative,
335            self.coefficient * other.coefficient,
336            self.exponent + other.exponent,
337        )
338    }
339
340    pub(super) fn effective_factor(format: &ResolvedFormat<'_>) -> Result<Self> {
341        Self::decode(format.multiplier, format.rate.shift())?.divide(format.divisor)
342    }
343
344    pub(super) fn divide(self, factor: Option<&NumericFactor>) -> Result<Self> {
345        match factor {
346            None => Ok(self),
347            Some(NumericFactor::Value(value)) => {
348                let divisor = Self::decode(*value, 0)?;
349                Self::ratio(
350                    self.negative ^ divisor.negative,
351                    self.coefficient,
352                    self.denominator * divisor.coefficient,
353                    self.exponent - divisor.exponent,
354                )
355            }
356            Some(NumericFactor::PowerOfTen(exponent)) => {
357                let exponent =
358                    BigInt::parse_bytes(exponent.as_bytes(), 10).ok_or_else(arithmetic_error)?;
359                Self::ratio(
360                    self.negative,
361                    self.coefficient,
362                    self.denominator,
363                    self.exponent - exponent,
364                )
365            }
366            Some(NumericFactor::AutomaticDecimal) => Err(Error::Render(
367                "automatic numeric factor was not resolved by its set owner".into(),
368            )),
369        }
370    }
371
372    pub(super) fn compare_abs(&self, other: &Self) -> Result<std::cmp::Ordering> {
373        match (self.coefficient.bits() == 0, other.coefficient.bits() == 0) {
374            (true, true) => return Ok(std::cmp::Ordering::Equal),
375            (true, false) => return Ok(std::cmp::Ordering::Less),
376            (false, true) => return Ok(std::cmp::Ordering::Greater),
377            _ => (),
378        }
379        if self.decade != other.decade {
380            return Ok(self.decade.cmp(&other.decade));
381        }
382        let shift = &self.exponent - &other.exponent;
383        let mut top = &self.coefficient * &other.denominator;
384        let mut bottom = &other.coefficient * &self.denominator;
385        let power =
386            decimal_power(u64::try_from(shift.magnitude()).map_err(|_| arithmetic_error())?)?;
387        if shift.sign() == Sign::Minus {
388            bottom *= power;
389        } else {
390            top *= power;
391        }
392        Ok(top.cmp(&bottom))
393    }
394
395    pub(super) fn round(self, format: &ResolvedFormat<'_>) -> Result<RoundedDecimal> {
396        let quantum = decimal_quantum(&self.decade, format);
397        let shift = &quantum - &self.exponent;
398        if (shift.sign() != Sign::Plus && self.denominator == BigUint::from(1_u8))
399            || self.coefficient.bits() == 0
400        {
401            return Ok(RoundedDecimal {
402                negative: self.negative,
403                coefficient: self.coefficient,
404                exponent: self.exponent,
405            });
406        }
407        let coefficient = if &self.decade - &quantum < BigInt::from(-1) {
408            tiny_coefficient(self.negative, format.rounding)
409        } else {
410            let power =
411                decimal_power(u64::try_from(shift.magnitude()).map_err(|_| arithmetic_error())?)?;
412            let (numerator, denominator) = if shift.sign() == Sign::Minus {
413                (self.coefficient * power, self.denominator)
414            } else {
415                (self.coefficient, self.denominator * power)
416            };
417            round_integer(&numerator, &denominator, self.negative, format.rounding)
418        };
419        Ok(RoundedDecimal {
420            negative: self.negative,
421            coefficient,
422            exponent: quantum,
423        })
424    }
425
426    pub(super) fn ceiling_at(&self, quantum: &BigInt) -> Result<BigUint> {
427        let shift = &self.exponent - quantum;
428        let power =
429            decimal_power(u64::try_from(shift.magnitude()).map_err(|_| arithmetic_error())?)?;
430        let (numerator, denominator) = if shift.sign() == Sign::Minus {
431            (self.coefficient.clone(), &self.denominator * power)
432        } else {
433            (&self.coefficient * power, self.denominator.clone())
434        };
435        Ok(round_integer(
436            &numerator,
437            &denominator,
438            false,
439            NumericRounding::Ceiling,
440        ))
441    }
442}
443
444fn decimal_power(power: u64) -> Result<BigUint> {
445    Ok(BigUint::from(10_u8).pow(u32::try_from(power).map_err(|_| arithmetic_error())?))
446}
447
448pub(super) fn tiny_coefficient(negative: bool, rounding: NumericRounding) -> BigUint {
449    BigUint::from(u8::from(match rounding {
450        NumericRounding::AwayFromZero => true,
451        NumericRounding::Floor => negative,
452        NumericRounding::Ceiling => !negative,
453        _ => false,
454    }))
455}
456
457pub(super) fn decimal_quantum(decade: &BigInt, format: &ResolvedFormat<'_>) -> BigInt {
458    match format.precision {
459        ResolvedPrecision::Significant(digits) => decade - (digits - 1),
460        ResolvedPrecision::Fractional(digits) => {
461            let origin = match format.notation {
462                NumericNotation::Decimal | NumericNotation::Integer(_) => BigInt::ZERO,
463                NumericNotation::Scientific | NumericNotation::General => decade.clone(),
464                NumericNotation::Engineering => engineering_exponent(decade),
465            };
466            origin - digits
467        }
468    }
469}
470
471fn engineering_exponent(decade: &BigInt) -> BigInt {
472    let mut remainder = decade % 3_u8;
473    if remainder.sign() == Sign::Minus {
474        remainder += 3_u8;
475    }
476    decade - remainder
477}
478
479/// One exact signed-magnitude quantizer for ordinary rationals and power endpoints.
480pub(super) fn round_integer(
481    numerator: &BigUint,
482    denominator: &BigUint,
483    negative: bool,
484    rounding: NumericRounding,
485) -> BigUint {
486    let mut quotient = numerator / denominator;
487    let remainder = numerator % denominator;
488    let increment = match rounding {
489        NumericRounding::TowardZero => false,
490        NumericRounding::AwayFromZero => remainder.bits() != 0,
491        NumericRounding::Floor => negative && remainder.bits() != 0,
492        NumericRounding::Ceiling => !negative && remainder.bits() != 0,
493        NumericRounding::NearestEven
494        | NumericRounding::NearestAway
495        | NumericRounding::NearestTowardZero => {
496            let twice = remainder << 1_usize;
497            twice > *denominator
498                || (twice == *denominator
499                    && match rounding {
500                        NumericRounding::NearestEven => quotient.bit(0),
501                        NumericRounding::NearestAway => true,
502                        _ => false,
503                    })
504        }
505    };
506    if increment {
507        quotient += 1_u8;
508    }
509    quotient
510}
511
512pub(crate) fn format_finite(value: f64, format: &ResolvedFormat<'_>) -> Result<String> {
513    format.validate()?;
514    let operand = finite_operand(value, format)?;
515    let plan = super::power::PowerPlan::new(
516        &operand.decade,
517        &operand.exponent,
518        operand.coefficient.bits(),
519        true,
520        operand.negative,
521        format,
522    )?;
523    operand.round(format)?.emit_reserved(format, plan.output)
524}
525
526pub(super) fn finite_operand(value: f64, format: &ResolvedFormat<'_>) -> Result<ExactDecimal> {
527    ExactDecimal::decode(value, format.decimal_scale)?
528        .multiply(format.multiplier, format.rate.shift())?
529        .divide(format.divisor)
530}
531
532impl RoundedDecimal {
533    /// Serialize an already rounded number. Scale has already been consumed by
534    /// its mathematical operand, and must not be applied again at this boundary.
535    #[cfg(test)]
536    pub(crate) fn emit(&self, format: &ResolvedFormat<'_>) -> Result<String> {
537        self.emit_reserved(format, DecimalBuffer::default())
538    }
539
540    /// A power operand reserves its symbolic output bound before any refinement
541    /// or physical coefficient construction. Reuse that same empty buffer here.
542    #[expect(
543        clippy::too_many_lines,
544        reason = "exact carry normalization and fallible output reservation precede the single numeric emission"
545    )]
546    pub(crate) fn emit_reserved(
547        &self,
548        format: &ResolvedFormat<'_>,
549        mut buffer: DecimalBuffer,
550    ) -> Result<String> {
551        format.validate()?;
552        if let NumericNotation::Integer(radix) = format.notation {
553            return self.emit_integer(radix, format, buffer);
554        }
555        if !buffer.text.is_empty() {
556            return Err(Error::Render(
557                "numeric output reservation must be empty".into(),
558            ));
559        }
560        buffer.convert(&self.coefficient)?;
561        let digits = buffer.digit_count()?;
562        let zero = self.coefficient.bits() == 0;
563        let negative = self.negative && (!zero || format.negative_zero == NegativeZero::Preserve);
564        let decade = if zero {
565            BigInt::ZERO
566        } else {
567            &self.exponent + BigInt::from(digits - 1)
568        };
569        let display_exponent = match format.notation {
570            NumericNotation::Decimal => BigInt::ZERO,
571            NumericNotation::Scientific => decade.clone(),
572            NumericNotation::Engineering => engineering_exponent(&decade),
573            NumericNotation::General => {
574                let ResolvedPrecision::Significant(count) = format.precision else {
575                    unreachable!("validated significant precision")
576                };
577                if decade >= BigInt::from(-4) && decade < BigInt::from(count) {
578                    BigInt::ZERO
579                } else {
580                    decade.clone()
581                }
582            }
583            NumericNotation::Integer(_) => unreachable!("integer emission"),
584        };
585        let point = if zero {
586            BigInt::from(1_u8)
587        } else {
588            BigInt::from(digits) + &self.exponent - &display_exponent
589        };
590        let fractional = match format.precision {
591            ResolvedPrecision::Fractional(count) => usize::from(count),
592            ResolvedPrecision::Significant(count) => {
593                let places = if zero {
594                    BigInt::from(count - 1)
595                } else {
596                    BigInt::from(count) - &point
597                };
598                if places.sign() == Sign::Minus {
599                    0
600                } else {
601                    usize::try_from(places).map_err(|_| arithmetic_error())?
602                }
603            }
604        };
605        let point = isize::try_from(point).map_err(|_| arithmetic_error())?;
606        let integral = usize::try_from(point.max(1)).map_err(|_| arithmetic_error())?;
607        let exponent = match format.notation {
608            NumericNotation::Decimal => false,
609            NumericNotation::General => display_exponent != BigInt::ZERO,
610            _ => true,
611        };
612        let exponent_length = if exponent {
613            // 2^3 < 10; this is a checked capacity bound, not spelling.
614            let digits = usize::try_from(display_exponent.bits().div_ceil(3).max(1))
615                .map_err(|_| arithmetic_error())?;
616            digits
617                .checked_add(1 + usize::from(display_exponent.sign() == Sign::Minus))
618                .ok_or_else(arithmetic_error)?
619        } else {
620            0
621        };
622        buffer.reserve_chunks(display_exponent.bits())?;
623        let prefix = format.prefix.unwrap_or_default();
624        let suffix = format.suffix.unwrap_or_default();
625        let length = [
626            prefix.len(),
627            usize::from(negative),
628            integral,
629            usize::from(fractional > 0),
630            fractional,
631            exponent_length,
632            suffix.len(),
633        ]
634        .into_iter()
635        .try_fold(0_usize, usize::checked_add)
636        .filter(|length| isize::try_from(*length).is_ok())
637        .ok_or_else(arithmetic_error)?;
638        buffer
639            .text
640            .try_reserve_exact(length)
641            .map_err(|error| Error::Render(format!("numeric presentation output: {error}")))?;
642        let text = &mut buffer.text;
643        text.push_str(prefix);
644        if negative {
645            text.push('-');
646        }
647        emit_magnitude(text, &buffer.chunks, digits, point, fractional)?;
648        if fractional > 0 && format.trailing_zeros == TrailingZeros::Trim {
649            while text.ends_with('0') {
650                text.pop();
651            }
652            if text.ends_with('.') {
653                text.pop();
654            }
655        }
656        if exponent {
657            buffer.append_exponent(&display_exponent)?;
658        }
659        buffer.text.push_str(suffix);
660        Ok(buffer.text)
661    }
662
663    fn emit_integer(
664        &self,
665        radix: NumericRadix,
666        format: &ResolvedFormat<'_>,
667        mut buffer: DecimalBuffer,
668    ) -> Result<String> {
669        let base: u32 = match radix {
670            NumericRadix::Decimal => 10,
671            NumericRadix::Binary => 2,
672            NumericRadix::Octal => 8,
673            NumericRadix::HexLower | NumericRadix::HexUpper => 16,
674        };
675        let zero = self.coefficient.bits() == 0;
676        let power = if zero {
677            0
678        } else {
679            u32::try_from(&self.exponent).map_err(|_| arithmetic_error())?
680        };
681        let bits = usize::try_from(self.coefficient.bits())
682            .map_err(|_| arithmetic_error())?
683            .checked_add(
684                (power as usize)
685                    .checked_mul(4)
686                    .ok_or_else(arithmetic_error)?,
687            )
688            .and_then(|bits| bits.checked_add(1))
689            .ok_or_else(arithmetic_error)?;
690        let mut digits = Vec::new();
691        digits
692            .try_reserve_exact(bits)
693            .map_err(|error| Error::Render(format!("numeric radix digits: {error}")))?;
694        let mut magnitude = &self.coefficient * BigUint::from(10_u8).pow(power);
695        let alphabet = if radix == NumericRadix::HexUpper {
696            b"0123456789ABCDEF"
697        } else {
698            b"0123456789abcdef"
699        };
700        loop {
701            let digit = usize::try_from(&magnitude % base).map_err(|_| arithmetic_error())?;
702            digits.push(alphabet[digit]);
703            magnitude /= base;
704            if magnitude.bits() == 0 {
705                break;
706            }
707        }
708        let negative = self.negative && (!zero || format.negative_zero == NegativeZero::Preserve);
709        let length = digits
710            .len()
711            .checked_add(usize::from(negative))
712            .and_then(|n| n.checked_add(format.prefix.map_or(0, str::len)))
713            .and_then(|n| n.checked_add(format.suffix.map_or(0, str::len)))
714            .ok_or_else(arithmetic_error)?;
715        buffer
716            .text
717            .try_reserve_exact(length)
718            .map_err(|error| Error::Render(format!("numeric radix output: {error}")))?;
719        buffer.text.push_str(format.prefix.unwrap_or_default());
720        if negative {
721            buffer.text.push('-');
722        }
723        for digit in digits.iter().rev() {
724            buffer.text.push(char::from(*digit));
725        }
726        buffer.text.push_str(format.suffix.unwrap_or_default());
727        Ok(buffer.text)
728    }
729}
730
731fn emit_magnitude(
732    text: &mut String,
733    chunks: &[u32],
734    digits: usize,
735    point: isize,
736    fractional: usize,
737) -> Result<()> {
738    let integral_digits = usize::try_from(point.max(0)).map_err(|_| arithmetic_error())?;
739    let taken = integral_digits.min(digits);
740    if integral_digits == 0 {
741        text.push('0');
742    } else {
743        visit_digits(chunks, 0..taken, |digits| {
744            text.push_str(std::str::from_utf8(digits).expect("ASCII decimal digits"));
745        });
746        push_zeroes(text, integral_digits - taken);
747    }
748    let leading = if point < 0 { point.unsigned_abs() } else { 0 };
749    let leading = fractional.min(leading);
750    let copied = (fractional - leading).min(digits - taken);
751    if fractional > 0 {
752        text.push('.');
753        push_zeroes(text, leading);
754        visit_digits(chunks, taken..taken + copied, |digits| {
755            text.push_str(std::str::from_utf8(digits).expect("ASCII decimal digits"));
756        });
757        push_zeroes(text, fractional - leading - copied);
758    }
759    let mut discarded_nonzero = false;
760    visit_digits(chunks, taken + copied..digits, |digits| {
761        discarded_nonzero |= digits.iter().any(|digit| *digit != b'0');
762    });
763    if discarded_nonzero {
764        return Err(Error::Render(
765            "numeric decimal emission would discard nonzero digits".into(),
766        ));
767    }
768    Ok(())
769}
770
771fn chunk_width(value: u32) -> usize {
772    if value == 0 {
773        1
774    } else {
775        value.ilog10() as usize + 1
776    }
777}
778
779/// View ordinary decimal digit spans without allocating a reversed digit string.
780fn visit_digits(chunks: &[u32], range: std::ops::Range<usize>, mut visit: impl FnMut(&[u8])) {
781    if range.is_empty() {
782        return;
783    }
784    let mut offset = 0;
785    for (index, &chunk) in chunks.iter().rev().enumerate() {
786        let width = if index == 0 { chunk_width(chunk) } else { 9 };
787        let end = offset + width;
788        if range.start < end && range.end > offset {
789            let mut bytes = [b'0'; 9];
790            let mut value = chunk;
791            for byte in bytes.iter_mut().rev() {
792                *byte += u8::try_from(value % 10).expect("decimal digit");
793                value /= 10;
794            }
795            let start = range.start.max(offset) - offset;
796            let finish = range.end.min(end) - offset;
797            visit(&bytes[9 - width + start..9 - width + finish]);
798        }
799        offset = end;
800        if offset >= range.end {
801            break;
802        }
803    }
804}
805
806fn push_zeroes(text: &mut String, mut count: usize) {
807    const ZEROES: &str = "0000000000000000000000000000000000000000000000000000000000000000";
808    while count > 0 {
809        let part = count.min(ZEROES.len());
810        text.push_str(&ZEROES[..part]);
811        count -= part;
812    }
813}
814
815fn arithmetic_error() -> Error {
816    Error::Render("numeric presentation output length or decimal arithmetic overflow".into())
817}
818
819#[cfg(test)]
820mod tests;