mahbot 0.11.0

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
//! Excel number formats: a stored numeric value rendered the way Excel would display
//! it, or `None` when the format cannot be reproduced — a sheet cell's value and a
//! chart cache's value alike, so one number is shown one way.
//!
//! # Invariants
//!
//! - **Never panics.** The format code, the placeholders and fractional-second digits a
//!   section names, the scaled integer its display may need and the serial domain are
//!   all bounded before they are used.
//! - **Never silently wrong.** An unimplemented format, a value outside the format's
//!   domain, a scaled value with no exact display, a format no section of which serves
//!   the value, and a section that shows nothing or would have to carry the value's own
//!   sign all come back as `None` — which the caller turns into the stored value, marked
//!   as stored, never an empty or invented rendering.
//! - **The shown value is the one Excel displays.** Excel works with 15 significant
//!   decimal digits, so `1.005` under `0.00` shows `1.01` although the double holding it
//!   is a hair below the tie; [`scaled_magnitude`] canonicalises before rounding
//!   half-away-from-zero.
//! - **A section serves a value by Excel's own rule.** Sections carrying a comparison
//!   make a conditional format: the first two sections' conditions are tested in order
//!   and the holder serves the value — as a magnitude when the condition names the
//!   negative side (`[<0]0.0;0.00` shows -1 as `1.0`), else keeping its own minus
//!   (`[>=1]0;0` shows -2 as `-2`). A value no condition serves falls to the section
//!   Excel keeps for it (the second of two, the third of more), where the minus is
//!   dropped only for a format that has a section of its own for the negative side.
//!   Otherwise sections stand for positive;negative;zero;text, the negative one carrying
//!   its own sign, and a lone section shows the minus for a value that did not round
//!   away to nothing. A value no section serves is declined.
//! - **A code is read as Excel reads it.** Digits go where the section puts them, with
//!   the literals it stands between (`000-00-0000`), and a currency symbol or `%` prints
//!   where it stands; what shows nothing of its own (a colour, a condition, a bare
//!   locale, a `*` fill) leaves nothing behind. A fraction, a text placeholder, an
//!   unknown localized format word, a misplaced decimal point, a digit the layout has no
//!   place for or a place the digits do not fill are declined rather than guessed at. A
//!   section naming a fractional part keeps the point even with no digit behind it
//!   (`#.#####` shows 1 as `1.`).

use std::cmp::Ordering;

/// Excel's own limit: a longer code is not a format the application could store.
const MAX_FORMAT_LENGTH: usize = 255;
/// Past this a section stops being one this reader reproduces.
const MAX_PLACEHOLDERS: usize = 30;
/// The fractional-second digits a time section may name (Excel writes at most three, a
/// millisecond).
const MAX_SUB_SECOND_DIGITS: usize = 9;
/// Far past anything Excel displays, but still a value whose days, seconds and hours
/// have an exact integer form.
const VALUE_LIMIT: f64 = 1e9;
/// The sections a format may carry: one per sign and one for text, Excel's own limit.
const MAX_SECTIONS: usize = 4;
/// The serial of 9999-12-31 in the 1900 system: the last day Excel's calendar holds.
const SERIAL_LIMIT: i64 = 2_958_465;
/// The same last day in the 1904 system, whose day 0 is four years later.
const SERIAL_LIMIT_1904: i64 = SERIAL_LIMIT - 1_462;
/// The largest scaled integer a number's display may need, so that a value
/// without any plausible display is declined rather than rendered into a
/// three-hundred-digit line.
const MAX_SCALED: i128 = 10_i128.pow(30);

/// The built-in number-format code for `id`, or `None` when the id has no ECMA-376/POI builtin
/// meaning.
const fn builtin(id: u32) -> Option<&'static str> {
    Some(match id {
        0 => "General",
        1 => "0",
        2 => "0.00",
        3 => "#,##0",
        4 => "#,##0.00",
        5 => "\"$\"#,##0_);(\"$\"#,##0)",
        6 => "\"$\"#,##0_);[Red](\"$\"#,##0)",
        7 => "\"$\"#,##0.00_);(\"$\"#,##0.00)",
        8 => "\"$\"#,##0.00_);[Red](\"$\"#,##0.00)",
        9 => "0%",
        10 => "0.00%",
        11 => "0.00E+00",
        12 => "# ?/?",
        13 => "# ??/??",
        14 => "mm-dd-yy",
        15 => "d-mmm-yy",
        16 => "d-mmm",
        17 => "mmm-yy",
        18 => "h:mm AM/PM",
        19 => "h:mm:ss AM/PM",
        20 => "h:mm",
        21 => "h:mm:ss",
        22 => "m/d/yy h:mm",
        37 => "#,##0_);(#,##0)",
        38 => "#,##0_);[Red](#,##0)",
        39 => "#,##0.00_);(#,##0.00)",
        40 => "#,##0.00_);[Red](#,##0.00)",
        41 => "_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)",
        42 => "_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)",
        43 => "_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)",
        44 => "_(\"$\"* #,##0.00_);_(\"$\"* (#,##0.00);_(\"$\"* \"-\"??_);_(@_)",
        45 => "mm:ss",
        46 => "[h]:mm:ss",
        47 => "mm:ss.0",
        48 => "##0.0E+0",
        49 => "@",
        _ => return None,
    })
}

/// Whether a cell shows its stored text: the format its `id` and `code` resolve to is `General`.
#[must_use]
pub(crate) fn is_general(id: u32, code: Option<&str>) -> bool {
    match code {
        // An empty declared code names no format this reader can show, so the caller
        // falls through to the stored value marked as stored.
        Some("") => false,
        Some(code) => is_general_code(code),
        None => builtin(id).is_some_and(is_general_code),
    }
}

/// `General` under the directives a workbook wraps it in (`[DBNum1][$-804]General`),
/// the padding it carries and its repetition across sections (`General;General`).
fn is_general_code(code: &str) -> bool {
    split_sections(code).map_or_else(
        || general_section(code),
        |sections| sections.iter().all(|section| general_section(section)),
    )
}

/// Whether a section's body is `General`. The body does not depend on the value its condition is
/// read against.
fn general_section(section: &str) -> bool {
    split_section(section, 0.0)
        .0
        .trim()
        .eq_ignore_ascii_case("General")
}

/// `None` when this reader has no display for it: an unparseable or unsupported
/// format, a value outside the format's domain, no serving section, a section showing
/// nothing or one that would have to carry the value's sign. `General` is never asked
/// here — its display is the value's own stored text, so the caller shows that text
/// itself ([`is_general`]).
#[must_use]
pub(crate) fn display(value: f64, id: u32, code: Option<&str>, date1904: bool) -> Option<String> {
    if !value.is_finite() {
        return None;
    }
    // A declared non-empty code always wins over the built-in meaning of `id`.
    let format = match code {
        Some("") => return None,
        Some(code) => code,
        None => builtin(id)?,
    };
    if format.len() > MAX_FORMAT_LENGTH {
        return None;
    }
    let sections = split_sections(format)?;
    let Selection { body, signed } = select_section(&sections, value)?;
    if body.trim().is_empty() {
        return None;
    }
    let tokens = tokenize(body);
    let rendered = if is_date(&tokens) {
        render_date(value, date1904, &tokens)?
    } else {
        let Rendered { text, shows_number } = render_number(value.abs(), &tokens)?;
        // A section with no digit placeholder shows the format's own text. For a negative
        // value whose sign is this reader's to write, that sign has no place, so the
        // format is declined rather than shown with the sign dropped.
        if signed && value < 0.0 && !tokens.iter().any(|tok| matches!(tok, Tok::Digit(_))) {
            return None;
        }
        // The minus is the reader's only where the section writes none of its own, and
        // only for a value that did not round away: Excel shows `0` for -0.4 under `0`.
        if signed && value < 0.0 && shows_number && !text.starts_with('-') {
            format!("-{text}")
        } else {
            text
        }
    };
    let rendered = rendered.trim();
    if rendered.is_empty() {
        return None;
    }
    Some(rendered.to_owned())
}

/// Split on top-level `;`; `None` beyond four sections. A `;` inside `"..."`, escaped
/// by `\`, or inside `[...]` never splits.
fn split_sections(format: &str) -> Option<Vec<&str>> {
    let bytes = format.as_bytes();
    let mut sections = Vec::new();
    let mut start = 0usize;
    let mut index = 0usize;
    while index < bytes.len() {
        match bytes[index] {
            b'"' => {
                index += 1;
                while index < bytes.len() && bytes[index] != b'"' {
                    index += 1;
                }
                index += 1;
            }
            b'\\' => index += 2,
            b'[' => {
                index += 1;
                while index < bytes.len() && bytes[index] != b']' {
                    index += 1;
                }
                index += 1;
            }
            b';' => {
                sections.push(&format[start..index]);
                if sections.len() == MAX_SECTIONS {
                    return None;
                }
                index += 1;
                start = index;
            }
            _ => index += 1,
        }
    }
    sections.push(&format[start..]);
    Some(sections)
}

/// The section `value` renders with, and whether the minus it shows is the reader's
/// to write (the rule is in the module's invariants).
struct Selection<'a> {
    body: &'a str,
    /// A lone section for every value shows it; a conditional format shows it unless
    /// its condition serves the value through a section written to display a negative
    /// side. A sign-ordered format's negative section carries its own sign.
    signed: bool,
}

/// For a conditional format the one Excel's rule serves ([`conditional_section`]),
/// otherwise the one its sign names. `None` when no section serves the value.
fn select_section<'a>(sections: &[&'a str], value: f64) -> Option<Selection<'a>> {
    // One walk reads each section once for both questions: does the format compare,
    // and which section serves this value.
    let mut split = [("", None); MAX_SECTIONS];
    for (slot, section) in split.iter_mut().zip(sections) {
        *slot = split_section(section, value);
    }
    let split = &split[..sections.len()];
    // Only the first two sections can carry a condition; one standing later is no part
    // of Excel's rule, so the format is read by sign.
    if split
        .iter()
        .take(2)
        .any(|(_, condition)| condition.is_some())
    {
        return conditional_section(split, value);
    }
    let position = sign_position(split.len(), value)?;
    Some(Selection {
        body: split[position].0,
        // A lone section stands for every value, so a negative one has no section of its
        // own to carry the minus.
        signed: split.len() == 1,
    })
}

/// The rule is the module's invariants; worked out here is its order — a first section
/// stating no condition, then the first two sections' conditions, then the section Excel
/// keeps for what none of them takes. `None` where no section serves the value.
fn conditional_section<'a>(
    split: &[(&'a str, Option<Condition>)],
    value: f64,
) -> Option<Selection<'a>> {
    // A one-section format draws every value through it; a two-section one repeats its
    // first for a zero value.
    let at = |index: usize| split.get(index).copied().unwrap_or(split[0]);
    let (first, second) = (at(0).1, at(1).1);
    if first.is_none() && value > 0.0 {
        return Some(Selection {
            body: at(0).0,
            signed: false,
        });
    }
    if let Some(held) = first.filter(|it| it.held) {
        return Some(Selection {
            body: at(0).0,
            signed: !held.names_the_negative(),
        });
    }
    if let Some(held) = second.filter(|it| it.held) {
        return Some(Selection {
            body: at(1).0,
            signed: !held.names_the_negative(),
        });
    }
    let (index, signed) = if second.is_none() && value < 0.0 {
        // The second section states no condition, so it is the format's own negative side.
        // Three or more sections carry such a side showing its own minus, and a zero
        // boundary named from above ([`Condition::covers_the_positive`]) leaves a
        // two-section one no positive side: either way the value goes through the second as
        // its magnitude (`[>=1]0;0;0.00` and `[>=-1]0;0` both show -2 as `2`). Otherwise it
        // keeps its own minus (`[>=1]0;0` shows -2 as `-2`).
        (
            1,
            !(split.len() >= 3 || first.is_some_and(Condition::covers_the_positive)),
        )
    } else if split.len() >= 3 {
        // A longer format's third section serves the value no condition takes, and shows
        // the value's own minus.
        (2, true)
    } else if value < 0.0 || split.len() == 1 {
        // Declined rather than shown against a condition that does not hold — which is also
        // what a format whose only section is gated comes to.
        return None;
    } else {
        // A positive value both conditions let past goes through the second section when
        // they do not compare (the negative side, the only one left), else through the
        // first — where a two-section format repeats its first for a zero value.
        (usize::from(!(first.is_some() && second.is_some())), false)
    };
    Some(Selection {
        body: at(index).0,
        signed,
    })
}

/// One section serves every value, two pick the second for a negative value, three or four
/// pick positive, negative and zero in order.
fn sign_position(count: usize, value: f64) -> Option<usize> {
    match count {
        1 => Some(0),
        2 => Some(usize::from(value < 0.0)),
        3 | 4 => Some(if value > 0.0 {
            0
        } else if value < 0.0 {
            1
        } else {
            2
        }),
        _ => None,
    }
}

/// A section split into the text it renders and the condition it is gated on
/// (`[>1000]0.0;[<=1000]0.00`), already evaluated for `value`. Every bracket in the run the
/// section leads with is read wherever it stands: a comparison is evaluated, a directive
/// printing nothing leaves the body, and a bracket that *is* a format element (`[h]`,
/// `[$€-407]`) begins it.
fn split_section(section: &str, value: f64) -> (&str, Option<Condition>) {
    let mut rest = section;
    let mut condition = None;
    let mut body = None;
    while let Some(inner) = rest.trim_start().strip_prefix('[') {
        let Some((bracket, after)) = inner.split_once(']') else {
            break;
        };
        if body.is_none()
            && (elapsed_unit(bracket).is_some() || !currency_symbol(bracket).is_empty())
        {
            body = Some(rest.trim_start());
        }
        if condition.is_none()
            && let Some(read) = condition_of(bracket, value)
        {
            condition = Some(read);
        }
        rest = after;
    }
    (body.unwrap_or(rest), condition)
}

/// The operators a numbered condition may carry, longest first so a two-character operator is never
/// read as one of its halves.
const CONDITIONS: [&str; 6] = ["<=", ">=", "<>", "<", ">", "="];

/// One of a section's own conditions: how Excel tests a value against it, and whether the test
/// passed.
#[derive(Clone, Copy)]
struct Condition {
    operator: &'static str,
    threshold: f64,
    held: bool,
}

impl Condition {
    /// Whether the condition is Excel's way of naming the negative side — `[<0]`,
    /// `[<=-1]`, `[=-3]`: such a section displays a negative value, so Excel shows the
    /// magnitude through it and writes no minus.
    fn names_the_negative(self) -> bool {
        match self.operator {
            // Named from below, the negative side includes its own zero boundary; from
            // above, a zero boundary still names a positive range.
            "=" | "<=" => self.threshold < 0.0,
            "<" => self.threshold <= 0.0,
            _ => false,
        }
    }

    /// Whether it holds for every non-negative number — `[>-1]`, `[>=0]`. Such a format
    /// has no positive section of its own, so no minus can be written through one.
    fn covers_the_positive(self) -> bool {
        match self.operator {
            ">" => self.threshold < 0.0,
            ">=" => self.threshold <= 0.0,
            _ => false,
        }
    }
}

/// `None` when the run is not a comparison at all (a colour, a locale), which is what
/// tells a gated section from one the value's sign selects.
///
/// An operand that is not a number is a condition no value satisfies: the value falls to
/// another section or is declined and marked as stored.
fn condition_of(bracket: &str, value: f64) -> Option<Condition> {
    let (operator, operand) = CONDITIONS
        .iter()
        .find_map(|operator| bracket.strip_prefix(operator).map(|rest| (*operator, rest)))?;
    // Not a number, and no reading of it as a negative or a positive side either.
    let Some(threshold) = operand.trim().parse::<f64>().ok() else {
        return Some(Condition {
            operator,
            threshold: f64::NAN,
            held: false,
        });
    };
    // Excel compares the named serial with the exactness the stored value carries.
    let ordering = value.partial_cmp(&threshold);
    let held = match operator {
        "<" => ordering == Some(Ordering::Less),
        ">" => ordering == Some(Ordering::Greater),
        "<=" => matches!(ordering, Some(Ordering::Less | Ordering::Equal)),
        ">=" => matches!(ordering, Some(Ordering::Greater | Ordering::Equal)),
        "<>" => ordering != Some(Ordering::Equal),
        _ => ordering == Some(Ordering::Equal),
    };
    Some(Condition {
        operator,
        threshold,
        held,
    })
}

/// `m` is emitted as `Month` and reclassified as a minute by its neighbours; `Minute` is
/// only ever produced by an elapsed `[m]`.
#[derive(Clone, Copy)]
enum Unit {
    Year,
    Month,
    Day,
    Hour,
    Minute,
    Second,
    AmPm,
}

/// One meaningful token of a section, with the literal text a number format prints around its
/// placeholders.
#[derive(Clone, Copy)]
enum Tok {
    /// Asked for by the format's author, printed as written.
    Lit(char),
    /// In a section with no placeholder it is as likely a format word this reader does
    /// not know as text the author meant to show.
    Raw(char),
    /// `0`, `#` or `?`.
    Digit(char),
    Dot,
    Comma,
    Percent,
    Slash,
    /// The unquoted `@`: a number cell has no text for it, so its section is declined.
    Text,
    /// A bracketed directive printing a symbol into the placeholders around it
    /// (`[$€-407]`); any other bracket contributes nothing to a number.
    Directive(char),
    /// A `*` jump: Excel pads the cell to its width with the next character — not
    /// reproducible in a line of text.
    Star,
    /// `E+`/`E-`/`e+`/`e-`: the sign that follows the exponent marker.
    ExpSign(char),
    Date(Unit),
    /// An elapsed `[h]`/`[m]`/`[s]`.
    Elapsed(Unit),
}

/// Quoted and escaped text is literal, `_x`/`*x` emit nothing, and a bracketed run emits
/// nothing unless it is an elapsed unit or a currency directive (`[$€-407]`, whose symbol
/// is printed). Conditions and colours carry no text.
fn tokenize(section: &str) -> Vec<Tok> {
    let chars: Vec<char> = section.chars().collect();
    let mut tokens = Vec::new();
    let mut index = 0usize;
    while index < chars.len() {
        let current = chars[index];
        match current {
            '"' => {
                index += 1;
                while index < chars.len() && chars[index] != '"' {
                    tokens.push(Tok::Lit(chars[index]));
                    index += 1;
                }
                index += 1;
            }
            '\\' => {
                if let Some(&escaped) = chars.get(index + 1) {
                    tokens.push(Tok::Lit(escaped));
                }
                index += 2;
            }
            '_' => index += 2,
            '*' => {
                tokens.push(Tok::Star);
                index += 2;
            }
            '[' => {
                let close = chars[index + 1..]
                    .iter()
                    .position(|&c| c == ']')
                    .map_or(chars.len(), |offset| index + 1 + offset);
                let inner: String = chars[index + 1..close].iter().collect();
                if let Some(unit) = elapsed_unit(&inner) {
                    tokens.push(Tok::Elapsed(unit));
                } else {
                    for symbol in currency_symbol(&inner).chars() {
                        tokens.push(Tok::Directive(symbol));
                    }
                }
                index = close + 1;
            }
            '0' | '#' | '?' => {
                tokens.push(Tok::Digit(current));
                index += 1;
            }
            '.' => {
                tokens.push(Tok::Dot);
                index += 1;
            }
            ',' => {
                tokens.push(Tok::Comma);
                index += 1;
            }
            '%' => {
                tokens.push(Tok::Percent);
                index += 1;
            }
            '/' => {
                tokens.push(Tok::Slash);
                index += 1;
            }
            '@' => {
                tokens.push(Tok::Text);
                index += 1;
            }
            'y' | 'Y' => push_date_run(&chars, &mut index, Unit::Year, &mut tokens),
            'd' | 'D' => push_date_run(&chars, &mut index, Unit::Day, &mut tokens),
            'h' | 'H' => push_date_run(&chars, &mut index, Unit::Hour, &mut tokens),
            's' | 'S' => push_date_run(&chars, &mut index, Unit::Second, &mut tokens),
            'm' | 'M' => push_date_run(&chars, &mut index, Unit::Month, &mut tokens),
            'a' | 'A' if starts_with_ignore_ascii_case(&chars, index, "am/pm") => {
                tokens.push(Tok::Date(Unit::AmPm));
                index += 5;
            }
            'a' | 'A' if starts_with_ignore_ascii_case(&chars, index, "a/p") => {
                tokens.push(Tok::Date(Unit::AmPm));
                index += 3;
            }
            'e' | 'E' if matches!(chars.get(index + 1), Some('+' | '-')) => {
                tokens.push(Tok::ExpSign(chars[index + 1]));
                index += 2;
            }
            other => {
                tokens.push(Tok::Raw(other));
                index += 1;
            }
        }
    }
    tokens
}

fn push_date_run(chars: &[char], index: &mut usize, unit: Unit, tokens: &mut Vec<Tok>) {
    let letter = chars[*index].to_ascii_lowercase();
    tokens.push(Tok::Date(unit));
    *index += 1;
    while *index < chars.len() && chars[*index].to_ascii_lowercase() == letter {
        *index += 1;
    }
}

fn starts_with_ignore_ascii_case(chars: &[char], at: usize, needle: &str) -> bool {
    let needle: Vec<char> = needle.chars().collect();
    chars.len() >= at + needle.len()
        && chars[at..at + needle.len()]
            .iter()
            .zip(&needle)
            .all(|(current, expected)| current.to_ascii_lowercase() == *expected)
}

/// The elapsed unit a bracketed run names, or `None` for any other bracket (`[Red]`, `[$-409]`,
/// `[>=100]`, …).
fn elapsed_unit(inner: &str) -> Option<Unit> {
    match inner.to_ascii_lowercase().as_str() {
        "h" | "hh" => Some(Unit::Hour),
        "m" | "mm" => Some(Unit::Minute),
        "s" | "ss" => Some(Unit::Second),
        _ => None,
    }
}

/// `€` from `[$€-407]`, `$` from `[$$-409]`, `USD` from `[$USD-409]` — or `""` when the
/// bracket names no symbol: a colour, a condition, or a locale alone (the hex LCID
/// `[$-409]` or a BCP-47 tag like `[$-en-US]`). The locale is always dropped: the code's
/// own separators print, so the format stays locale-independent.
fn currency_symbol(inner: &str) -> &str {
    let Some(rest) = inner.strip_prefix('$') else {
        return "";
    };
    match rest.split_once('-') {
        Some((symbol, _)) if !symbol.is_empty() => symbol,
        Some(_) => "",
        None => rest,
    }
}

fn is_date(tokens: &[Tok]) -> bool {
    tokens
        .iter()
        .any(|tok| matches!(tok, Tok::Date(_) | Tok::Elapsed(_)))
}

/// Which date/time units a section names, and whether a minute-role `m`, a day, a month or a year
/// is present — the shape the date renderer works from.
#[derive(Default)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "each unit is an independent yes/no the renderer reads"
)]
struct DateShape {
    has_date: bool,
    has_time: bool,
    hour: bool,
    minute: bool,
    second: bool,
    elapsed_hour: bool,
    elapsed_minute: bool,
    elapsed_second: bool,
}

fn date_shape(tokens: &[Tok]) -> DateShape {
    let mut shape = DateShape::default();
    for (index, tok) in tokens.iter().enumerate() {
        match tok {
            Tok::Date(Unit::Month) if minute_role(tokens, index) => {
                shape.has_time = true;
                shape.minute = true;
            }
            Tok::Date(Unit::Year | Unit::Month | Unit::Day) => shape.has_date = true,
            Tok::Date(Unit::Hour) => {
                shape.has_time = true;
                shape.hour = true;
            }
            Tok::Date(Unit::Second) => {
                shape.has_time = true;
                shape.second = true;
            }
            Tok::Date(Unit::AmPm) => shape.has_time = true,
            Tok::Elapsed(Unit::Hour) => {
                shape.has_time = true;
                shape.hour = true;
                shape.elapsed_hour = true;
            }
            Tok::Elapsed(Unit::Minute) => {
                shape.has_time = true;
                shape.minute = true;
                shape.elapsed_minute = true;
            }
            Tok::Elapsed(Unit::Second) => {
                shape.has_time = true;
                shape.second = true;
                shape.elapsed_second = true;
            }
            _ => {}
        }
    }
    shape
}

/// Whether the `m` at `index` is a minute: it follows an hour, or precedes a second, else it is a
/// month.
fn minute_role(tokens: &[Tok], index: usize) -> bool {
    let is_date_token = |tok: &&Tok| matches!(tok, Tok::Date(_) | Tok::Elapsed(_));
    let preceding = tokens[..index].iter().rev().find(is_date_token);
    if matches!(
        preceding,
        Some(Tok::Date(Unit::Hour) | Tok::Elapsed(Unit::Hour))
    ) {
        return true;
    }
    let following = tokens[index + 1..].iter().find(is_date_token);
    matches!(
        following,
        Some(Tok::Date(Unit::Second) | Tok::Elapsed(Unit::Second))
    )
}

/// `None` outside the domain a serial has: a negative value or one past
/// [`VALUE_LIMIT`] (Excel shows `#####`, this reader declines to guess), and a day the
/// calendar Excel's epochs define does not hold.
#[expect(
    clippy::cast_possible_truncation,
    reason = "a value bounded by VALUE_LIMIT has a day count that fits i64"
)]
fn render_date(value: f64, date1904: bool, tokens: &[Tok]) -> Option<String> {
    if !(0.0..=VALUE_LIMIT).contains(&value) {
        return None;
    }
    let shape = date_shape(tokens);
    let places = fractional_second_places(tokens);
    if places > MAX_SUB_SECOND_DIGITS {
        return None;
    }
    let mut days = value.trunc() as i64;
    let (mut seconds, ticks) = split_seconds(value.fract() * 86_400.0, places);
    if seconds >= 86_400 {
        seconds -= 86_400;
        days += 1;
    }
    let fraction = if places == 0 {
        String::new()
    } else {
        format!(".{ticks:0places$}")
    };
    if shape.elapsed_hour || shape.elapsed_minute || shape.elapsed_second {
        let total = days * 86_400 + seconds;
        return Some(duration(&shape, total, &fraction));
    }
    let hour = seconds / 3_600;
    let minute = (seconds % 3_600) / 60;
    let second = seconds % 60;
    let clock = format!("{hour:02}:{minute:02}:{second:02}{fraction}");
    if shape.has_date {
        let (year, month, day) = civil_date(days, date1904)?;
        let mut out = format!("{year:04}-{month:02}-{day:02}");
        if shape.has_time || seconds != 0 {
            out.push(' ');
            out.push_str(&clock);
        }
        return Some(out);
    }
    // Time-only: the units the section names, hour/minute/second order.
    let mut parts = Vec::new();
    if shape.hour {
        parts.push(format!("{hour:02}"));
    }
    if shape.minute {
        parts.push(format!("{minute:02}"));
    }
    if shape.second {
        parts.push(format!("{second:02}{fraction}"));
    }
    if parts.is_empty() {
        return Some(clock);
    }
    Some(parts.join(":"))
}

/// The section's own precision decides both: no fractional digit rounds the second itself,
/// and naming them carries a rounded-up fraction into it.
#[expect(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    reason = "the seconds a day holds bound every count here, so each fits both the integer type it \
              is cast to and the 53-bit mantissa it is cast from"
)]
fn split_seconds(raw: f64, places: usize) -> (i64, i64) {
    if places == 0 {
        return (raw.round() as i64, 0);
    }
    let scale = 10_i64.pow(u32::try_from(places).unwrap_or(0));
    let mut ticks = (raw.fract() * scale as f64).round() as i64;
    let mut seconds = raw.trunc() as i64;
    if ticks >= scale {
        ticks -= scale;
        seconds += 1;
    }
    (seconds, ticks)
}

/// (`ss.0` names one, `ss.000` three); zero when the smallest unit named is not a second.
fn fractional_second_places(tokens: &[Tok]) -> usize {
    let Some(dot) = tokens.iter().rposition(|tok| matches!(tok, Tok::Dot)) else {
        return 0;
    };
    let places = tokens[dot + 1..]
        .iter()
        .filter(|tok| matches!(tok, Tok::Digit(_)))
        .count();
    if places == 0 {
        return 0;
    }
    match tokens[..dot]
        .iter()
        .rev()
        .find(|tok| matches!(tok, Tok::Date(_) | Tok::Elapsed(_)))
    {
        Some(Tok::Date(Unit::Second) | Tok::Elapsed(Unit::Second)) => places,
        _ => 0,
    }
}

/// The elapsed unit counts the whole span, the smaller named units the remainder, the
/// fraction belongs to the seconds.
fn duration(shape: &DateShape, total_seconds: i64, fraction: &str) -> String {
    let mut parts = Vec::new();
    if shape.hour {
        parts.push(format!("{:02}", total_seconds / 3_600));
    }
    if shape.minute {
        let minutes = if shape.elapsed_minute {
            total_seconds / 60
        } else {
            (total_seconds % 3_600) / 60
        };
        parts.push(format!("{minutes:02}"));
    }
    if shape.second {
        let seconds = if shape.elapsed_second {
            total_seconds
        } else {
            total_seconds % 60
        };
        parts.push(format!("{seconds:02}{fraction}"));
    }
    parts.join(":")
}

struct Rendered {
    text: String,
    /// A body of nothing but zeros is what a value rounded away to nothing shows, and the
    /// minus on it is a zero Excel never writes (`-0.4` under `0` is `0`); a digit from the
    /// format's own literals (`"v1 "0`) is no number of the cell's. Neither earns the minus
    /// a lone section adds.
    shows_number: bool,
}

/// The digits alone, the format's literals excluded.
fn has_digits(digits: &str) -> bool {
    digits
        .bytes()
        .any(|byte| byte.is_ascii_digit() && byte != b'0')
}

/// Where the one decimal point a section body may name stands.
#[derive(Clone, Copy)]
enum Point {
    /// The section names no point at all: its layout has no fraction.
    Absent,
    /// The section's point, as its position in the section's tokens.
    At(usize),
}

impl Point {
    /// Every placeholder when the section names no point.
    fn is_integer(self, index: usize) -> bool {
        match self {
            Self::Absent => true,
            Self::At(at) => index < at,
        }
    }

    fn is_fraction(self, index: usize) -> bool {
        match self {
            Self::Absent => false,
            Self::At(at) => index > at,
        }
    }
}

/// The one decimal point a section body may name. `None` is a section this reader has no place for
/// — one naming a second point (`0.0.0`), or one whose point stands outside the placeholders
/// `first..=last`: before the first (`.00`, whose digits would be counted as the whole part) or
/// after the last (`0.5`, whose `5` is literal in Excel).
fn decimal_point(tokens: &[Tok], first: usize, last: usize) -> Option<Point> {
    let mut point = Point::Absent;
    for (index, tok) in tokens.iter().enumerate() {
        // A second point is no layout this reader has a place for.
        if matches!(tok, Tok::Dot) {
            if matches!(point, Point::At(_)) {
                return None;
            }
            point = Point::At(index);
        }
    }
    if let Point::At(at) = point
        && (at <= first || at >= last)
    {
        return None;
    }
    Some(point)
}

/// `None` for a form this reader does not implement: a fraction, the text placeholder, or a section
/// naming no placeholder at all — a format string or a directive, never a number a cell holds.
fn render_number(value: f64, tokens: &[Tok]) -> Option<Rendered> {
    if tokens
        .iter()
        .any(|tok| matches!(tok, Tok::Slash | Tok::Text))
    {
        return None;
    }
    if tokens.iter().any(|tok| matches!(tok, Tok::ExpSign(_))) {
        return render_scientific(value, tokens);
    }
    let (Some(first), Some(last)) = (
        tokens.iter().position(|tok| matches!(tok, Tok::Digit(_))),
        tokens.iter().rposition(|tok| matches!(tok, Tok::Digit(_))),
    ) else {
        // With no placeholder, only text the format asked for is shown: a quoted or escaped
        // run (`"neg"`, `_(* "-"_)`). Anything else — an unknown localized format word, a
        // lone marker or directive (`%`, `,`, `[$USD-409]`) or `General` — is a format
        // string, never a number a cell holds.
        return tokens
            .iter()
            .any(|tok| matches!(tok, Tok::Lit(_)))
            .then(|| Rendered {
                text: literal_text(tokens),
                shows_number: false,
            });
    };
    // The point must stand between the placeholders; anywhere else it would be dropped with
    // the layout around it, so the section is declined ([`decimal_point`]).
    let point = decimal_point(tokens, first, last)?;
    // A literal standing *between* the placeholders (`000-00-0000`) is laid between the
    // digits; one only around them is a plain prefix or suffix.
    if tokens[first..=last].iter().copied().any(is_text) {
        return render_layered(value, tokens, first, last, point);
    }
    render_plain(value, tokens, first, last, point)
}

/// Whether a token prints text of its own, in the place the section puts it: a literal, a
/// directive's symbol or the sign a `%` stands for. A body holding one cannot be a plain layout of
/// digits — the text would drop out of it — so such a section is laid out in place instead
/// ([`render_layered`]).
fn is_text(tok: Tok) -> bool {
    matches!(
        tok,
        Tok::Lit(_) | Tok::Raw(_) | Tok::Directive(_) | Tok::Percent
    )
}

/// The literal text tokens carry, placeholders and markers contributing nothing: the `%` a section
/// prints, a currency directive's symbol and escaped or quoted characters.
fn literal_text(tokens: &[Tok]) -> String {
    let mut out = String::new();
    for tok in tokens {
        push_literal(*tok, &mut out);
    }
    out
}

fn push_literal(tok: Tok, out: &mut String) {
    match tok {
        Tok::Lit(c) | Tok::Raw(c) | Tok::Directive(c) => out.push(c),
        Tok::Percent => out.push('%'),
        Tok::Comma => out.push(','),
        _ => {}
    }
}

/// How many placeholders are in the integer part (the `0`s force its width), how many
/// are fractional and how many of those force a digit, and whether a `,` groups the
/// integer part.
#[derive(Default)]
struct PlainShape {
    int_zeros: usize,
    frac_zeros: usize,
    frac_placeholders: usize,
    grouping: bool,
}

/// Count the shape of the placeholders in `tokens[first..=last]`, whose section names its
/// decimal point `point`: a `,` inside the body groups rather than scales.
fn plain_shape(tokens: &[Tok], first: usize, last: usize, point: Point) -> PlainShape {
    let mut shape = PlainShape::default();
    for (offset, tok) in tokens[first..=last].iter().enumerate() {
        let fractional = point.is_fraction(first + offset);
        match *tok {
            Tok::Digit('0') if fractional => {
                shape.frac_placeholders += 1;
                shape.frac_zeros += 1;
            }
            Tok::Digit('0') => shape.int_zeros += 1,
            Tok::Digit(_) if fractional => shape.frac_placeholders += 1,
            Tok::Comma => shape.grouping = true,
            _ => {}
        }
    }
    shape
}

/// Each scales the value by a thousand; a `,` between placeholders groups instead.
fn leading_commas(tokens: &[Tok]) -> usize {
    tokens
        .iter()
        .take_while(|tok| matches!(tok, Tok::Comma))
        .count()
}

/// Each scales the value by a thousand (`,`, `,,`).
fn scaling_commas(tokens: &[Tok], last: usize) -> usize {
    leading_commas(&tokens[last + 1..])
}

/// The scaled integer a section's placeholders show: `value` after the `%` and trailing-comma
/// scaling the section asks for, rounded at its own precision.
fn scaled_plain(value: f64, tokens: &[Tok], last: usize, places: i32) -> Option<i128> {
    let mut value = value;
    for tok in tokens {
        if matches!(tok, Tok::Percent) {
            value *= 100.0;
        }
    }
    for _ in 0..scaling_commas(tokens, last) {
        value /= 1_000.0;
    }
    scaled_magnitude(value, places)
}

/// A scaled integer as the digit body a section shows: the integer part padded to the `0`s that
/// force its width and grouped when the section asks, the fraction trimmed to the digits that force
/// one, behind the point a section naming any fractional part always carries.
fn digit_text(scaled: i128, shape: &PlainShape) -> Option<String> {
    let rendered = magnitude_text(scaled, u32::try_from(shape.frac_placeholders).ok()?)?;
    let (int_raw, mut frac_digits) = rendered.find('.').map_or_else(
        || (rendered.clone(), String::new()),
        |at| (rendered[..at].to_owned(), rendered[at + 1..].to_owned()),
    );
    while frac_digits.len() > shape.frac_zeros && frac_digits.ends_with('0') {
        frac_digits.pop();
    }
    // The integer part: `0`s force its width, and a bare zero prints nothing.
    let mut int_digits = if int_raw == "0" && shape.int_zeros == 0 {
        String::new()
    } else {
        int_raw
    };
    while int_digits.len() < shape.int_zeros {
        int_digits.insert(0, '0');
    }
    if shape.grouping {
        int_digits = group_thousands(&int_digits);
    }
    // The point stands even when the value shows no digit after it (`#.#####` shows 1 as
    // `1.` and 0 as `.`); a section naming no fraction never writes one.
    if shape.frac_placeholders > 0 {
        int_digits.push('.');
        int_digits.push_str(&frac_digits);
    }
    Some(int_digits)
}

/// The literal text standing before and after a digit body, and the body itself.
struct Pieces {
    digits: String,
    prefix: String,
    suffix: String,
}

/// The integer part padded to the `0`s that force its width and grouped when the section
/// asks, the fraction trimmed to the digits that force one, with the literals before and
/// after it (scaling commas excluded). `grouping` says whether this form can carry the
/// section's grouping at all: a body whose literals stand *between* its placeholders
/// cannot, since the commas would land in a placeholder.
fn plain_pieces(
    value: f64,
    tokens: &[Tok],
    first: usize,
    last: usize,
    grouping: bool,
    point: Point,
) -> Option<Pieces> {
    let shape = plain_shape(tokens, first, last, point);
    if shape.int_zeros > MAX_PLACEHOLDERS
        || shape.frac_placeholders > MAX_PLACEHOLDERS
        || (shape.grouping && !grouping)
    {
        return None;
    }
    let places = i32::try_from(shape.frac_placeholders).ok()?;
    let digits = digit_text(scaled_plain(value, tokens, last, places)?, &shape)?;
    Some(Pieces {
        digits,
        prefix: literal_text(&tokens[..first]),
        suffix: literal_text(&tokens[last + 1 + scaling_commas(tokens, last)..]),
    })
}

/// A plain fixed-point section: literals around a digit body of integer and fractional
/// placeholders, with `%`, scaling commas and grouping.
fn render_plain(
    value: f64,
    tokens: &[Tok],
    first: usize,
    last: usize,
    point: Point,
) -> Option<Rendered> {
    let Pieces {
        digits,
        prefix,
        suffix,
    } = plain_pieces(value, tokens, first, last, true, point)?;
    Some(Rendered {
        text: format!("{prefix}{digits}{suffix}"),
        shows_number: has_digits(&digits),
    })
}

/// The digits are laid into the placeholder positions and the literals keep their own. A
/// body naming a fractional part or a grouping comma is not one this layout can carry, nor
/// is a value whose digits do not fill it exactly — more digits would be shown shorter
/// than they are, fewer leave a literal nothing stands beside.
fn render_layered(
    value: f64,
    tokens: &[Tok],
    first: usize,
    last: usize,
    point: Point,
) -> Option<Rendered> {
    let body = &tokens[first..=last];
    // The section's own point is the one its body names ([`decimal_point`]); a body with
    // literals between its placeholders cannot carry a fractional part.
    if matches!(point, Point::At(_)) {
        return None;
    }
    let Pieces {
        digits,
        prefix,
        suffix,
    } = plain_pieces(value, tokens, first, last, false, point)?;
    let places = body
        .iter()
        .filter(|tok| matches!(tok, Tok::Digit(_)))
        .count();
    if digits.len() != places {
        return None;
    }
    // Each placeholder takes the next digit; the lengths above are equal, so every one has one.
    let mut chars = digits.chars();
    let mut out = prefix;
    for tok in body {
        match *tok {
            Tok::Digit(_) => out.push(chars.next()?),
            other => push_literal(other, &mut out),
        }
    }
    out.push_str(&suffix);
    Some(Rendered {
        text: out,
        shows_number: has_digits(&digits),
    })
}

/// A mantissa the section's placeholders lay out, then `E`, the sign and the exponent.
/// Excel normalises the mantissa into `[1, 10^width)`, `width` being the integer
/// placeholders the section names, so the exponent is the largest multiple of that width at
/// or below the value's decade: `##0.0E+0` shows 1234 as `1.2E+3`, `00.0E+0` shows 12345
/// as `01.2E+4`.
fn render_scientific(value: f64, tokens: &[Tok]) -> Option<Rendered> {
    let marker = tokens
        .iter()
        .position(|tok| matches!(tok, Tok::ExpSign(_)))?;
    let Tok::ExpSign(sign) = tokens[marker] else {
        return None;
    };
    let mantissa_tokens = &tokens[..marker];
    let first = mantissa_tokens
        .iter()
        .position(|tok| matches!(tok, Tok::Digit(_)))?;
    let last = mantissa_tokens
        .iter()
        .rposition(|tok| matches!(tok, Tok::Digit(_)))?;
    let exponent_tokens = &tokens[marker + 1..];
    // The exponent prints its one run of placeholders, with the literals around them and the
    // scaling commas after them. A decimal point in the region, or a placeholder the run does
    // not reach (`E+0.0`, `E+0,0`), would be dropped from the display, so the section is declined.
    let digits_at = exponent_tokens
        .iter()
        .position(|tok| matches!(tok, Tok::Digit(_)))?;
    let last_digit = exponent_tokens
        .iter()
        .rposition(|tok| matches!(tok, Tok::Digit(_)))?;
    if exponent_tokens.iter().any(|tok| matches!(tok, Tok::Dot))
        || exponent_tokens[digits_at..=last_digit]
            .iter()
            .any(|tok| !matches!(tok, Tok::Digit(_)))
    {
        return None;
    }
    let exponent_width = last_digit - digits_at + 1;

    // The point must stand between the mantissa's placeholders; anywhere else it would be
    // dropped with the part around it, so the section is declined ([`decimal_point`]).
    let point = decimal_point(mantissa_tokens, first, last)?;
    // The mantissa's integer placeholders that force a digit.
    let int_zeros = plain_shape(mantissa_tokens, first, last, point).int_zeros;
    let width = mantissa_tokens
        .iter()
        .enumerate()
        .filter(|(index, tok)| matches!(tok, Tok::Digit(_)) && point.is_integer(*index))
        .count()
        .max(1);
    let places = mantissa_tokens
        .iter()
        .enumerate()
        .filter(|(index, tok)| matches!(tok, Tok::Digit(_)) && point.is_fraction(*index))
        .count();
    if width > MAX_PLACEHOLDERS || places > MAX_PLACEHOLDERS || exponent_width > MAX_PLACEHOLDERS {
        return None;
    }
    let width = i32::try_from(width).ok()?;
    let places = i32::try_from(places).ok()?;

    // A `%` scales by a hundred each and prints where it stands; a `,` run after the
    // mantissa's or the exponent's placeholders scales by a thousand each and does not
    // print — as in a plain section.
    let mut value = value;
    for tok in tokens {
        if matches!(tok, Tok::Percent) {
            value *= 100.0;
        }
    }
    let exponent_end = digits_at + exponent_width;
    let scaling = leading_commas(&exponent_tokens[exponent_end..]);
    let mantissa_scaling = scaling_commas(mantissa_tokens, last);
    for _ in 0..scaling + mantissa_scaling {
        value /= 1_000.0;
    }

    let mut exponent = 0i32;
    let mut scaled = 0i128;
    if value != 0.0 {
        exponent = decade(value.abs())?.div_euclid(width) * width;
        scaled = scaled_magnitude(value, places - exponent)?;
        // The mantissa's own rounding can carry it into the next decade (`0.00E+00` shows
        // 999.5 as `1.00E+03`), which raises the exponent.
        let ceiling = pow10_int(usize::try_from(places).ok()?)?
            .checked_mul(pow10_int(usize::try_from(width).ok()?)?)?;
        if scaled >= ceiling {
            exponent += width;
            scaled = scaled_magnitude(value, places - exponent)?;
        }
    }

    // Excel lays a zero mantissa out to the section's integer width, so `##0.0E+0` shows 0 as
    // `000.0E+0`; this reader does not, and declines a section whose integer placeholders
    // force a wider zero (an all-`0` run like `0.00E+00` keeps its zero).
    if scaled == 0 && usize::try_from(width).ok()? > int_zeros {
        return None;
    }

    let mantissa = mantissa_text(mantissa_tokens, first, last, scaled, point)?;
    if mantissa.trim().is_empty() {
        return None;
    }
    let mut exponent_digits = exponent.unsigned_abs().to_string();
    while exponent_digits.len() < exponent_width {
        exponent_digits.insert(0, '0');
    }
    let mut out = mantissa;
    out.push('E');
    if exponent < 0 {
        out.push('-');
    } else if sign == '+' {
        out.push('+');
    }
    out.push_str(&literal_text(&exponent_tokens[..digits_at]));
    out.push_str(&exponent_digits);
    out.push_str(&literal_text(&exponent_tokens[exponent_end + scaling..]));
    Some(Rendered {
        text: out,
        shows_number: scaled != 0,
    })
}

/// The digits `scaled` stands for, laid out by the section's placeholders with the literals
/// around them. A mantissa with literals between its placeholders, or with placeholders a
/// display cannot hold, is declined rather than laid out wrong.
fn mantissa_text(
    tokens: &[Tok],
    first: usize,
    last: usize,
    scaled: i128,
    point: Point,
) -> Option<String> {
    if tokens[first..=last].iter().copied().any(is_text) {
        return None;
    }
    let shape = plain_shape(tokens, first, last, point);
    if shape.int_zeros > MAX_PLACEHOLDERS || shape.frac_placeholders > MAX_PLACEHOLDERS {
        return None;
    }
    Some(format!(
        "{}{}{}",
        literal_text(&tokens[..first]),
        digit_text(scaled, &shape)?,
        literal_text(&tokens[last + 1 + scaling_commas(tokens, last)..])
    ))
}

/// Its digits and the decimal point `places` digits from the right. The sign is the
/// section's own business — every caller here works from a magnitude.
fn magnitude_text(scaled: i128, places: u32) -> Option<String> {
    let digits = scaled.to_string();
    let places = usize::try_from(places).ok()?;
    if places == 0 {
        return Some(digits);
    }
    Some(match digits.len().checked_sub(places) {
        Some(point) => format!("{}.{}", &digits[..point], &digits[point..]),
        // Fewer digits than places: the magnitude is a fraction of one.
        None => format!("0.{}{digits}", "0".repeat(places - digits.len())),
    })
}

/// The magnitude canonicalised to the 15 significant decimal digits Excel works with, then
/// rounded half away from zero at the place `shift` names; `None` when it has no exact
/// display there.
///
/// The 15-digit step is what displays `1.005` under `0.00` as `1.01` — the double holding it
/// is a hair below the tie — and what normalises a scientific mantissa. A `shift` no integer
/// can reach means the value rounds to nothing there.
fn scaled_magnitude(value: f64, shift: i32) -> Option<i128> {
    if !value.is_finite() {
        return None;
    }
    let magnitude = value.abs();
    // `d.dddddddddddddde±XX`: the magnitude's 15 significant decimal digits, so
    // `magnitude == digits * 10^(exponent - 14)`.
    let text = format!("{magnitude:.14e}");
    let (mantissa, exponent) = text.split_once('e')?;
    let exponent: i32 = exponent.parse().ok()?;
    let digits: i128 = mantissa.replace('.', "").parse().ok()?;
    let shift = exponent.checked_sub(14)?.checked_add(shift)?;
    let rounded = if shift >= 0 {
        // The digits reach past the place: the product is exact.
        let mut value = digits;
        for _ in 0..usize::try_from(shift).ok()? {
            value = value.checked_mul(10)?;
        }
        value
    } else {
        // The place is finer than the digits reach: round at it. A divisor past
        // what an integer holds is far beyond them, so they round to nothing.
        let Some(divisor) = pow10_int(usize::try_from(shift.unsigned_abs()).ok()?) else {
            return Some(0);
        };
        let quotient = digits / divisor;
        let remainder = digits % divisor;
        if remainder * 2 >= divisor {
            quotient + 1
        } else {
            quotient
        }
    };
    (rounded <= MAX_SCALED).then_some(rounded)
}
/// The decade of a finite non-zero magnitude: the exponent of its leading significant digit, read
/// from the same canonical decimal the display rounding works from rather than from a logarithm a
/// binary value can land just under.
fn decade(magnitude: f64) -> Option<i32> {
    let text = format!("{magnitude:.14e}");
    text.split_once('e')?.1.parse().ok()
}

/// `10^power` as an exact integer, or `None` when it has no integer form here.
fn pow10_int(power: usize) -> Option<i128> {
    let mut value: i128 = 1;
    for _ in 0..power {
        value = value.checked_mul(10)?;
    }
    Some(value)
}

/// Insert Excel's thousands separators into a run of ASCII digits.
fn group_thousands(digits: &str) -> String {
    let mut out = String::with_capacity(digits.len() + digits.len() / 3);
    for (index, digit) in digits.chars().enumerate() {
        if index > 0 && (digits.len() - index).is_multiple_of(3) {
            out.push(',');
        }
        out.push(digit);
    }
    out
}

/// Days from the Unix epoch to 1899-12-31, the 1900 system's day 0.
const EPOCH_1900: i64 = days_from_civil(1899, 12, 31);
/// Days from the Unix epoch to 1904-01-01, the 1904 system's day 0.
const EPOCH_1904: i64 = days_from_civil(1904, 1, 1);

/// The serial's civil date, applying Excel's phantom 1900-02-29 (serial 60) in
/// the 1900 system and the 1904 base otherwise. `None` for a serial day outside
/// the calendar that system defines — day 0 of the 1900 system, the fake
/// `1900-01-00` Excel writes for a zero date, and anything past 9999-12-31 in either.
fn civil_date(serial_days: i64, date1904: bool) -> Option<(i64, u32, u32)> {
    if date1904 {
        return (0..=SERIAL_LIMIT_1904)
            .contains(&serial_days)
            .then(|| civil_from_days(EPOCH_1904 + serial_days));
    }
    if !(1..=SERIAL_LIMIT).contains(&serial_days) {
        return None;
    }
    Some(match serial_days.cmp(&60) {
        Ordering::Equal => (1900, 2, 29),
        Ordering::Greater => civil_from_days(EPOCH_1900 + serial_days - 1),
        Ordering::Less => civil_from_days(EPOCH_1900 + serial_days),
    })
}

/// Days since 1970-01-01 for a proleptic Gregorian date (Howard Hinnant's
/// `days_from_civil`).
#[expect(
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss,
    reason = "the civil year is bounded by the callers, so every era and day count fits the type it \
              is cast to and is non-negative where it is cast to an unsigned one"
)]
const fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
    let year = if month <= 2 { year - 1 } else { year };
    let era = if year >= 0 { year } else { year - 399 } / 400;
    let year_of_era = (year - era * 400) as u64;
    let day_of_year =
        (153 * (if month > 2 { month - 3 } else { month + 9 }) as u64 + 2) / 5 + (day as u64 - 1);
    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
    era * 146_097 + day_of_era as i64 - 719_468
}

/// The proleptic Gregorian `(year, month, day)` for days since 1970-01-01
/// (Howard Hinnant's `civil_from_days`).
#[expect(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss,
    reason = "the day count is bounded by the callers, so every era, year and day-of-month here \
              fits the type it is cast to and is non-negative where it is cast to an unsigned one"
)]
const fn civil_from_days(days: i64) -> (i64, u32, u32) {
    let days = days + 719_468;
    let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
    let day_of_era = (days - era * 146_097) as u64;
    let year_of_era =
        (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
    let year = year_of_era as i64 + era * 400;
    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
    let month_phase = (5 * day_of_year + 2) / 153;
    let day = (day_of_year - (153 * month_phase + 2) / 5 + 1) as u32;
    let month = if month_phase < 10 {
        month_phase + 3
    } else {
        month_phase - 9
    } as u32;
    let year = if month <= 2 { year + 1 } else { year };
    (year, month, day)
}

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

    /// [`display`] for a builtin format of the 1900 system, the shape most of these
    /// tests use.
    fn by_id(value: f64, id: u32) -> Option<String> {
        display(value, id, None, false)
    }

    #[test]
    fn general_is_detected_from_the_id_or_the_declared_code() {
        assert!(is_general(0, None));
        assert!(!is_general(0, Some("")));
        assert!(!is_general(14, None));
        assert!(is_general(5, Some("General")));
        assert!(is_general(5, Some("general")));
        assert!(!is_general(0, Some("#,##0")));
        // A directive, padding or a repeated section does not hide `General`.
        assert!(is_general(164, Some("[DBNum1][$-804]General")));
        assert!(is_general(164, Some(" General ")));
        assert!(is_general(164, Some("General;General")));
        assert!(!is_general(164, Some("General;0")));
        assert_eq!(by_id(5.0, 0), None);
        assert_eq!(display(5.0, 164, Some("General"), false), None);
        assert_eq!(display(5.0, 164, Some("[$-409]general"), false), None);
    }

    /// The plain, grouped and percentage sections of the builtin table: the places
    /// a section names decide what is shown, and a `%` scales the value by a hundred.
    #[test]
    fn plain_formats_round_pad_and_group() {
        for (label, value, id, shown) in [
            ("a whole section has no places", 5.4, 1_u32, "5"),
            ("a value on the tie rounds up", 5.5, 1, "6"),
            ("two places pad a short fraction", 5.5, 2, "5.50"),
            ("a grouped section prints its commas", 1234.0, 3, "1,234"),
            ("a grouped section rounds", 1234.5, 3, "1,235"),
            ("a grouped section keeps two places", 1234.5, 4, "1,234.50"),
            ("a percentage scales the value", 0.25, 9, "25%"),
            ("a percentage keeps two places", 0.25, 10, "25.00%"),
        ] {
            assert_eq!(by_id(value, id).as_deref(), Some(shown), "{label}");
        }
    }

    /// The currency and accounting sections, and the `[$…]` directive a format may
    /// name: a negative is parenthesised where the format says so, a zero shows the
    /// dash section, and a directive prints the symbol it names while a directive
    /// naming no symbol is only a locale.
    #[test]
    fn currency_formats_wrap_negatives_in_parentheses() {
        for (label, value, id, code, shown) in [
            ("a dollar section", 1234.0, 5_u32, None, Some("$1,234")),
            (
                "a negative is parenthesised",
                -1234.0,
                5,
                None,
                Some("($1,234)"),
            ),
            (
                "the plain currency negative section",
                -1234.0,
                6,
                None,
                Some("($1,234)"),
            ),
            (
                "a negative with places",
                -1234.5,
                7,
                None,
                Some("($1,234.50)"),
            ),
            ("a positive with places", 1234.5, 8, None, Some("$1,234.50")),
            ("an accounting section", 1234.0, 41, None, Some("1,234")),
            ("an accounting negative", -1234.0, 41, None, Some("(1,234)")),
            ("zero shows the dash section", 0.0, 41, None, Some("-")),
            (
                "zero in the dollar accounting zero section",
                0.0,
                42,
                None,
                Some("$-"),
            ),
            (
                "zero in the two-place accounting zero section",
                0.0,
                43,
                None,
                Some("-"),
            ),
            (
                "zero in the two-place dollar zero section",
                0.0,
                44,
                None,
                Some("$-"),
            ),
            (
                "a suffix directive",
                1234.5,
                164,
                Some("#,##0.00 [$€-407]"),
                Some("1,234.50 €"),
            ),
            (
                "a prefix directive",
                1234.5,
                164,
                Some("[$$-409]#,##0.00"),
                Some("$1,234.50"),
            ),
            (
                "a named symbol",
                1234.5,
                164,
                Some("[$USD-409]#,##0.00"),
                Some("USD1,234.50"),
            ),
            (
                "a locale-only directive prints nothing",
                1234.5,
                164,
                Some("#,##0.00[$-409]"),
                Some("1,234.50"),
            ),
            (
                "a BCP-47 locale prints nothing",
                1234.5,
                164,
                Some("[$-en-US]#,##0.00"),
                Some("1,234.50"),
            ),
            (
                "a system-date directive prints nothing",
                1234.5,
                164,
                Some("[$-x-sysdate]0.0"),
                Some("1234.5"),
            ),
        ] {
            assert_eq!(display(value, id, code, false).as_deref(), shown, "{label}");
        }
    }

    /// Excel displays a number rounded from the 15 significant decimal digits it
    /// works with, so a value that is really the decimal `1.005` shows `1.01`
    /// under `0.00` even though the binary double holding it is a hair below the
    /// tie. A value that rounds away to nothing is never shown as a negative zero.
    #[test]
    fn a_tie_rounds_the_way_excel_displays_it() {
        for (label, value, id, shown) in [
            ("a decimal tie", 1.005, 2_u32, "1.01"),
            ("a tie from below", 0.145, 2, "0.15"),
            ("another tie", 0.285, 2, "0.29"),
            ("a tie in a longer fraction", 8.575, 2, "8.58"),
            ("a half rounds away from zero", 2.5, 1, "3"),
            ("a tie rounds into the exponent", 999.5, 11, "1.00E+03"),
            ("a tie rounds to the next decade", 0.9995, 11, "1.00E+00"),
            ("a value rounding to nothing has no minus", -0.4, 1, "0"),
            ("a value keeping a digit keeps its minus", -0.04, 2, "-0.04"),
            ("a negative half rounds away from zero", -0.5, 1, "-1"),
        ] {
            assert_eq!(by_id(value, id).as_deref(), Some(shown), "{label}");
        }
    }

    /// Excel normalises a scientific mantissa into `[1, 10^width)` — `width` the
    /// integer placeholders the section names — so the exponent is a multiple of
    /// that width, and the section keeps everything it names after the exponent: a
    /// `%` scales the value and is printed where it is written, and a literal
    /// stands where it is written.
    #[test]
    fn scientific_formats_normalise_the_mantissa() {
        for (label, value, id, code, shown) in [
            (
                "a two-integer mantissa",
                12345.678,
                11_u32,
                None,
                "1.23E+04",
            ),
            ("three integer places", 12345.0, 48, None, "12.3E+3"),
            ("one integer place", 1234.0, 48, None, "1.2E+3"),
            ("a single digit", 1.0, 48, None, "1.0E+0"),
            ("a million", 1_000_000.0, 48, None, "1.0E+6"),
            (
                "a zero placeholder pads the mantissa",
                12_345.0,
                164,
                Some("00.0E+0"),
                "01.2E+4",
            ),
            (
                "a trailing percent scales and prints",
                0.25,
                164,
                Some("0.00E+00%"),
                "2.50E+01%",
            ),
            (
                "a percent inside the mantissa is applied once",
                0.25,
                164,
                Some("0.00%E+00"),
                "2.50%E+01",
            ),
            (
                "a percent ahead of the mantissa",
                0.25,
                164,
                Some("%0.00E+00"),
                "%2.50E+01",
            ),
            (
                "a literal after the exponent",
                1234.5,
                164,
                Some("0.00E+00\" kg\""),
                "1.23E+03 kg",
            ),
            ("a negative mantissa", -1234.5, 11, None, "-1.23E+03"),
            (
                "a trailing comma run scales and is not printed",
                1.5,
                164,
                Some("0.0E+0,,"),
                "1.5E-6",
            ),
        ] {
            assert_eq!(
                display(value, id, code, false).as_deref(),
                Some(shown),
                "{label}"
            );
        }
    }

    /// Excel uses the first section whose condition holds — not simply the section
    /// the value's sign names. The first two sections' conditions are tested in
    /// order, the one that holds serves the value through its own section — as a
    /// magnitude when the condition itself names the negative side (`[<0]`,
    /// `[<=-1]`, `[=-3]`) — and a value no condition serves falls to the section
    /// Excel keeps for what none of them takes. A colour is not a condition.
    #[test]
    fn a_conditional_section_serves_the_value_its_condition_names() {
        for &(label, value, code, shown) in CONDITIONAL_SECTIONS {
            assert_eq!(
                display(value, 164, Some(code), false).as_deref(),
                shown,
                "{label}"
            );
        }
    }

    const CONDITIONAL_SECTIONS: &[(&str, f64, &str, Option<&str>)] = &[
        (
            "the first condition holds",
            500.0,
            "[>1000]0.0;[<=1000]0.00",
            Some("500.00"),
        ),
        (
            "the second condition holds",
            1500.0,
            "[>1000]0.0;[<=1000]0.00",
            Some("1500.0"),
        ),
        (
            "a positive through the second section",
            1234.0,
            "[<0]\"neg\";0",
            Some("1234"),
        ),
        (
            "a negative through the first section",
            -1234.0,
            "[<0]\"neg\";0",
            Some("neg"),
        ),
        (
            "a colour is not a condition",
            1234.0,
            "[Red]0.0",
            Some("1234.0"),
        ),
        (
            "a condition after a directive still gates",
            5000.0,
            "[$$-409][>100]0.00;0.0",
            Some("$5000.00"),
        ),
        (
            "a value under the condition",
            5.0,
            "[$$-409][>100]0.00;0.0",
            Some("5.0"),
        ),
        (
            "a negative under the condition",
            -5.0,
            "[$$-409][>100]0.00;0.0",
            Some("-5.0"),
        ),
        (
            "a positive the first condition serves",
            5.0,
            "[>=1]0;0",
            Some("5"),
        ),
        (
            "a negative the second section serves",
            -2.0,
            "[>=1]0;0",
            Some("-2"),
        ),
        (
            "a negative through the second's places",
            -12.3,
            "[>=1000000]#,,\" M\";####.00",
            Some("-12.30"),
        ),
        (
            "a negative through a third section",
            -2.0,
            "[>=1]0;0;0.00",
            Some("2"),
        ),
        (
            "a value no condition takes draws the third section",
            -2.0,
            "[>=1]0.0;[>=0]0.0;0.00",
            Some("-2.00"),
        ),
        (
            "a scaling section keeps its literal",
            1_021_021.0,
            "[>=1000000]0.0,,\"M\";[>=1000]0.0,\"K\";0",
            Some("1.0M"),
        ),
        (
            "the second scaling section",
            102_102.0,
            "[>=1000000]0.0,,\"M\";[>=1000]0.0,\"K\";0",
            Some("102.1K"),
        ),
        (
            "a negative no condition takes",
            -500.0,
            "[>=1000000]0.0,,\"M\";[>=1000]0.0,\"K\";0",
            Some("-500"),
        ),
        (
            "a condition serving a negative shows its magnitude",
            -2.0,
            "[>=-1]0;0",
            Some("2"),
        ),
        (
            "a negative served as a magnitude",
            -1.0,
            "[<0]0.0;0.00",
            Some("1.0"),
        ),
        (
            "a negative against a negative bound",
            -2.0,
            "[<=-1]0;0",
            Some("2"),
        ),
        ("an equality condition", -3.0, "[=-3]0;0", Some("3")),
        (
            "a minus the section writes itself",
            -2.0,
            "[<0]-0.0;0.00",
            Some("-2.0"),
        ),
        (
            "a value no condition takes draws the fallback",
            5.0,
            "[>10]0;0.0;\"n/a\"",
            Some("n/a"),
        ),
        (
            "a negative falls to the second section",
            -1.0,
            "[>10]0;0.0;\"n/a\"",
            Some("1.0"),
        ),
        (
            "a positive through a condition-less first section",
            200.0,
            "0.00;[>100]#,##0",
            Some("200.00"),
        ),
        (
            "a value no section serves is declined",
            -5.0,
            "0.00;[>100]#,##0",
            None,
        ),
        (
            "a value both conditions miss is declined",
            -2.0,
            "[>=1]0;[>=0]0",
            None,
        ),
        (
            "a text-only section whose minus would be the reader's is declined",
            -1.0,
            "[>0]\"plus\";\"minus\"",
            None,
        ),
    ];

    #[test]
    fn unsupported_formats_come_back_as_none() {
        for (label, value, id, code, shown) in [
            ("a date section for a fraction", 1.5, 12_u32, None, None),
            ("an id beyond the table", 1.5, 999, None, None),
            (
                "a declared code wins over an unknown id",
                1.5,
                999,
                Some("0.0"),
                Some("1.5"),
            ),
        ] {
            assert_eq!(display(value, id, code, false).as_deref(), shown, "{label}");
        }
    }

    /// A format no value can be shown through is declined rather than rendered
    /// into a wrong or unrepresentable line: a code past what Excel stores, a
    /// section naming more placeholders than a display could hold, a value
    /// without a finite display at the section's precision, and a serial outside
    /// the domain a date or a duration has.
    #[test]
    fn a_format_or_value_with_no_display_is_declined() {
        let long_code = format!("\"{}\"0", "x".repeat(MAX_FORMAT_LENGTH));
        assert_eq!(display(1.5, 164, Some(&long_code), false), None);
        let many_places = format!("0.{}", "0".repeat(MAX_PLACEHOLDERS + 1));
        assert_eq!(display(1.5, 164, Some(&many_places), false), None);
        assert_eq!(
            display(1.5, 164, Some(&format!("0{}.0", "0".repeat(100))), false),
            None
        );
        assert_eq!(by_id(1e308, 2), None);
        assert_eq!(by_id(1e308, 9), None);
        assert_eq!(by_id(1e19, 14), None);
        assert_eq!(display(1e19, 164, Some("[h]"), false), None);
        // A magnitude no integer can hold as a display: declined, not rendered
        // into a line that could not be a cell's value.
        assert_eq!(display(f64::MAX, 164, Some("0.000"), false), None);
        // A decimal point outside the placeholders' run — a section whose whole
        // part is empty (`.00`), one with a literal where a fraction belongs
        // (`0.5`) or one naming two (`.0.0`) — is a layout whose dot and the part
        // around it would be dropped, so it is declined.
        for code in [".00", "0.5", "0.5%", "0.0.0", "0.", "#,##0."] {
            assert_eq!(display(0.5, 164, Some(code), false), None, "{code}");
        }
        assert_eq!(display(5.0, 164, Some("0.0.0"), false), None);
        // The exponent region is held to the same rule: the placeholders it prints
        // are one run, so a point between them (`0E+0.0`), a token between them
        // (`0E+0,0`) or a point outside the run, before the placeholders (`0E+.0`)
        // or after them (`0E+0.`), is declined.
        for code in ["0E+0.0", "0E+0,0", "0E+.0", "0E+0."] {
            assert_eq!(display(5.0, 164, Some(code), false), None, "{code}");
        }
        // A scientific mantissa's point is held to the same rule: one outside the
        // placeholders, or a second beside it, is declined too.
        for code in [".0E+0", "0.E+0", "0.0.0E+0", "#.E+0"] {
            assert_eq!(display(1234.0, 164, Some(code), false), None, "{code}");
        }
    }

    /// The 1900 system counts from its own epoch, `1904` from its, and a section
    /// carrying both a date and a time appends the clock.
    #[test]
    fn dates_follow_the_1900_system_by_default() {
        for (label, value, id, date1904, shown) in [
            ("a 1900 serial", 45000.0, 14_u32, false, "2023-03-15"),
            ("the 1900 leap-day fiction", 60.0, 14, false, "1900-02-29"),
            ("the day after the fiction", 61.0, 14, false, "1900-03-01"),
            ("a 1904 serial", 45000.0, 14, true, "2027-03-16"),
            ("the 1904 epoch", 0.0, 14, true, "1904-01-01"),
            (
                "a date and a time",
                45000.5,
                22,
                false,
                "2023-03-15 12:00:00",
            ),
        ] {
            assert_eq!(
                display(value, id, None, date1904).as_deref(),
                Some(shown),
                "{label}"
            );
        }
    }

    /// A time-only section prints the units it names, and nothing it does not.
    #[test]
    fn time_only_sections_print_the_units_they_name() {
        for (label, value, id, shown) in [
            ("a half day is noon", 0.5, 20_u32, "12:00"),
            ("minutes and seconds alone", 1805.0 / 86_400.0, 45, "30:05"),
        ] {
            assert_eq!(by_id(value, id).as_deref(), Some(shown), "{label}");
        }
    }

    /// A section naming fractional seconds shows them, and the section's own
    /// precision decides the rounding — a `mm:ss.0` rounds at the tenth of a
    /// second, a `hh:mm:ss` at the second — while an elapsed unit counts the whole
    /// span, however long.
    #[test]
    fn a_section_naming_fractional_seconds_shows_them() {
        for (label, value, id, code, shown) in [
            (
                "a tenth of a second rounds at the tenth",
                0.500_046_3,
                47_u32,
                None,
                "00:04.0",
            ),
            (
                "seconds alone round at the second",
                0.500_046_3,
                45,
                None,
                "00:04",
            ),
            (
                "three fractional digits",
                4.492 / 86_400.0,
                164,
                Some("hh:mm:ss.000"),
                "00:00:04.492",
            ),
            (
                "an elapsed hour keeps its tenth",
                1.5,
                164,
                Some("[h]:mm:ss.0"),
                "36:00:00.0",
            ),
        ] {
            assert_eq!(
                display(value, id, code, false).as_deref(),
                Some(shown),
                "{label}"
            );
        }
    }

    #[test]
    fn a_negative_date_serial_is_declined() {
        for (label, value, id) in [
            ("a negative serial", -1.0, 14_u32),
            // The 1900 system's day 0 is the fake `1900-01-00`, which is no date.
            ("the 1900 day zero", 0.0, 14),
        ] {
            assert_eq!(by_id(value, id), None, "{label}");
        }
    }

    /// The minus the reader writes follows the cell's own number and the section's
    /// own text: a digit standing in that text (`"v1 "0`) is no number of the
    /// cell's, and a minus standing there is not written a second time.
    #[test]
    fn the_reader_writes_the_minus_only_where_no_section_does() {
        for (label, value, code, shown) in [
            ("a literal digit is no number", -0.4, "\"v1 \"0", "v1 0"),
            ("the reader writes the minus", -1.4, "\"v1 \"0", "-v1 1"),
            (
                "a minus in the section's own text",
                -2.0,
                "-$0.00",
                "-$2.00",
            ),
        ] {
            assert_eq!(
                display(value, 164, Some(code), false).as_deref(),
                Some(shown),
                "{label}"
            );
        }
    }

    /// The point a section names stands even when the value shows no digit behind
    /// it, and a zero scientific mantissa is laid out to the section's own integer
    /// width: one whose width would widen the zero is declined rather than shown
    /// with a mantissa Excel would fill, while one whose integer run is all `0`
    /// keeps its zero.
    #[test]
    fn a_named_point_stands_and_a_zero_mantissa_follows_its_width() {
        for (label, value, id, code, shown) in [
            (
                "the point stands alone",
                1.0,
                164_u32,
                Some("#.#####"),
                Some("1."),
            ),
            (
                "a zero value still names its point",
                0.0,
                164,
                Some("#.#####"),
                Some("."),
            ),
            (
                "a fraction with no integer",
                0.5,
                164,
                Some("#.##"),
                Some(".5"),
            ),
            (
                "a grouped whole part leaves its point",
                1000.0,
                164,
                Some("#,##0.##"),
                Some("1,000."),
            ),
            (
                "a zero mantissa whose width would widen it is declined",
                0.0,
                48,
                None,
                None,
            ),
            (
                "a zero mantissa keeps its integer run",
                0.0,
                11,
                None,
                Some("0.00E+00"),
            ),
        ] {
            assert_eq!(display(value, id, code, false).as_deref(), shown, "{label}");
        }
    }

    /// A literal standing *between* the placeholders keeps its place among the
    /// digits — a phone number or an identifier is never rendered as its digits
    /// followed by the format's punctuation — and a `*` fill contributes nothing.
    /// The `@` text placeholder has no text to stand for in a cell holding a
    /// number, so the caller shows the stored value instead.
    #[test]
    fn a_literal_between_placeholders_lays_out_with_the_digits() {
        let phone = "[<=9999999]###-####;(###) ###-####";
        for (label, value, id, code, shown) in [
            (
                "a phone number",
                5_551_234.0,
                164_u32,
                Some(phone),
                Some("555-1234"),
            ),
            (
                "a parenthesised phone number",
                5_551_234_567.0,
                164,
                Some(phone),
                Some("(555) 123-4567"),
            ),
            (
                "an identifier",
                123_456_789.0,
                164,
                Some("000-00-0000"),
                Some("123-45-6789"),
            ),
            (
                "a percent keeps its place among the digits",
                1.0,
                164,
                Some("0%00"),
                Some("1%00"),
            ),
            (
                "a percent with no digit to hold it",
                5.0,
                164,
                Some("0%0"),
                None,
            ),
            (
                "an escaped prefix",
                1234.5,
                164,
                Some("\\$#,##0.00"),
                Some("$1,234.50"),
            ),
            (
                "a quoted suffix",
                -1234.5,
                164,
                Some("#,##0.00\" kr\""),
                Some("-1,234.50 kr"),
            ),
            (
                "a fill contributes nothing",
                5_551_234.0,
                164,
                Some("###-####* "),
                Some("555-1234"),
            ),
            ("a text-only builtin section", 1.5, 49, None, None),
            ("a text placeholder beside text", 1.5, 164, Some("@"), None),
            (
                "a text placeholder after text",
                1.5,
                164,
                Some("pre @"),
                None,
            ),
        ] {
            assert_eq!(display(value, id, code, false).as_deref(), shown, "{label}");
        }
    }

    /// An over-wide value, an under-wide one, a fractional part and a grouping
    /// comma are all layouts this reader cannot put the digits into, so they are
    /// declined rather than shown as a shorter, longer, ungrouped or misplaced number.
    #[test]
    fn a_layered_body_declines_what_it_cannot_hold() {
        for (label, value, code) in [
            ("more digits than places", 1_234_567_890.0, "000-00-0000"),
            ("a value wider than the layout", 12_345_678.0, "###-####"),
            (
                "a value wider than a parenthesised layout",
                55_512_345_678.0,
                "(###) ###-####",
            ),
            (
                "fewer digits than places, so no literal keeps its neighbour",
                123.0,
                "###-####",
            ),
            (
                "a literal with no digits beside it",
                5_551_234.0,
                "(###) ###-####",
            ),
            ("a grouping comma in a layered body", 12_345.0, "#,##0-#"),
            ("a fraction in a layered body", 1234.5, "##-###.0"),
        ] {
            assert_eq!(display(value, 164, Some(code), false), None, "{label}");
        }
    }

    /// A section with no placeholder at all is a format's own wording, and only
    /// the text its author asked for is shown: a quoted or escaped literal is text
    /// the format prints, while an unquoted run, a lone marker or a directive is a
    /// format string this reader does not know, so it is declined rather than
    /// passed off as the cell's value.
    #[test]
    fn a_placeholder_less_section_is_text_only_when_the_format_asks_for_it() {
        for (label, value, code, shown) in [
            ("a quoted text section", -5.0, "0;\"neg\"", Some("neg")),
            ("a quoted literal", 5.0, "\"-\"", Some("-")),
            ("a date-format code", 5.0, "[$-419]ДД.ММ.ГГГГ", None),
            ("General names no placeholder", 5.0, "General", None),
            ("padding does not hide General", 5.0, " General ", None),
            ("a repeated General", 5.0, "General;General", None),
            ("a lone percent", 5.0, "%", None),
            ("a lone comma", 5.0, ",", None),
            ("a lone directive", 5.0, "[$USD-409]", None),
        ] {
            assert_eq!(
                display(value, 164, Some(code), false).as_deref(),
                shown,
                "{label}"
            );
        }
    }
}