lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
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
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
//! Display formatting for `FormattedNumber` and `FormattedDate` without `Intl`.
//!
//! [`format_lumen_number`] ports Lumen's `formatLumenNumber`, which wraps `Intl.NumberFormat`, for
//! English. It validates options the same way, rounds the shortest round-trip decimal of the value
//! half away from zero the way ICU does, and reads currency, unit, and compact text from the
//! generated `number_format_data` tables for `en` and `en-US`. Other locales and Unicode
//! numbering-system extensions use ICU4X and generated CLDR patterns in `localized`.
//!
//! [`format_lumen_date`] renders an ISO 8601 date or date-time as
//! `Intl.DateTimeFormat("en-US", { timeZone: "UTC" })` does.

// cspell:words CLDR feff

use super::number_format_data::{
    COMPACT_LONG, COMPACT_SHORT, COMPOUND_UNITS, CURRENCIES, Currency, UNITS, Unit,
};

#[path = "localized_number.rs"]
mod localized;

/// Number style for `FormattedNumber`: the `Intl.NumberFormat` `style` option.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormattedNumberFormat {
    /// A plain number, such as "1,234.5".
    #[default]
    Decimal,
    /// Money in the given currency, such as "$1,234.50". Formats as `Decimal` without a valid code.
    Currency,
    /// A ratio shown as a percentage, so `0.25` reads "25%".
    Percent,
    /// A measurement in the given unit, such as "16 km/h". Formats as `Decimal` without a unit.
    Unit,
}

impl FormattedNumberFormat {
    /// The `Intl.NumberFormat` `style` value, such as `"currency"`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Decimal => "decimal",
            Self::Currency => "currency",
            Self::Percent => "percent",
            Self::Unit => "unit",
        }
    }
}

/// How `FormattedNumber` writes the magnitude: the `Intl.NumberFormat` `notation` option.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormattedNumberNotation {
    /// Every digit, such as "1,234,567".
    #[default]
    Standard,
    /// One integer digit and a power of ten, such as "1.235E6".
    Scientific,
    /// A power of ten that is a multiple of three, such as "1.235E6" or "12.346E3".
    Engineering,
    /// Rounded with a magnitude word, such as "1.2M", with "1.2 million" for assistive technology.
    Compact,
}

impl FormattedNumberNotation {
    /// The `Intl.NumberFormat` `notation` value, such as `"compact"`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Standard => "standard",
            Self::Scientific => "scientific",
            Self::Engineering => "engineering",
            Self::Compact => "compact",
        }
    }
}

/// When `FormattedNumber` shows a sign: the `Intl.NumberFormat` `signDisplay` option.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormattedNumberSignDisplay {
    /// A minus sign for negative values, including negative zero.
    #[default]
    Auto,
    /// A plus or minus sign on every value, including zero.
    Always,
    /// A plus or minus sign on every value except zero.
    ExceptZero,
    /// No sign at all.
    Never,
}

impl FormattedNumberSignDisplay {
    /// The `Intl.NumberFormat` `signDisplay` value, such as `"exceptZero"`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Always => "always",
            Self::ExceptZero => "exceptZero",
            Self::Never => "never",
        }
    }
}

/// How `FormattedNumber` names a currency: the `Intl.NumberFormat` `currencyDisplay` option.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormattedNumberCurrencyDisplay {
    /// The locale's symbol, such as "$" for CAD in en-CA and "CA$" in en-US.
    #[default]
    Symbol,
    /// The shortest symbol, such as "$" for both USD and CAD.
    NarrowSymbol,
    /// The ISO 4217 code, such as "USD".
    Code,
    /// The full name, such as "US dollars".
    Name,
}

impl FormattedNumberCurrencyDisplay {
    /// The `Intl.NumberFormat` `currencyDisplay` value, such as `"narrowSymbol"`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Symbol => "symbol",
            Self::NarrowSymbol => "narrowSymbol",
            Self::Code => "code",
            Self::Name => "name",
        }
    }
}

/// When `FormattedNumber` reads the full currency name to assistive technology.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormattedNumberCurrencyName {
    /// Only for symbols that several currencies share, such as "$", "¥", "£", or "kr".
    #[default]
    Auto,
    /// For every currency symbol and code.
    Always,
    /// Never; assistive technology reads the visible symbol.
    Never,
}

impl FormattedNumberCurrencyName {
    /// The Lumen `currencyName` value, such as `"auto"`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Always => "always",
            Self::Never => "never",
        }
    }
}

/// How `FormattedNumber` writes a unit: the `Intl.NumberFormat` `unitDisplay` option.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormattedNumberUnitDisplay {
    /// An abbreviation, such as "16 km/h".
    #[default]
    Short,
    /// The tightest abbreviation, such as "16km/h".
    Narrow,
    /// The full name, such as "16 kilometers per hour".
    Long,
}

impl FormattedNumberUnitDisplay {
    /// The `Intl.NumberFormat` `unitDisplay` value, such as `"long"`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Short => "short",
            Self::Narrow => "narrow",
            Self::Long => "long",
        }
    }
}

/// Date length for `FormattedDate`: the `Intl.DateTimeFormat` `dateStyle` option.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormattedDateStyle {
    /// Weekday and full month, such as "Tuesday, December 1, 2026".
    Full,
    /// Full month, such as "December 1, 2026".
    Long,
    /// Abbreviated month, such as "Dec 1, 2026".
    #[default]
    Medium,
    /// Numeric, such as "12/1/26".
    Short,
}

impl FormattedDateStyle {
    /// The `Intl.DateTimeFormat` `dateStyle` value, such as `"medium"`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Full => "full",
            Self::Long => "long",
            Self::Medium => "medium",
            Self::Short => "short",
        }
    }
}

/// Time length for `FormattedDate`: the `Intl.DateTimeFormat` `timeStyle` option. Times are UTC.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormattedDateTimeStyle {
    /// Seconds and the zone name, such as "3:04:05 PM Coordinated Universal Time".
    Full,
    /// Seconds and the zone abbreviation, such as "3:04:05 PM UTC".
    Long,
    /// Seconds, such as "3:04:05 PM".
    #[default]
    Medium,
    /// Hours and minutes, such as "3:04 PM".
    Short,
}

impl FormattedDateTimeStyle {
    /// The `Intl.DateTimeFormat` `timeStyle` value, such as `"short"`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Full => "full",
            Self::Long => "long",
            Self::Medium => "medium",
            Self::Short => "short",
        }
    }
}

/// The value `FormattedNumber` formats: a number, or text read the way Lumen's `parseLumenNumber`
/// reads it.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum FormattedNumberValue {
    /// A double, like a JavaScript number. NaN and infinities render the fallback text.
    Number(f64),
    /// Plain decimal text such as `"-1234.5"` or `" 2e3 "`. Surrounding whitespace is ignored;
    /// hexadecimal, `"Infinity"`, empty text, and text longer than 64 characters render the
    /// fallback text.
    Text(String),
}

/// Formats a double as is.
impl From<f64> for FormattedNumberValue {
    fn from(value: f64) -> Self {
        Self::Number(value)
    }
}

/// Widens a single-precision float without loss.
impl From<f32> for FormattedNumberValue {
    fn from(value: f32) -> Self {
        Self::Number(f64::from(value))
    }
}

/// Converts the integer without loss.
impl From<i32> for FormattedNumberValue {
    fn from(value: i32) -> Self {
        Self::Number(f64::from(value))
    }
}

/// Converts the integer without loss.
impl From<u32> for FormattedNumberValue {
    fn from(value: u32) -> Self {
        Self::Number(f64::from(value))
    }
}

/// Rounds integers beyond 2^53 to the nearest double, as JavaScript's `Number(bigint)` does.
impl From<i64> for FormattedNumberValue {
    #[allow(
        clippy::cast_precision_loss,
        reason = "JavaScript numbers are doubles, so large integers round the same way"
    )]
    fn from(value: i64) -> Self {
        Self::Number(value as f64)
    }
}

/// Rounds integers beyond 2^53 to the nearest double, as JavaScript's `Number(bigint)` does.
impl From<u64> for FormattedNumberValue {
    #[allow(
        clippy::cast_precision_loss,
        reason = "JavaScript numbers are doubles, so large integers round the same way"
    )]
    fn from(value: u64) -> Self {
        Self::Number(value as f64)
    }
}

/// Rounds integers beyond 2^53 to the nearest double, as JavaScript's `Number(bigint)` does.
impl From<usize> for FormattedNumberValue {
    #[allow(
        clippy::cast_precision_loss,
        reason = "JavaScript numbers are doubles, so large integers round the same way"
    )]
    fn from(value: usize) -> Self {
        Self::Number(value as f64)
    }
}

/// Parses the text when formatting, like `parseLumenNumber`.
impl From<&str> for FormattedNumberValue {
    fn from(value: &str) -> Self {
        Self::Text(value.to_owned())
    }
}

/// Parses the text when formatting, like `parseLumenNumber`.
impl From<String> for FormattedNumberValue {
    fn from(value: String) -> Self {
        Self::Text(value)
    }
}

/// `formatLumenNumber` options. Invalid currency codes, units, and fraction digits fall back the way
/// Lumen's `resolveLumenNumberFormatOptions` does.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct NumberFormatOptions {
    /// Number style.
    pub(crate) format: FormattedNumberFormat,
    /// Magnitude notation.
    pub(crate) notation: FormattedNumberNotation,
    /// Sign display.
    pub(crate) sign_display: FormattedNumberSignDisplay,
    /// ISO 4217 code, such as `"USD"`, in any letter case. Required for the currency format.
    pub(crate) currency: Option<String>,
    /// Currency display.
    pub(crate) currency_display: FormattedNumberCurrencyDisplay,
    /// When to read the full currency name to assistive technology.
    pub(crate) currency_name: FormattedNumberCurrencyName,
    /// Sanctioned unit, such as `"kilobyte"` or `"kilometer-per-hour"`. Required for the unit format.
    pub(crate) unit: Option<String>,
    /// Unit display.
    pub(crate) unit_display: FormattedNumberUnitDisplay,
    /// BCP 47 locale. Omitted, invalid, or unsupported locales use English.
    pub(crate) locale: Option<String>,
    /// Minimum fraction digits, floored and clamped to 0 through 20.
    pub(crate) minimum_fraction_digits: Option<f64>,
    /// Maximum fraction digits, floored and clamped to 0 through 20, and never below the minimum.
    pub(crate) maximum_fraction_digits: Option<f64>,
}

/// The result of [`format_lumen_number`], like Lumen's `LumenFormattedNumber`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct FormattedNumberText {
    /// Visible text.
    pub(crate) text: String,
    /// Fuller reading for assistive technology, present only when it differs from `text`.
    pub(crate) accessible_text: Option<String>,
    /// False when the input was not a finite number and `text` is the fallback.
    pub(crate) valid: bool,
    /// Machine-readable value, as JavaScript's `String(number)` writes it, or `None` when invalid.
    pub(crate) value: Option<String>,
}

/// Text `FormattedNumber` shows when its value is not a finite number.
pub(crate) const FORMATTED_NUMBER_FALLBACK: &str = "—";

/// Longest numeric text, unit, or date accepted, like `maxNumericTextLength`.
const MAX_TEXT_LENGTH: usize = 64;

/// Largest fraction digit count, like `maxFractionDigits`.
const MAX_FRACTION_DIGITS: u8 = 20;

/// Currency symbols that several currencies display the same way in at least one locale.
const AMBIGUOUS_CURRENCY_SYMBOLS: [&str; 18] = [
    "$", "¥", "¥", "£", "₩", "₨", "kr", "kr.", "Kr", "Kr.", "Rs", "Rs.", "Fr", "Fr.", "L", "R",
    "元", "円",
];

/// Formats a display-only number like Lumen's `formatLumenNumber` in the requested locale.
///
/// Invalid input renders `fallback`. For compact notation, units, and ambiguous currency symbols
/// it also returns the long reading for assistive technology, such as "1.2 thousand US dollars"
/// for a visible "$1.2K".
pub(crate) fn format_lumen_number(
    value: &FormattedNumberValue,
    options: &NumberFormatOptions,
    fallback: &str,
) -> FormattedNumberText {
    let Some(number) = parse_number(value) else {
        return FormattedNumberText {
            text: fallback.to_owned(),
            accessible_text: None,
            valid: false,
            value: None,
        };
    };
    let decimal = Decimal::from_f64(number);
    let negative = number.is_sign_negative();
    let used = resolve_spec(options);
    let locale = localized::resolve_locale(options.locale.as_deref());
    let format = |spec: &Spec| {
        locale.as_ref().map_or_else(
            || Some(format_spec(&decimal, negative, spec)),
            |locale| localized::format(&decimal, negative, spec, locale),
        )
    };
    let Some(text) = format(&used) else {
        return FormattedNumberText {
            text: fallback.to_owned(),
            accessible_text: None,
            valid: false,
            value: None,
        };
    };
    let currency_name = match (&used.style, &locale, options.currency_name) {
        (Style::Currency(currency), Some(locale), FormattedNumberCurrencyName::Auto)
            if currency.display != FormattedNumberCurrencyDisplay::Name =>
        {
            if localized::currency_is_ambiguous(currency, locale).unwrap_or(true) {
                FormattedNumberCurrencyName::Always
            } else {
                FormattedNumberCurrencyName::Never
            }
        }
        _ => options.currency_name,
    };
    let accessible = format(&accessible_spec(&used, currency_name)).unwrap_or_else(|| text.clone());

    FormattedNumberText {
        accessible_text: (accessible != text).then_some(accessible),
        text,
        valid: true,
        value: Some(js_number_to_string(&decimal, negative)),
    }
}

/// Reads a finite number like `parseLumenNumber`.
fn parse_number(value: &FormattedNumberValue) -> Option<f64> {
    match value {
        FormattedNumberValue::Number(number) => number.is_finite().then_some(*number),
        FormattedNumberValue::Text(text) => parse_number_text(text),
    }
}

/// Reads plain decimal text. After the character check, Rust's float grammar is the same as
/// JavaScript's `StrDecimalLiteral` without `Infinity`, and both round correctly.
fn parse_number_text(text: &str) -> Option<f64> {
    let trimmed = js_trim(text);
    let numeric =
        |byte: u8| byte.is_ascii_digit() || matches!(byte, b'+' | b'-' | b'.' | b'e' | b'E');

    if trimmed.is_empty() || trimmed.len() > MAX_TEXT_LENGTH || !trimmed.bytes().all(numeric) {
        return None;
    }

    trimmed
        .parse::<f64>()
        .ok()
        .filter(|number| number.is_finite())
}

/// Trims the characters JavaScript's `String.prototype.trim` removes.
fn js_trim(text: &str) -> &str {
    text.trim_matches(|character: char| {
        matches!(
            character,
            '\u{9}'..='\u{d}'
                | ' '
                | '\u{a0}'
                | '\u{1680}'
                | '\u{2000}'..='\u{200a}'
                | '\u{2028}'
                | '\u{2029}'
                | '\u{202f}'
                | '\u{205f}'
                | '\u{3000}'
                | '\u{feff}'
        )
    })
}

/// Floors a fraction digit count and clamps it to 0 through 20; non-finite counts are ignored.
fn resolve_fraction_digits(value: Option<f64>) -> Option<u8> {
    let value = value.filter(|value| value.is_finite())?;

    Some(
        (0..=MAX_FRACTION_DIGITS)
            .rev()
            .find(|digits| f64::from(*digits) <= value)
            .unwrap_or(0),
    )
}

/// Validates a three-letter ASCII currency code and converts it to uppercase.
fn resolve_currency_code(currency: Option<&str>) -> Option<String> {
    let currency = currency?;

    (currency.len() == 3 && currency.bytes().all(|byte| byte.is_ascii_alphabetic()))
        .then(|| currency.to_ascii_uppercase())
}

/// Patterns of a unit `Intl.NumberFormat` accepts.
#[derive(Clone, Copy)]
enum UnitPatterns {
    /// A simple unit or an `X-per-Y` unit with its own CLDR patterns.
    Stored(&'static [[&'static str; 2]; 3]),
    /// An `X-per-Y` unit composed from the patterns of `X` and the `per` pattern of `Y`.
    Per(&'static Unit, &'static Unit),
}

/// The unit option after validation.
enum UnitLookup {
    /// No usable unit text, so the format falls back to decimal.
    Missing,
    /// Text `Intl.NumberFormat` rejects, so `createFormatter` falls back to a plain decimal.
    Unknown,
    /// A sanctioned unit, and whether its numerator is `percent`.
    Known(UnitPatterns, bool),
}

/// Validates a unit like `resolveUnit`, then looks it up like `Intl.NumberFormat`.
fn resolve_unit(unit: Option<&str>) -> UnitLookup {
    let Some(unit) = unit else {
        return UnitLookup::Missing;
    };

    if unit.encode_utf16().nth(MAX_TEXT_LENGTH).is_some() {
        return UnitLookup::Missing;
    }

    let unit = js_trim(unit);

    if unit.is_empty() {
        return UnitLookup::Missing;
    }

    if let Some(simple) = find_unit(unit) {
        return UnitLookup::Known(
            UnitPatterns::Stored(&simple.patterns),
            simple.id == "percent",
        );
    }

    let Some((numerator, denominator)) = unit.split_once("-per-") else {
        return UnitLookup::Unknown;
    };
    let (Some(numerator), Some(denominator)) = (find_unit(numerator), find_unit(denominator))
    else {
        return UnitLookup::Unknown;
    };

    let percent = numerator.id == "percent";

    match COMPOUND_UNITS.binary_search_by(|compound| compound.id.cmp(unit)) {
        Ok(index) => COMPOUND_UNITS
            .get(index)
            .map_or(UnitLookup::Unknown, |compound| {
                UnitLookup::Known(UnitPatterns::Stored(&compound.patterns), percent)
            }),
        Err(_) => UnitLookup::Known(UnitPatterns::Per(numerator, denominator), percent),
    }
}

/// Finds a sanctioned simple unit.
fn find_unit(id: &str) -> Option<&'static Unit> {
    let index = UNITS.binary_search_by(|unit| unit.id.cmp(id)).ok()?;

    UNITS.get(index)
}

/// Finds the display data of a currency code ICU knows.
fn find_currency(code: &str) -> Option<&'static Currency> {
    let index = CURRENCIES
        .binary_search_by(|currency| currency.code.cmp(code))
        .ok()?;

    CURRENCIES.get(index)
}

/// A validated currency.
#[derive(Clone)]
struct CurrencyStyle {
    /// Uppercase code.
    code: String,
    /// ICU display data, or `None` for a code that displays as itself.
    data: Option<&'static Currency>,
    /// Requested display.
    display: FormattedNumberCurrencyDisplay,
}

impl CurrencyStyle {
    /// Default fraction digits.
    fn digits(&self) -> u8 {
        self.data.map_or(2, |data| data.digits)
    }

    /// Prefix text and whether a no-break space follows it, for every display except `Name`.
    fn symbol(&self) -> (&str, bool) {
        match (self.display, self.data) {
            (FormattedNumberCurrencyDisplay::Symbol, Some(data)) => {
                (data.symbol, data.symbol_spaced)
            }
            (FormattedNumberCurrencyDisplay::NarrowSymbol, Some(data)) => {
                (data.narrow, data.narrow_spaced)
            }
            _ => (&self.code, true),
        }
    }

    /// Full name for the plural category `one` or `other`.
    fn name(&self, one: bool) -> &str {
        match self.data {
            Some(data) if one => data.one,
            Some(data) => data.other,
            None => &self.code,
        }
    }
}

/// Number style after validation.
#[derive(Clone)]
enum Style {
    /// Plain number.
    Decimal,
    /// Percentage of a ratio.
    Percent,
    /// Money.
    Currency(CurrencyStyle),
    /// Measurement.
    Unit(UnitStyle),
}

/// A validated unit.
#[derive(Clone)]
struct UnitStyle {
    /// Validated ECMA-402 unit identifier, retained for locale-specific patterns.
    id: String,
    /// Patterns for every display.
    patterns: UnitPatterns,
    /// Requested display.
    display: FormattedNumberUnitDisplay,
    /// Whether the numerator is `percent`, which ICU formats with the percent pattern unless the
    /// display is long or the notation is compact; any `-per-` denominator is then dropped.
    percent: bool,
}

/// Options a formatter was built with, like the `Intl.NumberFormatOptions` `createFormatter` used.
#[derive(Clone)]
struct Spec {
    /// Number style.
    style: Style,
    /// Magnitude notation.
    notation: FormattedNumberNotation,
    /// Whether compact notation uses long words, like `compactDisplay: "long"`.
    compact_long: bool,
    /// Sign display.
    sign_display: FormattedNumberSignDisplay,
    /// Requested minimum fraction digits.
    minimum_fraction_digits: Option<u8>,
    /// Requested maximum fraction digits, never below the minimum.
    maximum_fraction_digits: Option<u8>,
}

/// Resolves options like `resolveLumenNumberFormatOptions` followed by `createFormatter`.
fn resolve_spec(options: &NumberFormatOptions) -> Spec {
    let minimum_fraction_digits = resolve_fraction_digits(options.minimum_fraction_digits);
    let maximum_fraction_digits = resolve_fraction_digits(options.maximum_fraction_digits)
        .map(|maximum| maximum.max(minimum_fraction_digits.unwrap_or(0)));
    let mut spec = Spec {
        style: Style::Decimal,
        notation: options.notation,
        compact_long: false,
        sign_display: options.sign_display,
        minimum_fraction_digits,
        maximum_fraction_digits,
    };

    match options.format {
        FormattedNumberFormat::Decimal => {}
        FormattedNumberFormat::Percent => spec.style = Style::Percent,
        FormattedNumberFormat::Currency => {
            if let Some(code) = resolve_currency_code(options.currency.as_deref()) {
                spec.style = Style::Currency(CurrencyStyle {
                    data: find_currency(&code),
                    code,
                    display: options.currency_display,
                });
            }
        }
        FormattedNumberFormat::Unit => match resolve_unit(options.unit.as_deref()) {
            UnitLookup::Missing => {}
            // `Intl.NumberFormat` throws for the unit with and without fraction limits, so
            // `createFormatter` keeps only the notation and sign display.
            UnitLookup::Unknown => {
                spec.minimum_fraction_digits = None;
                spec.maximum_fraction_digits = None;
            }
            UnitLookup::Known(patterns, percent) => {
                spec.style = Style::Unit(UnitStyle {
                    id: options
                        .unit
                        .as_deref()
                        .map(js_trim)
                        .unwrap_or_default()
                        .to_owned(),
                    patterns,
                    display: options.unit_display,
                    percent,
                });
            }
        },
    }

    spec
}

/// Options for the long reading, like `resolveAccessibleOptions`.
fn accessible_spec(used: &Spec, currency_name: FormattedNumberCurrencyName) -> Spec {
    let mut spec = used.clone();

    if spec.notation == FormattedNumberNotation::Compact {
        spec.compact_long = true;
    }

    match &mut spec.style {
        Style::Unit(unit) => unit.display = FormattedNumberUnitDisplay::Long,
        Style::Currency(currency)
            if currency.display != FormattedNumberCurrencyDisplay::Name
                && currency_name != FormattedNumberCurrencyName::Never =>
        {
            let ambiguous = AMBIGUOUS_CURRENCY_SYMBOLS.contains(&js_trim(currency.symbol().0));

            if currency_name == FormattedNumberCurrencyName::Always || ambiguous {
                currency.display = FormattedNumberCurrencyDisplay::Name;
            }
        }
        Style::Decimal | Style::Percent | Style::Currency(_) => {}
    }

    spec
}

/// Rounding the way `Intl.NumberFormat` resolves its digit options.
#[derive(Clone, Copy, Debug)]
enum Precision {
    /// Round to `maximum` fraction digits and show at least `minimum`.
    Fraction {
        /// Fraction digits always shown.
        minimum: u8,
        /// Fraction digits kept when rounding.
        maximum: u8,
    },
    /// Compact default: round to an integer, keeping at least two significant digits.
    Compact,
}

impl Precision {
    /// Resolves the digit options for a spec, like ECMA-402 `SetNumberFormatDigitOptions` in V8,
    /// which uses the currency digits as defaults in every notation.
    fn of(spec: &Spec) -> Self {
        let (minimum_default, maximum_default) = match &spec.style {
            Style::Currency(currency) => (currency.digits(), currency.digits()),
            Style::Percent => (0, 0),
            Style::Decimal | Style::Unit(_) => (0, 3),
        };

        match (spec.minimum_fraction_digits, spec.maximum_fraction_digits) {
            (None, None) if spec.notation == FormattedNumberNotation::Compact => Self::Compact,
            (None, None) => Self::Fraction {
                minimum: minimum_default,
                maximum: maximum_default,
            },
            (Some(minimum), None) => Self::Fraction {
                minimum,
                maximum: maximum_default.max(minimum),
            },
            (None, Some(maximum)) => Self::Fraction {
                minimum: minimum_default.min(maximum),
                maximum,
            },
            (Some(minimum), Some(maximum)) => Self::Fraction { minimum, maximum },
        }
    }

    /// Rounds `decimal` and returns the fraction digits that must be shown.
    fn apply(self, decimal: &mut Decimal) -> u8 {
        match self {
            Self::Fraction { minimum, maximum } => {
                decimal.round_to(-i32::from(maximum));
                minimum
            }
            Self::Compact => {
                if !decimal.is_zero() {
                    decimal.round_to(0.min(decimal.magnitude() - 1));
                }
                0
            }
        }
    }

    /// Scales `decimal` by the multiplier for its magnitude and rounds it, moving to the next
    /// multiplier when rounding carries into a new magnitude, like ICU's
    /// `chooseMultiplierAndApply`. Returns the shown fraction digits and the multiplier.
    fn apply_with_multiplier(
        self,
        decimal: &mut Decimal,
        multiplier_for: impl Fn(i32) -> i32,
    ) -> (u8, i32) {
        if decimal.is_zero() {
            return (self.apply(decimal), 0);
        }

        let magnitude = decimal.magnitude();
        let multiplier = multiplier_for(magnitude);

        decimal.shift(multiplier);

        let minimum = self.apply(decimal);

        if decimal.is_zero() || decimal.magnitude() == magnitude + multiplier {
            return (minimum, multiplier);
        }

        let next = multiplier_for(magnitude + 1);

        if next == multiplier {
            return (minimum, multiplier);
        }

        decimal.shift(next - multiplier);

        (self.apply(decimal), next)
    }
}

/// Power-of-ten shift that turns a number of `magnitude` into its compact mantissa.
fn compact_multiplier(magnitude: i32) -> i32 {
    if magnitude < 3 {
        0
    } else {
        let capped = magnitude.min(14);

        -(capped - capped % 3)
    }
}

/// A non-negative decimal `digits × 10^scale` with no leading or trailing zero digits; zero has
/// no digits.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Decimal {
    /// Decimal digits, most significant first.
    digits: Vec<u8>,
    /// Power of ten of the last digit.
    scale: i32,
}

impl Decimal {
    /// The shortest decimal that round-trips to `|value|`, which ICU rounds and JavaScript's
    /// `String(number)` writes. When two shortest decimals are equally close, both pick the one
    /// with an even last digit, while Rust's `{:e}` picks the larger one.
    fn from_f64(value: f64) -> Self {
        let value = value.abs();
        let mut decimal = Self::from_scientific(&format!("{value:e}"));

        if decimal.digits.last().is_some_and(|digit| digit % 2 == 1) {
            let mut even = decimal.clone();

            if let Some(last) = even.digits.last_mut() {
                *last -= 1;
            }

            // A tie means the exact binary value ends with a 5 right after the shorter digits.
            let mut midpoint = even.clone();

            midpoint.digits.push(5);
            midpoint.scale -= 1;

            if even.to_f64() == Some(value)
                && Self::from_scientific(&format!("{value:.767e}")) == midpoint
            {
                decimal = even;
            }
        }

        decimal.normalize();
        decimal
    }

    /// Reads Rust's `{:e}` output, such as `1.2345e-3`.
    fn from_scientific(text: &str) -> Self {
        let (mantissa, exponent) = text.split_once('e').unwrap_or((text, "0"));
        let digits: Vec<u8> = mantissa
            .bytes()
            .filter(u8::is_ascii_digit)
            .map(|byte| byte - b'0')
            .collect();
        let scale = exponent.parse::<i32>().unwrap_or(0) - to_i32(digits.len().saturating_sub(1));
        let mut decimal = Self { digits, scale };

        decimal.normalize();
        decimal
    }

    /// The nearest double, for the round-trip check.
    fn to_f64(&self) -> Option<f64> {
        let digits: String = self.digits.iter().map(|digit| digit_char(*digit)).collect();

        format!("{digits}e{}", self.scale).parse().ok()
    }

    /// Removes leading and trailing zero digits.
    fn normalize(&mut self) {
        let leading = self.digits.iter().take_while(|digit| **digit == 0).count();

        self.digits.drain(..leading);

        while self.digits.last() == Some(&0) {
            self.digits.pop();
            self.scale += 1;
        }

        if self.digits.is_empty() {
            self.scale = 0;
        }
    }

    /// Whether the value is zero.
    fn is_zero(&self) -> bool {
        self.digits.is_empty()
    }

    /// Whether the value is exactly one.
    fn is_one(&self) -> bool {
        self.digits == [1] && self.scale == 0
    }

    /// Power of ten of the first digit, or zero for zero.
    fn magnitude(&self) -> i32 {
        if self.is_zero() {
            0
        } else {
            self.scale + to_i32(self.digits.len()) - 1
        }
    }

    /// Digit at a power of ten.
    fn digit_at(&self, magnitude: i32) -> u8 {
        usize::try_from(self.magnitude() - magnitude)
            .ok()
            .and_then(|index| self.digits.get(index))
            .copied()
            .unwrap_or(0)
    }

    /// Multiplies by `10^shift`.
    fn shift(&mut self, shift: i32) {
        if !self.is_zero() {
            self.scale += shift;
        }
    }

    /// Rounds half away from zero to a multiple of `10^magnitude`.
    fn round_to(&mut self, magnitude: i32) {
        if self.is_zero() || self.scale >= magnitude {
            return;
        }

        let Ok(keep) = usize::try_from(self.magnitude() - magnitude + 1) else {
            self.digits.clear();
            self.scale = 0;
            return;
        };
        let round_up = self.digits.get(keep).is_some_and(|digit| *digit >= 5);

        self.digits.truncate(keep);
        self.scale = magnitude;

        if round_up {
            let mut carry = true;

            for digit in self.digits.iter_mut().rev() {
                if *digit == 9 {
                    *digit = 0;
                } else {
                    *digit += 1;
                    carry = false;
                    break;
                }
            }

            if carry {
                self.digits.insert(0, 1);
            }
        }

        self.normalize();
    }

    /// Fraction digits shown with at least `minimum` of them.
    fn fraction_count(&self, minimum: u8) -> i32 {
        (-self.scale).max(i32::from(minimum)).max(0)
    }

    /// Writes the digits with English grouping when the integer part has at least
    /// `grouping_threshold` digits, and at least `minimum` fraction digits.
    fn write(&self, out: &mut String, minimum: u8, grouping_threshold: i32) {
        let upper = self.magnitude().max(0);
        let grouped = upper + 1 >= grouping_threshold;

        for magnitude in (0..=upper).rev() {
            out.push(digit_char(self.digit_at(magnitude)));

            if grouped && magnitude > 0 && magnitude % 3 == 0 {
                out.push(',');
            }
        }

        let fraction = self.fraction_count(minimum);

        if fraction > 0 {
            out.push('.');

            for magnitude in (-fraction..0).rev() {
                out.push(digit_char(self.digit_at(magnitude)));
            }
        }
    }
}

/// ASCII character of a decimal digit.
fn digit_char(digit: u8) -> char {
    char::from(b'0' + digit.min(9))
}

/// Converts a small length to `i32`, saturating.
fn to_i32(length: usize) -> i32 {
    i32::try_from(length).unwrap_or(i32::MAX)
}

/// A number after notation scaling and rounding.
struct Rounded {
    /// Rounded mantissa.
    decimal: Decimal,
    /// Fraction digits that must be shown.
    minimum: u8,
    /// Power of ten applied by scientific or compact notation.
    multiplier: i32,
}

impl Rounded {
    /// Scales and rounds an absolute value for a spec.
    fn new(value: &Decimal, spec: &Spec) -> Self {
        let precision = Precision::of(spec);
        let mut decimal = value.clone();

        if matches!(spec.style, Style::Percent) {
            decimal.shift(2);
        }

        let (minimum, multiplier) = match spec.notation {
            FormattedNumberNotation::Standard => (precision.apply(&mut decimal), 0),
            FormattedNumberNotation::Scientific => {
                precision.apply_with_multiplier(&mut decimal, |magnitude| -magnitude)
            }
            FormattedNumberNotation::Engineering => precision
                .apply_with_multiplier(&mut decimal, |magnitude| {
                    magnitude.rem_euclid(3) - magnitude
                }),
            FormattedNumberNotation::Compact => {
                precision.apply_with_multiplier(&mut decimal, compact_multiplier)
            }
        };

        Self {
            decimal,
            minimum,
            multiplier,
        }
    }

    /// English plural category `one`: exactly 1 with no visible fraction digits or scaling.
    fn is_one(&self) -> bool {
        self.decimal.is_one() && self.minimum == 0 && self.multiplier == 0
    }

    /// Digits, exponent, and compact suffix, without the sign.
    fn text(&self, spec: &Spec) -> String {
        let compact = spec.notation == FormattedNumberNotation::Compact;
        let mut text = String::new();

        self.decimal
            .write(&mut text, self.minimum, if compact { 5 } else { 4 });

        match spec.notation {
            FormattedNumberNotation::Standard => {}
            FormattedNumberNotation::Scientific | FormattedNumberNotation::Engineering => {
                text.push('E');
                text.push_str(&(-self.multiplier).to_string());
            }
            FormattedNumberNotation::Compact => {
                let magnitude = self.decimal.magnitude() - self.multiplier;
                // English currency patterns have no long form.
                let long = spec.compact_long
                    && !matches!(
                        &spec.style,
                        Style::Currency(currency)
                            if currency.display != FormattedNumberCurrencyDisplay::Name
                    );
                let suffixes = if long { COMPACT_LONG } else { COMPACT_SHORT };
                let index = usize::try_from(magnitude / 3 - 1)
                    .ok()
                    .map(|index| index.min(3));

                if let Some(suffix) = index.and_then(|index| suffixes.get(index)) {
                    text.push_str(suffix);
                }
            }
        }

        text
    }
}

/// Sign for a value, after rounding decides whether it is zero.
fn sign_text(display: FormattedNumberSignDisplay, negative: bool, zero: bool) -> &'static str {
    match display {
        FormattedNumberSignDisplay::Auto => {
            if negative {
                "-"
            } else {
                ""
            }
        }
        FormattedNumberSignDisplay::Always => {
            if negative {
                "-"
            } else {
                "+"
            }
        }
        FormattedNumberSignDisplay::ExceptZero => match (zero, negative) {
            (true, _) => "",
            (false, true) => "-",
            (false, false) => "+",
        },
        FormattedNumberSignDisplay::Never => "",
    }
}

/// Formats the absolute value `value` and its sign with resolved options, like
/// `Intl.NumberFormat.prototype.format`.
fn format_spec(value: &Decimal, negative: bool, spec: &Spec) -> String {
    let rounded = Rounded::new(value, spec);
    let sign = sign_text(spec.sign_display, negative, rounded.decimal.is_zero());
    let digits = rounded.text(spec);

    match &spec.style {
        Style::Decimal => format!("{sign}{digits}"),
        Style::Percent => format!("{sign}{digits}%"),
        Style::Currency(currency) if currency.display == FormattedNumberCurrencyDisplay::Name => {
            format!("{sign}{digits} {}", currency.name(rounded.is_one()))
        }
        Style::Currency(currency) => {
            let (symbol, spaced) = currency.symbol();
            let space = if spaced { "\u{a0}" } else { "" };

            format!("{sign}{symbol}{space}{digits}")
        }
        Style::Unit(unit)
            if unit.percent
                && unit.display != FormattedNumberUnitDisplay::Long
                && spec.notation != FormattedNumberNotation::Compact =>
        {
            format!("{sign}{digits}%")
        }
        Style::Unit(unit) => apply_unit_pattern(
            unit.patterns,
            unit.display,
            rounded.is_one(),
            &format!("{sign}{digits}"),
        ),
    }
}

/// Puts the formatted number into the unit pattern for a display and plural category.
fn apply_unit_pattern(
    patterns: UnitPatterns,
    display: FormattedNumberUnitDisplay,
    one: bool,
    number: &str,
) -> String {
    let width = match display {
        FormattedNumberUnitDisplay::Short => 0,
        FormattedNumberUnitDisplay::Narrow => 1,
        FormattedNumberUnitDisplay::Long => 2,
    };
    let plural = usize::from(!one);
    let split = |pattern: &'static str| pattern.split_once("{0}").unwrap_or((pattern, ""));
    let pick = |table: &'static [[&'static str; 2]; 3]| {
        table
            .get(width)
            .and_then(|pair| pair.get(plural))
            .copied()
            .unwrap_or("{0}")
    };

    match patterns {
        UnitPatterns::Stored(table) => {
            let (prefix, suffix) = split(pick(table));

            format!("{prefix}{number}{suffix}")
        }
        UnitPatterns::Per(numerator, denominator) => {
            let (prefix, suffix) = split(pick(&numerator.patterns));
            let (per_prefix, per_suffix) =
                split(denominator.per.get(width).copied().unwrap_or("{0}"));

            format!("{per_prefix}{prefix}{number}{suffix}{per_suffix}")
        }
    }
}

/// Writes a finite number, given as its absolute value and sign, like JavaScript's
/// `String(number)`.
fn js_number_to_string(decimal: &Decimal, negative: bool) -> String {
    if decimal.is_zero() {
        return "0".to_owned();
    }

    let digits: String = decimal
        .digits
        .iter()
        .map(|digit| digit_char(*digit))
        .collect();
    let length = to_i32(digits.len());
    let point = decimal.magnitude() + 1;
    let mut text = String::from(if negative { "-" } else { "" });

    if length <= point && point <= 21 {
        text.push_str(&digits);
        text.extend((length..point).map(|_| '0'));
    } else if 0 < point && point <= 21 {
        let (integer, fraction) = digits.split_at(usize::try_from(point).unwrap_or(0));

        text.push_str(integer);
        text.push('.');
        text.push_str(fraction);
    } else if -6 < point && point <= 0 {
        text.push_str("0.");
        text.extend((point..0).map(|_| '0'));
        text.push_str(&digits);
    } else {
        let (first, rest) = digits.split_at(1);
        let exponent = point - 1;

        text.push_str(first);

        if !rest.is_empty() {
            text.push('.');
            text.push_str(rest);
        }

        text.push('e');
        text.push(if exponent < 0 { '-' } else { '+' });
        text.push_str(&exponent.unsigned_abs().to_string());
    }

    text
}

/// English month names.
const MONTHS: [&str; 12] = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
];

/// English weekday names, starting on Sunday.
const WEEKDAYS: [&str; 7] = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
];

/// Minutes in a day.
const MINUTES_PER_DAY: i64 = 1_440;

/// A UTC moment between 0001-01-01 and 9999-12-31.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Moment {
    /// Days since 1970-01-01.
    days: i64,
    /// Year, 1 through 9999.
    year: i64,
    /// Month, 1 through 12.
    month: i64,
    /// Day of the month.
    day: i64,
    /// Hour, 0 through 23.
    hour: i64,
    /// Minute.
    minute: i64,
    /// Second.
    second: i64,
}

/// Formats an ISO 8601 date like
/// `new Intl.DateTimeFormat("en-US", { dateStyle, timeStyle, timeZone: "UTC" }).format(new Date(input))`.
///
/// Accepts `YYYY-MM-DD` and `YYYY-MM-DDTHH:MM`, optionally with `:SS` and a fraction of a second,
/// followed by `Z`, a `±HH:MM` offset, or nothing. A date-time without an offset is read as UTC,
/// where JavaScript reads it as local time. Returns `None` for any other text, an impossible date
/// such as February 29 of a common year (JavaScript rolls it over), text longer than 64 characters,
/// and moments outside the years 1 through 9999 in UTC. Without either style it formats like
/// `dateStyle: "medium"`.
pub(crate) fn format_lumen_date(
    input: &str,
    date_style: Option<FormattedDateStyle>,
    time_style: Option<FormattedDateTimeStyle>,
) -> Option<String> {
    let moment = parse_moment(input)?;
    let date_style = match (date_style, time_style) {
        (None, None) => Some(FormattedDateStyle::Medium),
        (style, _) => style,
    };
    let date = date_style.map(|style| format_date(&moment, style));
    let time = time_style.map(|style| format_time(&moment, style));

    match (date, time) {
        (Some(date), Some(time)) => {
            let glue = match date_style {
                Some(FormattedDateStyle::Full | FormattedDateStyle::Long) => " at ",
                _ => ", ",
            };

            Some(format!("{date}{glue}{time}"))
        }
        (date, time) => date.or(time),
    }
}

/// Reads fixed-width ASCII fields from the date text.
struct Cursor<'a> {
    /// Remaining bytes.
    bytes: &'a [u8],
}

impl Cursor<'_> {
    /// Reads exactly `count` digits as a number.
    fn number(&mut self, count: usize) -> Option<i64> {
        let (field, rest) = self.bytes.split_at_checked(count)?;

        if !field.iter().all(u8::is_ascii_digit) {
            return None;
        }

        self.bytes = rest;

        Some(
            field
                .iter()
                .fold(0, |total, digit| total * 10 + i64::from(digit - b'0')),
        )
    }

    /// Consumes `byte` when it comes next.
    fn eat(&mut self, byte: u8) -> bool {
        match self.bytes.split_first() {
            Some((first, rest)) if *first == byte => {
                self.bytes = rest;
                true
            }
            _ => false,
        }
    }

    /// Requires `byte` next.
    fn expect(&mut self, byte: u8) -> Option<()> {
        self.eat(byte).then_some(())
    }

    /// Consumes one or more digits and returns whether they are all zero.
    fn fraction(&mut self) -> Option<bool> {
        let count = self
            .bytes
            .iter()
            .take_while(|byte| byte.is_ascii_digit())
            .count();
        let (digits, rest) = self.bytes.split_at_checked(count)?;

        self.bytes = rest;

        (count > 0).then(|| digits.iter().all(|digit| *digit == b'0'))
    }
}

/// Parses the accepted ISO 8601 forms into a UTC moment.
fn parse_moment(input: &str) -> Option<Moment> {
    if input.len() > MAX_TEXT_LENGTH {
        return None;
    }

    let mut cursor = Cursor {
        bytes: input.as_bytes(),
    };
    let year = cursor.number(4)?;

    cursor.expect(b'-')?;

    let month = cursor.number(2)?;

    cursor.expect(b'-')?;

    let day = cursor.number(2)?;

    if !(1..=9999).contains(&year) || !(1..=days_in_month(year, month)).contains(&day) {
        return None;
    }

    let (mut hour, mut minute, mut second, mut offset) = (0, 0, 0, 0);

    if !cursor.bytes.is_empty() {
        cursor.expect(b'T')?;
        hour = cursor.number(2)?;
        cursor.expect(b':')?;
        minute = cursor.number(2)?;

        let mut whole_second = true;

        if cursor.eat(b':') {
            second = cursor.number(2)?;

            if cursor.eat(b'.') {
                whole_second = cursor.fraction()?;
            }
        }

        // Nothing after the time means no offset: read as UTC.
        if !cursor.eat(b'Z') && !cursor.bytes.is_empty() {
            let sign = if cursor.eat(b'+') {
                1
            } else {
                cursor.expect(b'-')?;
                -1
            };
            let offset_hour = cursor.number(2)?;

            cursor.expect(b':')?;

            let offset_minute = cursor.number(2)?;

            if offset_hour > 23 || offset_minute > 59 {
                return None;
            }

            offset = sign * (offset_hour * 60 + offset_minute);
        }

        if !cursor.bytes.is_empty() {
            return None;
        }

        let end_of_day = hour == 24 && minute == 0 && second == 0 && whole_second;

        if (hour > 23 && !end_of_day) || minute > 59 || second > 59 {
            return None;
        }
    }

    let minutes = days_from_civil(year, month, day) * MINUTES_PER_DAY + hour * 60 + minute - offset;
    let days = minutes.div_euclid(MINUTES_PER_DAY);
    let minute_of_day = minutes.rem_euclid(MINUTES_PER_DAY);
    let (year, month, day) = civil_from_days(days);

    (1..=9999).contains(&year).then_some(Moment {
        days,
        year,
        month,
        day,
        hour: minute_of_day / 60,
        minute: minute_of_day % 60,
        second,
    })
}

/// Days in a proleptic Gregorian month, or zero for an invalid month.
fn days_in_month(year: i64, month: i64) -> i64 {
    match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) => 29,
        2 => 28,
        _ => 0,
    }
}

/// Days from 1970-01-01 to a proleptic Gregorian date.
fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
    let year = if month <= 2 { year - 1 } else { year };
    let era = year.div_euclid(400);
    let year_of_era = year - era * 400;
    let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 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 - 719_468
}

/// Proleptic Gregorian `(year, month, day)` of a day count from 1970-01-01.
fn civil_from_days(days: i64) -> (i64, i64, i64) {
    let days = days + 719_468;
    let era = days.div_euclid(146_097);
    let day_of_era = days - era * 146_097;
    let year_of_era =
        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
    let shifted_month = (5 * day_of_year + 2) / 153;
    let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
    let month = if shifted_month < 10 {
        shifted_month + 3
    } else {
        shifted_month - 9
    };
    let year = year_of_era + era * 400 + i64::from(month <= 2);

    (year, month, day)
}

/// Reads an English name from a table, by a validated index.
fn name_at(names: &'static [&'static str], index: i64) -> &'static str {
    usize::try_from(index)
        .ok()
        .and_then(|index| names.get(index))
        .copied()
        .unwrap_or_default()
}

/// Writes the date part.
fn format_date(moment: &Moment, style: FormattedDateStyle) -> String {
    let Moment {
        year, month, day, ..
    } = *moment;
    let month_name = name_at(&MONTHS, month - 1);

    match style {
        FormattedDateStyle::Full => {
            let weekday = name_at(&WEEKDAYS, (moment.days + 4).rem_euclid(7));

            format!("{weekday}, {month_name} {day}, {year}")
        }
        FormattedDateStyle::Long => format!("{month_name} {day}, {year}"),
        FormattedDateStyle::Medium => {
            format!(
                "{} {day}, {year}",
                month_name.get(..3).unwrap_or(month_name)
            )
        }
        FormattedDateStyle::Short => format!("{month}/{day}/{:02}", year % 100),
    }
}

/// Writes the time part in UTC.
fn format_time(moment: &Moment, style: FormattedDateTimeStyle) -> String {
    let Moment {
        hour,
        minute,
        second,
        ..
    } = *moment;
    let hour12 = if hour % 12 == 0 { 12 } else { hour % 12 };
    let period = if hour < 12 { "AM" } else { "PM" };

    match style {
        FormattedDateTimeStyle::Full => {
            format!("{hour12}:{minute:02}:{second:02} {period} Coordinated Universal Time")
        }
        FormattedDateTimeStyle::Long => format!("{hour12}:{minute:02}:{second:02} {period} UTC"),
        FormattedDateTimeStyle::Medium => format!("{hour12}:{minute:02}:{second:02} {period}"),
        FormattedDateTimeStyle::Short => format!("{hour12}:{minute:02} {period}"),
    }
}

#[cfg(test)]
mod tests {
    // Expected text comes from Node 22 (ICU 78, CLDR 48) running Lumen's `formatLumenNumber`.
    use super::*;
    use FormattedNumberCurrencyDisplay as Display;
    use FormattedNumberCurrencyName as CurrencyName;
    use FormattedNumberNotation as Notation;
    use FormattedNumberSignDisplay as Sign;
    use FormattedNumberUnitDisplay as UnitDisplay;

    /// Formats a valid number and compares every field.
    fn check(
        value: impl Into<FormattedNumberValue>,
        options: &NumberFormatOptions,
        text: &str,
        accessible_text: Option<&str>,
        js_value: &str,
    ) {
        let expected = FormattedNumberText {
            text: text.to_owned(),
            accessible_text: accessible_text.map(str::to_owned),
            valid: true,
            value: Some(js_value.to_owned()),
        };

        assert_eq!(
            format_lumen_number(&value.into(), options, FORMATTED_NUMBER_FALLBACK),
            expected,
            "{options:?}"
        );
    }

    /// Formats a value that must render the fallback.
    fn check_invalid(value: impl Into<FormattedNumberValue>) {
        let value = value.into();
        let expected = FormattedNumberText {
            text: FORMATTED_NUMBER_FALLBACK.to_owned(),
            accessible_text: None,
            valid: false,
            value: None,
        };

        assert_eq!(
            format_lumen_number(&value, &decimal(), FORMATTED_NUMBER_FALLBACK),
            expected,
            "{value:?}"
        );
    }

    fn decimal() -> NumberFormatOptions {
        NumberFormatOptions::default()
    }

    fn fraction(minimum: Option<f64>, maximum: Option<f64>) -> NumberFormatOptions {
        NumberFormatOptions {
            minimum_fraction_digits: minimum,
            maximum_fraction_digits: maximum,
            ..decimal()
        }
    }

    fn sign(sign_display: Sign) -> NumberFormatOptions {
        NumberFormatOptions {
            sign_display,
            ..decimal()
        }
    }

    fn notation(notation: Notation) -> NumberFormatOptions {
        NumberFormatOptions {
            notation,
            ..decimal()
        }
    }

    fn compact() -> NumberFormatOptions {
        notation(Notation::Compact)
    }

    fn percent() -> NumberFormatOptions {
        NumberFormatOptions {
            format: FormattedNumberFormat::Percent,
            ..decimal()
        }
    }

    fn currency(code: &str, currency_display: Display) -> NumberFormatOptions {
        NumberFormatOptions {
            format: FormattedNumberFormat::Currency,
            currency: Some(code.to_owned()),
            currency_display,
            ..decimal()
        }
    }

    fn unit(id: &str, unit_display: UnitDisplay) -> NumberFormatOptions {
        NumberFormatOptions {
            format: FormattedNumberFormat::Unit,
            unit: Some(id.to_owned()),
            unit_display,
            ..decimal()
        }
    }

    #[test]
    fn formats_decimal_numbers() {
        check(1234.5678, &decimal(), "1,234.568", None, "1234.5678");
        check(0.0, &decimal(), "0", None, "0");
        check(-0.0, &decimal(), "-0", None, "0");
        check(
            1e21,
            &decimal(),
            "1,000,000,000,000,000,000,000",
            None,
            "1e+21",
        );
        check(1e-7, &decimal(), "0", None, "1e-7");
        check(
            f64::MIN_POSITIVE,
            &decimal(),
            "0",
            None,
            "2.2250738585072014e-308",
        );
        check(5e-324, &decimal(), "0", None, "5e-324");
        check(
            2f64.powi(60),
            &decimal(),
            "1,152,921,504,606,847,000",
            None,
            "1152921504606847000",
        );
        check(
            256_079_881_684_854.0 + 0.625,
            &decimal(),
            "256,079,881,684,854.62",
            None,
            "256079881684854.62",
        );
        check(
            0.1 + 0.2,
            &fraction(None, Some(20.0)),
            "0.30000000000000004",
            None,
            "0.30000000000000004",
        );
        check(1e-7, &fraction(None, Some(20.0)), "0.0000001", None, "1e-7");
    }

    #[test]
    fn rounds_half_away_from_zero_on_the_shortest_decimal() {
        check(1.005, &fraction(None, Some(2.0)), "1.01", None, "1.005");
        check(2.675, &fraction(None, Some(2.0)), "2.68", None, "2.675");
        check(-2.5, &fraction(None, Some(0.0)), "-3", None, "-2.5");
        check(0.5, &fraction(None, Some(0.0)), "1", None, "0.5");
        check(9.9995, &decimal(), "10", None, "9.9995");
        check(-0.0001, &decimal(), "-0", None, "-0.0001");
    }

    #[test]
    fn clamps_fraction_digits() {
        check(1.5, &fraction(Some(-2.0), None), "1.5", None, "1.5");
        check(
            1.0 / 3.0,
            &fraction(None, Some(25.0)),
            "0.3333333333333333",
            None,
            "0.3333333333333333",
        );
        check(1.5, &fraction(Some(2.0), Some(1.0)), "1.50", None, "1.5");
        check(
            1.23456,
            &fraction(Some(f64::NAN), Some(2.9)),
            "1.23",
            None,
            "1.23456",
        );
        check(
            1.23456,
            &fraction(Some(f64::INFINITY), None),
            "1.235",
            None,
            "1.23456",
        );
        check(
            2.0,
            &fraction(Some(21.0), None),
            "2.00000000000000000000",
            None,
            "2",
        );
    }

    #[test]
    fn shows_signs() {
        check(5.0, &sign(Sign::Always), "+5", None, "5");
        check(0.0, &sign(Sign::Always), "+0", None, "0");
        check(-0.0, &sign(Sign::Always), "-0", None, "0");
        check(0.0, &sign(Sign::ExceptZero), "0", None, "0");
        check(-0.0001, &sign(Sign::ExceptZero), "0", None, "-0.0001");
        check(5.0, &sign(Sign::ExceptZero), "+5", None, "5");
        check(-5.0, &sign(Sign::ExceptZero), "-5", None, "-5");
        check(-5.0, &sign(Sign::Never), "5", None, "-5");
    }

    #[test]
    fn formats_percentages() {
        check(0.145, &percent(), "15%", None, "0.145");
        check(-0.001, &percent(), "-0%", None, "-0.001");
        check(
            12.34,
            &NumberFormatOptions {
                notation: Notation::Compact,
                ..percent()
            },
            "1.2K%",
            Some("1.2 thousand%"),
            "12.34",
        );
    }

    #[test]
    fn formats_currencies() {
        check(
            1.0,
            &currency("USD", Display::Symbol),
            "$1.00",
            Some("1.00 US dollars"),
            "1",
        );
        check(
            1.0,
            &currency("USD", Display::Name),
            "1.00 US dollars",
            None,
            "1",
        );
        check(
            1.0,
            &currency("JPY", Display::Name),
            "1 Japanese yen",
            None,
            "1",
        );
        check(
            1234.5,
            &currency("JPY", Display::Symbol),
            "¥1,235",
            Some("1,235 Japanese yen"),
            "1234.5",
        );
        check(
            1.0,
            &currency("KWD", Display::Symbol),
            "KWD\u{a0}1.000",
            None,
            "1",
        );
        check(
            -1.0,
            &currency("EUR", Display::Symbol),
            "-€1.00",
            None,
            "-1",
        );
        check(
            1.0,
            &currency("GBP", Display::Symbol),
            "£1.00",
            Some("1.00 British pounds"),
            "1",
        );
        check(1.0, &currency("CAD", Display::Symbol), "CA$1.00", None, "1");
        check(
            1.0,
            &currency("CAD", Display::NarrowSymbol),
            "$1.00",
            Some("1.00 Canadian dollars"),
            "1",
        );
        check(
            1.0,
            &currency("CHF", Display::Symbol),
            "CHF\u{a0}1.00",
            None,
            "1",
        );
        check(
            1.0,
            &currency("USD", Display::Code),
            "USD\u{a0}1.00",
            None,
            "1",
        );
        check(
            1.0,
            &currency("usd", Display::Symbol),
            "$1.00",
            Some("1.00 US dollars"),
            "1",
        );
        check(
            1.0,
            &currency("XYZ", Display::Symbol),
            "XYZ\u{a0}1.00",
            None,
            "1",
        );
        check(1.0, &currency("XYZ", Display::Name), "1.00 XYZ", None, "1");
    }

    #[test]
    fn formats_currencies_with_other_options() {
        check(1.0, &currency("US", Display::Symbol), "1", None, "1");
        check(
            1.0,
            &NumberFormatOptions {
                currency: None,
                ..currency("USD", Display::Symbol)
            },
            "1",
            None,
            "1",
        );
        check(
            1.0,
            &NumberFormatOptions {
                maximum_fraction_digits: Some(0.0),
                ..currency("USD", Display::Symbol)
            },
            "$1",
            Some("1 US dollar"),
            "1",
        );
        check(
            1234.0,
            &NumberFormatOptions {
                notation: Notation::Compact,
                ..currency("USD", Display::Symbol)
            },
            "$1.2K",
            Some("1.2 thousand US dollars"),
            "1234",
        );
        check(
            1000.0,
            &NumberFormatOptions {
                notation: Notation::Compact,
                maximum_fraction_digits: Some(1.0),
                ..currency("USD", Display::Symbol)
            },
            "$1.0K",
            Some("1.0 thousand US dollars"),
            "1000",
        );
        check(
            1234.5,
            &NumberFormatOptions {
                notation: Notation::Scientific,
                ..currency("USD", Display::Symbol)
            },
            "$1.23E3",
            Some("1.23E3 US dollars"),
            "1234.5",
        );
        check(
            -1.0,
            &NumberFormatOptions {
                sign_display: Sign::Always,
                ..currency("XOF", Display::Symbol)
            },
            "-F\u{202f}CFA\u{a0}1",
            None,
            "-1",
        );
    }

    #[test]
    fn names_currencies_for_assistive_technology() {
        check(
            1.0,
            &NumberFormatOptions {
                currency_name: CurrencyName::Never,
                ..currency("USD", Display::Symbol)
            },
            "$1.00",
            None,
            "1",
        );
        check(
            1.0,
            &NumberFormatOptions {
                currency_name: CurrencyName::Always,
                ..currency("EUR", Display::Symbol)
            },
            "€1.00",
            Some("1.00 euros"),
            "1",
        );
        check(
            1.0,
            &NumberFormatOptions {
                currency_name: CurrencyName::Always,
                ..currency("KWD", Display::Code)
            },
            "KWD\u{a0}1.000",
            Some("1.000 Kuwaiti dinars"),
            "1",
        );
        check(
            1.0,
            &currency("DKK", Display::NarrowSymbol),
            "kr\u{a0}1.00",
            Some("1.00 Danish kroner"),
            "1",
        );
        check(
            1.0,
            &currency("DKK", Display::Symbol),
            "DKK\u{a0}1.00",
            None,
            "1",
        );
    }

    #[test]
    fn formats_units() {
        check(
            1.0,
            &unit("kilobyte", UnitDisplay::Short),
            "1 kB",
            Some("1 kilobyte"),
            "1",
        );
        check(
            2.0,
            &unit("kilobyte", UnitDisplay::Long),
            "2 kilobytes",
            None,
            "2",
        );
        check(
            16.0,
            &unit("kilometer-per-hour", UnitDisplay::Narrow),
            "16km/h",
            Some("16 kilometers per hour"),
            "16",
        );
        check(
            -5.0,
            &unit("celsius", UnitDisplay::Short),
            "-5°C",
            Some("-5 degrees Celsius"),
            "-5",
        );
        check(1.0, &unit("day", UnitDisplay::Long), "1 day", None, "1");
        check(
            1.5,
            &unit("day", UnitDisplay::Short),
            "1.5 days",
            None,
            "1.5",
        );
        check(
            0.0,
            &unit("byte", UnitDisplay::Narrow),
            "0B",
            Some("0 bytes"),
            "0",
        );
        check(
            50.0,
            &unit("percent", UnitDisplay::Short),
            "50%",
            Some("50 percent"),
            "50",
        );
        check(
            5.0,
            &unit("percent-per-hour", UnitDisplay::Short),
            "5%",
            Some("5 percent per hour"),
            "5",
        );
        check(
            1.0,
            &unit("byte-per-day", UnitDisplay::Long),
            "1 byte per day",
            None,
            "1",
        );
        check(
            30.0,
            &unit("mile-per-gallon", UnitDisplay::Short),
            "30 mpg",
            Some("30 miles per gallon"),
            "30",
        );
        check(
            1.0,
            &unit(" meter ", UnitDisplay::Short),
            "1 m",
            Some("1 meter"),
            "1",
        );
        check(
            1.0,
            &NumberFormatOptions {
                minimum_fraction_digits: Some(1.0),
                ..unit("day", UnitDisplay::Long)
            },
            "1.0 days",
            None,
            "1",
        );
    }

    #[test]
    fn falls_back_for_unusable_units() {
        check(
            1.23456,
            &NumberFormatOptions {
                maximum_fraction_digits: Some(1.0),
                ..unit("parsec", UnitDisplay::Short)
            },
            "1.235",
            None,
            "1.23456",
        );
        check(
            1.23456,
            &NumberFormatOptions {
                maximum_fraction_digits: Some(1.0),
                ..unit("Meter", UnitDisplay::Short)
            },
            "1.235",
            None,
            "1.23456",
        );
        check(
            1.23456,
            &NumberFormatOptions {
                maximum_fraction_digits: Some(1.0),
                ..unit("  ", UnitDisplay::Short)
            },
            "1.2",
            None,
            "1.23456",
        );
        check(
            1.23456,
            &NumberFormatOptions {
                maximum_fraction_digits: Some(1.0),
                ..unit(&"x".repeat(65), UnitDisplay::Short)
            },
            "1.2",
            None,
            "1.23456",
        );
        check(
            1234.0,
            &NumberFormatOptions {
                notation: Notation::Compact,
                ..unit("meter-per-second-per-hour", UnitDisplay::Short)
            },
            "1.2K",
            Some("1.2 thousand"),
            "1234",
        );
    }

    #[test]
    fn formats_compact_numbers() {
        check(1234.0, &compact(), "1.2K", Some("1.2 thousand"), "1234");
        check(12345.0, &compact(), "12K", Some("12 thousand"), "12345");
        check(999_999.0, &compact(), "1M", Some("1 million"), "999999");
        check(
            1e15,
            &compact(),
            "1000T",
            Some("1000 trillion"),
            "1000000000000000",
        );
        check(
            1e16,
            &compact(),
            "10,000T",
            Some("10,000 trillion"),
            "10000000000000000",
        );
        check(-1234.0, &compact(), "-1.2K", Some("-1.2 thousand"), "-1234");
        check(1249.5, &compact(), "1.2K", Some("1.2 thousand"), "1249.5");
        check(0.001_234_5, &compact(), "0.0012", None, "0.0012345");
        check(
            1234.0,
            &NumberFormatOptions {
                maximum_fraction_digits: Some(2.0),
                ..compact()
            },
            "1.23K",
            Some("1.23 thousand"),
            "1234",
        );
        check(
            1000.0,
            &NumberFormatOptions {
                minimum_fraction_digits: Some(2.0),
                ..compact()
            },
            "1.00K",
            Some("1.00 thousand"),
            "1000",
        );
        check(
            1000.0,
            &NumberFormatOptions {
                notation: Notation::Compact,
                ..unit("day", UnitDisplay::Long)
            },
            "1K days",
            Some("1 thousand days"),
            "1000",
        );
        check(
            1234.5,
            &NumberFormatOptions {
                notation: Notation::Compact,
                ..unit("percent-per-acre", UnitDisplay::Short)
            },
            "1.2K%/ac",
            Some("1.2 thousand percent per acre"),
            "1234.5",
        );
    }

    #[test]
    fn formats_scientific_and_engineering_numbers() {
        check(
            1234.5,
            &notation(Notation::Scientific),
            "1.235E3",
            None,
            "1234.5",
        );
        check(
            0.000_123_45,
            &notation(Notation::Scientific),
            "1.235E-4",
            None,
            "0.00012345",
        );
        check(0.0, &notation(Notation::Scientific), "0E0", None, "0");
        check(
            -9.9996,
            &notation(Notation::Scientific),
            "-1E1",
            None,
            "-9.9996",
        );
        check(
            f64::MAX,
            &notation(Notation::Scientific),
            "1.798E308",
            None,
            "1.7976931348623157e+308",
        );
        check(
            123_456.0,
            &notation(Notation::Engineering),
            "123.456E3",
            None,
            "123456",
        );
        check(
            0.000_123_45,
            &notation(Notation::Engineering),
            "123.45E-6",
            None,
            "0.00012345",
        );
        check(
            5e-324,
            &notation(Notation::Engineering),
            "5E-324",
            None,
            "5e-324",
        );
        check(
            1.0,
            &NumberFormatOptions {
                notation: Notation::Scientific,
                ..unit("day", UnitDisplay::Long)
            },
            "1E0 day",
            None,
            "1",
        );
        check(
            0.5,
            &NumberFormatOptions {
                notation: Notation::Scientific,
                ..percent()
            },
            "5E1%",
            None,
            "0.5",
        );
    }

    #[test]
    fn reads_numeric_text() {
        check("1234.5", &decimal(), "1,234.5", None, "1234.5");
        check(" 2e3 ", &decimal(), "2,000", None, "2000");
        check("+.5", &decimal(), "0.5", None, "0.5");
        check("5.", &decimal(), "5", None, "5");
        check("\u{a0}1\u{feff}", &decimal(), "1", None, "1");
        check("\u{2028}7\u{3000}", &decimal(), "7", None, "7");
        check("-1e-400", &decimal(), "-0", None, "0");
        check("00012", &decimal(), "12", None, "12");
    }

    #[test]
    fn rejects_values_that_are_not_finite_numbers() {
        check_invalid(f64::NAN);
        check_invalid(f64::INFINITY);
        check_invalid(f64::NEG_INFINITY);

        for text in [
            "0x10",
            "Infinity",
            "-Infinity",
            "",
            "   ",
            ".",
            "+",
            "1e",
            "1e400",
            "1,000",
            "1 2",
            "1_000",
            "\u{85}1",
            "\u{180e}1",
            "NaN",
            "1",
            "٣",
        ] {
            check_invalid(text);
        }

        check_invalid("1".repeat(65));
        check(
            "1".repeat(64),
            &decimal(),
            "1,111,111,111,111,111,200,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000",
            None,
            "1.1111111111111112e+63",
        );
    }

    #[test]
    fn renders_a_custom_fallback() {
        let result = format_lumen_number(&"n/a".into(), &decimal(), "Not available");

        assert_eq!(result.text, "Not available");
        assert!(!result.valid);
    }

    #[test]
    fn writes_values_like_javascript() {
        for (number, expected) in [
            (1e21, "1e+21"),
            (1e-7, "1e-7"),
            (1.23e-18, "1.23e-18"),
            (0.000_001, "0.000001"),
            (-0.0, "0"),
            (1.5, "1.5"),
            (100.0, "100"),
            (2f64.powi(60), "1152921504606847000"),
            (-f64::MAX, "-1.7976931348623157e+308"),
            (5e-324, "5e-324"),
            (0.1 + 0.2, "0.30000000000000004"),
            (123_456_789_012_345_680_000.0, "123456789012345680000"),
            (9.499_999_999_999_999e-7, "9.499999999999999e-7"),
            (256_079_881_684_854.0 + 0.625, "256079881684854.62"),
        ] {
            assert_eq!(
                js_number_to_string(&Decimal::from_f64(number), number.is_sign_negative()),
                expected,
                "{number:e}"
            );
        }
    }

    #[test]
    fn converts_rust_numbers_like_javascript() {
        let value = |value: FormattedNumberValue| format_lumen_number(&value, &decimal(), "").value;

        assert_eq!(
            value(i64::MAX.into()),
            Some("9223372036854776000".to_owned())
        );
        assert_eq!(
            value(u64::MAX.into()),
            Some("18446744073709552000".to_owned())
        );
        assert_eq!(value(42_usize.into()), Some("42".to_owned()));
        assert_eq!(value((-7_i32).into()), Some("-7".to_owned()));
        assert_eq!(value(7_u32.into()), Some("7".to_owned()));
        assert_eq!(
            value(0.1_f32.into()),
            Some("0.10000000149011612".to_owned())
        );
        assert_eq!(value(String::from("8").into()), Some("8".to_owned()));
    }

    #[test]
    fn formats_german_currency_in_its_requested_locale() {
        let german = NumberFormatOptions {
            locale: Some("de".to_owned()),
            ..currency("EUR", Display::Symbol)
        };

        assert_eq!(
            format_lumen_number(&1234.5.into(), &german, "").text,
            "1.234,50\u{a0}€"
        );
    }

    #[test]
    fn exposes_javascript_option_names() {
        assert_eq!(FormattedNumberFormat::Unit.as_str(), "unit");
        assert_eq!(Notation::Engineering.as_str(), "engineering");
        assert_eq!(Sign::ExceptZero.as_str(), "exceptZero");
        assert_eq!(Display::NarrowSymbol.as_str(), "narrowSymbol");
        assert_eq!(CurrencyName::Always.as_str(), "always");
        assert_eq!(UnitDisplay::Narrow.as_str(), "narrow");
        assert_eq!(FormattedDateStyle::default().as_str(), "medium");
        assert_eq!(FormattedDateTimeStyle::Full.as_str(), "full");
    }

    #[test]
    fn stays_linear_on_adversarial_input() {
        let long_number = format!("{}1{}", " ".repeat(1_000_000), "\u{3000}".repeat(100_000));

        check(long_number, &decimal(), "1", None, "1");
        check_invalid("1".repeat(1_000_000));
        check_invalid("-".repeat(1_000_000));
        check(
            1.5,
            &unit(&"-per-".repeat(200_000), UnitDisplay::Long),
            "1.5",
            None,
            "1.5",
        );
        check(
            1.5,
            &unit(&"a".repeat(1_000_000), UnitDisplay::Long),
            "1.5",
            None,
            "1.5",
        );
        check(
            1.5,
            &currency(&"USD".repeat(300_000), Display::Name),
            "1.5",
            None,
            "1.5",
        );

        let huge = format_lumen_number(
            &f64::MAX.into(),
            &NumberFormatOptions {
                minimum_fraction_digits: Some(1e300),
                ..percent()
            },
            "",
        );

        // Node: 311 integer digits with grouping, 20 fraction digits, and the percent sign.
        assert_eq!(huge.text.len(), 436);
        assert!(huge.text.starts_with("17,976,931,348,623,157,000,000"));
        assert!(huge.text.ends_with(",000,000.00000000000000000000%"));
        assert_eq!(format_lumen_date(&"2".repeat(1_000_000), None, None), None);
        assert_eq!(
            format_lumen_date(
                &format!("2020-01-01T12:00:00.{}Z", "0".repeat(1_000_000)),
                None,
                None
            ),
            None
        );
    }

    #[test]
    fn formats_dates_in_every_style() {
        use FormattedDateStyle as Date;
        use FormattedDateTimeStyle as Time;

        let cases = [
            (
                None,
                Some(Time::Full),
                "3:04:05 PM Coordinated Universal Time",
            ),
            (None, Some(Time::Long), "3:04:05 PM UTC"),
            (None, Some(Time::Medium), "3:04:05 PM"),
            (None, Some(Time::Short), "3:04 PM"),
            (Some(Date::Full), None, "Tuesday, December 1, 2026"),
            (Some(Date::Long), None, "December 1, 2026"),
            (Some(Date::Medium), None, "Dec 1, 2026"),
            (None, None, "Dec 1, 2026"),
            (Some(Date::Short), None, "12/1/26"),
            (
                Some(Date::Full),
                Some(Time::Full),
                "Tuesday, December 1, 2026 at 3:04:05 PM Coordinated Universal Time",
            ),
            (
                Some(Date::Long),
                Some(Time::Long),
                "December 1, 2026 at 3:04:05 PM UTC",
            ),
            (
                Some(Date::Long),
                Some(Time::Short),
                "December 1, 2026 at 3:04 PM",
            ),
            (
                Some(Date::Medium),
                Some(Time::Full),
                "Dec 1, 2026, 3:04:05 PM Coordinated Universal Time",
            ),
            (
                Some(Date::Medium),
                Some(Time::Medium),
                "Dec 1, 2026, 3:04:05 PM",
            ),
            (
                Some(Date::Short),
                Some(Time::Long),
                "12/1/26, 3:04:05 PM UTC",
            ),
            (Some(Date::Short), Some(Time::Short), "12/1/26, 3:04 PM"),
        ];

        for (date_style, time_style, expected) in cases {
            assert_eq!(
                format_lumen_date("2026-12-01T15:04:05Z", date_style, time_style).as_deref(),
                Some(expected),
                "{date_style:?} {time_style:?}"
            );
        }
    }

    #[test]
    fn converts_dates_to_utc() {
        let full = |input: &str| {
            format_lumen_date(
                input,
                Some(FormattedDateStyle::Full),
                Some(FormattedDateTimeStyle::Medium),
            )
        };
        let short = |input: &str| format_lumen_date(input, Some(FormattedDateStyle::Short), None);

        for (input, expected) in [
            (
                "2026-12-31T23:30:00-05:00",
                "Friday, January 1, 2027 at 4:30:00 AM",
            ),
            ("2024-02-29", "Thursday, February 29, 2024 at 12:00:00 AM"),
            (
                "2000-02-29T00:00:00.5+00:00",
                "Tuesday, February 29, 2000 at 12:00:00 AM",
            ),
            (
                "2020-01-01T24:00Z",
                "Thursday, January 2, 2020 at 12:00:00 AM",
            ),
            ("0001-01-01", "Monday, January 1, 1 at 12:00:00 AM"),
            ("1970-01-01", "Thursday, January 1, 1970 at 12:00:00 AM"),
            (
                "2026-01-01T00:00:00+14:00",
                "Wednesday, December 31, 2025 at 10:00:00 AM",
            ),
            (
                "9999-12-31T23:59:59.999Z",
                "Friday, December 31, 9999 at 11:59:59 PM",
            ),
            // Without an offset the time is UTC, not local time as in JavaScript.
            (
                "2026-12-01T15:04",
                "Tuesday, December 1, 2026 at 3:04:00 PM",
            ),
        ] {
            assert_eq!(full(input).as_deref(), Some(expected), "{input}");
        }

        assert_eq!(short("0001-01-01").as_deref(), Some("1/1/01"));
        assert_eq!(short("9999-12-31").as_deref(), Some("12/31/99"));
    }

    #[test]
    fn rejects_invalid_dates() {
        for input in [
            "2023-02-29",
            "1900-02-29",
            "2021-04-31",
            "2021-13-01",
            "2021-00-10",
            "2021-01-00",
            "0000-01-01",
            "10000-01-01",
            "+002020-01-01",
            "2020-1-01",
            "2020-01-01T",
            "2020-01-01T12",
            "2020-01-01T12Z",
            "2020-01-01T24:00:01Z",
            "2020-01-01T24:00:00.001Z",
            "2020-01-01T23:60Z",
            "2020-01-01T12:00:60Z",
            "2020-01-01T12:00:00.Z",
            "2020-01-01T12:00+24:00",
            "2020-01-01T12:00+0530",
            "2020-01-01t12:00Z",
            "2020-01-01 12:00Z",
            "2020-01-01T12:00Z ",
            "2020-01-01Z",
            "9999-12-31T23:30-05:00",
            "0001-01-01T00:00+01:00",
            "",
            "garbage",
            "2020-01-01",
        ] {
            assert_eq!(format_lumen_date(input, None, None), None, "{input}");
        }

        let overlong = format!("2020-01-01T12:00:00.{}Z", "0".repeat(44));

        assert_eq!(overlong.len(), 65);
        assert_eq!(format_lumen_date(&overlong, None, None), None);
        assert!(format_lumen_date(&overlong[..63], None, None).is_some());
        assert!(format_lumen_date(&format!("{}Z", &overlong[..63]), None, None).is_some());
    }

    #[test]
    fn counts_days_like_the_gregorian_calendar() {
        let mut days = days_from_civil(1, 1, 1);

        assert_eq!(days, -719_162);
        assert_eq!(days_from_civil(1970, 1, 1), 0);

        for year in 1..=9999 {
            for month in 1..=12 {
                for day in 1..=days_in_month(year, month) {
                    assert_eq!(civil_from_days(days), (year, month, day));
                    assert_eq!(days_from_civil(year, month, day), days);
                    days += 1;
                }
            }
        }
    }
}