kakemono 0.22.1

Convert PDF, Word and EPUB documents and web pages to HTML, Markdown, EPUB, LaTeX and JSON in Rust
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
//! Numbers formatted as Excel shows them in a cell: with the cell's
//! number format, built-in (by id) or custom (a format code such as
//! `#,##0.00;(#,##0.00)`).
//!
//! A format code has up to four sections, `positive;negative;zero;text`,
//! made of digit placeholders (`0`, `#`, `?`), the decimal point, `,`
//! (thousands, or a scale of 1000 after the last digit), `%`, an exponent
//! (`E+`), fractions (`?/?`), literal text (quoted, escaped with `\`, or
//! `[$€-407]`) and, for dates and times, `y m d h s AM/PM [h]`. Conditions
//! (`[>100]`) are left out, and so is the padding (`_x`); a colour
//! (`[Red]`, `[Color10]`) writes nothing, and [`color`] gives it; the fill (`*x`, which repeats a character to the cell's width)
//! writes nothing, and [`format_filled`] says where it is.
//!
//! Dates and times are always written ISO (`2024-01-31`, `14:05`,
//! `2024-01-31 14:05`, with seconds only when the code shows them),
//! whatever order and separators the code uses; `.` is the decimal point
//! and `,` the thousands separator, whatever the locale.

/// The number format of a cell.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub(crate) enum NumFmt {
    /// Excel's `General`: the number as it is, up to 11 significant digits.
    #[default]
    General,
    /// A format code.
    Code(String),
}

/// Significant digits of Excel's General format in a cell.
const GENERAL_DIGITS: i32 = 11;
/// Significant digits of the mantissa when General writes a number in
/// scientific notation (`1.23457E+11`).
const GENERAL_SCIENTIFIC_DIGITS: usize = 6;
/// Below this magnitude, General writes a number in scientific notation.
const GENERAL_SMALLEST: f64 = 1e-9;
/// Significant digits Excel keeps of a number before formatting it.
const EXCEL_DIGITS: usize = 15;
/// The last serial of a date: 9999-12-31 in the 1900 system.
const MAX_SERIAL_1900: f64 = 2_958_465.0;
/// The last serial of a date in the 1904 system (9999-12-31).
const MAX_SERIAL_1904: f64 = MAX_SERIAL_1900 - 1462.0;
/// The serial of 1900-02-29, a day Excel has and the calendar has not.
const LEAP_DAY_1900: i64 = 60;
/// The most digits a fraction's denominator is searched with (`???/???`).
const MAX_FRACTION_DIGITS: usize = 3;
/// The longest format code Excel accepts, in characters; a longer one is
/// read as General.
const MAX_CODE_CHARS: usize = 255;
/// The most decimals of the seconds a time shows (`ss.000`).
const MAX_SECOND_DECIMALS: usize = 3;
/// Seconds in a day.
const DAY_SECONDS: i64 = 86_400;
/// Days from 1970-01-01 back to 1899-12-30, the day before serial 1 that
/// serials after the leap day of 1900 count from.
const EPOCH_1900_DAYS: i64 = -25_569;
/// Days from 1970-01-01 back to 1904-01-01, serial 0 of the 1904 system.
const EPOCH_1904_DAYS: i64 = -24_107;

/// The number format of a built-in id, as Excel (en-US) defines it, except
/// that dates and times are ISO and the currency formats have no symbol.
/// An id Excel does not define is General.
pub(crate) fn builtin(id: u32) -> NumFmt {
    let code = match id {
        1 => "0",
        2 => "0.00",
        3 => "#,##0",
        4 => "#,##0.00",
        5 | 6 => "#,##0_);(#,##0)",
        7 | 8 => "#,##0.00_);(#,##0.00)",
        9 => "0%",
        10 => "0.00%",
        11 => "0.00E+00",
        12 => "# ?/?",
        13 => "# ??/??",
        // The dates and times of en-US, and those of the East Asian
        // locales (27–36, 50–58), all written ISO.
        14..=17 | 27..=31 | 34..=36 | 50..=58 => "yyyy-mm-dd",
        18 | 20 | 32 => "hh:mm",
        19 | 21 | 33 => "hh:mm:ss",
        22 => "yyyy-mm-dd hh:mm",
        37 | 38 => "#,##0 ;(#,##0)",
        39 | 40 => "#,##0.00;(#,##0.00)",
        41 | 42 => "_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)",
        43 | 44 => "_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)",
        45 => "mm:ss",
        46 => "[h]:mm:ss",
        47 => "mm:ss.0",
        48 => "##0.0E+0",
        49 => "@",
        _ => return NumFmt::General,
    };
    NumFmt::Code(code.to_string())
}

/// Whether `fmt` shows a date or a time.
pub(crate) fn is_date(fmt: &NumFmt) -> bool {
    match fmt {
        NumFmt::General => false,
        NumFmt::Code(code) => sections(code).first().is_some_and(|tokens| is_date_section(tokens)),
    }
}

/// Marks the fill (`*x`) in the text a section writes.
const FILL_MARK: char = '\u{1}';

/// `value` as Excel shows it with the format `fmt`; `date1904` when the
/// workbook counts dates from 1904. The fill (`*x`) of an accounting
/// format, which sets its parts apart across the cell (`$` at the left
/// edge, the amount at the right), is a space between them: `$ -`,
/// `$ 1,234.00`.
pub(crate) fn format(value: f64, fmt: &NumFmt, date1904: bool) -> String {
    let (text, fill) = format_filled(value, fmt, date1904);
    match fill.and_then(|at| Some((text.get(..at)?, text.get(at..)?))) {
        Some((before, after))
            if !before.trim().is_empty()
                && !after.trim().is_empty()
                && !before.ends_with(' ')
                && !after.starts_with(' ') =>
        {
            format!("{before} {after}")
        }
        _ => text,
    }
}

/// `value` as [`format`] writes it, and where in it (a byte offset) the
/// fill of its section (`*x`) widens it to the cell's width: an
/// accounting format (`_("$"* #,##0.00_)`) sets the currency at the left
/// edge and the number at the right. `None` when the code has no fill.
pub(crate) fn format_filled(value: f64, fmt: &NumFmt, date1904: bool) -> (String, Option<usize>) {
    let mut text = formatted(value, fmt, date1904);
    let fill = text.find(FILL_MARK);
    if fill.is_some() {
        text.retain(|ch| ch != FILL_MARK);
    }
    (text, fill)
}

/// `value` as Excel shows it with the format `fmt`, with [`FILL_MARK`]
/// where the fill is.
fn formatted(value: f64, fmt: &NumFmt, date1904: bool) -> String {
    let NumFmt::Code(code) = fmt else {
        return general(value);
    };
    // An overlong code is not one Excel writes, and it would be slow.
    if !value.is_finite() || code.chars().count() > MAX_CODE_CHARS {
        return general(value);
    }
    let sections = sections(code);
    // An empty code is General; only an empty section of a longer code
    // (`;;;`) hides the value.
    if sections.len() == 1 && sections[0].is_empty() {
        return general(value);
    }
    if sections.first().is_some_and(|tokens| is_date_section(tokens)) {
        return date_time(value, &sections[0], date1904).unwrap_or_else(|| general(value));
    }
    // Which section shows the value, and whether it writes the minus sign
    // itself (a negative section does, by its literal text).
    let (tokens, minus) = match (sections.len(), value) {
        (0, _) => return general(value),
        (1, _) => (&sections[0], value < 0.0),
        (_, negative) if negative < 0.0 => (&sections[1], false),
        (2, _) => (&sections[0], false),
        (_, 0.0) => (&sections[2], false),
        _ => (&sections[0], false),
    };
    if tokens.is_empty() {
        return String::new();
    }
    let text = number(value.abs(), tokens);
    // A value that rounds to zero is written without a minus sign.
    let shows_digit = text.bytes().any(|byte| byte.is_ascii_digit() && byte != b'0');
    let sign = if minus && shows_digit { "-" } else { "" };
    format!("{sign}{}", text.trim())
}

/// The colours a format code may name (`[Red]`), as indices of the
/// legacy palette: `[Color1]` is its index 8, black.
const NAMED_COLORS: [(&str, u8); 8] = [
    ("black", 8),
    ("white", 9),
    ("red", 10),
    ("green", 11),
    ("blue", 12),
    ("yellow", 13),
    ("magenta", 14),
    ("cyan", 15),
];
/// The palette index of `[Color1]`.
const FIRST_COLOR_INDEX: u8 = 8;
/// The most `[ColorN]` names: `[Color56]`.
const MAX_COLOR_NUMBER: u8 = 56;

/// The colour, as an index of the legacy palette, that the section of
/// `fmt` showing `value` sets the text in (`[Red]`, `[Color10]`); `None`
/// when it names none.
pub(crate) fn color(value: f64, fmt: &NumFmt) -> Option<u8> {
    let NumFmt::Code(code) = fmt else { return None };
    if code.chars().count() > MAX_CODE_CHARS {
        return None;
    }
    // The colour of each section, split as `sections` does.
    let mut colors = vec![None];
    let mut chars = code.chars();
    while let Some(ch) = chars.next() {
        match ch {
            ';' => colors.push(None),
            '"' => {
                chars.by_ref().find(|&next| next == '"');
            }
            '\\' | '_' | '*' => {
                chars.next();
            }
            '[' => {
                let inside: String = chars.by_ref().take_while(|&next| next != ']').collect();
                let last = colors.last_mut().expect("there is always a section");
                *last = last.or_else(|| color_name(&inside));
            }
            _ => {}
        }
    }
    // The section shown, as `formatted` picks it.
    let index = match (colors.len(), value) {
        (1, _) => 0,
        (_, negative) if negative < 0.0 => 1,
        (2, _) => 0,
        (_, 0.0) => 2,
        _ => 0,
    };
    colors.get(index).copied().flatten()
}

/// The palette index of the colour named `name` in a format code (`Red`,
/// `Color10`).
fn color_name(name: &str) -> Option<u8> {
    let lower = name.trim().to_ascii_lowercase();
    if let Some(number) = lower.strip_prefix("color") {
        let number = number
            .parse::<u8>()
            .ok()
            .filter(|number| (1..=MAX_COLOR_NUMBER).contains(number))?;
        return Some(FIRST_COLOR_INDEX + number - 1);
    }
    NAMED_COLORS
        .iter()
        .find(|(named, _)| *named == lower)
        .map(|(_, index)| *index)
}

/// One piece of a section of a format code.
#[derive(Debug, Clone, PartialEq)]
enum Token {
    /// Text written as it is.
    Literal(String),
    /// A digit placeholder: `0` (a digit, zero when there is none), `#`
    /// (a digit, nothing when there is none) or `?` (a digit, a space).
    Digit(char),
    /// The decimal point.
    Point,
    /// A comma: thousands separators, or a scale of 1000 after the digits.
    Comma,
    /// `%`: the number times 100.
    Percent,
    /// The exponent: `E+` (sign always written) or `E-` (only the minus).
    Exponent { plus: bool },
    /// The bar of a fraction.
    Slash,
    /// `General` inside a code, or the text placeholder `@`, which shows
    /// a number as General does.
    General,
    /// A date or time part.
    Date(DatePart),
    /// The fill (`*x`): the character repeated to the cell's width.
    Fill,
}

/// A date or time part of a format code.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DatePart {
    /// `yy` or `yyyy`.
    Year,
    /// `m`: the month, or the minutes after hours or before seconds.
    MonthOrMinute,
    /// `d` or `dd` (`ddd` and `dddd`, the weekday, too).
    Day,
    /// `h` or `hh`.
    Hour,
    /// `m` or `mm` read as the minutes.
    Minute,
    /// `s` or `ss`.
    Second,
    /// `AM/PM` or `A/P`.
    AmPm,
    /// `[h]`, `[mm]` or `[ss]`: a duration, whose hours go past 24.
    Elapsed,
}

/// The sections of `code`, each as its tokens.
fn sections(code: &str) -> Vec<Vec<Token>> {
    let chars: Vec<char> = code.chars().collect();
    let mut sections = vec![Vec::new()];
    let mut at = 0;
    while at < chars.len() {
        let ch = chars[at];
        let tokens = sections.last_mut().expect("there is always a section");
        at += 1;
        match ch {
            ';' => sections.push(Vec::new()),
            '"' | '[' => {
                let close = if ch == '"' { '"' } else { ']' };
                let len = chars[at..]
                    .iter()
                    .position(|&next| next == close)
                    .unwrap_or(chars.len() - at);
                let inside: String = chars[at..at + len].iter().collect();
                at += len + 1;
                if ch == '"' {
                    tokens.push(Token::Literal(inside));
                } else {
                    tokens.extend(bracket(&inside));
                }
            }
            '\\' => {
                if let Some(&next) = chars.get(at) {
                    tokens.push(Token::Literal(next.to_string()));
                }
                at += 1;
            }
            // Padding to the width of a character: not text.
            '_' => at += 1,
            '*' => {
                if !tokens.contains(&Token::Fill) {
                    tokens.push(Token::Fill);
                }
                at += 1;
            }
            '0' | '#' | '?' => tokens.push(Token::Digit(ch)),
            '.' => tokens.push(Token::Point),
            ',' => tokens.push(Token::Comma),
            '%' => tokens.push(Token::Percent),
            '/' => tokens.push(Token::Slash),
            // The text placeholder shows a number as General does.
            '@' => tokens.push(Token::General),
            'E' | 'e' if matches!(chars.get(at), Some('+' | '-')) => {
                tokens.push(Token::Exponent { plus: chars[at] == '+' });
                at += 1;
            }
            _ => {
                let (token, len) = word(&chars[at - 1..]);
                tokens.push(token);
                at += len - 1;
            }
        }
    }
    sections
}

/// The token of a bracketed part (without its brackets): the symbol of a
/// currency (`$€-407`), an elapsed time (`h`, `mm`), or nothing (a colour,
/// a condition, a locale).
fn bracket(inside: &str) -> Option<Token> {
    if let Some(currency) = inside.strip_prefix('$') {
        let symbol = currency.split('-').next().unwrap_or_default();
        return (!symbol.is_empty()).then(|| Token::Literal(symbol.to_string()));
    }
    let elapsed = !inside.is_empty()
        && inside
            .chars()
            .all(|letter| matches!(letter.to_ascii_lowercase(), 'h' | 'm' | 's'));
    elapsed.then_some(Token::Date(DatePart::Elapsed))
}

/// The token at the start of `chars` (`General`, `AM/PM`, a date part such
/// as `yyyy`, or one literal character) and how many characters it takes.
fn word(chars: &[char]) -> (Token, usize) {
    for (name, token) in [
        ("general", Token::General),
        ("am/pm", Token::Date(DatePart::AmPm)),
        ("a/p", Token::Date(DatePart::AmPm)),
    ] {
        if starts_with(chars, name) {
            return (token, name.len());
        }
    }
    let ch = chars[0];
    let part = match ch.to_ascii_lowercase() {
        'y' | 'e' => DatePart::Year,
        'm' => DatePart::MonthOrMinute,
        'd' => DatePart::Day,
        'h' => DatePart::Hour,
        's' => DatePart::Second,
        _ => return (Token::Literal(ch.to_string()), 1),
    };
    // A run of the same letter (`yyyy`) is one part.
    let len = chars.iter().take_while(|next| next.eq_ignore_ascii_case(&ch)).count();
    (Token::Date(part), len)
}

/// Whether `chars` starts with `word`, ignoring case.
fn starts_with(chars: &[char], word: &str) -> bool {
    chars.len() >= word.len()
        && word
            .chars()
            .zip(chars)
            .all(|(letter, ch)| ch.eq_ignore_ascii_case(&letter))
}

/// Whether a section shows a date or a time.
fn is_date_section(tokens: &[Token]) -> bool {
    tokens.iter().any(|token| matches!(token, Token::Date(_)))
}

/// The date parts of a section, with each `m` read as the month or the
/// minutes: minutes right after hours or right before seconds.
fn date_parts(tokens: &[Token]) -> Vec<DatePart> {
    let parts: Vec<DatePart> = tokens
        .iter()
        .filter_map(|token| match token {
            Token::Date(part) => Some(*part),
            _ => None,
        })
        .collect();
    parts
        .iter()
        .enumerate()
        .map(|(at, &part)| {
            let after_hours = at > 0 && matches!(parts[at - 1], DatePart::Hour | DatePart::Elapsed);
            let before_seconds = parts.get(at + 1) == Some(&DatePart::Second);
            if part == DatePart::MonthOrMinute && (after_hours || before_seconds) {
                DatePart::Minute
            } else {
                part
            }
        })
        .collect()
}

/// A serial as an ISO date, time, or both, as the section shows it; `None`
/// when the serial is not a date (negative, or past 9999-12-31).
fn date_time(value: f64, tokens: &[Token], date1904: bool) -> Option<String> {
    let max = if date1904 { MAX_SERIAL_1904 } else { MAX_SERIAL_1900 };
    if value < 0.0 || value >= max + 1.0 {
        return None;
    }
    let parts = date_parts(tokens);
    let has_date = parts
        .iter()
        .any(|part| matches!(part, DatePart::Year | DatePart::MonthOrMinute | DatePart::Day));
    let has_seconds = parts.contains(&DatePart::Second);
    let has_minutes = parts.contains(&DatePart::Minute);
    let elapsed = parts.contains(&DatePart::Elapsed);
    let has_hours = elapsed || parts.contains(&DatePart::Hour);
    let has_time = has_seconds
        || has_minutes
        || parts
            .iter()
            .any(|part| matches!(part, DatePart::Hour | DatePart::AmPm | DatePart::Elapsed));
    // The decimals of the seconds (`ss.0`), in tenths, hundredths or
    // thousandths.
    let decimals = if has_seconds { second_decimals(tokens) } else { 0 };
    let scale = 10i64.pow(decimals);
    // The serial in ticks (a second divided by `scale`), rounded to what
    // the code shows.
    let unit: i64 = if has_seconds {
        1
    } else if has_time {
        60 * scale
    } else {
        scale
    };
    #[allow(clippy::cast_possible_truncation)] // below 2958466 days
    let ticks = ((value * (DAY_SECONDS * scale) as f64 / unit as f64).round() as i64) * unit;
    let (seconds, fraction) = (ticks.div_euclid(scale), ticks.rem_euclid(scale));
    let (days, time) = (seconds.div_euclid(DAY_SECONDS), seconds.rem_euclid(DAY_SECONDS));
    let mut out = Vec::new();
    if has_date {
        let (year, month, day) = serial_date(days, date1904)?;
        out.push(format!("{year:04}-{month:02}-{day:02}"));
    }
    if has_time {
        let hours = if elapsed { seconds / 3600 } else { time / 3600 };
        let minutes = time % 3600 / 60;
        // A code without hours (`mm:ss`) shows the minutes and seconds of
        // the hour, as Excel does; one with only seconds, the seconds.
        let mut clock = if has_hours || !(has_minutes || has_seconds) {
            format!("{hours:02}:{minutes:02}")
        } else if has_minutes {
            format!("{minutes:02}")
        } else {
            String::new()
        };
        if has_seconds {
            if !clock.is_empty() {
                clock.push(':');
            }
            clock.push_str(&format!("{:02}", time % 60));
            if decimals > 0 {
                let width = decimals as usize;
                clock.push_str(&format!(".{fraction:0width$}"));
            }
        }
        out.push(clock);
    }
    Some(out.join(" "))
}

/// How many decimals of the seconds a date section shows: the `0`s right
/// after the point that follows the seconds (`ss.00`), at most 3, as
/// Excel allows.
fn second_decimals(tokens: &[Token]) -> u32 {
    let Some(at) = tokens.iter().position(|token| *token == Token::Date(DatePart::Second)) else {
        return 0;
    };
    if tokens.get(at + 1) != Some(&Token::Point) {
        return 0;
    }
    let zeros = tokens[at + 2..]
        .iter()
        .take_while(|token| **token == Token::Digit('0'))
        .count();
    u32::try_from(zeros.min(MAX_SECOND_DECIMALS)).unwrap_or(0)
}

/// The calendar date of a day serial.
fn serial_date(days: i64, date1904: bool) -> Option<(i64, u32, u32)> {
    let unix_days = if date1904 {
        EPOCH_1904_DAYS + days
    } else if days == LEAP_DAY_1900 {
        return Some((1900, 2, 29));
    } else if days < LEAP_DAY_1900 {
        // Before the leap day Excel invented, serials count from one day
        // later.
        EPOCH_1900_DAYS + days + 1
    } else {
        EPOCH_1900_DAYS + days
    };
    let date = civil(unix_days);
    (date.0 <= 9999).then_some(date)
}

/// The date of a count of days from 1970-01-01, in the Gregorian calendar
/// (Howard Hinnant's `civil_from_days`).
fn civil(days: i64) -> (i64, u32, u32) {
    let shifted = days + 719_468;
    let era = shifted.div_euclid(146_097);
    let doe = shifted.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = yoe + era * 400 + i64::from(month <= 2);
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // 1..=31, 1..=12
    (year, month as u32, day as u32)
}

/// `value` in Excel's General format: up to 11 significant digits,
/// scientific notation for very large or very small numbers.
fn general(value: f64) -> String {
    if value == 0.0 {
        return "0".into();
    }
    if !value.is_finite() {
        return value.to_string();
    }
    let sign = if value < 0.0 { "-" } else { "" };
    let value = value.abs();
    let exponent = decimal_exponent(value);
    if exponent >= GENERAL_DIGITS || value < GENERAL_SMALLEST {
        let (mantissa, exponent) = scientific(value, GENERAL_SCIENTIFIC_DIGITS - 1, 1);
        let mantissa = strip_zeros(&mantissa);
        let exp_sign = if exponent < 0 { '-' } else { '+' };
        return format!("{sign}{mantissa}E{exp_sign}{:02}", exponent.abs());
    }
    #[allow(clippy::cast_sign_loss)] // clamped
    let decimals = (GENERAL_DIGITS - 1 - exponent).max(0) as usize;
    let (int, frac) = digits(value, decimals);
    let int = if int.is_empty() { "0".to_string() } else { int };
    format!("{sign}{}", strip_zeros(&format!("{int}.{frac}")))
}

/// `text` (`1.2500`) without trailing zeros after the point, nor the point
/// itself when nothing is left after it.
fn strip_zeros(text: &str) -> String {
    if !text.contains('.') {
        return text.to_string();
    }
    text.trim_end_matches('0').trim_end_matches('.').to_string()
}

/// The power of ten of the first significant digit of `value` (not zero),
/// after Excel's rounding to 15 digits.
fn decimal_exponent(value: f64) -> i32 {
    let text = format!("{:.*e}", EXCEL_DIGITS - 1, value);
    text.split('e').nth(1).and_then(|exp| exp.parse().ok()).unwrap_or(0)
}

/// `value` (not negative) rounded half up to `decimals` decimals, as its
/// integer digits (empty for zero) and its `decimals` decimal digits.
/// Excel rounds to 15 significant digits first, so `2.675` is `2.68`.
fn digits(value: f64, decimals: usize) -> (String, String) {
    let text = format!("{:.*e}", EXCEL_DIGITS - 1, value);
    let (mantissa, exponent) = text.split_once('e').unwrap_or((&text, "0"));
    let exponent: i64 = exponent.parse().unwrap_or(0);
    let mut digits: Vec<u8> = mantissa.bytes().filter(u8::is_ascii_digit).map(|b| b - b'0').collect();
    // Where the decimal point falls in `digits`.
    let mut point = exponent + 1;
    if point < 0 {
        #[allow(clippy::cast_sign_loss)]
        let zeros = vec![0; (-point) as usize];
        digits.splice(0..0, zeros);
        point = 0;
    }
    #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
    let mut point = point as usize;
    let keep = point + decimals;
    if digits.len() > keep {
        let round_up = digits[keep] >= 5;
        digits.truncate(keep);
        if round_up {
            let mut at = keep;
            loop {
                if at == 0 {
                    digits.insert(0, 1);
                    point += 1;
                    break;
                }
                at -= 1;
                if digits[at] == 9 {
                    digits[at] = 0;
                } else {
                    digits[at] += 1;
                    break;
                }
            }
        }
    }
    digits.resize(point + decimals, 0);
    let text: String = digits.iter().map(|digit| char::from(b'0' + digit)).collect();
    let (int, frac) = text.split_at(point);
    (int.trim_start_matches('0').to_string(), frac.to_string())
}

/// `value` (not negative) as a mantissa with `decimals` decimals and its
/// exponent, a multiple of `step` (`##0.0E+0` steps by 3).
fn scientific(value: f64, decimals: usize, step: i32) -> (String, i32) {
    if value == 0.0 {
        let frac = "0".repeat(decimals);
        return (if decimals > 0 { format!("0.{frac}") } else { "0".into() }, 0);
    }
    let mut exponent = decimal_exponent(value).div_euclid(step) * step;
    loop {
        let (int, frac) = digits(value / 10f64.powi(exponent), decimals);
        // Rounding up can give one digit too many (9.999 → 10.00).
        if int.len() > usize::try_from(step).unwrap_or(1) {
            exponent += step;
            continue;
        }
        let int = if int.is_empty() { "0".to_string() } else { int };
        let mantissa = if decimals > 0 { format!("{int}.{frac}") } else { int };
        return (mantissa, exponent);
    }
}

/// Whether `token` is a digit placeholder.
fn is_digit(token: &Token) -> bool {
    matches!(token, Token::Digit(_))
}

/// Where the parts of a number section are, by index of its tokens.
struct Layout {
    /// The exponent (`E+`), when the number is scientific.
    exponent_at: Option<usize>,
    /// The end of the mantissa: the exponent, or the end of the section.
    mantissa_end: usize,
    /// The integer digit placeholders.
    int_places: Vec<usize>,
    /// The decimal digit placeholders.
    frac_places: Vec<usize>,
    /// Commas separate the thousands.
    thousands: bool,
    /// How many times the number is divided by 1000 (commas after the
    /// last digit).
    scale: usize,
    /// How many times the number is multiplied by 100 (`%`).
    percents: usize,
}

impl Layout {
    /// The layout of a number section.
    fn of(tokens: &[Token]) -> Self {
        let exponent_at = tokens.iter().position(|token| matches!(token, Token::Exponent { .. }));
        let mantissa_end = exponent_at.unwrap_or(tokens.len());
        let int_end = tokens[..mantissa_end]
            .iter()
            .position(|token| *token == Token::Point)
            .unwrap_or(mantissa_end);
        let last_digit = tokens[..mantissa_end].iter().rposition(is_digit);
        let first_digit = tokens.iter().position(is_digit);
        // Commas after the last digit divide by 1000; commas between
        // integer digits separate the thousands.
        let mut scale = 0;
        let mut thousands = false;
        for (at, token) in tokens[..mantissa_end].iter().enumerate() {
            if *token == Token::Comma {
                if last_digit.is_none_or(|last| at > last) {
                    scale += 1;
                } else if at < int_end && first_digit.is_some_and(|first| at > first) {
                    thousands = true;
                }
            }
        }
        Self {
            exponent_at,
            mantissa_end,
            int_places: (0..int_end).filter(|&at| is_digit(&tokens[at])).collect(),
            frac_places: (int_end..mantissa_end).filter(|&at| is_digit(&tokens[at])).collect(),
            thousands,
            scale,
            percents: tokens.iter().filter(|token| **token == Token::Percent).count(),
        }
    }
}

/// `value` (not negative) with the tokens of a number section.
fn number(value: f64, tokens: &[Token]) -> String {
    if tokens.contains(&Token::Slash) && tokens.iter().any(is_digit) {
        return fraction(value, tokens);
    }
    let layout = Layout::of(tokens);
    let mut value = value;
    for _ in 0..layout.percents {
        value *= 100.0;
    }
    for _ in 0..layout.scale {
        value /= 1000.0;
    }
    let (int, frac, exponent) = if layout.exponent_at.is_some() {
        let places = layout.int_places.len();
        // `##0.0E+0` keeps the exponent a multiple of 3.
        let engineering = places > 1 && layout.int_places.iter().any(|&at| tokens[at] == Token::Digit('#'));
        let step = if engineering {
            i32::try_from(places).unwrap_or(1)
        } else {
            1
        };
        let (mantissa, exponent) = scientific(value, layout.frac_places.len(), step);
        let (int, frac) = mantissa.split_once('.').unwrap_or((&mantissa, ""));
        let int = if int == "0" { "" } else { int };
        (int.to_string(), frac.to_string(), Some(exponent))
    } else {
        let (int, frac) = digits(value, layout.frac_places.len());
        (int, frac, None)
    };
    let int_out = fill_integer(&int, tokens, &layout);
    let frac_out = fill_decimals(&frac, tokens, &layout.frac_places);
    let mut out = String::new();
    let mut exponent_digits = Vec::new();
    for (at, token) in tokens.iter().enumerate() {
        match token {
            Token::Literal(text) => out.push_str(text),
            Token::Percent => out.push('%'),
            Token::Slash => out.push('/'),
            Token::General => out.push_str(&general(value)),
            Token::Fill => out.push(FILL_MARK),
            Token::Point if at < layout.mantissa_end => out.push('.'),
            Token::Digit(_) if layout.exponent_at.is_some_and(|exp_at| at > exp_at) => {
                exponent_digits.push(token.clone());
                // The exponent is written at its last placeholder.
                if !tokens[at + 1..].iter().any(is_digit) {
                    out.push_str(&exponent_text(exponent.unwrap_or(0), &exponent_digits));
                }
            }
            Token::Digit(_) => {
                if let Some(slot) = layout.int_places.iter().position(|&place| place == at) {
                    out.push_str(&int_out[slot]);
                } else if let Some(slot) = layout.frac_places.iter().position(|&place| place == at) {
                    out.push_str(&frac_out[slot]);
                }
            }
            Token::Exponent { plus } => {
                out.push('E');
                match exponent {
                    Some(exp) if exp < 0 => out.push('-'),
                    _ if *plus => out.push('+'),
                    _ => {}
                }
            }
            _ => {}
        }
    }
    out
}

/// What each integer placeholder writes of the digits `int` (empty for
/// zero), filled from the right: a digit, or for none `0`, a space (`?`)
/// or nothing (`#`). The first placeholder takes the digits left over.
fn fill_integer(int: &str, tokens: &[Token], layout: &Layout) -> Vec<String> {
    let mut int_out: Vec<String> = vec![String::new(); layout.int_places.len()];
    let int_digits: Vec<char> = int.chars().collect();
    let mut from_right = 0;
    for (slot, &at) in layout.int_places.iter().enumerate().rev() {
        let Token::Digit(placeholder) = tokens[at] else {
            continue;
        };
        let take = if slot == 0 {
            int_digits.len().saturating_sub(from_right).max(1)
        } else {
            1
        };
        let mut written = String::new();
        for _ in 0..take {
            let digit = int_digits
                .len()
                .checked_sub(from_right + 1)
                .map(|index| int_digits[index]);
            let ch = match (digit, placeholder) {
                (Some(digit), _) => digit,
                (None, '0') => '0',
                (None, '?') => ' ',
                _ => continue,
            };
            if layout.thousands && from_right > 0 && from_right % 3 == 0 && ch != ' ' {
                written.insert(0, ',');
            }
            written.insert(0, ch);
            from_right += 1;
        }
        int_out[slot] = written;
    }
    int_out
}

/// What each decimal placeholder writes of the digits `frac`: trailing
/// zeros are dropped by `#` and made spaces by `?`.
fn fill_decimals(frac: &str, tokens: &[Token], frac_places: &[usize]) -> Vec<String> {
    let frac_digits: Vec<char> = frac.chars().collect();
    let mut frac_out: Vec<String> = frac_digits.iter().map(char::to_string).collect();
    for (slot, &at) in frac_places.iter().enumerate().rev() {
        if frac_digits[slot] != '0' {
            break;
        }
        match tokens[at] {
            Token::Digit('#') => frac_out[slot].clear(),
            Token::Digit('?') => frac_out[slot] = " ".into(),
            _ => break,
        }
    }
    frac_out
}

/// The digits of an exponent, with at least as many as the code has `0`.
fn exponent_text(exponent: i32, placeholders: &[Token]) -> String {
    let min = placeholders.iter().filter(|token| **token == Token::Digit('0')).count();
    format!("{:0min$}", exponent.unsigned_abs())
}

/// `value` (not negative) as a fraction (`# ?/?`, `# ??/??`, `?/8`): a
/// whole part when the code has one, then the closest fraction whose
/// denominator has at most as many digits as the code shows.
fn fraction(value: f64, tokens: &[Token]) -> String {
    let slash = tokens.iter().position(|token| *token == Token::Slash).unwrap_or(0);
    // The denominator: placeholders, or a fixed number (`?/8`).
    let after = &tokens[slash + 1..];
    // `?/100`: the literal digits, and the zeros that follow them.
    let fixed: String = if matches!(after.first(), Some(Token::Literal(text)) if text.chars().all(|ch| ch.is_ascii_digit()))
    {
        after
            .iter()
            .map_while(|token| match token {
                Token::Literal(text) if text.chars().all(|ch| ch.is_ascii_digit()) => Some(text.as_str()),
                Token::Digit('0') => Some("0"),
                _ => None,
            })
            .collect()
    } else {
        String::new()
    };
    let den_places = after.iter().take_while(|token| is_digit(token)).count();
    // The numerator: the placeholders right before the bar.
    let num_start = tokens[..slash]
        .iter()
        .rposition(|token| !is_digit(token))
        .map_or(0, |at| at + 1);
    let has_whole = tokens[..num_start].iter().any(is_digit);
    let (whole, part) = if has_whole {
        (value.trunc(), value.fract())
    } else {
        (0.0, value)
    };
    let (num, den) = match fixed.parse::<u64>() {
        Ok(den) if den > 0 => {
            #[allow(
                clippy::cast_possible_truncation,
                clippy::cast_sign_loss,
                clippy::cast_precision_loss
            )]
            let num = (part * den as f64).round() as u64;
            (num, den)
        }
        _ => closest_fraction(
            part,
            10u64.pow(u32::try_from(den_places.clamp(1, MAX_FRACTION_DIGITS)).unwrap_or(1)) - 1,
        ),
    };
    let (whole, num) = if has_whole && num == den {
        (whole + 1.0, 0)
    } else {
        (whole, num)
    };
    let whole_text = if whole > 0.0 || num == 0 {
        general(whole)
    } else {
        String::new()
    };
    if num == 0 {
        return whole_text;
    }
    format!("{whole_text} {num}/{den}").trim().to_string()
}

/// The fraction closest to `value`, with a denominator up to `max_den`
/// (the smallest denominator among equally close ones).
fn closest_fraction(value: f64, max_den: u64) -> (u64, u64) {
    let mut best = (value.round() as u64, 1, f64::INFINITY);
    for den in 1..=max_den {
        #[allow(clippy::cast_precision_loss)]
        let den_f = den as f64;
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let num = (value * den_f).round() as u64;
        #[allow(clippy::cast_precision_loss)]
        let error = (value - num as f64 / den_f).abs();
        if error < best.2 - f64::EPSILON {
            best = (num, den, error);
        }
    }
    (best.0, best.1)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `value` formatted with the custom code `code`, in the 1900 system.
    fn code(value: f64, code: &str) -> String {
        format(value, &NumFmt::Code(code.to_string()), false)
    }

    #[test]
    fn formats_as_excel_shows_them_with_iso_dates() {
        let cases: &[(f64, &str, &str)] = &[
            (1234.5, "General", "1234.5"),
            (0.1 + 0.2, "General", "0.3"),
            (1e20, "General", "1E+20"),
            (1234.5, "#,##0.00", "1,234.50"),
            (-1234.5, "#,##0.00;(#,##0.00)", "(1,234.50)"),
            (0.0, "0.00;-0.00;\"-\"", "-"),
            (0.125, "0.0%", "12.5%"),
            (12345.678, "0.00E+00", "1.23E+04"),
            (1500.0, "\"¥\"#,##0", "¥1,500"),
            (2.0, "[$€-407] #,##0.00", "€ 2.00"),
            (5.0, "[Red]0", "5"),
            (45322.0, "m/d/yyyy", "2024-01-31"),
            (45322.0, "dd\\.mm\\.yy", "2024-01-31"),
            (45322.5856, "yyyy-mm-dd hh:mm", "2024-01-31 14:03"),
            (0.5856, "h:mm AM/PM", "14:03"),
            (0.585601, "hh:mm:ss", "14:03:16"),
            (60.0, "yyyy-mm-dd", "1900-02-29"), // Excel's own leap day of 1900
        ];
        for (value, code, want) in cases {
            assert_eq!(format(*value, &NumFmt::Code(code.to_string()), false), *want, "{code}");
        }
    }

    #[test]
    fn builtin_14_is_iso_and_builtin_7_has_no_symbol() {
        assert_eq!(format(45322.0, &builtin(14), false), "2024-01-31");
        assert_eq!(format(1234.5, &builtin(7), false), "1,234.50");
        assert_eq!(format(-1234.5, &builtin(7), false), "(1,234.50)");
        assert!(is_date(&builtin(14)));
        assert!(!is_date(&builtin(7)));
    }

    #[test]
    fn the_1904_system_shifts_dates() {
        assert_eq!(format(0.0, &builtin(14), true), "1904-01-01");
        assert_eq!(format(60.0, &builtin(14), true), "1904-03-01");
    }

    #[test]
    fn impossible_dates_fall_back_to_numbers() {
        assert_eq!(code(-1.0, "yyyy-mm-dd"), "-1");
        assert_eq!(code(3e6, "yyyy-mm-dd"), "3000000");
    }

    #[test]
    fn days_around_the_leap_day_of_1900() {
        assert_eq!(code(1.0, "yyyy-mm-dd"), "1900-01-01");
        assert_eq!(code(59.0, "yyyy-mm-dd"), "1900-02-28");
        assert_eq!(code(61.0, "yyyy-mm-dd"), "1900-03-01");
        assert_eq!(code(2_958_465.0, "yyyy-mm-dd"), "9999-12-31");
    }

    #[test]
    fn elapsed_hours_go_past_a_day() {
        assert_eq!(code(27.5 / 24.0, "[h]:mm"), "27:30");
        assert_eq!(code(1.5, "h:mm"), "12:00");
        assert_eq!(code(0.999_999, "hh:mm"), "00:00");
        assert_eq!(code(45_322.999_999, "yyyy-mm-dd hh:mm"), "2024-02-01 00:00");
    }

    #[test]
    fn minutes_after_hours_are_not_months() {
        assert_eq!(code(0.5856, "h \"h\" m \"min\""), "14:03");
        assert_eq!(code(0.585601, "mm:ss"), "03:16");
        assert!(is_date(&NumFmt::Code("mmm-yy".into())));
        assert!(!is_date(&NumFmt::Code("0.00E+00".into())));
        assert!(!is_date(&NumFmt::Code("\"day\" 0".into())));
        assert!(!is_date(&NumFmt::General));
    }

    #[test]
    fn a_time_without_hours_shows_minutes_and_seconds() {
        let seconds = |seconds: f64| seconds / 86_400.0;
        assert_eq!(format(seconds(308.0), &builtin(45), false), "05:08");
        assert_eq!(format(seconds(308.44), &builtin(47), false), "05:08.4");
        assert_eq!(format(seconds(308.96), &builtin(47), false), "05:09.0");
        // An hour and more: the minutes of the hour, as Excel shows them.
        assert_eq!(format(seconds(3_908.0), &builtin(45), false), "05:08");
        assert_eq!(code(seconds(8.126), "ss.00"), "08.13");
        assert_eq!(code(seconds(3_908.25), "hh:mm:ss.000"), "01:05:08.250");
        assert_eq!(format(seconds(3_908.0), &builtin(46), false), "01:05:08");
    }

    #[test]
    fn general_keeps_eleven_digits() {
        let general = |value: f64| format(value, &NumFmt::General, false);
        assert_eq!(general(0.0), "0");
        assert_eq!(general(-42.0), "-42");
        assert_eq!(general(1.0 / 3.0), "0.33333333333");
        assert_eq!(general(2.0 / 3.0), "0.66666666667");
        assert_eq!(general(12_345_678_901.0), "12345678901");
        assert_eq!(general(123_456_789_012.0), "1.23457E+11");
        assert_eq!(general(1.5e-10), "1.5E-10");
        assert_eq!(general(0.000_012_5), "0.0000125");
    }

    #[test]
    fn sections_and_signs() {
        assert_eq!(code(-5.0, "0"), "-5");
        assert_eq!(code(-5.0, "0;0"), "5");
        assert_eq!(code(0.0, "0;-0;"), "");
        assert_eq!(code(-1234.0, "#,##0;[Red]-#,##0"), "-1,234");
        // An accounting format's fill is a space in the text.
        let accounting = r#"_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)"#;
        assert_eq!(code(0.0, accounting), "$ -");
        assert_eq!(code(1234.0, accounting), "$ 1,234.00");
        let fmt = |code: &str| NumFmt::Code(code.to_string());
        assert_eq!(color(-1.0, &fmt("#,##0;[Red]-#,##0")), Some(10));
        assert_eq!(color(1.0, &fmt("#,##0;[Red]-#,##0")), None);
        assert_eq!(color(-9.1, &fmt(r"[Red]\-0.0")), Some(10));
        assert_eq!(color(0.0, &fmt("0;[Blue]-0;[Color10]0")), Some(17));
        assert_eq!(color(-1.0, &fmt(r#""[Red]"0;-0"#)), None);
        assert_eq!(color(1.0, &fmt("[$-411]0")), None);
        assert_eq!(code(-0.001, "0.00"), "0.00");
        assert_eq!(code(3.0, "General\" units\""), "3 units");
    }

    #[test]
    fn placeholders_round_half_up_and_pad() {
        assert_eq!(code(2.5, "0"), "3");
        assert_eq!(code(2.675, "0.00"), "2.68");
        assert_eq!(code(0.5, "#"), "1");
        assert_eq!(code(0.0, "#"), "");
        assert_eq!(code(7.0, "000"), "007");
        assert_eq!(code(1.5, "#.##"), "1.5");
        assert_eq!(code(1.0, "0.0#"), "1.0");
        assert_eq!(code(1_234_567.0, "#,##0"), "1,234,567");
        assert_eq!(code(999.5, "#,##0"), "1,000");
        assert_eq!(code(1_234_567.0, "#,##0.0,,\"M\""), "1.2M");
        assert_eq!(code(5_551_234.0, "000-0000"), "555-1234");
        assert_eq!(code(0.25, "0%"), "25%");
    }

    #[test]
    fn accounting_formats() {
        assert_eq!(format(1234.0, &builtin(41), false), "1,234");
        assert_eq!(format(-1234.0, &builtin(41), false), "(1,234)");
        assert_eq!(format(0.0, &builtin(43), false), "-");
        assert_eq!(format(1234.5, &builtin(44), false), "1,234.50");
        assert_eq!(format(1234.0, &builtin(37), false), "1,234");
        // The fill sets the currency at the cell's left edge.
        let dollars = NumFmt::Code(r#"_-"$"* #,##0.00_-;\-"$"* #,##0.00_-;_-"$"* "-"??_-;_-@_-"#.into());
        assert_eq!(format_filled(705.84, &dollars, false), ("$705.84".to_string(), Some(1)));
        assert_eq!(format_filled(-5.0, &dollars, false), ("-$5.00".to_string(), Some(2)));
        assert_eq!(format_filled(1.0, &builtin(4), false), ("1.00".to_string(), None));
    }

    #[test]
    fn scientific_and_fractions() {
        assert_eq!(code(0.000_123, "0.00E+00"), "1.23E-04");
        assert_eq!(code(9.999, "0.00E+00"), "1.00E+01");
        assert_eq!(code(12345.0, "##0.0E+0"), "12.3E+3");
        assert_eq!(code(0.0, "0.00E+00"), "0.00E+00");
        assert_eq!(format(1.5, &builtin(12), false), "1 1/2");
        assert_eq!(format(0.75, &builtin(12), false), "3/4");
        assert_eq!(format(3.0, &builtin(12), false), "3");
        assert_eq!(format(0.333, &builtin(13), false), "1/3");
        assert_eq!(code(2.25, "# ?/100"), "2 25/100");
        assert_eq!(code(0.5, "?/8"), "4/8");
    }

    #[test]
    fn text_and_empty_codes_show_the_number() {
        assert_eq!(format(5.0, &builtin(49), false), "5");
        assert_eq!(code(-2.5, "@"), "-2.5");
        assert_eq!(code(5.0, ""), "5");
        assert_eq!(code(5.0, ";;;"), "");
    }

    #[test]
    fn overlong_codes_are_general() {
        assert_eq!(code(1234.5, &"0".repeat(10_000)), "1234.5");
    }

    #[test]
    fn builtin_ids() {
        assert_eq!(builtin(0), NumFmt::General);
        assert_eq!(builtin(4), NumFmt::Code("#,##0.00".into()));
        assert_eq!(builtin(10), NumFmt::Code("0.00%".into()));
        assert_eq!(builtin(25), NumFmt::General);
        assert_eq!(builtin(163), NumFmt::General);
        assert!((14..=22).chain(45..=47).all(|id| is_date(&builtin(id))));
        assert_eq!(format(0.5, &builtin(18), false), "12:00");
        assert_eq!(format(45322.25, &builtin(22), false), "2024-01-31 06:00");
        assert_eq!(format(1.0 + 1.0 / 24.0, &builtin(46), false), "25:00:00");
        assert_eq!(format(1.0 / 1440.0, &builtin(45), false), "01:00");
    }
}