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        crate::operation::string(&buffer.text, output_bytes)?;
185        buffer
186            .text
187            .try_reserve_exact(output_bytes)
188            .map_err(|error| {
189                Error::Render(format!("numeric presentation output: {error}").into())
190            })?;
191        Ok(buffer)
192    }
193
194    fn reserve_chunks(&mut self, bits: u64) -> Result<()> {
195        // 2^29 < 10^9, so ceil(bits/29) bounds the exact division count.
196        let count = usize::try_from(bits.div_ceil(29).max(1)).map_err(|_| arithmetic_error())?;
197        let additional = count.saturating_sub(self.chunks.len());
198        crate::data::source::reserve_source(&mut self.chunks, additional)
199    }
200
201    fn convert(&mut self, value: &BigUint) -> Result<()> {
202        self.chunks.clear();
203        self.reserve_chunks(value.bits())?;
204        let mut remaining = value.clone();
205        loop {
206            let quotient = &remaining / 1_000_000_000_u32;
207            let remainder =
208                u32::try_from(&remaining % 1_000_000_000_u32).expect("decimal chunk below 10^9");
209            if self.chunks.len() == self.chunks.capacity() {
210                return Err(arithmetic_error());
211            }
212            self.chunks.push(remainder);
213            if quotient.bits() == 0 {
214                break;
215            }
216            remaining = quotient;
217        }
218        Ok(())
219    }
220
221    fn digit_count(&self) -> Result<usize> {
222        let leading = *self.chunks.last().ok_or_else(arithmetic_error)?;
223        (self.chunks.len() - 1)
224            .checked_mul(9)
225            .and_then(|length| length.checked_add(chunk_width(leading)))
226            .ok_or_else(arithmetic_error)
227    }
228
229    fn append_exponent(&mut self, exponent: &BigInt) -> Result<()> {
230        self.convert(exponent.magnitude())?;
231        self.text.push('e');
232        if exponent.sign() == Sign::Minus {
233            self.text.push('-');
234        }
235        visit_digits(&self.chunks, 0..self.digit_count()?, |digits| {
236            self.text
237                .push_str(std::str::from_utf8(digits).expect("ASCII decimal digits"));
238        });
239        Ok(())
240    }
241}
242
243pub(super) struct ExactDecimal {
244    pub(super) negative: bool,
245    pub(super) coefficient: BigUint,
246    pub(super) denominator: BigUint,
247    pub(super) exponent: BigInt,
248    pub(super) decade: BigInt,
249}
250
251impl ExactDecimal {
252    pub(super) fn new(negative: bool, coefficient: BigUint, exponent: BigInt) -> Result<Self> {
253        Self::ratio(negative, coefficient, BigUint::from(1_u8), exponent)
254    }
255
256    pub(super) fn ratio(
257        negative: bool,
258        coefficient: BigUint,
259        denominator: BigUint,
260        exponent: BigInt,
261    ) -> Result<Self> {
262        let decade = if coefficient.bits() == 0 {
263            BigInt::ZERO
264        } else {
265            let mut digits = DecimalBuffer::default();
266            digits.convert(&coefficient)?;
267            let top = digits.digit_count()?;
268            digits.convert(&denominator)?;
269            let bottom = digits.digit_count()?;
270            let mut power = i64::try_from(top).map_err(|_| arithmetic_error())?
271                - i64::try_from(bottom).map_err(|_| arithmetic_error())?;
272            let lower = if power >= 0 {
273                coefficient < &denominator * decimal_power(power.unsigned_abs())?
274            } else {
275                &coefficient * decimal_power(power.unsigned_abs())? < denominator
276            };
277            power -= i64::from(lower);
278            &exponent + power
279        };
280        Ok(Self {
281            negative,
282            coefficient,
283            denominator,
284            exponent,
285            decade,
286        })
287    }
288
289    pub(super) fn decode(value: f64, scale: i16) -> Result<Self> {
290        if !value.is_finite() {
291            return Err(Error::Data(
292                "numeric presentation operand must be finite".into(),
293            ));
294        }
295        let bits = value.to_bits();
296        let stored = i32::try_from((bits >> 52) & 0x7ff).expect("11 exponent bits");
297        let mut significand = bits & ((1_u64 << 52) - 1);
298        let mut exponent = if stored == 0 {
299            -1074
300        } else {
301            significand |= 1_u64 << 52;
302            stored - 1023 - 52
303        };
304        if significand == 0 {
305            return Ok(Self {
306                negative: value.is_sign_negative(),
307                coefficient: BigUint::ZERO,
308                denominator: BigUint::from(1_u8),
309                exponent: BigInt::ZERO,
310                decade: BigInt::ZERO,
311            });
312        }
313        let common = significand.trailing_zeros();
314        significand >>= common;
315        exponent += i32::try_from(common).expect("at most 52 common bits");
316
317        // Binary64 bounds these powers/shifts by 1074/1023 and the exact
318        // decimal coefficient by 767 digits. No scratch quota is involved.
319        let (coefficient, decimal_exponent) = if exponent >= 0 {
320            (
321                BigUint::from(significand) << exponent.unsigned_abs() as usize,
322                0,
323            )
324        } else {
325            (
326                BigUint::from(significand) * BigUint::from(5_u8).pow(exponent.unsigned_abs()),
327                exponent,
328            )
329        };
330        let exponent = decimal_exponent + i32::from(scale);
331        Self::new(value.is_sign_negative(), coefficient, exponent.into())
332    }
333
334    fn multiply(self, multiplier: f64, shift: i16) -> Result<Self> {
335        let other = Self::decode(multiplier, shift)?;
336        Self::new(
337            self.negative ^ other.negative,
338            self.coefficient * other.coefficient,
339            self.exponent + other.exponent,
340        )
341    }
342
343    pub(super) fn effective_factor(format: &ResolvedFormat<'_>) -> Result<Self> {
344        Self::decode(format.multiplier, format.rate.shift())?.divide(format.divisor)
345    }
346
347    pub(super) fn divide(self, factor: Option<&NumericFactor>) -> Result<Self> {
348        match factor {
349            None => Ok(self),
350            Some(NumericFactor::Value(value)) => {
351                let divisor = Self::decode(*value, 0)?;
352                Self::ratio(
353                    self.negative ^ divisor.negative,
354                    self.coefficient,
355                    self.denominator * divisor.coefficient,
356                    self.exponent - divisor.exponent,
357                )
358            }
359            Some(NumericFactor::PowerOfTen(exponent)) => {
360                let exponent =
361                    BigInt::parse_bytes(exponent.as_bytes(), 10).ok_or_else(arithmetic_error)?;
362                Self::ratio(
363                    self.negative,
364                    self.coefficient,
365                    self.denominator,
366                    self.exponent - exponent,
367                )
368            }
369            Some(NumericFactor::AutomaticDecimal) => Err(Error::Render(
370                "automatic numeric factor was not resolved by its set owner".into(),
371            )),
372        }
373    }
374
375    pub(super) fn compare_abs(&self, other: &Self) -> Result<std::cmp::Ordering> {
376        match (self.coefficient.bits() == 0, other.coefficient.bits() == 0) {
377            (true, true) => return Ok(std::cmp::Ordering::Equal),
378            (true, false) => return Ok(std::cmp::Ordering::Less),
379            (false, true) => return Ok(std::cmp::Ordering::Greater),
380            _ => (),
381        }
382        if self.decade != other.decade {
383            return Ok(self.decade.cmp(&other.decade));
384        }
385        let shift = &self.exponent - &other.exponent;
386        let mut top = &self.coefficient * &other.denominator;
387        let mut bottom = &other.coefficient * &self.denominator;
388        let power =
389            decimal_power(u64::try_from(shift.magnitude()).map_err(|_| arithmetic_error())?)?;
390        if shift.sign() == Sign::Minus {
391            bottom *= power;
392        } else {
393            top *= power;
394        }
395        Ok(top.cmp(&bottom))
396    }
397
398    pub(super) fn round(self, format: &ResolvedFormat<'_>) -> Result<RoundedDecimal> {
399        let quantum = decimal_quantum(&self.decade, format);
400        let shift = &quantum - &self.exponent;
401        if (shift.sign() != Sign::Plus && self.denominator == BigUint::from(1_u8))
402            || self.coefficient.bits() == 0
403        {
404            return Ok(RoundedDecimal {
405                negative: self.negative,
406                coefficient: self.coefficient,
407                exponent: self.exponent,
408            });
409        }
410        let coefficient = if &self.decade - &quantum < BigInt::from(-1) {
411            tiny_coefficient(self.negative, format.rounding)
412        } else {
413            let power =
414                decimal_power(u64::try_from(shift.magnitude()).map_err(|_| arithmetic_error())?)?;
415            let (numerator, denominator) = if shift.sign() == Sign::Minus {
416                (self.coefficient * power, self.denominator)
417            } else {
418                (self.coefficient, self.denominator * power)
419            };
420            round_integer(&numerator, &denominator, self.negative, format.rounding)
421        };
422        Ok(RoundedDecimal {
423            negative: self.negative,
424            coefficient,
425            exponent: quantum,
426        })
427    }
428
429    pub(super) fn ceiling_at(&self, quantum: &BigInt) -> Result<BigUint> {
430        let shift = &self.exponent - quantum;
431        let power =
432            decimal_power(u64::try_from(shift.magnitude()).map_err(|_| arithmetic_error())?)?;
433        let (numerator, denominator) = if shift.sign() == Sign::Minus {
434            (self.coefficient.clone(), &self.denominator * power)
435        } else {
436            (&self.coefficient * power, self.denominator.clone())
437        };
438        Ok(round_integer(
439            &numerator,
440            &denominator,
441            false,
442            NumericRounding::Ceiling,
443        ))
444    }
445}
446
447fn decimal_power(power: u64) -> Result<BigUint> {
448    Ok(BigUint::from(10_u8).pow(u32::try_from(power).map_err(|_| arithmetic_error())?))
449}
450
451pub(super) fn tiny_coefficient(negative: bool, rounding: NumericRounding) -> BigUint {
452    BigUint::from(u8::from(match rounding {
453        NumericRounding::AwayFromZero => true,
454        NumericRounding::Floor => negative,
455        NumericRounding::Ceiling => !negative,
456        _ => false,
457    }))
458}
459
460pub(super) fn decimal_quantum(decade: &BigInt, format: &ResolvedFormat<'_>) -> BigInt {
461    match format.precision {
462        ResolvedPrecision::Significant(digits) => decade - (digits - 1),
463        ResolvedPrecision::Fractional(digits) => {
464            let origin = match format.notation {
465                NumericNotation::Decimal | NumericNotation::Integer(_) => BigInt::ZERO,
466                NumericNotation::Scientific | NumericNotation::General => decade.clone(),
467                NumericNotation::Engineering => engineering_exponent(decade),
468            };
469            origin - digits
470        }
471    }
472}
473
474fn engineering_exponent(decade: &BigInt) -> BigInt {
475    let mut remainder = decade % 3_u8;
476    if remainder.sign() == Sign::Minus {
477        remainder += 3_u8;
478    }
479    decade - remainder
480}
481
482/// One exact signed-magnitude quantizer for ordinary rationals and power endpoints.
483pub(super) fn round_integer(
484    numerator: &BigUint,
485    denominator: &BigUint,
486    negative: bool,
487    rounding: NumericRounding,
488) -> BigUint {
489    let mut quotient = numerator / denominator;
490    let remainder = numerator % denominator;
491    let increment = match rounding {
492        NumericRounding::TowardZero => false,
493        NumericRounding::AwayFromZero => remainder.bits() != 0,
494        NumericRounding::Floor => negative && remainder.bits() != 0,
495        NumericRounding::Ceiling => !negative && remainder.bits() != 0,
496        NumericRounding::NearestEven
497        | NumericRounding::NearestAway
498        | NumericRounding::NearestTowardZero => {
499            let twice = remainder << 1_usize;
500            twice > *denominator
501                || (twice == *denominator
502                    && match rounding {
503                        NumericRounding::NearestEven => quotient.bit(0),
504                        NumericRounding::NearestAway => true,
505                        _ => false,
506                    })
507        }
508    };
509    if increment {
510        quotient += 1_u8;
511    }
512    quotient
513}
514
515pub(crate) fn format_finite(value: f64, format: &ResolvedFormat<'_>) -> Result<String> {
516    format.validate()?;
517    let operand = finite_operand(value, format)?;
518    let plan = super::power::PowerPlan::new(
519        &operand.decade,
520        &operand.exponent,
521        operand.coefficient.bits(),
522        true,
523        operand.negative,
524        format,
525    )?;
526    operand.round(format)?.emit_reserved(format, plan.output)
527}
528
529pub(super) fn finite_operand(value: f64, format: &ResolvedFormat<'_>) -> Result<ExactDecimal> {
530    ExactDecimal::decode(value, format.decimal_scale)?
531        .multiply(format.multiplier, format.rate.shift())?
532        .divide(format.divisor)
533}
534
535impl RoundedDecimal {
536    /// Serialize an already rounded number. Scale has already been consumed by
537    /// its mathematical operand, and must not be applied again at this boundary.
538    #[cfg(test)]
539    pub(crate) fn emit(&self, format: &ResolvedFormat<'_>) -> Result<String> {
540        self.emit_reserved(format, DecimalBuffer::default())
541    }
542
543    /// A power operand reserves its symbolic output bound before any refinement
544    /// or physical coefficient construction. Reuse that same empty buffer here.
545    #[expect(
546        clippy::too_many_lines,
547        reason = "exact carry normalization and fallible output reservation precede the single numeric emission"
548    )]
549    pub(crate) fn emit_reserved(
550        &self,
551        format: &ResolvedFormat<'_>,
552        mut buffer: DecimalBuffer,
553    ) -> Result<String> {
554        format.validate()?;
555        if let NumericNotation::Integer(radix) = format.notation {
556            return self.emit_integer(radix, format, buffer);
557        }
558        if !buffer.text.is_empty() {
559            return Err(Error::Render(
560                "numeric output reservation must be empty".into(),
561            ));
562        }
563        buffer.convert(&self.coefficient)?;
564        let digits = buffer.digit_count()?;
565        let zero = self.coefficient.bits() == 0;
566        let negative = self.negative && (!zero || format.negative_zero == NegativeZero::Preserve);
567        let decade = if zero {
568            BigInt::ZERO
569        } else {
570            &self.exponent + BigInt::from(digits - 1)
571        };
572        let display_exponent = match format.notation {
573            NumericNotation::Decimal => BigInt::ZERO,
574            NumericNotation::Scientific => decade.clone(),
575            NumericNotation::Engineering => engineering_exponent(&decade),
576            NumericNotation::General => {
577                let ResolvedPrecision::Significant(count) = format.precision else {
578                    unreachable!("validated significant precision")
579                };
580                if decade >= BigInt::from(-4) && decade < BigInt::from(count) {
581                    BigInt::ZERO
582                } else {
583                    decade.clone()
584                }
585            }
586            NumericNotation::Integer(_) => unreachable!("integer emission"),
587        };
588        let point = if zero {
589            BigInt::from(1_u8)
590        } else {
591            BigInt::from(digits) + &self.exponent - &display_exponent
592        };
593        let fractional = match format.precision {
594            ResolvedPrecision::Fractional(count) => usize::from(count),
595            ResolvedPrecision::Significant(count) => {
596                let places = if zero {
597                    BigInt::from(count - 1)
598                } else {
599                    BigInt::from(count) - &point
600                };
601                if places.sign() == Sign::Minus {
602                    0
603                } else {
604                    usize::try_from(places).map_err(|_| arithmetic_error())?
605                }
606            }
607        };
608        let point = isize::try_from(point).map_err(|_| arithmetic_error())?;
609        let integral = usize::try_from(point.max(1)).map_err(|_| arithmetic_error())?;
610        let exponent = match format.notation {
611            NumericNotation::Decimal => false,
612            NumericNotation::General => display_exponent != BigInt::ZERO,
613            _ => true,
614        };
615        let exponent_length = if exponent {
616            // 2^3 < 10; this is a checked capacity bound, not spelling.
617            let digits = usize::try_from(display_exponent.bits().div_ceil(3).max(1))
618                .map_err(|_| arithmetic_error())?;
619            digits
620                .checked_add(1 + usize::from(display_exponent.sign() == Sign::Minus))
621                .ok_or_else(arithmetic_error)?
622        } else {
623            0
624        };
625        buffer.reserve_chunks(display_exponent.bits())?;
626        let prefix = format.prefix.unwrap_or_default();
627        let suffix = format.suffix.unwrap_or_default();
628        let length = [
629            prefix.len(),
630            usize::from(negative),
631            integral,
632            usize::from(fractional > 0),
633            fractional,
634            exponent_length,
635            suffix.len(),
636        ]
637        .into_iter()
638        .try_fold(0_usize, usize::checked_add)
639        .filter(|length| isize::try_from(*length).is_ok())
640        .ok_or_else(arithmetic_error)?;
641        crate::operation::string(&buffer.text, length)?;
642        buffer.text.try_reserve_exact(length).map_err(|error| {
643            Error::Render(format!("numeric presentation output: {error}").into())
644        })?;
645        let text = &mut buffer.text;
646        text.push_str(prefix);
647        if negative {
648            text.push('-');
649        }
650        emit_magnitude(text, &buffer.chunks, digits, point, fractional)?;
651        if fractional > 0 && format.trailing_zeros == TrailingZeros::Trim {
652            while text.ends_with('0') {
653                text.pop();
654            }
655            if text.ends_with('.') {
656                text.pop();
657            }
658        }
659        if exponent {
660            buffer.append_exponent(&display_exponent)?;
661        }
662        buffer.text.push_str(suffix);
663        Ok(buffer.text)
664    }
665
666    fn emit_integer(
667        &self,
668        radix: NumericRadix,
669        format: &ResolvedFormat<'_>,
670        mut buffer: DecimalBuffer,
671    ) -> Result<String> {
672        let base: u32 = match radix {
673            NumericRadix::Decimal => 10,
674            NumericRadix::Binary => 2,
675            NumericRadix::Octal => 8,
676            NumericRadix::HexLower | NumericRadix::HexUpper => 16,
677        };
678        let zero = self.coefficient.bits() == 0;
679        let power = if zero {
680            0
681        } else {
682            u32::try_from(&self.exponent).map_err(|_| arithmetic_error())?
683        };
684        let bits = usize::try_from(self.coefficient.bits())
685            .map_err(|_| arithmetic_error())?
686            .checked_add(
687                (power as usize)
688                    .checked_mul(4)
689                    .ok_or_else(arithmetic_error)?,
690            )
691            .and_then(|bits| bits.checked_add(1))
692            .ok_or_else(arithmetic_error)?;
693        let mut digits = Vec::new();
694        crate::operation::vector(&digits, bits)?;
695        digits
696            .try_reserve_exact(bits)
697            .map_err(|error| Error::Render(format!("numeric radix digits: {error}").into()))?;
698        let mut magnitude = &self.coefficient * BigUint::from(10_u8).pow(power);
699        let alphabet = if radix == NumericRadix::HexUpper {
700            b"0123456789ABCDEF"
701        } else {
702            b"0123456789abcdef"
703        };
704        loop {
705            let digit = usize::try_from(&magnitude % base).map_err(|_| arithmetic_error())?;
706            digits.push(alphabet[digit]);
707            magnitude /= base;
708            if magnitude.bits() == 0 {
709                break;
710            }
711        }
712        let negative = self.negative && (!zero || format.negative_zero == NegativeZero::Preserve);
713        let length = digits
714            .len()
715            .checked_add(usize::from(negative))
716            .and_then(|n| n.checked_add(format.prefix.map_or(0, str::len)))
717            .and_then(|n| n.checked_add(format.suffix.map_or(0, str::len)))
718            .ok_or_else(arithmetic_error)?;
719        crate::operation::string(&buffer.text, length)?;
720        buffer
721            .text
722            .try_reserve_exact(length)
723            .map_err(|error| Error::Render(format!("numeric radix output: {error}").into()))?;
724        buffer.text.push_str(format.prefix.unwrap_or_default());
725        if negative {
726            buffer.text.push('-');
727        }
728        for digit in digits.iter().rev() {
729            buffer.text.push(char::from(*digit));
730        }
731        buffer.text.push_str(format.suffix.unwrap_or_default());
732        Ok(buffer.text)
733    }
734}
735
736fn emit_magnitude(
737    text: &mut String,
738    chunks: &[u32],
739    digits: usize,
740    point: isize,
741    fractional: usize,
742) -> Result<()> {
743    let integral_digits = usize::try_from(point.max(0)).map_err(|_| arithmetic_error())?;
744    let taken = integral_digits.min(digits);
745    if integral_digits == 0 {
746        text.push('0');
747    } else {
748        visit_digits(chunks, 0..taken, |digits| {
749            text.push_str(std::str::from_utf8(digits).expect("ASCII decimal digits"));
750        });
751        push_zeroes(text, integral_digits - taken);
752    }
753    let leading = if point < 0 { point.unsigned_abs() } else { 0 };
754    let leading = fractional.min(leading);
755    let copied = (fractional - leading).min(digits - taken);
756    if fractional > 0 {
757        text.push('.');
758        push_zeroes(text, leading);
759        visit_digits(chunks, taken..taken + copied, |digits| {
760            text.push_str(std::str::from_utf8(digits).expect("ASCII decimal digits"));
761        });
762        push_zeroes(text, fractional - leading - copied);
763    }
764    let mut discarded_nonzero = false;
765    visit_digits(chunks, taken + copied..digits, |digits| {
766        discarded_nonzero |= digits.iter().any(|digit| *digit != b'0');
767    });
768    if discarded_nonzero {
769        return Err(Error::Render(
770            "numeric decimal emission would discard nonzero digits".into(),
771        ));
772    }
773    Ok(())
774}
775
776fn chunk_width(value: u32) -> usize {
777    if value == 0 {
778        1
779    } else {
780        value.ilog10() as usize + 1
781    }
782}
783
784/// View ordinary decimal digit spans without allocating a reversed digit string.
785fn visit_digits(chunks: &[u32], range: std::ops::Range<usize>, mut visit: impl FnMut(&[u8])) {
786    if range.is_empty() {
787        return;
788    }
789    let mut offset = 0;
790    for (index, &chunk) in chunks.iter().rev().enumerate() {
791        let width = if index == 0 { chunk_width(chunk) } else { 9 };
792        let end = offset + width;
793        if range.start < end && range.end > offset {
794            let mut bytes = [b'0'; 9];
795            let mut value = chunk;
796            for byte in bytes.iter_mut().rev() {
797                *byte += u8::try_from(value % 10).expect("decimal digit");
798                value /= 10;
799            }
800            let start = range.start.max(offset) - offset;
801            let finish = range.end.min(end) - offset;
802            visit(&bytes[9 - width + start..9 - width + finish]);
803        }
804        offset = end;
805        if offset >= range.end {
806            break;
807        }
808    }
809}
810
811fn push_zeroes(text: &mut String, mut count: usize) {
812    const ZEROES: &str = "0000000000000000000000000000000000000000000000000000000000000000";
813    while count > 0 {
814        let part = count.min(ZEROES.len());
815        text.push_str(&ZEROES[..part]);
816        count -= part;
817    }
818}
819
820fn arithmetic_error() -> Error {
821    Error::Render("numeric presentation output length or decimal arithmetic overflow".into())
822}
823
824#[cfg(test)]
825mod tests;