f-office-docx 0.2.3

DOCX model and Word's layout rules.
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
//! The number formats of chart labels: how a value label or a data label writes its value under
//! its number format code (`formatCode` of a `c:numFmt`, or the `c:formatCode` of a series'
//! cache), as a spreadsheet's number format code says (ECMA-376 Part 1, 18.8.31).

use std::cmp::Ordering;
use std::sync::Arc;

use f_office_paint::Rgb;
use f_office_units::scale::TENTHS;

use super::Decimal;
use crate::configuration::NumberSeparators;
use crate::params::{
    CHART_AXIS_GENERAL_CHARACTERS, CHART_DIGIT_GROUP, CHART_EXPONENT_DIGITS, CHART_FORMAT_RED,
    CHART_FORMAT_SECTIONS, CHART_GENERAL_CHARACTERS, CHART_NUMBER_SECTIONS,
    CHART_SIGNIFICANT_DIGITS,
};

/// How a chart's labels write their values.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LabelFormat(Form);

/// The kinds of [`LabelFormat`].
#[derive(Clone, Debug, PartialEq, Eq)]
enum Form {
    /// General with every digit of the value, as its cache writes it.
    AllDigits,
    /// General in a few characters, with these separators.
    General(NumberSeparators, LabelPlace),
    /// A format code with up to three sections.
    Code(Arc<Code>),
}

/// The text of a label in its number format: its pieces, and the color that the format's
/// section sets.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WrittenLabel {
    /// The pieces in their order.
    pub pieces: Vec<LabelPiece>,
    /// The color of the section's text (`[Red]`), or `None` for the label's own.
    pub color: Option<Rgb>,
}

/// Where a label stands, which sets the most characters that General writes in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LabelPlace {
    /// A data label: [`CHART_GENERAL_CHARACTERS`].
    Data,
    /// A numeric category label: [`CHART_GENERAL_CHARACTERS`], enabled under
    /// `ChartLabelFormats::Codes`.
    CategoryAxis,
    /// A value label of a value axis: [`CHART_AXIS_GENERAL_CHARACTERS`].
    ValueAxis,
}

impl LabelPlace {
    /// The most characters in which General writes a value at this place, its decimal point
    /// counted.
    const fn general_characters(self) -> usize {
        match self {
            Self::Data | Self::CategoryAxis => CHART_GENERAL_CHARACTERS,
            Self::ValueAxis => CHART_AXIS_GENERAL_CHARACTERS,
        }
    }

    /// Whether the minus sign of a value below zero counts in those characters: on a value
    /// label, not on a data or category label.
    const fn counts_sign(self) -> bool {
        match self {
            Self::Data | Self::CategoryAxis => false,
            Self::ValueAxis => true,
        }
    }
}

/// A piece of a written label.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LabelPiece {
    /// Text that the label draws.
    Text(String),
    /// A blank as wide as this character (`_` and the character in a format code).
    Blank(char),
}

impl LabelFormat {
    /// General with every digit of the value.
    #[must_use]
    pub(crate) const fn all_digits() -> Self {
        Self(Form::AllDigits)
    }

    /// General as a target that writes number formats writes it at `place`: the value,
    /// rounded half away from zero after [`CHART_SIGNIFICANT_DIGITS`] significant digits, then
    /// within the place's characters ([`LabelPlace::general_characters`]) in decimal or in
    /// scientific notation, whichever shows more of its significant digits, decimal when both
    /// show as many, without trailing zeros, with the decimal separator `separators` gives.
    #[must_use]
    pub(crate) const fn general(separators: NumberSeparators, place: LabelPlace) -> Self {
        Self(Form::General(separators, place))
    }

    /// The format of the code `code` with the machine's separators `separators`, or `None`
    /// when the code holds a part that F-Office does not write: more than four sections, a
    /// condition, a bracket other than `[Red]` or a currency-locale `[$<sym>-<lcid>]`, a
    /// fraction, a date or time, a text placeholder (`@`), an engineering exponent, a
    /// character that the code does not quote, or no code at all. A fourth section, for
    /// text, is left out.
    #[must_use]
    pub(crate) fn code(code: &str, separators: NumberSeparators) -> Option<Self> {
        if code.is_empty() {
            return None;
        }
        let texts = sections(code)?;
        let sections = texts
            .into_iter()
            .take(CHART_NUMBER_SECTIONS)
            .map(Section::read)
            .collect::<Option<Vec<_>>>()?;
        Some(Self(Form::Code(Arc::new(Code {
            sections,
            separators,
        }))))
    }

    /// The label of `value` in this format, or `None` when the format does not write the value:
    /// General for a value that needs more than [`CHART_GENERAL_CHARACTERS`] characters or
    /// whose digits it rounds away, or a section that writes nothing.
    #[must_use]
    pub fn write(&self, value: Decimal) -> Option<WrittenLabel> {
        let text = match &self.0 {
            Form::AllDigits => all_digits(value),
            Form::General(separators, place) => general(value, (*separators, *place))?,
            Form::Code(code) => return code.write(value),
        };
        Some(WrittenLabel {
            pieces: vec![LabelPiece::Text(text)],
            color: None,
        })
    }
}

/// A format code's sections and the machine's separators.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Code {
    /// One to three sections: for values at or above zero (all values when it is the only
    /// one), for values below zero, and for zero.
    sections: Vec<Section>,
    /// The decimal and group separators.
    separators: NumberSeparators,
}

impl Code {
    /// The label of `value`: rounded to [`CHART_SIGNIFICANT_DIGITS`] significant digits, in
    /// the section of its sign, a value below zero with a minus sign before a single section's
    /// text unless its number rounds to zero, and without one in its own section.
    fn write(&self, value: Decimal) -> Option<WrittenLabel> {
        let value = significant(value, CHART_SIGNIFICANT_DIGITS)?;
        let sign = value.digits.cmp(&0);
        let (section, minus) = match (self.sections.as_slice(), sign) {
            ([only], _) => (only, sign == Ordering::Less),
            ([_, below, ..], Ordering::Less) => (below, false),
            ([_, _, zero], Ordering::Equal) => (zero, false),
            ([above, ..], _) => (above, false),
            ([], _) => return None,
        };
        let number = match section.number {
            Some(digits) => {
                let shown = Decimal {
                    digits: value.digits.checked_abs()?,
                    exponent: value.exponent.checked_add(section.scale)?,
                };
                Some(digits.write(shown, self.separators)?)
            }
            None => None,
        };
        let rounds_to_zero = number
            .as_deref()
            .is_some_and(|pieces| !has_nonzero_digit(pieces));
        let mut pieces = Vec::new();
        if minus && !rounds_to_zero {
            pieces.push(LabelPiece::Text("-".to_owned()));
        }
        pieces.extend(section.before.iter().cloned());
        pieces.extend(number.into_iter().flatten());
        pieces.extend(section.after.iter().cloned());
        let pieces = joined(pieces);
        (!pieces.is_empty()).then_some(WrittenLabel {
            pieces,
            color: section.color,
        })
    }
}

/// Whether any text piece of `pieces` holds a nonzero digit (`1`..=`9`).
fn has_nonzero_digit(pieces: &[LabelPiece]) -> bool {
    pieces.iter().any(|piece| match piece {
        LabelPiece::Text(text) => text.chars().any(|ch| matches!(ch, '1'..='9')),
        LabelPiece::Blank(_) => false,
    })
}

/// One section of a format code: the literal pieces before and after its number, its number,
/// its color and the power of ten that it multiplies the value by.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Section {
    /// The text and blanks before the number.
    before: Vec<LabelPiece>,
    /// The number's digit placeholders, or `None` when the section writes no number.
    number: Option<Digits>,
    /// The text and blanks after the number.
    after: Vec<LabelPiece>,
    /// The color that the section names, or `None`.
    color: Option<Rgb>,
    /// The power of ten that the value is multiplied by: 2 for each percent sign, -3 for each
    /// comma after the last digit placeholder.
    scale: i32,
}

/// Where the reading of a section stands.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Stage {
    /// Before the number.
    Before,
    /// In the number's whole part, with the commas read since its last digit placeholder.
    Whole(i32),
    /// In the number's decimals, after the point, with the commas read since its last digit
    /// placeholder.
    Decimals(i32),
    /// In the scientific exponent's digits, after `E+` or `E-`.
    Exponent,
    /// After the number.
    After,
}

impl Stage {
    /// The stage after a comma read at this one: one more comma in the number, or `None` for a
    /// comma outside it.
    fn comma(self) -> Option<Self> {
        match self {
            Self::Whole(commas) => Some(Self::Whole(commas.checked_add(1)?)),
            Self::Decimals(commas) => Some(Self::Decimals(commas.checked_add(1)?)),
            Self::Before | Self::Exponent | Self::After => None,
        }
    }
}

impl Section {
    /// Reads the text of one section, or `None` when it holds a part that F-Office does not
    /// write.
    fn read(text: &str) -> Option<Self> {
        let mut section = Self::default();
        let mut digits = Digits::default();
        let mut stage = Stage::Before;
        let mut chars = text.chars();
        while let Some(ch) = chars.next() {
            stage = section.step(&mut digits, ch, &mut chars, stage)?;
        }
        if digits.exponent.is_some_and(|exp| exp.digits == 0) {
            return None;
        }
        section.end(stage)?;
        section.number = (stage != Stage::Before).then_some(digits);
        Some(section)
    }

    /// Reads one token starting at `ch` in `stage` and returns the next stage.
    fn step(
        &mut self,
        digits: &mut Digits,
        ch: char,
        chars: &mut std::str::Chars<'_>,
        stage: Stage,
    ) -> Option<Stage> {
        match ch {
            '0' | '#' | '?' => digits.placeholder(ch, stage),
            '.' => digits.point(stage),
            ',' => stage.comma(),
            'E' | 'e' => digits.start_exponent(ch, chars, stage),
            '*' => self.fill(chars, stage),
            '[' => self.bracket(&until(chars, ']')?, stage),
            '%' => self.percent(stage),
            _ => self.literal(literal(ch, chars)?, stage),
        }
    }

    /// Takes a repeating fill `*<ch>` read at `stage`, which writes no characters in chart
    /// labels and ends the number when it follows digit placeholders.
    fn fill(&mut self, rest: &mut std::str::Chars<'_>, stage: Stage) -> Option<Stage> {
        rest.next()?;
        if stage == Stage::Before {
            return Some(stage);
        }
        self.end(stage)?;
        Some(Stage::After)
    }

    /// Takes a percent sign read at `stage`, which writes itself and multiplies the value by a
    /// hundred, and gives the stage after it.
    fn percent(&mut self, stage: Stage) -> Option<Stage> {
        self.scale = self.scale.checked_add(2)?;
        self.literal(LabelPiece::Text("%".to_owned()), stage)
    }

    /// Takes the literal `piece` read at `stage`, and gives the stage after it: a literal
    /// after the number's first placeholder ends the number.
    fn literal(&mut self, piece: LabelPiece, stage: Stage) -> Option<Stage> {
        if stage == Stage::Before {
            self.before.push(piece);
            return Some(stage);
        }
        self.end(stage)?;
        self.after.push(piece);
        Some(Stage::After)
    }

    /// Ends the number at `stage`: each comma after its last digit placeholder drops a group
    /// of [`CHART_DIGIT_GROUP`] digits, scaling the value down by a thousand.
    fn end(&mut self, stage: Stage) -> Option<()> {
        if let Stage::Whole(commas) | Stage::Decimals(commas) = stage {
            let group = i32::try_from(CHART_DIGIT_GROUP).ok()?;
            self.scale = self.scale.checked_sub(commas.checked_mul(group)?)?;
        }
        Some(())
    }

    /// Takes a bracketed token `[...]` read at `stage`: either `[Red]` (in any case) or a
    /// currency-locale prefix `[$<sym>]` / `[$<sym>-<lcid>]` with a non-empty currency symbol.
    fn bracket(&mut self, token: &str, stage: Stage) -> Option<Stage> {
        if let Some(currency) = token.strip_prefix('$') {
            let symbol = currency.split('-').next()?;
            if symbol.is_empty() {
                return None;
            }
            return self.literal(LabelPiece::Text(symbol.to_owned()), stage);
        }
        if self.color.is_some() || !token.eq_ignore_ascii_case("Red") {
            return None;
        }
        self.color = Some(CHART_FORMAT_RED);
        Some(stage)
    }
}

/// The literal piece that `ch` starts, reading what it needs of `rest`: quoted text, an
/// escaped character, a blank, a percent sign, or a character that a code writes without
/// quotes. `None` for any other character.
fn literal(ch: char, rest: &mut std::str::Chars<'_>) -> Option<LabelPiece> {
    match ch {
        '"' => until(rest, '"').map(LabelPiece::Text),
        '\\' => rest
            .next()
            .map(|escaped| LabelPiece::Text(escaped.to_string())),
        '_' => rest.next().map(LabelPiece::Blank),
        '%' | '$' | '-' | '+' | '/' | '(' | ')' | ':' | '!' | '^' | '&' | '\'' | '~' | '{'
        | '}' | '<' | '>' | '=' | ' ' => Some(LabelPiece::Text(ch.to_string())),
        _ => None,
    }
}

/// The characters of `rest` up to `end`, which is taken out, or `None` without `end`.
fn until(rest: &mut std::str::Chars<'_>, end: char) -> Option<String> {
    let mut text = String::new();
    for ch in rest.by_ref() {
        if ch == end {
            return Some(text);
        }
        text.push(ch);
    }
    None
}

/// The sections of `code`, split at each `;` outside quotes and escapes, or `None` for more
/// than [`CHART_FORMAT_SECTIONS`].
fn sections(code: &str) -> Option<Vec<&str>> {
    let mut sections = Vec::new();
    let (mut start, mut quoted, mut escaped) = (0, false, false);
    for (at, ch) in code.char_indices() {
        match ch {
            _ if escaped => escaped = false,
            '\\' if !quoted => escaped = true,
            '"' => quoted = !quoted,
            ';' if !quoted => {
                sections.push(code.get(start..at)?);
                start = at + 1;
            }
            _ => {}
        }
    }
    sections.push(code.get(start..)?);
    (sections.len() <= CHART_FORMAT_SECTIONS).then_some(sections)
}

/// The adjacent text pieces of `pieces` joined.
fn joined(pieces: Vec<LabelPiece>) -> Vec<LabelPiece> {
    let mut out: Vec<LabelPiece> = Vec::with_capacity(pieces.len());
    for piece in pieces {
        match (out.last_mut(), piece) {
            (Some(LabelPiece::Text(last)), LabelPiece::Text(text)) => last.push_str(&text),
            (_, piece) => out.push(piece),
        }
    }
    out
}

/// The scientific exponent of a section's number (`E+00`, `E-00`, `e+00`, `e-00`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Exponent {
    /// Whether the exponent letter is uppercase (`E`) rather than lowercase (`e`).
    upper: bool,
    /// Whether non-negative exponents write `+` (`E+`), rather than omitting it (`E-`).
    always_plus: bool,
    /// The minimum number of exponent digits (`0` placeholders after `E+`/`E-`).
    digits: u32,
}

/// The digit placeholders of a section's number.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Digits {
    /// The placeholders of the whole part.
    whole_places: u32,
    /// The digits that the whole part writes at least: its placeholders from its first `0`.
    whole: u32,
    /// The placeholders of the whole part from its first `?` or `0`: missing positions above
    /// `whole` write space-wide blanks.
    whole_pad: u32,
    /// Whether the whole part writes its digits in groups (`,` between its placeholders).
    grouped: bool,
    /// Whether the number writes the decimal separator.
    point: bool,
    /// The decimals that it writes always: its placeholders after the point up to the last
    /// `0`.
    fixed: u32,
    /// The decimals padded with space-wide blanks when omitted: up to the last `?` after the
    /// point.
    decimal_pad: u32,
    /// The decimals that it writes at most: its placeholders after the point.
    most: u32,
    /// Scientific notation exponent, when the format holds `E+`/`E-` after one whole placeholder.
    exponent: Option<Exponent>,
}

impl Digits {
    /// Takes the digit placeholder `ch` (`0`, `#`, or `?`) read at `stage`, and gives the
    /// stage after it, or `None` for a placeholder after the number.
    fn placeholder(&mut self, ch: char, stage: Stage) -> Option<Stage> {
        match stage {
            Stage::Before => self.whole_placeholder(ch, 0),
            Stage::Whole(commas) => self.whole_placeholder(ch, commas),
            Stage::Decimals(0) => self.decimal_placeholder(ch),
            Stage::Exponent => self.exponent_placeholder(ch),
            Stage::Decimals(_) | Stage::After => None,
        }
    }

    /// Takes the digit placeholder `ch` of the whole part, read after `commas` commas since the
    /// last one: a comma between placeholders groups the digits.
    fn whole_placeholder(&mut self, ch: char, commas: i32) -> Option<Stage> {
        self.grouped |= commas > 0;
        self.whole_places = self.whole_places.checked_add(1)?;
        if ch == '0' || self.whole > 0 {
            self.whole = self.whole.checked_add(1)?;
        }
        if ch == '0' || ch == '?' || self.whole_pad > 0 {
            self.whole_pad = self.whole_pad.checked_add(1)?;
        }
        Some(Stage::Whole(0))
    }

    /// Takes the digit placeholder `ch` of the fractional part.
    fn decimal_placeholder(&mut self, ch: char) -> Option<Stage> {
        self.most = self.most.checked_add(1)?;
        if ch == '0' {
            self.fixed = self.most;
        } else if ch == '?' {
            self.decimal_pad = self.most;
        }
        Some(Stage::Decimals(0))
    }

    /// Takes a digit placeholder `ch` of the scientific exponent (`0` only).
    fn exponent_placeholder(&mut self, ch: char) -> Option<Stage> {
        if ch != '0' {
            return None;
        }
        let exp = self.exponent.as_mut()?;
        exp.digits = exp.digits.checked_add(1)?;
        Some(Stage::Exponent)
    }

    /// Starts a scientific exponent (`E+` or `E-`) after a single ungrouped whole placeholder.
    fn start_exponent(
        &mut self,
        ch: char,
        rest: &mut std::str::Chars<'_>,
        stage: Stage,
    ) -> Option<Stage> {
        let valid_stage = matches!(stage, Stage::Whole(0) | Stage::Decimals(0));
        if !valid_stage || self.whole_places != 1 || self.grouped || self.decimal_pad > 0 {
            return None;
        }
        let always_plus = match rest.next()? {
            '+' => true,
            '-' => false,
            _ => return None,
        };
        self.exponent = Some(Exponent {
            upper: ch == 'E',
            always_plus,
            digits: 0,
        });
        Some(Stage::Exponent)
    }

    /// Takes the decimal point read at `stage`, and gives the stage after it, or `None` for a
    /// second point or a point after the number.
    fn point(&mut self, stage: Stage) -> Option<Stage> {
        match stage {
            Stage::Before | Stage::Whole(0) => {
                self.point = true;
                Some(Stage::Decimals(0))
            }
            Stage::Whole(_) | Stage::Decimals(_) | Stage::Exponent | Stage::After => None,
        }
    }

    /// The pieces of `value`, at or above zero, rounded half away from zero to the most
    /// decimals, with at least the whole digits and the fixed decimals, space-wide blanks for
    /// omitted `?` placeholders, the group separator between groups of [`CHART_DIGIT_GROUP`]
    /// digits of a grouped whole part, and the decimal separator or scientific exponent where
    /// the format writes it.
    fn write(self, value: Decimal, separators: NumberSeparators) -> Option<Vec<LabelPiece>> {
        if let Some(exp) = self.exponent {
            return self.write_scientific(value, separators, exp);
        }
        let (text, lead_blanks, trail_blanks) = self.format_decimal(value, separators)?;
        let mut pieces = vec![LabelPiece::Blank(' '); lead_blanks];
        if !text.is_empty() {
            pieces.push(LabelPiece::Text(text));
        }
        pieces.extend(std::iter::repeat_n(LabelPiece::Blank(' '), trail_blanks));
        Some(pieces)
    }

    /// Formats `value`, at or above zero, in fixed/grouped decimal form, returning its text
    /// along with the counts of leading and trailing `?` space blanks.
    fn format_decimal(
        self,
        value: Decimal,
        separators: NumberSeparators,
    ) -> Option<(String, usize, usize)> {
        let rounded = places(value, self.most)?;
        let (whole, mut decimals) = split(rounded, self.most)?;
        let fixed = usize::try_from(self.fixed).ok()?;
        while decimals.len() > fixed && decimals.ends_with('0') {
            decimals.pop();
        }
        let shown = whole.trim_start_matches('0');
        let least = usize::try_from(self.whole).ok()?;
        let zeros = least.saturating_sub(shown.len());
        let lead_blanks = usize::try_from(self.whole_pad)
            .ok()?
            .saturating_sub(shown.len() + zeros);
        let mut text = "0".repeat(zeros);
        text.push_str(shown);
        if self.grouped {
            text = grouped(&text, separators.group());
        }
        if self.point {
            text.push(separators.decimal());
            text.push_str(&decimals);
        }
        let trail_blanks = usize::try_from(self.decimal_pad)
            .ok()?
            .saturating_sub(decimals.len());
        Some((text, lead_blanks, trail_blanks))
    }

    /// Formats `value`, at or above zero, in scientific notation (`0.00E+00`).
    fn write_scientific(
        self,
        value: Decimal,
        separators: NumberSeparators,
        exp: Exponent,
    ) -> Option<Vec<LabelPiece>> {
        let (power, mantissa) = if value.digits == 0 {
            (
                0_i64,
                Decimal {
                    digits: 0,
                    exponent: 0,
                },
            )
        } else {
            let rounded = significant(value, self.most.checked_add(1)?)?.normalized();
            let power = leading_power(rounded);
            let exponent = rounded.exponent.checked_sub(i32::try_from(power).ok()?)?;
            (
                power,
                Decimal {
                    digits: rounded.digits,
                    exponent,
                },
            )
        };
        let (text, _, _) = self.format_decimal(mantissa, separators)?;
        let width = usize::try_from(exp.digits).ok()?;
        let letter = if exp.upper { 'E' } else { 'e' };
        let sign = if power < 0 {
            "-"
        } else if exp.always_plus {
            "+"
        } else {
            ""
        };
        let shown = format!("{text}{letter}{sign}{:0>width$}", power.unsigned_abs());
        Some(vec![LabelPiece::Text(shown)])
    }
}

/// `digits` with `separator` between each group of [`CHART_DIGIT_GROUP`] digits from the
/// right.
fn grouped(digits: &str, separator: char) -> String {
    let count = digits.chars().count();
    let mut out = String::with_capacity(digits.len() + count / CHART_DIGIT_GROUP);
    for (at, ch) in digits.chars().enumerate() {
        if at > 0 && (count - at).is_multiple_of(CHART_DIGIT_GROUP) {
            out.push(separator);
        }
        out.push(ch);
    }
    out
}

/// The whole digits and exactly `decimals` decimal digits of `value`, at or above zero, whose
/// exponent is at least `-decimals`: the whole part `0` for a value below one.
fn split(value: Decimal, decimals: u32) -> Option<(String, String)> {
    let digits = value.digits.unsigned_abs().to_string();
    let shift = i64::from(value.exponent) + i64::from(decimals);
    let zeros = usize::try_from(shift).ok()?;
    let all = format!("{digits}{}", "0".repeat(zeros));
    let decimals = usize::try_from(decimals).ok()?;
    let padded = format!("{all:0>width$}", width = decimals + 1);
    let (whole, fraction) = padded.split_at(padded.len() - decimals);
    Some((whole.to_owned(), fraction.to_owned()))
}

/// The count of the digits of `digits`, at least one.
fn digit_count(digits: i64) -> u32 {
    digits
        .unsigned_abs()
        .checked_ilog10()
        .map_or(1, |log| log + 1)
}

/// The count of the digits of the whole part of `value`, at least one.
fn whole_digits(value: Decimal) -> Option<usize> {
    let whole = i64::from(digit_count(value.digits)) + i64::from(value.exponent);
    usize::try_from(whole.max(1)).ok()
}

/// `value` rounded half away from zero to `count` significant digits.
fn significant(value: Decimal, count: u32) -> Option<Decimal> {
    match digit_count(value.digits).checked_sub(count) {
        Some(drop) if drop > 0 => dropped(value, drop),
        _ => Some(value),
    }
}

/// `value` rounded half away from zero to `count` decimals.
fn places(value: Decimal, count: u32) -> Option<Decimal> {
    let below = -i64::from(value.exponent) - i64::from(count);
    match u32::try_from(below) {
        Ok(drop) if drop > 0 => dropped(value, drop),
        _ => Some(value),
    }
}

/// `value` without its last `drop` digits, rounded half away from zero, with its exponent
/// raised by `drop`. Beyond the 19 digits that a value holds, it rounds to zero.
fn dropped(value: Decimal, drop: u32) -> Option<Decimal> {
    let exponent = value.exponent.checked_add(i32::try_from(drop).ok()?)?;
    let Some(power) = i128::from(TENTHS).checked_pow(drop) else {
        return Some(Decimal {
            digits: 0,
            exponent,
        });
    };
    let digits = i128::from(value.digits);
    let rest = digits.checked_rem(power)?.checked_abs()?;
    let away = rest.checked_mul(2)? >= power;
    let kept = digits.checked_div(power)? + if away { digits.signum() } else { 0 };
    Some(Decimal {
        digits: i64::try_from(kept).ok()?,
        exponent,
    })
}

/// Every digit of `value`, as its cache writes it: the digits and the sign of the value, with
/// the decimal point where its exponent puts it.
pub(crate) fn all_digits(value: Decimal) -> String {
    let value = value.normalized();
    let sign = if value.digits < 0 { "-" } else { "" };
    let digits = value.digits.unsigned_abs().to_string();
    match usize::try_from(-value.exponent) {
        Ok(0) | Err(_) => {
            let zeros = usize::try_from(value.exponent).unwrap_or(0);
            format!("{sign}{digits}{}", "0".repeat(zeros))
        }
        Ok(places) if places < digits.len() => {
            let (whole, fraction) = digits.split_at(digits.len() - places);
            format!("{sign}{whole}.{fraction}")
        }
        Ok(places) => format!("{sign}0.{}{digits}", "0".repeat(places - digits.len())),
    }
}

/// `value` in General at `place`: rounded to [`CHART_SIGNIFICANT_DIGITS`] significant digits,
/// then within the place's characters ([`LabelPlace::general_characters`], the minus sign
/// counted only where [`LabelPlace::counts_sign`]) in decimal ([`general_decimal`]) when that
/// shows at least as many of the value's significant digits as scientific notation
/// ([`general_scientific`]), and in scientific notation otherwise. `None` when neither fits.
fn general(value: Decimal, (separators, place): (NumberSeparators, LabelPlace)) -> Option<String> {
    let value = significant(value, CHART_SIGNIFICANT_DIGITS)?.normalized();
    if value.digits == 0 {
        return Some("0".to_owned());
    }
    let below = value.digits < 0;
    let room = place
        .general_characters()
        .checked_sub(usize::from(below && place.counts_sign()))?;
    let magnitude = Decimal {
        digits: value.digits.checked_abs()?,
        exponent: value.exponent,
    };
    let held = i64::from(digit_count(magnitude.digits));
    let decimal = general_decimal(magnitude, (separators, room));
    let scientific = general_scientific(magnitude, (separators, room));
    let text = match (decimal, scientific) {
        (Some((text, shown)), Some((_, other))) if shown.min(held) >= other.min(held) => text,
        (Some((text, _)), None) | (_, Some((text, _))) => text,
        (None, None) => return None,
    };
    Some(if below { format!("-{text}") } else { text })
}

/// `magnitude`, above zero, in decimal within `room` characters: rounded to the most decimals
/// that fit, without trailing zeros, and the count of the significant digits that those
/// decimals can hold. `None` when its whole part does not fit, or when the rounding leaves zero.
fn general_decimal(
    magnitude: Decimal,
    (separators, room): (NumberSeparators, usize),
) -> Option<(String, i64)> {
    let left = room.checked_sub(whole_digits(magnitude)?)?;
    let decimals = u32::try_from(left.saturating_sub(1)).ok()?;
    let shown = i64::from(decimals) + leading_power(magnitude) + 1;
    let rounded = places(magnitude, decimals)?.normalized();
    if rounded.digits == 0 {
        return None;
    }
    let (mut text, fraction) = split(rounded, decimals)?;
    let fraction = fraction.trim_end_matches('0');
    if !fraction.is_empty() {
        text.push(separators.decimal());
        text.push_str(fraction);
    }
    (text.chars().count() <= room).then_some((text, shown))
}

/// `magnitude`, above zero, in scientific notation within `room` characters: one digit, the
/// decimal separator and the most digits that fit, rounded half away from zero, then `E`, the
/// exponent's sign and at least [`CHART_EXPONENT_DIGITS`] digits of the exponent, without the
/// zeros at the end of its digits, such as `1.6E+09`; and the count of the significant digits
/// that it can hold. `None` when not even its first digit fits.
fn general_scientific(
    magnitude: Decimal,
    (separators, room): (NumberSeparators, usize),
) -> Option<(String, i64)> {
    let mut best = None;
    for kept in 1..=CHART_SIGNIFICANT_DIGITS {
        let (length, text) = scientific(magnitude, kept, separators)?;
        if length > room {
            break;
        }
        best = Some((text, i64::from(kept)));
    }
    best
}

/// `value`, not zero, rounded half away from zero to `kept` significant digits, in scientific
/// notation without its sign: the length of the text with all `kept` digits, and the text
/// without the zeros at the end of its digits.
fn scientific(value: Decimal, kept: u32, separators: NumberSeparators) -> Option<(usize, String)> {
    let rounded = significant(value, kept)?.normalized();
    let power = leading_power(rounded);
    let digits = rounded.digits.unsigned_abs().to_string();
    let width = usize::try_from(kept).ok()?;
    let padded = format!("{digits:0<width$}");
    let (first, rest) = padded.split_at(1);
    let width = usize::try_from(CHART_EXPONENT_DIGITS).ok()?;
    let exponent_sign = if power < 0 { '-' } else { '+' };
    let exponent = format!("E{exponent_sign}{:0>width$}", power.unsigned_abs());
    let length = padded.len() + usize::from(!rest.is_empty()) + exponent.len();
    let rest = rest.trim_end_matches('0');
    let text = if rest.is_empty() {
        format!("{first}{exponent}")
    } else {
        format!("{first}{}{rest}{exponent}", separators.decimal())
    };
    Some((length, text))
}

/// The power of ten of the first digit of `value`, not zero: `9` for 1,600,000,000 and `-5` for
/// 0.0000123.
fn leading_power(value: Decimal) -> i64 {
    i64::from(digit_count(value.digits)) - 1 + i64::from(value.exponent)
}

#[cfg(test)]
mod tests;