lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
//! Exact finite-binary64 decimal conversion and one-round decimal emission.
//!
//! A finite dyadic m*2^e is an integer when e>=0, otherwise
//! (m*5^-e)*10^e. Decimal scaling shifts that exponent exactly. Quantization
//! divides by a power of ten and uses the exact remainder and quotient parity.
//! Notation changes only the quantum and final decimal-point/exponent placement;
//! carry normalization never rounds again. No floating arithmetic is used here.

use super::emission::NumericRate;
use super::prefixes::NumericFactor;
use num_bigint::{BigInt, BigUint, Sign};

use crate::{Error, Result};

pub(super) const MAX_FRACTIONAL_DIGITS: u8 = 20;
pub(super) const MAX_SIGNIFICANT_DIGITS: u8 = 21;

/// Decimal-point and exponent spelling for numeric presentation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumericNotation {
    /// Plain decimal notation, without an exponent.
    Decimal,
    /// One leading integral digit and a decimal exponent.
    Scientific,
    /// One to three integral digits and an exponent divisible by three.
    Engineering,
    /// Significant digits, switching between decimal and scientific after rounding.
    General,
    /// An exact rounded mathematical integer in the selected radix.
    Integer(NumericRadix),
}

/// Digit alphabet for integer numeric presentation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumericRadix {
    /// Base ten.
    Decimal,
    /// Base two.
    Binary,
    /// Base eight.
    Octal,
    /// Base sixteen with lowercase letters.
    HexLower,
    /// Base sixteen with uppercase letters.
    HexUpper,
}

/// Exact rounding at the selected decimal quantum, before numeric emission.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumericRounding {
    /// Round to the nearest value; an exact tie chooses the even coefficient.
    NearestEven,
    /// Round to the nearest value; an exact tie rounds away from zero.
    NearestAway,
    /// Round to the nearest value; an exact tie rounds toward zero.
    NearestTowardZero,
    /// Discard the fractional remainder toward zero.
    TowardZero,
    /// Round every nonzero fractional remainder away from zero.
    AwayFromZero,
    /// Round toward negative infinity.
    Floor,
    /// Round toward positive infinity.
    Ceiling,
}

/// One precision already selected by its semantic owner, never by geometry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ResolvedPrecision {
    Fractional(u8),
    Significant(u8),
}

/// Whether actual or rounded negative zero retains its minus sign.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NegativeZero {
    /// Preserve the source sign, including when rounding produces zero.
    Preserve,
    /// Display every zero without a minus sign.
    Normalize,
}

/// Fractional trailing-zero handling after numeric rounding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrailingZeros {
    /// Retain the digits required by the selected precision.
    Keep,
    /// Remove fractional trailing zeros and an empty decimal point.
    /// Integral place-value zeros are never removed.
    Trim,
}

/// Borrowed effective inputs to the one emitter; not a second public policy.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct ResolvedFormat<'a> {
    pub(crate) notation: NumericNotation,
    pub(crate) precision: ResolvedPrecision,
    pub(crate) decimal_scale: i16,
    pub(crate) prefix: Option<&'a str>,
    pub(crate) suffix: Option<&'a str>,
    pub(crate) negative_zero: NegativeZero,
    pub(crate) trailing_zeros: TrailingZeros,
    pub(crate) rounding: NumericRounding,
    pub(crate) multiplier: f64,
    pub(crate) rate: NumericRate,
    pub(crate) divisor: Option<&'a NumericFactor>,
}

impl Default for ResolvedFormat<'_> {
    fn default() -> Self {
        Self {
            notation: NumericNotation::Decimal,
            precision: ResolvedPrecision::Fractional(2),
            decimal_scale: 0,
            prefix: None,
            suffix: None,
            negative_zero: NegativeZero::Preserve,
            trailing_zeros: TrailingZeros::Keep,
            rounding: NumericRounding::NearestEven,
            multiplier: 1.0,
            rate: NumericRate::Value,
            divisor: None,
        }
    }
}

impl ResolvedFormat<'_> {
    pub(crate) fn validate(&self) -> Result<()> {
        let valid = match self.precision {
            ResolvedPrecision::Fractional(digits) => digits <= MAX_FRACTIONAL_DIGITS,
            ResolvedPrecision::Significant(digits) => {
                (1..=MAX_SIGNIFICANT_DIGITS).contains(&digits)
            }
        };
        if !valid || !(-324..=324).contains(&self.decimal_scale) || !self.multiplier.is_finite() {
            return Err(Error::Data(
                "numeric presentation precision or decimal scale is outside its admitted range"
                    .into(),
            ));
        }
        if (self.notation == NumericNotation::General
            && !matches!(self.precision, ResolvedPrecision::Significant(_)))
            || (matches!(self.notation, NumericNotation::Integer(_))
                && self.precision != ResolvedPrecision::Fractional(0))
        {
            return Err(Error::Data(
                "numeric notation and precision are incompatible".into(),
            ));
        }
        if [self.prefix, self.suffix]
            .into_iter()
            .flatten()
            .any(|text| text.is_empty() || text.chars().any(char::is_control))
        {
            return Err(Error::Data(
                "numeric presentation affixes must be nonempty and contain no control characters"
                    .into(),
            ));
        }
        Ok(())
    }
}

/// A rounded magnitude at one exact decimal quantum, plus the source sign.
/// Arbitrary-size exponents also admit the later symbolic Forest operand.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RoundedDecimal {
    pub(crate) negative: bool,
    pub(crate) coefficient: BigUint,
    pub(crate) exponent: BigInt,
}

/// One output allocation and a reusable, fallible base-10^9 conversion buffer.
#[derive(Debug, Default)]
pub(crate) struct DecimalBuffer {
    text: String,
    chunks: Vec<u32>,
}

impl DecimalBuffer {
    pub(crate) fn reserve(output_bytes: usize, integer_bits: usize) -> Result<Self> {
        let mut buffer = Self::default();
        buffer.reserve_chunks(u64::try_from(integer_bits).map_err(|_| arithmetic_error())?)?;
        crate::operation::string(&buffer.text, output_bytes)?;
        buffer
            .text
            .try_reserve_exact(output_bytes)
            .map_err(|error| {
                Error::Render(format!("numeric presentation output: {error}").into())
            })?;
        Ok(buffer)
    }

    fn reserve_chunks(&mut self, bits: u64) -> Result<()> {
        // 2^29 < 10^9, so ceil(bits/29) bounds the exact division count.
        let count = usize::try_from(bits.div_ceil(29).max(1)).map_err(|_| arithmetic_error())?;
        let additional = count.saturating_sub(self.chunks.len());
        crate::data::source::reserve_source(&mut self.chunks, additional)
    }

    fn convert(&mut self, value: &BigUint) -> Result<()> {
        self.chunks.clear();
        self.reserve_chunks(value.bits())?;
        let mut remaining = value.clone();
        loop {
            let quotient = &remaining / 1_000_000_000_u32;
            let remainder =
                u32::try_from(&remaining % 1_000_000_000_u32).expect("decimal chunk below 10^9");
            if self.chunks.len() == self.chunks.capacity() {
                return Err(arithmetic_error());
            }
            self.chunks.push(remainder);
            if quotient.bits() == 0 {
                break;
            }
            remaining = quotient;
        }
        Ok(())
    }

    fn digit_count(&self) -> Result<usize> {
        let leading = *self.chunks.last().ok_or_else(arithmetic_error)?;
        (self.chunks.len() - 1)
            .checked_mul(9)
            .and_then(|length| length.checked_add(chunk_width(leading)))
            .ok_or_else(arithmetic_error)
    }

    fn append_exponent(&mut self, exponent: &BigInt) -> Result<()> {
        self.convert(exponent.magnitude())?;
        self.text.push('e');
        if exponent.sign() == Sign::Minus {
            self.text.push('-');
        }
        visit_digits(&self.chunks, 0..self.digit_count()?, |digits| {
            self.text
                .push_str(std::str::from_utf8(digits).expect("ASCII decimal digits"));
        });
        Ok(())
    }
}

pub(super) struct ExactDecimal {
    pub(super) negative: bool,
    pub(super) coefficient: BigUint,
    pub(super) denominator: BigUint,
    pub(super) exponent: BigInt,
    pub(super) decade: BigInt,
}

impl ExactDecimal {
    pub(super) fn new(negative: bool, coefficient: BigUint, exponent: BigInt) -> Result<Self> {
        Self::ratio(negative, coefficient, BigUint::from(1_u8), exponent)
    }

    pub(super) fn ratio(
        negative: bool,
        coefficient: BigUint,
        denominator: BigUint,
        exponent: BigInt,
    ) -> Result<Self> {
        let decade = if coefficient.bits() == 0 {
            BigInt::ZERO
        } else {
            let mut digits = DecimalBuffer::default();
            digits.convert(&coefficient)?;
            let top = digits.digit_count()?;
            digits.convert(&denominator)?;
            let bottom = digits.digit_count()?;
            let mut power = i64::try_from(top).map_err(|_| arithmetic_error())?
                - i64::try_from(bottom).map_err(|_| arithmetic_error())?;
            let lower = if power >= 0 {
                coefficient < &denominator * decimal_power(power.unsigned_abs())?
            } else {
                &coefficient * decimal_power(power.unsigned_abs())? < denominator
            };
            power -= i64::from(lower);
            &exponent + power
        };
        Ok(Self {
            negative,
            coefficient,
            denominator,
            exponent,
            decade,
        })
    }

    pub(super) fn decode(value: f64, scale: i16) -> Result<Self> {
        if !value.is_finite() {
            return Err(Error::Data(
                "numeric presentation operand must be finite".into(),
            ));
        }
        let bits = value.to_bits();
        let stored = i32::try_from((bits >> 52) & 0x7ff).expect("11 exponent bits");
        let mut significand = bits & ((1_u64 << 52) - 1);
        let mut exponent = if stored == 0 {
            -1074
        } else {
            significand |= 1_u64 << 52;
            stored - 1023 - 52
        };
        if significand == 0 {
            return Ok(Self {
                negative: value.is_sign_negative(),
                coefficient: BigUint::ZERO,
                denominator: BigUint::from(1_u8),
                exponent: BigInt::ZERO,
                decade: BigInt::ZERO,
            });
        }
        let common = significand.trailing_zeros();
        significand >>= common;
        exponent += i32::try_from(common).expect("at most 52 common bits");

        // Binary64 bounds these powers/shifts by 1074/1023 and the exact
        // decimal coefficient by 767 digits. No scratch quota is involved.
        let (coefficient, decimal_exponent) = if exponent >= 0 {
            (
                BigUint::from(significand) << exponent.unsigned_abs() as usize,
                0,
            )
        } else {
            (
                BigUint::from(significand) * BigUint::from(5_u8).pow(exponent.unsigned_abs()),
                exponent,
            )
        };
        let exponent = decimal_exponent + i32::from(scale);
        Self::new(value.is_sign_negative(), coefficient, exponent.into())
    }

    fn multiply(self, multiplier: f64, shift: i16) -> Result<Self> {
        let other = Self::decode(multiplier, shift)?;
        Self::new(
            self.negative ^ other.negative,
            self.coefficient * other.coefficient,
            self.exponent + other.exponent,
        )
    }

    pub(super) fn effective_factor(format: &ResolvedFormat<'_>) -> Result<Self> {
        Self::decode(format.multiplier, format.rate.shift())?.divide(format.divisor)
    }

    pub(super) fn divide(self, factor: Option<&NumericFactor>) -> Result<Self> {
        match factor {
            None => Ok(self),
            Some(NumericFactor::Value(value)) => {
                let divisor = Self::decode(*value, 0)?;
                Self::ratio(
                    self.negative ^ divisor.negative,
                    self.coefficient,
                    self.denominator * divisor.coefficient,
                    self.exponent - divisor.exponent,
                )
            }
            Some(NumericFactor::PowerOfTen(exponent)) => {
                let exponent =
                    BigInt::parse_bytes(exponent.as_bytes(), 10).ok_or_else(arithmetic_error)?;
                Self::ratio(
                    self.negative,
                    self.coefficient,
                    self.denominator,
                    self.exponent - exponent,
                )
            }
            Some(NumericFactor::AutomaticDecimal) => Err(Error::Render(
                "automatic numeric factor was not resolved by its set owner".into(),
            )),
        }
    }

    pub(super) fn compare_abs(&self, other: &Self) -> Result<std::cmp::Ordering> {
        match (self.coefficient.bits() == 0, other.coefficient.bits() == 0) {
            (true, true) => return Ok(std::cmp::Ordering::Equal),
            (true, false) => return Ok(std::cmp::Ordering::Less),
            (false, true) => return Ok(std::cmp::Ordering::Greater),
            _ => (),
        }
        if self.decade != other.decade {
            return Ok(self.decade.cmp(&other.decade));
        }
        let shift = &self.exponent - &other.exponent;
        let mut top = &self.coefficient * &other.denominator;
        let mut bottom = &other.coefficient * &self.denominator;
        let power =
            decimal_power(u64::try_from(shift.magnitude()).map_err(|_| arithmetic_error())?)?;
        if shift.sign() == Sign::Minus {
            bottom *= power;
        } else {
            top *= power;
        }
        Ok(top.cmp(&bottom))
    }

    pub(super) fn round(self, format: &ResolvedFormat<'_>) -> Result<RoundedDecimal> {
        let quantum = decimal_quantum(&self.decade, format);
        let shift = &quantum - &self.exponent;
        if (shift.sign() != Sign::Plus && self.denominator == BigUint::from(1_u8))
            || self.coefficient.bits() == 0
        {
            return Ok(RoundedDecimal {
                negative: self.negative,
                coefficient: self.coefficient,
                exponent: self.exponent,
            });
        }
        let coefficient = if &self.decade - &quantum < BigInt::from(-1) {
            tiny_coefficient(self.negative, format.rounding)
        } else {
            let power =
                decimal_power(u64::try_from(shift.magnitude()).map_err(|_| arithmetic_error())?)?;
            let (numerator, denominator) = if shift.sign() == Sign::Minus {
                (self.coefficient * power, self.denominator)
            } else {
                (self.coefficient, self.denominator * power)
            };
            round_integer(&numerator, &denominator, self.negative, format.rounding)
        };
        Ok(RoundedDecimal {
            negative: self.negative,
            coefficient,
            exponent: quantum,
        })
    }

    pub(super) fn ceiling_at(&self, quantum: &BigInt) -> Result<BigUint> {
        let shift = &self.exponent - quantum;
        let power =
            decimal_power(u64::try_from(shift.magnitude()).map_err(|_| arithmetic_error())?)?;
        let (numerator, denominator) = if shift.sign() == Sign::Minus {
            (self.coefficient.clone(), &self.denominator * power)
        } else {
            (&self.coefficient * power, self.denominator.clone())
        };
        Ok(round_integer(
            &numerator,
            &denominator,
            false,
            NumericRounding::Ceiling,
        ))
    }
}

fn decimal_power(power: u64) -> Result<BigUint> {
    Ok(BigUint::from(10_u8).pow(u32::try_from(power).map_err(|_| arithmetic_error())?))
}

pub(super) fn tiny_coefficient(negative: bool, rounding: NumericRounding) -> BigUint {
    BigUint::from(u8::from(match rounding {
        NumericRounding::AwayFromZero => true,
        NumericRounding::Floor => negative,
        NumericRounding::Ceiling => !negative,
        _ => false,
    }))
}

pub(super) fn decimal_quantum(decade: &BigInt, format: &ResolvedFormat<'_>) -> BigInt {
    match format.precision {
        ResolvedPrecision::Significant(digits) => decade - (digits - 1),
        ResolvedPrecision::Fractional(digits) => {
            let origin = match format.notation {
                NumericNotation::Decimal | NumericNotation::Integer(_) => BigInt::ZERO,
                NumericNotation::Scientific | NumericNotation::General => decade.clone(),
                NumericNotation::Engineering => engineering_exponent(decade),
            };
            origin - digits
        }
    }
}

fn engineering_exponent(decade: &BigInt) -> BigInt {
    let mut remainder = decade % 3_u8;
    if remainder.sign() == Sign::Minus {
        remainder += 3_u8;
    }
    decade - remainder
}

/// One exact signed-magnitude quantizer for ordinary rationals and power endpoints.
pub(super) fn round_integer(
    numerator: &BigUint,
    denominator: &BigUint,
    negative: bool,
    rounding: NumericRounding,
) -> BigUint {
    let mut quotient = numerator / denominator;
    let remainder = numerator % denominator;
    let increment = match rounding {
        NumericRounding::TowardZero => false,
        NumericRounding::AwayFromZero => remainder.bits() != 0,
        NumericRounding::Floor => negative && remainder.bits() != 0,
        NumericRounding::Ceiling => !negative && remainder.bits() != 0,
        NumericRounding::NearestEven
        | NumericRounding::NearestAway
        | NumericRounding::NearestTowardZero => {
            let twice = remainder << 1_usize;
            twice > *denominator
                || (twice == *denominator
                    && match rounding {
                        NumericRounding::NearestEven => quotient.bit(0),
                        NumericRounding::NearestAway => true,
                        _ => false,
                    })
        }
    };
    if increment {
        quotient += 1_u8;
    }
    quotient
}

pub(crate) fn format_finite(value: f64, format: &ResolvedFormat<'_>) -> Result<String> {
    format.validate()?;
    let operand = finite_operand(value, format)?;
    let plan = super::power::PowerPlan::new(
        &operand.decade,
        &operand.exponent,
        operand.coefficient.bits(),
        true,
        operand.negative,
        format,
    )?;
    operand.round(format)?.emit_reserved(format, plan.output)
}

pub(super) fn finite_operand(value: f64, format: &ResolvedFormat<'_>) -> Result<ExactDecimal> {
    ExactDecimal::decode(value, format.decimal_scale)?
        .multiply(format.multiplier, format.rate.shift())?
        .divide(format.divisor)
}

impl RoundedDecimal {
    /// Serialize an already rounded number. Scale has already been consumed by
    /// its mathematical operand, and must not be applied again at this boundary.
    #[cfg(test)]
    pub(crate) fn emit(&self, format: &ResolvedFormat<'_>) -> Result<String> {
        self.emit_reserved(format, DecimalBuffer::default())
    }

    /// A power operand reserves its symbolic output bound before any refinement
    /// or physical coefficient construction. Reuse that same empty buffer here.
    #[expect(
        clippy::too_many_lines,
        reason = "exact carry normalization and fallible output reservation precede the single numeric emission"
    )]
    pub(crate) fn emit_reserved(
        &self,
        format: &ResolvedFormat<'_>,
        mut buffer: DecimalBuffer,
    ) -> Result<String> {
        format.validate()?;
        if let NumericNotation::Integer(radix) = format.notation {
            return self.emit_integer(radix, format, buffer);
        }
        if !buffer.text.is_empty() {
            return Err(Error::Render(
                "numeric output reservation must be empty".into(),
            ));
        }
        buffer.convert(&self.coefficient)?;
        let digits = buffer.digit_count()?;
        let zero = self.coefficient.bits() == 0;
        let negative = self.negative && (!zero || format.negative_zero == NegativeZero::Preserve);
        let decade = if zero {
            BigInt::ZERO
        } else {
            &self.exponent + BigInt::from(digits - 1)
        };
        let display_exponent = match format.notation {
            NumericNotation::Decimal => BigInt::ZERO,
            NumericNotation::Scientific => decade.clone(),
            NumericNotation::Engineering => engineering_exponent(&decade),
            NumericNotation::General => {
                let ResolvedPrecision::Significant(count) = format.precision else {
                    unreachable!("validated significant precision")
                };
                if decade >= BigInt::from(-4) && decade < BigInt::from(count) {
                    BigInt::ZERO
                } else {
                    decade.clone()
                }
            }
            NumericNotation::Integer(_) => unreachable!("integer emission"),
        };
        let point = if zero {
            BigInt::from(1_u8)
        } else {
            BigInt::from(digits) + &self.exponent - &display_exponent
        };
        let fractional = match format.precision {
            ResolvedPrecision::Fractional(count) => usize::from(count),
            ResolvedPrecision::Significant(count) => {
                let places = if zero {
                    BigInt::from(count - 1)
                } else {
                    BigInt::from(count) - &point
                };
                if places.sign() == Sign::Minus {
                    0
                } else {
                    usize::try_from(places).map_err(|_| arithmetic_error())?
                }
            }
        };
        let point = isize::try_from(point).map_err(|_| arithmetic_error())?;
        let integral = usize::try_from(point.max(1)).map_err(|_| arithmetic_error())?;
        let exponent = match format.notation {
            NumericNotation::Decimal => false,
            NumericNotation::General => display_exponent != BigInt::ZERO,
            _ => true,
        };
        let exponent_length = if exponent {
            // 2^3 < 10; this is a checked capacity bound, not spelling.
            let digits = usize::try_from(display_exponent.bits().div_ceil(3).max(1))
                .map_err(|_| arithmetic_error())?;
            digits
                .checked_add(1 + usize::from(display_exponent.sign() == Sign::Minus))
                .ok_or_else(arithmetic_error)?
        } else {
            0
        };
        buffer.reserve_chunks(display_exponent.bits())?;
        let prefix = format.prefix.unwrap_or_default();
        let suffix = format.suffix.unwrap_or_default();
        let length = [
            prefix.len(),
            usize::from(negative),
            integral,
            usize::from(fractional > 0),
            fractional,
            exponent_length,
            suffix.len(),
        ]
        .into_iter()
        .try_fold(0_usize, usize::checked_add)
        .filter(|length| isize::try_from(*length).is_ok())
        .ok_or_else(arithmetic_error)?;
        crate::operation::string(&buffer.text, length)?;
        buffer.text.try_reserve_exact(length).map_err(|error| {
            Error::Render(format!("numeric presentation output: {error}").into())
        })?;
        let text = &mut buffer.text;
        text.push_str(prefix);
        if negative {
            text.push('-');
        }
        emit_magnitude(text, &buffer.chunks, digits, point, fractional)?;
        if fractional > 0 && format.trailing_zeros == TrailingZeros::Trim {
            while text.ends_with('0') {
                text.pop();
            }
            if text.ends_with('.') {
                text.pop();
            }
        }
        if exponent {
            buffer.append_exponent(&display_exponent)?;
        }
        buffer.text.push_str(suffix);
        Ok(buffer.text)
    }

    fn emit_integer(
        &self,
        radix: NumericRadix,
        format: &ResolvedFormat<'_>,
        mut buffer: DecimalBuffer,
    ) -> Result<String> {
        let base: u32 = match radix {
            NumericRadix::Decimal => 10,
            NumericRadix::Binary => 2,
            NumericRadix::Octal => 8,
            NumericRadix::HexLower | NumericRadix::HexUpper => 16,
        };
        let zero = self.coefficient.bits() == 0;
        let power = if zero {
            0
        } else {
            u32::try_from(&self.exponent).map_err(|_| arithmetic_error())?
        };
        let bits = usize::try_from(self.coefficient.bits())
            .map_err(|_| arithmetic_error())?
            .checked_add(
                (power as usize)
                    .checked_mul(4)
                    .ok_or_else(arithmetic_error)?,
            )
            .and_then(|bits| bits.checked_add(1))
            .ok_or_else(arithmetic_error)?;
        let mut digits = Vec::new();
        crate::operation::vector(&digits, bits)?;
        digits
            .try_reserve_exact(bits)
            .map_err(|error| Error::Render(format!("numeric radix digits: {error}").into()))?;
        let mut magnitude = &self.coefficient * BigUint::from(10_u8).pow(power);
        let alphabet = if radix == NumericRadix::HexUpper {
            b"0123456789ABCDEF"
        } else {
            b"0123456789abcdef"
        };
        loop {
            let digit = usize::try_from(&magnitude % base).map_err(|_| arithmetic_error())?;
            digits.push(alphabet[digit]);
            magnitude /= base;
            if magnitude.bits() == 0 {
                break;
            }
        }
        let negative = self.negative && (!zero || format.negative_zero == NegativeZero::Preserve);
        let length = digits
            .len()
            .checked_add(usize::from(negative))
            .and_then(|n| n.checked_add(format.prefix.map_or(0, str::len)))
            .and_then(|n| n.checked_add(format.suffix.map_or(0, str::len)))
            .ok_or_else(arithmetic_error)?;
        crate::operation::string(&buffer.text, length)?;
        buffer
            .text
            .try_reserve_exact(length)
            .map_err(|error| Error::Render(format!("numeric radix output: {error}").into()))?;
        buffer.text.push_str(format.prefix.unwrap_or_default());
        if negative {
            buffer.text.push('-');
        }
        for digit in digits.iter().rev() {
            buffer.text.push(char::from(*digit));
        }
        buffer.text.push_str(format.suffix.unwrap_or_default());
        Ok(buffer.text)
    }
}

fn emit_magnitude(
    text: &mut String,
    chunks: &[u32],
    digits: usize,
    point: isize,
    fractional: usize,
) -> Result<()> {
    let integral_digits = usize::try_from(point.max(0)).map_err(|_| arithmetic_error())?;
    let taken = integral_digits.min(digits);
    if integral_digits == 0 {
        text.push('0');
    } else {
        visit_digits(chunks, 0..taken, |digits| {
            text.push_str(std::str::from_utf8(digits).expect("ASCII decimal digits"));
        });
        push_zeroes(text, integral_digits - taken);
    }
    let leading = if point < 0 { point.unsigned_abs() } else { 0 };
    let leading = fractional.min(leading);
    let copied = (fractional - leading).min(digits - taken);
    if fractional > 0 {
        text.push('.');
        push_zeroes(text, leading);
        visit_digits(chunks, taken..taken + copied, |digits| {
            text.push_str(std::str::from_utf8(digits).expect("ASCII decimal digits"));
        });
        push_zeroes(text, fractional - leading - copied);
    }
    let mut discarded_nonzero = false;
    visit_digits(chunks, taken + copied..digits, |digits| {
        discarded_nonzero |= digits.iter().any(|digit| *digit != b'0');
    });
    if discarded_nonzero {
        return Err(Error::Render(
            "numeric decimal emission would discard nonzero digits".into(),
        ));
    }
    Ok(())
}

fn chunk_width(value: u32) -> usize {
    if value == 0 {
        1
    } else {
        value.ilog10() as usize + 1
    }
}

/// View ordinary decimal digit spans without allocating a reversed digit string.
fn visit_digits(chunks: &[u32], range: std::ops::Range<usize>, mut visit: impl FnMut(&[u8])) {
    if range.is_empty() {
        return;
    }
    let mut offset = 0;
    for (index, &chunk) in chunks.iter().rev().enumerate() {
        let width = if index == 0 { chunk_width(chunk) } else { 9 };
        let end = offset + width;
        if range.start < end && range.end > offset {
            let mut bytes = [b'0'; 9];
            let mut value = chunk;
            for byte in bytes.iter_mut().rev() {
                *byte += u8::try_from(value % 10).expect("decimal digit");
                value /= 10;
            }
            let start = range.start.max(offset) - offset;
            let finish = range.end.min(end) - offset;
            visit(&bytes[9 - width + start..9 - width + finish]);
        }
        offset = end;
        if offset >= range.end {
            break;
        }
    }
}

fn push_zeroes(text: &mut String, mut count: usize) {
    const ZEROES: &str = "0000000000000000000000000000000000000000000000000000000000000000";
    while count > 0 {
        let part = count.min(ZEROES.len());
        text.push_str(&ZEROES[..part]);
        count -= part;
    }
}

fn arithmetic_error() -> Error {
    Error::Render("numeric presentation output length or decimal arithmetic overflow".into())
}

#[cfg(test)]
mod tests;