deser-json5 0.9.1

JSON5 support for deser
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
// @generated from deser-template-json/src/parser.rs by
// deser-template-json/generate.py.  Do not edit.
//! The JSON parser.
//!
//! The parser is a state machine which can be suspended between tokens: if
//! the input ends within a token and more input can follow, the parser
//! returns how much of the input it consumed (up to the start of the token)
//! and continues with more input.  With the complete input (`eof`) it
//! parses a value in one go.  The state of the current container is held
//! in locals while parsing and only stored in the parser when it's
//! suspended.
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use core::str;

use deser_core::__format::extend;
use deser_core::Text;
use deser_core::de::DeserializeDriver;
use deser_core::ext::{ExtValue, Number as ExactNumber};
use deser_core::{Atom, Error, ErrorKind, Event, State};

use crate::scan::skip_to_escape_single;
use crate::scan::{EscapeScanner, is_ascii, skip_to_escape, validate_utf8_slice};

/// A parsed string.
pub(crate) enum Str<'a, 'b> {
    /// The string is a slice of the input.
    Borrowed(&'a str),
    /// The string was unescaped into the scratch buffer.
    Scratch(&'b str),
}

pub(crate) enum Number<'a> {
    I64(i64),
    /// An integer that does not fit into 64 bits but into 128 bits.  This
    /// holds the (validated) textual representation.
    BigInt(&'a str),
    U64(u64),
    /// A float whose text is the shortest representation of its value.
    F64(f64),
    /// A float (or an integer which does not fit into 128 bits) whose text
    /// cannot be recovered from the value.  This is passed on as number
    /// extension value if exact numbers are enabled.
    Literal(f64),
    /// A hexadecimal integer that does not fit into 64 bits.
    U128(u128),
    /// A negative hexadecimal integer that does not fit into 64 bits.
    I128(i128),
}

impl Number<'_> {
    /// Returns the value of a float.
    fn into_f64(self) -> f64 {
        match self {
            Number::F64(value) | Number::Literal(value) => value,
            _ => unreachable!("not a float"),
        }
    }
}

macro_rules! overflow {
    ($a:ident * 10 + $b:ident, $c:expr) => {
        $a >= $c / 10 && ($a > $c / 10 || $b > $c % 10)
    };
}

/// Receives the events of the parser.
///
/// Atoms of strings which are slices of the input (strings and map keys) are
/// passed to [`emit_input`](Self::emit_input), which can pass them on
/// borrowed if the input lives long enough.
pub(crate) trait Out<'i> {
    fn state_mut(&mut self) -> &mut State;
    fn emit<'e, E: Into<Event<'e>>>(&mut self, event: E) -> Result<(), Error>;
    fn emit_input(&mut self, atom: Atom<'i>) -> Result<(), Error>;
}

/// Creates the atom of a map key.
///
/// JSON only has strings as keys, which are lexical: they can stand for
/// values of other types (like integers).
#[inline(always)]
fn key_atom(key: &str) -> Atom<'_> {
    Atom::Lexical(Text::borrowed(key))
}

/// Passes strings of the input on borrowed.
pub(crate) struct Borrowing<'a, 'd, 'i>(pub &'a mut DeserializeDriver<'d, 'i>);

impl<'i> Out<'i> for Borrowing<'_, '_, 'i> {
    #[inline(always)]
    fn state_mut(&mut self) -> &mut State {
        self.0.state_mut()
    }

    #[inline(always)]
    fn emit<'e, E: Into<Event<'e>>>(&mut self, event: E) -> Result<(), Error> {
        self.0.emit(event)
    }

    #[inline(always)]
    fn emit_input(&mut self, atom: Atom<'i>) -> Result<(), Error> {
        self.0.emit_borrowed(atom)
    }
}

/// Passes strings of the input on as data that is only valid for the call.
///
/// This is used when the input does not outlive the deserialization (for
/// instance a buffer that is refilled).
pub(crate) struct Copying<'a, 'd, 'de>(pub &'a mut DeserializeDriver<'d, 'de>);

impl<'i> Out<'i> for Copying<'_, '_, '_> {
    #[inline(always)]
    fn state_mut(&mut self) -> &mut State {
        self.0.state_mut()
    }

    #[inline(always)]
    fn emit<'e, E: Into<Event<'e>>>(&mut self, event: E) -> Result<(), Error> {
        self.0.emit(event)
    }

    #[inline(always)]
    fn emit_input(&mut self, atom: Atom<'i>) -> Result<(), Error> {
        self.0.emit(atom)
    }
}

/// Discards the events.
///
/// This is used to skip the rest of a value after an error.
pub(crate) struct Discard(pub State);

impl<'i> Out<'i> for Discard {
    #[inline(always)]
    fn state_mut(&mut self) -> &mut State {
        &mut self.0
    }

    #[inline(always)]
    fn emit<'e, E: Into<Event<'e>>>(&mut self, _event: E) -> Result<(), Error> {
        Ok(())
    }

    #[inline(always)]
    fn emit_input(&mut self, _atom: Atom<'i>) -> Result<(), Error> {
        Ok(())
    }
}

/// The options of the parser.
#[derive(Clone, Copy)]
pub(crate) struct Options {
    /// The input is a byte slice which needs to be validated as UTF-8.
    pub validate_utf8: bool,
    pub exact_numbers: bool,
}

/// The result of [`Parser::parse`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Progress {
    /// The value is complete, it ends at the given position.
    Done(usize),
    /// More input is needed.  The input up to the given position was
    /// consumed, the parser continues with the input after it.
    NeedMore(usize),
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Container {
    Top,
    Seq,
    Map,
}

/// What the parser expects next.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Expect {
    /// A value.
    Value,
    /// A value or the end of a sequence (after `[`).
    ValueOrEnd,
    /// A map key.
    Key,
    /// A map key or the end of a map (after `{`).
    KeyOrEnd,
    /// The colon after a key.
    Colon,
    /// A comma or the end of the container after a value.
    AfterValue,
}

/// An incomplete string at the start of the input.
///
/// The positions are relative to the opening quote, the scratch buffer holds
/// the string up to `copied`.
#[derive(Clone, Copy, Debug)]
struct PartialString {
    /// Where scanning continues.
    scanned: usize,
    /// The first byte which was not copied into the scratch buffer.
    copied: usize,
}

/// A JSON parser which can be suspended between tokens.
#[derive(Debug)]
pub(crate) struct Parser {
    // the outer containers, the current one is held in `container`
    stack: Vec<Container>,
    container: Container,
    expect: Expect,
    scratch: Vec<u8>,
    partial: Option<PartialString>,
    // the last error was an error of a sink, the rest of the value
    // continues at the position
    recoverable: Option<usize>,
}

impl Default for Parser {
    fn default() -> Parser {
        Parser {
            stack: Vec::new(),
            container: Container::Top,
            expect: Expect::Value,
            scratch: Vec::new(),
            partial: None,
            recoverable: None,
        }
    }
}

/// Emits an event with its input range.
macro_rules! emit {
    ($out:expr, $base:expr, $start:expr, $end:expr, $event:expr) => {{
        $out.state_mut()
            .set_input_range($base + $start, $base + $end);
        $out.emit($event)
    }};
}

impl Parser {
    /// Returns `true` if the parser is between values.
    pub(crate) fn is_idle(&self) -> bool {
        self.expect == Expect::Value && self.container == Container::Top && self.partial.is_none()
    }

    /// Resets the parser to parse a new value.
    ///
    /// This is needed after an error.
    pub(crate) fn reset(&mut self) {
        self.stack.clear();
        self.container = Container::Top;
        self.expect = Expect::Value;
        self.partial = None;
        self.recoverable = None;
    }

    /// Returns where the rest of the value continues if the last error was
    /// an error of a sink.
    ///
    /// In that case the state is as if the event was accepted and the rest
    /// of the value can be parsed from the position (for instance with
    /// [`Discard`]).
    pub(crate) fn recoverable(&self) -> Option<usize> {
        self.recoverable
    }

    /// Parses a value (or continues it) from `input[pos..]`.
    ///
    /// `eof` is `true` if no input follows, `base` is the offset of the
    /// input in the stream: the input ranges of the events and the offsets
    /// of errors refer to the stream.  After an error the parser has to be
    /// [reset](Self::reset).
    #[inline(always)]
    pub(crate) fn parse<'i, O: Out<'i>>(
        &mut self,
        input: &'i [u8],
        pos: usize,
        eof: bool,
        base: usize,
        options: Options,
        out: &mut O,
    ) -> Result<Progress, Error> {
        self.recoverable = None;
        let mut cur = Cursor {
            input,
            pos,
            validate_utf8: options.validate_utf8,
            hit_end: false,
            partial: (0, 0),
            number_start: 0,
            truncated: false,
            eof,
        };
        // the scratch space is kept with the state between values (and
        // deserializations), unless it holds a string which continues with
        // more input
        if self.scratch.capacity() == 0 {
            take_scratch(&mut self.scratch, out.state_mut());
        }
        let rv = match self.run(&mut cur, eof, base, options.exact_numbers, out) {
            Ok(progress) => Ok(progress),
            Err(err) if err.offset().is_none() => Err(err.with_offset(base + cur.pos)),
            Err(err) => Err(err),
        };
        if self.partial.is_none() && self.scratch.capacity() != 0 {
            put_scratch(&mut self.scratch, out.state_mut());
        }
        rv
    }

    #[inline(always)]
    fn run<'i, O: Out<'i>>(
        &mut self,
        cur: &mut Cursor<'i>,
        eof: bool,
        base: usize,
        exact_numbers: bool,
        out: &mut O,
    ) -> Result<Progress, Error> {
        let input = cur.input;
        let stack = &mut self.stack;
        let scratch = &mut self.scratch;
        let mut container = self.container;
        let mut partial = self.partial.take();

        // stores the state and returns that more input is needed
        macro_rules! suspend {
            ($consumed:expr, $expect:expr) => {{
                self.container = container;
                self.expect = $expect;
                return Ok(Progress::NeedMore($consumed));
            }};
        }

        // fails with an error of a sink.  The state is stored as if the
        // event was accepted so that the rest of the value can be skipped.
        macro_rules! sink {
            ($rv:expr, $expect:expr) => {
                if let Err(err) = $rv {
                    self.container = container;
                    self.expect = $expect;
                    self.recoverable = Some(cur.pos);
                    return Err(err);
                }
            };
        }

        // skips whitespace and returns the next byte, suspends at the end
        // of the input.
        macro_rules! next_byte {
            ($expect:expr) => {
                match cur.parse_whitespace() {
                    Some(byte) => byte,
                    None if eof => return Err(eof_error()),
                    None => suspend!(cur.pos, $expect),
                }
            };
        }

        // parses a string after its opening quote, suspends if it's
        // incomplete.
        macro_rules! string {
            ($start:expr, $expect:expr) => {{
                cur.hit_end = false;
                let rv = cur.parse_str(scratch, $start, partial.take());
                if cur.hit_end && !eof {
                    self.partial = Some(PartialString {
                        scanned: cur.partial.0 - $start,
                        copied: cur.partial.1 - $start,
                    });
                    suspend!($start, $expect)
                }
                rv?
            }};
        }

        // closes the current container
        macro_rules! close {
            ($start:expr, $event:expr) => {{
                container = stack.pop().unwrap_or(Container::Top);
                sink!(
                    emit!(out, base, $start, cur.pos, $event),
                    Expect::AfterValue
                );
            }};
        }

        // parses a map key and the colon after it
        macro_rules! key {
            ($byte:expr) => {{
                let start = cur.pos;
                let key = match $byte {
                    b'"' => {
                        cur.bump();
                        string!(start, Expect::Key)
                    }
                    b'\'' => {
                        cur.bump();
                        string!(start, Expect::Key)
                    }
                    b'a'..=b'z' | b'A'..=b'Z' | b'_' | b'$' | b'\\' | 0x80..=0xff => {
                        cur.hit_end = false;
                        let rv = cur.parse_identifier(scratch);
                        if cur.hit_end && !eof {
                            suspend!(start, Expect::Key)
                        }
                        rv?
                    }
                    _ => return Err(token_error(base + start, "expected map key")),
                };
                match key {
                    Str::Borrowed(key) => {
                        out.state_mut()
                            .set_input_range(base + start, base + cur.pos);
                        sink!(out.emit_input(key_atom(key)), Expect::Colon)
                    }
                    Str::Scratch(key) => sink!(
                        emit!(out, base, start, cur.pos, key_atom(key)),
                        Expect::Colon
                    ),
                }
                colon!();
            }};
        }

        macro_rules! colon {
            () => {
                match next_byte!(Expect::Colon) {
                    b':' => cur.bump(),
                    _ => return Err(Error::new(ErrorKind::Unexpected, "expected colon")),
                }
            };
        }

        // after `{`: the map ends or the first key follows.  Evaluates to
        // `true` if a value follows.
        macro_rules! open_map {
            () => {{
                let byte = if partial.is_some() {
                    b'"'
                } else {
                    next_byte!(Expect::KeyOrEnd)
                };
                if byte == b'}' {
                    let start = cur.pos;
                    cur.bump();
                    close!(start, Event::MapEnd);
                    false
                } else {
                    key!(byte);
                    true
                }
            }};
        }

        // after `[`: the sequence ends or the first value follows.
        // Evaluates to `true` if a value follows.
        macro_rules! open_seq {
            () => {{
                if next_byte!(Expect::ValueOrEnd) == b']' {
                    let start = cur.pos;
                    cur.bump();
                    close!(start, Event::SeqEnd);
                    false
                } else {
                    true
                }
            }};
        }

        // emits a string value, the cursor is after the opening quote
        macro_rules! string_value {
            ($start:expr) => {
                match string!($start, Expect::Value) {
                    Str::Borrowed(val) => {
                        out.state_mut()
                            .set_input_range(base + $start, base + cur.pos);
                        sink!(
                            out.emit_input(Atom::Str(Text::borrowed(val))),
                            Expect::AfterValue
                        )
                    }
                    Str::Scratch(val) => sink!(
                        emit!(out, base, $start, cur.pos, Event::from(val)),
                        Expect::AfterValue
                    ),
                }
            };
        }

        // emits a number, the cursor is after its first byte
        macro_rules! number {
            ($byte:expr, $start:expr) => {{
                cur.number_start = $start;
                cur.truncated = false;
                let rv = match $byte {
                    b'-' => {
                        let first_digit = cur.next_or_nul();
                        cur.parse_integer(false, first_digit)
                    }
                    b'+' => {
                        let first_digit = cur.next_or_nul();
                        cur.parse_integer(true, first_digit)
                    }
                    byte => cur.parse_integer(true, byte),
                };
                // the number might continue
                if cur.hit_end && !eof {
                    suspend!($start, Expect::Value)
                }
                let number = rv?;
                out.state_mut()
                    .set_input_range(base + $start, base + cur.pos);
                sink!(
                    emit_number(out, number, input, exact_numbers, $start, cur.pos),
                    Expect::AfterValue
                )
            }};
        }

        // continue where the parser was suspended
        let mut skip_value = match self.expect {
            Expect::Value => false,
            Expect::ValueOrEnd => !open_seq!(),
            Expect::KeyOrEnd => !open_map!(),
            Expect::Key => {
                let byte = if partial.is_some() {
                    b'"'
                } else {
                    next_byte!(Expect::Key)
                };
                key!(byte);
                false
            }
            Expect::Colon => {
                colon!();
                false
            }
            Expect::AfterValue => true,
        };

        'value: loop {
            if !skip_value {
                let byte = if partial.is_some() {
                    b'"'
                } else {
                    next_byte!(Expect::Value)
                };
                let start = cur.pos;
                cur.bump();
                cur.hit_end = false;
                match byte {
                    b'"' => string_value!(start),
                    b'\'' => string_value!(start),
                    b'0'..=b'9' | b'-' => number!(byte, start),
                    // `+1`, `.5`, `Infinity` and `NaN`
                    b'+' | b'.' | b'I' | b'N' => number!(byte, start),
                    b'n' | b't' | b'f' => {
                        let (rest, event): (&[u8], _) = match byte {
                            b'n' => (b"ull", Event::Atom(Atom::Null)),
                            b't' => (b"rue", Event::from(true)),
                            _ => (b"alse", Event::from(false)),
                        };
                        let rv = cur.parse_ident(rest);
                        if cur.hit_end && !eof {
                            suspend!(start, Expect::Value)
                        }
                        rv?;
                        sink!(emit!(out, base, start, cur.pos, event), Expect::AfterValue)
                    }
                    b'{' => {
                        stack.push(container);
                        container = Container::Map;
                        sink!(
                            emit!(out, base, start, cur.pos, Event::map_start()),
                            Expect::KeyOrEnd
                        );
                        if open_map!() {
                            continue 'value;
                        }
                    }
                    b'[' => {
                        stack.push(container);
                        container = Container::Seq;
                        sink!(
                            emit!(out, base, start, cur.pos, Event::seq_start()),
                            Expect::ValueOrEnd
                        );
                        if open_seq!() {
                            continue 'value;
                        }
                    }
                    b',' => return Err(token_error(base + start, "unexpected comma")),
                    b':' => return Err(token_error(base + start, "unexpected colon")),
                    b']' | b'}' => return Err(token_error(base + start, "expected a value")),
                    _ => return Err(token_error(base + start, "unexpected character")),
                }
            }
            skip_value = false;

            // a value was completed, either the container ends or the next
            // value follows.
            loop {
                let close = match container {
                    Container::Top => {
                        self.container = Container::Top;
                        self.expect = Expect::Value;
                        return Ok(Progress::Done(cur.pos));
                    }
                    Container::Map => b'}',
                    Container::Seq => b']',
                };
                match next_byte!(Expect::AfterValue) {
                    b',' => {
                        cur.bump();
                        // the container can end after the comma
                        let more = if container == Container::Map {
                            open_map!()
                        } else {
                            open_seq!()
                        };
                        if more {
                            continue 'value;
                        }
                    }
                    byte if byte == close => {
                        let start = cur.pos;
                        cur.bump();
                        close!(
                            start,
                            if close == b'}' {
                                Event::MapEnd
                            } else {
                                Event::SeqEnd
                            }
                        );
                    }
                    b']' | b'}' => {
                        return Err(Error::new(
                            ErrorKind::Unexpected,
                            if container == Container::Map {
                                "unexpected end of seq"
                            } else {
                                "unexpected end of map"
                            },
                        ));
                    }
                    _ => {
                        return Err(Error::new(ErrorKind::Unexpected, "expected a comma"));
                    }
                }
            }
        }
    }
}

/// Takes the scratch space that was kept with the state.
#[inline(never)]
fn take_scratch(scratch: &mut Vec<u8>, state: &mut State) {
    *scratch = state.__private_take_scratch();
}

/// Keeps the scratch space with the state.
#[inline(never)]
fn put_scratch(scratch: &mut Vec<u8>, state: &mut State) {
    state.__private_put_scratch(core::mem::take(scratch));
}

#[cold]
fn eof_error() -> Error {
    Error::new(ErrorKind::EndOfFile, "unexpected end of file")
}

/// Reads tokens from the input.
pub(crate) struct Cursor<'a> {
    pub(crate) input: &'a [u8],
    pub(crate) pos: usize,
    // `true` if the input is a byte slice which needs to be validated
    validate_utf8: bool,
    // `true` if a token ran into the end of the input
    hit_end: bool,
    // where an incomplete string continues (scan position and copy position)
    partial: (usize, usize),
    // where the number being parsed starts
    number_start: usize,
    // digits of the number were dropped from its significand
    truncated: bool,
    // `true` if no input follows, a comment at the end is complete
    eof: bool,
}

/// A comment in the input (see [`Cursor::skip_comment`]).
enum Comment {
    /// The comment ends at the position.
    End(usize),
    /// The input ends within the comment.
    Incomplete,
    /// The byte at the position is invalid (it's not a comment or the
    /// comment is not valid UTF-8).
    Invalid(usize),
}

impl<'a> Cursor<'a> {
    /// Creates a cursor to skip whitespace in a complete input.
    pub(crate) fn new(input: &'a [u8], pos: usize) -> Cursor<'a> {
        Cursor {
            input,
            pos,
            validate_utf8: true,
            hit_end: false,
            partial: (0, 0),
            number_start: 0,
            truncated: false,
            eof: true,
        }
    }

    /// Creates a cursor to skip whitespace in an input that more input
    /// might follow.
    pub(crate) fn new_partial(input: &'a [u8], pos: usize, eof: bool) -> Cursor<'a> {
        Cursor {
            eof,
            ..Cursor::new(input, pos)
        }
    }

    /// Parses a string, the cursor is after the opening quote at `start`.
    ///
    /// An incomplete string continues where it stopped.  If the string is
    /// incomplete, `partial` holds where it continues.
    ///
    /// Most strings have no escapes, they are slices of the input.  These
    /// are handled here, inlined into the parser, the others by
    /// [`parse_str_slow`](Self::parse_str_slow).
    #[inline(always)]
    fn parse_str<'b>(
        &mut self,
        buffer: &'b mut Vec<u8>,
        start: usize,
        resume: Option<PartialString>,
    ) -> Result<Str<'a, 'b>, Error> {
        let plain = resume.is_none() && self.input[start] != b'\'';
        if plain {
            let end = skip_to_escape(self.input, self.pos);
            if self.input.get(end) == Some(&b'"') {
                let bytes = &self.input[self.pos..end];
                if !self.validate_utf8 || is_ascii(bytes) || validate_utf8_slice(bytes) {
                    self.pos = end + 1;
                    // SAFETY: the input is valid UTF-8 as it comes from a
                    // `&str` or was validated above.  The slice starts and
                    // ends at ASCII characters (quotes).
                    return Ok(Str::Borrowed(unsafe { str::from_utf8_unchecked(bytes) }));
                }
            }
        }
        self.parse_str_slow(buffer, start, resume)
    }

    /// Parses a string that is incomplete or has escapes (see
    /// [`parse_str`](Self::parse_str)).
    #[inline(never)]
    fn parse_str_slow<'b>(
        &mut self,
        buffer: &'b mut Vec<u8>,
        start: usize,
        resume: Option<PartialString>,
    ) -> Result<Str<'a, 'b>, Error> {
        let validate_utf8 = self.validate_utf8;
        fn result(validate_utf8: bool, bytes: &[u8]) -> Result<&str, Error> {
            // Strings in byte slices are validated here.  Bytes outside of
            // strings are only accepted if they are ASCII so this validates
            // the entire input.  The decoded escapes are valid UTF-8 and
            // cannot complete an invalid sequence before them as they never
            // start with a continuation byte, so validating the unescaped
            // string is equivalent to validating the raw one.
            if validate_utf8 && !is_ascii(bytes) && !validate_utf8_slice(bytes) {
                return Err(Error::new(ErrorKind::Unexpected, "invalid utf-8 in string"));
            }
            // SAFETY: the input is valid UTF-8 as it comes from a `&str` or
            // was validated above.  The borrowed slices start and end at
            // ASCII characters (quotes and backslashes) so they are valid
            // UTF-8 too.  The \u-escapes are validated when they are decoded
            // into the buffer.
            Ok(unsafe { str::from_utf8_unchecked(bytes) })
        }

        // Index of the first byte not yet copied into the scratch space.
        let mut copied = match resume {
            Some(resume) => {
                self.pos = start + resume.scanned;
                start + resume.copied
            }
            None => {
                buffer.clear();
                self.pos
            }
        };

        // strings in single quotes end at a single quote
        let single = self.input[start] == b'\'';

        let mut escapes = EscapeScanner::new();
        loop {
            self.pos = if single {
                skip_to_escape_single(self.input, self.pos)
            } else {
                escapes.next(self.input, self.pos)
            };
            if self.pos == self.input.len() {
                self.hit_end = true;
                self.partial = (self.pos, copied);
                return Err(Error::new(
                    ErrorKind::Unexpected,
                    "unexpected end of string",
                ));
            }
            let byte = self.input[self.pos];
            // the closing single quote is handled like a double quote
            let byte = if single && byte == b'\'' { b'"' } else { byte };
            match byte {
                b'"' => {
                    if buffer.is_empty() {
                        // Fast path: return a slice of the raw JSON without any
                        // copying.
                        let input = self.input;
                        let borrowed = &input[copied..self.pos];
                        self.pos += 1;
                        return result(validate_utf8, borrowed).map(Str::Borrowed);
                    } else {
                        extend(buffer, &self.input[copied..self.pos]);
                        self.pos += 1;
                        return result(validate_utf8, buffer).map(Str::Scratch);
                    }
                }
                b'\\' => {
                    extend(buffer, &self.input[copied..self.pos]);
                    // the common escapes stand for a single byte
                    if let Some(&byte) = self.input.get(self.pos + 1)
                        && let unescaped @ 1.. = UNESCAPE[usize::from(byte)]
                    {
                        buffer.push(unescaped);
                        self.pos += 2;
                        copied = self.pos;
                        continue;
                    }
                    let escape = self.pos;
                    self.pos += 1;
                    if let Err(err) = self.parse_escape(buffer) {
                        // an incomplete escape is parsed again
                        self.partial = (escape, escape);
                        return Err(err);
                    }
                    copied = self.pos;
                }
                // control characters other than line breaks are allowed
                byte if byte != b'\n' && byte != b'\r' => self.pos += 1,
                _ => {
                    return Err(Error::new(
                        ErrorKind::Unexpected,
                        "unexpected character in string",
                    ));
                }
            }
        }
    }

    #[inline]
    fn next(&mut self) -> Option<u8> {
        if self.pos < self.input.len() {
            let ch = self.input[self.pos];
            self.pos += 1;
            Some(ch)
        } else {
            self.hit_end = true;
            None
        }
    }

    fn next_or_nul(&mut self) -> u8 {
        self.next().unwrap_or(b'\0')
    }

    #[inline]
    fn peek(&mut self) -> Option<u8> {
        if self.pos < self.input.len() {
            Some(self.input[self.pos])
        } else {
            self.hit_end = true;
            None
        }
    }

    fn peek_or_nul(&mut self) -> u8 {
        self.peek().unwrap_or(b'\0')
    }

    /// Consumes up to eight digits and returns their value and how many
    /// there were.
    ///
    /// The next eight bytes are loaded as a word, the digits at its start
    /// are combined at once.  If there are fewer than eight digits, the byte
    /// after them is not a digit.  Returns `None` if fewer than eight bytes
    /// are left, the digits at the end of the input are parsed one by one.
    #[inline(always)]
    fn digits(&mut self) -> Option<(u64, usize)> {
        let bytes = self.input.get(self.pos..self.pos + 8)?;
        let value = u64::from_le_bytes(bytes.try_into().unwrap());
        let digits = value.wrapping_sub(0x3030_3030_3030_3030);
        let above = value.wrapping_add(0x4646_4646_4646_4646);
        // the high bit of bytes below b'0' or above b'9' is set.  Only the
        // first of them is exact: the bytes before it are digits which do
        // not borrow or carry into it.
        let other = (digits | above) & 0x8080_8080_8080_8080;
        // Eight digits and no digits are separate branches, so that the
        // position after them does not depend on the data (a branch is
        // predicted, the next load can start right away).
        if other == 0 {
            self.pos += 8;
            return Some((combine_digits(digits), 8));
        }
        if other & 0x80 != 0 {
            return Some((0, 0));
        }
        let count = (other.trailing_zeros() / 8) as usize;
        self.pos += count;
        // move the digits to the top of the word, the bytes below them are
        // zeros (leading zeros of the number)
        Some((combine_digits(digits << (64 - 8 * count)), count))
    }

    #[inline]
    fn bump(&mut self) {
        self.pos += 1;
    }

    fn next_or_eof(&mut self) -> Result<u8, Error> {
        self.next()
            .ok_or_else(|| Error::new(ErrorKind::EndOfFile, "unexpected end of file"))
    }

    /// Parses a JSON escape sequence and appends it into the scratch space. Assumes
    /// the previous byte read was a backslash.
    fn parse_escape(&mut self, buffer: &mut Vec<u8>) -> Result<(), Error> {
        let ch = self.next_or_eof()?;

        match ch {
            b'"' => buffer.push(b'"'),
            b'\\' => buffer.push(b'\\'),
            b'/' => buffer.push(b'/'),
            b'b' => buffer.push(b'\x08'),
            b'f' => buffer.push(b'\x0c'),
            b'n' => buffer.push(b'\n'),
            b'r' => buffer.push(b'\r'),
            b't' => buffer.push(b'\t'),
            b'u' => {
                let c = match self.decode_hex_escape()? {
                    0xDC00..=0xDFFF => return Err(lone_surrogate()),

                    // Non-BMP characters are encoded as a sequence of
                    // two hex escapes, representing UTF-16 surrogates.
                    n1 @ 0xD800..=0xDBFF => {
                        if self.next_or_eof()? != b'\\' || self.next_or_eof()? != b'u' {
                            return Err(lone_surrogate());
                        }

                        let n2 = self.decode_hex_escape()?;

                        if !(0xDC00..=0xDFFF).contains(&n2) {
                            return Err(lone_surrogate());
                        }

                        let n = (u32::from(n1 - 0xD800) << 10 | u32::from(n2 - 0xDC00)) + 0x1_0000;

                        match char::from_u32(n) {
                            Some(c) => c,
                            None => return Err(lone_surrogate()),
                        }
                    }

                    n => match char::from_u32(u32::from(n)) {
                        Some(c) => c,
                        None => return Err(lone_surrogate()),
                    },
                };

                buffer.extend_from_slice(c.encode_utf8(&mut [0_u8; 4]).as_bytes());
            }
            b'\'' => buffer.push(b'\''),
            b'v' => buffer.push(b'\x0b'),
            // `\0` must not be followed by a digit
            b'0' => match self.peek() {
                Some(b'0'..=b'9') => return Err(invalid_escape()),
                Some(_) => buffer.push(b'\0'),
                None => return Err(eof_error()),
            },
            b'x' => {
                let mut n = 0;
                for _ in 0..2 {
                    match char::from(self.next_or_eof()?).to_digit(16) {
                        Some(digit) => n = n * 16 + digit,
                        None => {
                            return Err(Error::new(ErrorKind::Unexpected, "invalid hex escape"));
                        }
                    }
                }
                let c = char::from_u32(n).unwrap();
                buffer.extend_from_slice(c.encode_utf8(&mut [0_u8; 4]).as_bytes());
            }
            // escaped line breaks are removed
            b'\n' => {}
            b'\r' => match self.peek() {
                Some(b'\n') => self.bump(),
                Some(_) => {}
                None => return Err(eof_error()),
            },
            0xe2 => match self.input.get(self.pos..self.pos + 2) {
                // the line and paragraph separators
                Some([0x80, 0xa8 | 0xa9]) => self.pos += 2,
                Some(_) => buffer.push(0xe2),
                None => {
                    self.hit_end = true;
                    return Err(eof_error());
                }
            },
            b'1'..=b'9' => return Err(invalid_escape()),
            // other characters stand for themselves.  The rest of a
            // character that is not ASCII is copied with the string.
            byte => buffer.push(byte),
        }

        Ok(())
    }

    /// Parses an identifier (a map key without quotes).
    ///
    /// Identifiers are borrowed from the input unless they contain
    /// escapes, then they are copied into the buffer.
    fn parse_identifier<'b>(&mut self, buffer: &'b mut Vec<u8>) -> Result<Str<'a, 'b>, Error> {
        let start = self.pos;
        // the first byte not yet copied into the buffer after an escape
        let mut copied = None;
        loop {
            let first = self.pos == start;
            match self.peek() {
                Some(b'a'..=b'z' | b'A'..=b'Z' | b'_' | b'$') => self.bump(),
                Some(b'0'..=b'9') if !first => self.bump(),
                Some(b'\\') => {
                    let from = match copied {
                        Some(from) => from,
                        None => {
                            buffer.clear();
                            start
                        }
                    };
                    buffer.extend_from_slice(&self.input[from..self.pos]);
                    let escape = self.pos;
                    self.bump();
                    let c = match self.next_or_eof()? {
                        b'u' => char::from_u32(u32::from(self.decode_hex_escape()?)),
                        _ => None,
                    };
                    // the error is reported at the escape
                    let Some(c) = c.filter(|&c| is_identifier_char(c, first)) else {
                        self.pos = escape;
                        return Err(invalid_identifier());
                    };
                    buffer.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes());
                    copied = Some(self.pos);
                }
                Some(byte @ 0x80..=0xff) => {
                    let len = match byte {
                        0xc0..=0xdf => 2,
                        0xe0..=0xef => 3,
                        _ => 4,
                    };
                    let Some(bytes) = self.input.get(self.pos..self.pos + len) else {
                        self.hit_end = true;
                        return Err(eof_error());
                    };
                    match str::from_utf8(bytes).ok().and_then(|s| s.chars().next()) {
                        Some(c) if is_identifier_char(c, first) => self.pos += len,
                        Some(_) => break,
                        None => return Err(Error::new(ErrorKind::Unexpected, "invalid utf-8")),
                    }
                }
                _ => break,
            }
        }
        if self.pos == start {
            return Err(Error::new(ErrorKind::Unexpected, "expected map key"));
        }
        match copied {
            Some(from) => {
                buffer.extend_from_slice(&self.input[from..self.pos]);
                // SAFETY: the buffer holds validated characters and the
                // decoded escapes
                Ok(Str::Scratch(unsafe { str::from_utf8_unchecked(buffer) }))
            }
            // SAFETY: the identifier is ASCII or was validated above
            None => Ok(Str::Borrowed(unsafe {
                str::from_utf8_unchecked(&self.input[start..self.pos])
            })),
        }
    }

    fn decode_hex_escape(&mut self) -> Result<u16, Error> {
        let mut n = 0;
        for _ in 0..4 {
            n = match self.next_or_eof()? {
                c @ b'0'..=b'9' => n * 16_u16 + u16::from(c - b'0'),
                b'a' | b'A' => n * 16_u16 + 10_u16,
                b'b' | b'B' => n * 16_u16 + 11_u16,
                b'c' | b'C' => n * 16_u16 + 12_u16,
                b'd' | b'D' => n * 16_u16 + 13_u16,
                b'e' | b'E' => n * 16_u16 + 14_u16,
                b'f' | b'F' => n * 16_u16 + 15_u16,
                _ => {
                    return Err(Error::new(ErrorKind::Unexpected, "invalid hex escape"));
                }
            };
        }
        Ok(n)
    }

    #[inline(always)]
    pub(crate) fn parse_whitespace(&mut self) -> Option<u8> {
        const SPACES: u64 = u64::from_ne_bytes([b' '; 8]);
        let input = self.input;
        let mut pos = self.pos;
        loop {
            // indented JSON contains long runs of spaces, skip them a word
            // at a time.
            if pos + 8 <= input.len() {
                let mut bytes = [0u8; 8];
                bytes.copy_from_slice(&input[pos..pos + 8]);
                if u64::from_ne_bytes(bytes) == SPACES {
                    pos += 8;
                    continue;
                }
            }
            match input.get(pos) {
                Some(b' ' | b'\n' | b'\t' | b'\r') => pos += 1,
                // vertical tab and form feed
                Some(0x0b | 0x0c) => pos += 1,
                Some(b'/') => match self.skip_comment(pos) {
                    Comment::End(end) => pos = end,
                    // the comment is scanned again with more input
                    Comment::Incomplete => {
                        self.pos = pos;
                        self.hit_end = true;
                        return None;
                    }
                    Comment::Invalid(pos) => {
                        self.pos = pos;
                        return Some(input[pos]);
                    }
                },
                Some(&byte) if byte >= 0x80 => match unicode_whitespace(&input[pos..]) {
                    Some(len) => pos += len,
                    // the character is completed with more input
                    None if input.len() - pos < 3 && !self.eof => {
                        self.pos = pos;
                        self.hit_end = true;
                        return None;
                    }
                    None => {
                        self.pos = pos;
                        return Some(byte);
                    }
                },
                Some(&byte) => {
                    self.pos = pos;
                    return Some(byte);
                }
                None => {
                    self.pos = pos;
                    self.hit_end = true;
                    return None;
                }
            }
        }
    }

    /// Skips the comment at `pos` (which is at a slash).
    #[cold]
    fn skip_comment(&self, pos: usize) -> Comment {
        let input = self.input;
        let end = match input.get(pos + 1) {
            Some(b'/') => match line_comment_len(&input[pos + 2..]) {
                Some(len) => pos + 2 + len,
                None if self.eof => input.len(),
                None => return Comment::Incomplete,
            },
            // an unterminated comment at the end is reported as the end
            // of the input
            Some(b'*') => match input[pos + 2..].windows(2).position(|w| w == b"*/") {
                Some(index) => pos + 2 + index + 2,
                None => return Comment::Incomplete,
            },
            Some(_) => return Comment::Invalid(pos),
            None if self.eof => return Comment::Invalid(pos),
            None => return Comment::Incomplete,
        };
        // bytes outside of strings are validated here
        let comment = &input[pos..end];
        if self.validate_utf8
            && !is_ascii(comment)
            && let Err(err) = str::from_utf8(comment)
        {
            return Comment::Invalid(pos + err.valid_up_to());
        }
        Comment::End(end)
    }

    fn parse_ident(&mut self, ident: &[u8]) -> Result<(), Error> {
        for expected in ident {
            match self.next() {
                None => {
                    return Err(Error::new(ErrorKind::EndOfFile, "unexpected end of file"));
                }
                Some(next) => {
                    if next != *expected {
                        return Err(Error::new(ErrorKind::Unexpected, "unexpected character"));
                    }
                }
            }
        }
        Ok(())
    }

    fn parse_integer(&mut self, nonnegative: bool, first_digit: u8) -> Result<Number<'a>, Error> {
        match first_digit {
            b'0' => match self.peek_or_nul() {
                b'0'..=b'9' => Err(Error::new(
                    ErrorKind::Unexpected,
                    "only a single leading 0 is allowed",
                )),
                b'x' | b'X' => self.parse_hex(nonnegative),
                _ => self.parse_number(nonnegative, 0),
            },
            // a leading decimal point
            b'.' => match self.peek_or_nul() {
                b'0'..=b'9' => {
                    self.pos -= 1;
                    self.parse_decimal(nonnegative, 0, 0)
                }
                _ => Err(Error::new(ErrorKind::Unexpected, "expected a digit")),
            },
            b'I' => {
                self.parse_ident(b"nfinity")?;
                Ok(Number::F64(if nonnegative {
                    f64::INFINITY
                } else {
                    f64::NEG_INFINITY
                }))
            }
            b'N' => {
                self.parse_ident(b"aN")?;
                Ok(Number::F64(f64::NAN))
            }
            c @ b'1'..=b'9' => {
                let mut res = u64::from(c - b'0');
                // up to eight digits at a time while they cannot overflow
                while res < EIGHT_DIGITS_LIMIT
                    && let Some((digits, count)) = self.digits()
                {
                    res = res * POW10_U64[count] + digits;
                    if count < 8 {
                        return self.parse_number(nonnegative, res);
                    }
                }

                loop {
                    match self.peek_or_nul() {
                        c @ b'0'..=b'9' => {
                            self.bump();
                            let digit = u64::from(c - b'0');

                            // We need to be careful with overflow. If we can, try to keep the
                            // number as a `u64` until we grow too large. At that point, switch to
                            // parsing the value as a `f64`.
                            if overflow!(res * 10 + digit, u64::MAX) {
                                return self.parse_overflowing_integer(nonnegative, res);
                            }

                            res = res * 10 + digit;
                        }
                        _ => {
                            return self.parse_number(nonnegative, res);
                        }
                    }
                }
            }
            _ => Err(Error::new(ErrorKind::Unexpected, "invalid integer")),
        }
    }

    /// Returns the text of the number that was just parsed.
    ///
    /// This only works for integers as it scans backwards for digits.
    fn number_text(&self, nonnegative: bool) -> &'a str {
        let input = self.input;
        let mut start = self.pos;
        while start > 0 && input[start - 1].is_ascii_digit() {
            start -= 1;
        }
        if !nonnegative {
            start -= 1;
        }
        // the input is valid utf-8 as it was created from a string
        str::from_utf8(&input[start..self.pos]).unwrap()
    }

    /// Continues parsing an integer which no longer fits into 64 bits.
    ///
    /// If the number turns out to be an integer that fits into 128 bits it's
    /// passed on as big integer.  Otherwise it's parsed as float.
    #[cold]
    fn parse_overflowing_integer(
        &mut self,
        nonnegative: bool,
        significand: u64,
    ) -> Result<Number<'a>, Error> {
        let digits_start = self.pos - 1;
        // the digits after the first 19 are dropped from the significand
        self.truncated = true;
        let float = self.parse_long_integer(
            nonnegative,
            significand,
            1, // significand * 10^1
        )?;
        let is_integer = self.input[digits_start..self.pos]
            .iter()
            .all(|c| c.is_ascii_digit());
        if is_integer {
            let text = self.number_text(nonnegative);
            let fits = if nonnegative {
                text.parse::<u128>().is_ok()
            } else {
                text.parse::<i128>().is_ok()
            };
            if fits {
                return Ok(Number::BigInt(text));
            }
        }
        Ok(Number::Literal(float))
    }

    fn parse_long_integer(
        &mut self,
        nonnegative: bool,
        significand: u64,
        mut exponent: i32,
    ) -> Result<f64, Error> {
        loop {
            match self.peek_or_nul() {
                b'0'..=b'9' => {
                    self.bump();
                    // This could overflow... if your integer is gigabytes long.
                    // Ignore that possibility.
                    exponent += 1;
                }
                b'.' => {
                    return self
                        .parse_decimal(nonnegative, significand, exponent)
                        .map(Number::into_f64);
                }
                b'e' | b'E' => {
                    return self.parse_exponent(nonnegative, significand, exponent);
                }
                _ => {
                    return self.float(nonnegative, significand, exponent);
                }
            }
        }
    }

    fn parse_number(&mut self, nonnegative: bool, significand: u64) -> Result<Number<'a>, Error> {
        match self.peek_or_nul() {
            b'.' => self.parse_decimal(nonnegative, significand, 0),
            b'e' | b'E' => self
                .parse_exponent(nonnegative, significand, 0)
                .map(Number::Literal),
            _ => {
                Ok(if nonnegative {
                    Number::U64(significand)
                } else {
                    let neg = (significand as i64).wrapping_neg();

                    // Values below i64::MIN are passed on as 128 bit integers.
                    if neg > 0 {
                        Number::BigInt(self.number_text(false))
                    } else {
                        Number::I64(neg)
                    }
                })
            }
        }
    }

    /// Parses the fraction of a number.
    ///
    /// This returns a [`Number::Literal`] unless the text of the number is
    /// the shortest representation of its value.
    fn parse_decimal(
        &mut self,
        nonnegative: bool,
        mut significand: u64,
        starting_exp: i32,
    ) -> Result<Number<'a>, Error> {
        self.bump();

        let mut exponent = starting_exp;
        let mut overflowed = false;
        // up to eight digits at a time while they cannot overflow
        while significand < EIGHT_DIGITS_LIMIT
            && let Some((digits, count)) = self.digits()
        {
            significand = significand * POW10_U64[count] + digits;
            exponent -= count as i32;
            if count < 8 {
                break;
            }
        }
        while let c @ b'0'..=b'9' = self.peek_or_nul() {
            self.bump();
            let digit = u64::from(c - b'0');

            if overflow!(significand * 10 + digit, u64::MAX) {
                // The next multiply/add would overflow, so just ignore all
                // further digits.
                while let b'0'..=b'9' = self.peek_or_nul() {
                    self.bump();
                }
                overflowed = true;
                self.truncated = true;
                break;
            }

            significand = significand * 10 + digit;
            exponent -= 1;
        }

        match self.peek_or_nul() {
            b'e' | b'E' => self
                .parse_exponent(nonnegative, significand, exponent)
                .map(Number::Literal),
            _ => {
                let value = self.float(nonnegative, significand, exponent)?;
                Ok(
                    if !overflowed
                        && starting_exp == 0
                        && is_shortest_repr(significand, exponent.unsigned_abs())
                    {
                        Number::F64(value)
                    } else {
                        Number::Literal(value)
                    },
                )
            }
        }
    }

    /// Parses a hexadecimal integer, the cursor is at the `x`.
    ///
    /// Integers that do not fit into 128 bits are approximated as floats
    /// (like ECMAScript does for all integers beyond 53 bits).
    fn parse_hex(&mut self, nonnegative: bool) -> Result<Number<'a>, Error> {
        self.bump();
        let mut value = 0u128;
        // the digits that do not fit into 128 bits, and if one is not zero
        let mut dropped = 0u64;
        let mut sticky = false;
        let mut digits = 0;
        while let Some(digit) = char::from(self.peek_or_nul()).to_digit(16) {
            self.bump();
            digits += 1;
            match value.checked_mul(16) {
                Some(shifted) if dropped == 0 => value = shifted | u128::from(digit),
                _ => {
                    dropped += 1;
                    sticky |= digit != 0;
                }
            }
        }
        if digits == 0 {
            return Err(Error::new(ErrorKind::Unexpected, "expected a hex digit"));
        }
        if dropped > 0 {
            // the value has more than 64 significant bits, the lowest bit
            // stands for the dropped digits so that the value is rounded
            // correctly.  The scaling by a power of two is exact.
            // 2^(4 * dropped), infinite beyond the range of floats
            let scale = f64::from_bits((1023 + 4 * dropped.min(256)) << 52);
            let float = (value | u128::from(sticky)) as f64 * scale;
            if float.is_infinite() {
                return Err(number_out_of_range());
            }
            return Ok(Number::F64(if nonnegative { float } else { -float }));
        }
        Ok(match value {
            value if nonnegative => match u64::try_from(value) {
                Ok(value) => Number::U64(value),
                Err(_) => Number::U128(value),
            },
            value if value <= 1 << 63 => Number::I64((value as i64).wrapping_neg()),
            value if value <= 1 << 127 => Number::I128((value as i128).wrapping_neg()),
            value => Number::F64(-(value as f64)),
        })
    }

    fn parse_exponent(
        &mut self,
        nonnegative: bool,
        significand: u64,
        starting_exp: i32,
    ) -> Result<f64, Error> {
        self.bump();

        let positive_exp = match self.peek_or_nul() {
            b'+' => {
                self.bump();
                true
            }
            b'-' => {
                self.bump();
                false
            }
            _ => true,
        };

        let mut exp = match self.next_or_nul() {
            c @ b'0'..=b'9' => i32::from(c - b'0'),
            _ => {
                return Err(Error::new(
                    ErrorKind::Unexpected,
                    "expected digit after exponent",
                ));
            }
        };

        while let c @ b'0'..=b'9' = self.peek_or_nul() {
            self.bump();
            let digit = i32::from(c - b'0');

            if overflow!(exp * 10 + digit, i32::MAX) {
                return self.parse_exponent_overflow(nonnegative, significand, positive_exp);
            }

            exp = exp * 10 + digit;
        }

        let final_exp = if positive_exp {
            starting_exp.saturating_add(exp)
        } else {
            starting_exp.saturating_sub(exp)
        };

        self.float(nonnegative, significand, final_exp)
    }

    /// Returns the value of the float that was just parsed.
    ///
    /// The number is given as its significand (the digits) and decimal
    /// exponent.  For exponents up to 22 (which covers numbers with up to
    /// 22 fraction digits) the value is computed from them: if the
    /// significand has at most 53 bits, both it and the power of ten are
    /// exact as `f64` and their product (or quotient) is rounded correctly
    /// as only the result is rounded.  Otherwise the algorithm of Eisel and
    /// Lemire is used (see [`eisel_lemire`]).  For other exponents (and if
    /// digits were dropped from the significand) the text of the number is
    /// parsed, which rounds correctly too.
    #[inline]
    fn float(&self, nonnegative: bool, significand: u64, exponent: i32) -> Result<f64, Error> {
        if !self.truncated {
            let value = match POW10.get(exponent.unsigned_abs() as usize) {
                Some(&pow) if significand <= 1 << 53 => Some(if exponent >= 0 {
                    significand as f64 * pow
                } else {
                    significand as f64 / pow
                }),
                Some(_) => eisel_lemire(significand, exponent),
                None if significand == 0 => Some(0.0),
                None => None,
            };
            if let Some(value) = value {
                return Ok(if nonnegative { value } else { -value });
            }
        }
        self.parse_float_text()
    }

    /// Parses the text of the number that was just parsed as float.
    #[cold]
    #[inline(never)]
    fn parse_float_text(&self) -> Result<f64, Error> {
        // SAFETY: the number was validated and only consists of ASCII
        // characters
        let text = unsafe { str::from_utf8_unchecked(&self.input[self.number_start..self.pos]) };
        match text.parse::<f64>() {
            Ok(value) if value.is_finite() => Ok(value),
            _ => Err(number_out_of_range()),
        }
    }

    // This cold code should not be inlined into the middle of the hot
    // exponent-parsing loop above.
    #[cold]
    #[inline(never)]
    fn parse_exponent_overflow(
        &mut self,
        nonnegative: bool,
        significand: u64,
        positive_exp: bool,
    ) -> Result<f64, Error> {
        // Error instead of +/- infinity.
        if significand != 0 && positive_exp {
            return Err(Error::new(ErrorKind::Unexpected, "infinity takes no sign"));
        }

        while let b'0'..=b'9' = self.peek_or_nul() {
            self.bump();
        }
        Ok(if nonnegative { 0.0 } else { -0.0 })
    }
}

/// Eight more digits can be added to significands below this.
const EIGHT_DIGITS_LIMIT: u64 = (u64::MAX - 99_999_999) / 100_000_000;

/// Returns the value of eight digits (the values of the characters, the
/// first one in the lowest byte).
#[inline(always)]
fn combine_digits(digits: u64) -> u64 {
    // combine pairs of digits, then pairs of those and so on
    let pairs = digits.wrapping_mul(10).wrapping_add(digits >> 8);
    let low = (pairs & 0x0000_00ff_0000_00ff).wrapping_mul(0x000f_4240_0000_0064);
    let high = ((pairs >> 16) & 0x0000_00ff_0000_00ff).wrapping_mul(0x0000_2710_0000_0001);
    u64::from((low.wrapping_add(high) >> 32) as u32)
}

/// The bytes of the escapes that stand for a single byte (`\\n` and so
/// on), zero for the others.
static UNESCAPE: [u8; 256] = {
    let mut table = [0; 256];
    table[b'"' as usize] = b'"';
    table[b'\\' as usize] = b'\\';
    table[b'/' as usize] = b'/';
    table[b'b' as usize] = b'\x08';
    table[b'f' as usize] = b'\x0c';
    table[b'n' as usize] = b'\n';
    table[b'r' as usize] = b'\r';
    table[b't' as usize] = b'\t';
    table
};

/// The powers of ten that fit into 64 bits.
static POW10_U64: [u64; 20] = {
    let mut table = [1; 20];
    let mut idx = 1;
    while idx < table.len() {
        table[idx] = table[idx - 1] * 10;
        idx += 1;
    }
    table
};

/// Powers of ten which are exact as `f64`.
static POW10: [f64; 23] = [
    1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16,
    1e17, 1e18, 1e19, 1e20, 1e21, 1e22,
];

/// The powers of five from 5^-22 to 5^22 with 128 bits (as low and high
/// half) for [`eisel_lemire`].
///
/// The positive powers are exact (they have at most 52 bits) and shifted
/// so that the highest bit is set.  The negative ones are `2^(z + 127) /
/// 5^-q + 1` (rounded down) where `2^z` is the smallest power of two above
/// `5^-q`, which also has the highest bit set.
static POW5: [(u64, u64); 45] = {
    let mut table = [(0, 0); 45];
    let mut q = -22i32;
    while q <= 22 {
        let pow = 5u128.pow(q.unsigned_abs());
        let value = if q >= 0 {
            pow << pow.leading_zeros()
        } else {
            // 2^(z + 127) / pow by long division, the quotient has 128 bits
            let z = 128 - pow.leading_zeros();
            let mut quotient = 0u128;
            let mut rem = 1u128;
            let mut bit = 0;
            while bit < z + 127 {
                rem <<= 1;
                quotient <<= 1;
                if rem >= pow {
                    rem -= pow;
                    quotient |= 1;
                }
                bit += 1;
            }
            quotient + 1
        };
        table[(q + 22) as usize] = (value as u64, (value >> 64) as u64);
        q += 1;
    }
    table
};

/// Returns the correctly rounded value of `significand * 10^exponent`.
///
/// This is the algorithm of Eisel and Lemire ("Number Parsing at a
/// Gigabyte per Second", <https://arxiv.org/abs/2101.11408>) as used by the
/// standard library, for exponents from -22 to 22: the significand is
/// multiplied with a 128 bit approximation of the power of five, the
/// power of two is added to the exponent.  In this range the product is
/// precise enough to round correctly (ties to even only happen for
/// exponents from -4 to 23 where the powers of five are exact).  Returns
/// `None` for values out of the range of normal floats (which do not occur
/// in this range).
fn eisel_lemire(significand: u64, exponent: i32) -> Option<f64> {
    // the bits of the mantissa (without the implicit one) and the extra
    // bits of the product needed to round
    const MANTISSA_BITS: i32 = 52;
    const PRECISION_MASK: u64 = u64::MAX >> (MANTISSA_BITS + 3);

    let leading_zeros = significand.leading_zeros();
    let significand = significand << leading_zeros;
    let (pow_lo, pow_hi) = POW5[(exponent + 22) as usize];
    let product = u128::from(significand) * u128::from(pow_hi);
    let (mut lo, mut hi) = (product as u64, (product >> 64) as u64);
    if hi & PRECISION_MASK == PRECISION_MASK {
        // the bits below the mantissa might carry, the lower half of the
        // power is needed
        let carry = ((u128::from(significand) * u128::from(pow_lo)) >> 64) as u64;
        lo = lo.wrapping_add(carry);
        if carry > lo {
            hi += 1;
        }
    }

    let upper_bit = (hi >> 63) as i32;
    let shift = upper_bit + 64 - MANTISSA_BITS - 3;
    let mut mantissa = hi >> shift;
    // the biased exponent: floor(log2(10^exponent)) + 63 for the product,
    // the normalization and the bias of 1023
    let mut power2 = ((exponent.wrapping_mul(152_170 + 65536) >> 16) + 63) + upper_bit
        - leading_zeros as i32
        + 1023;
    if power2 <= 0 {
        return None;
    }
    // exactly half way between two floats rounds to the even one
    if lo <= 1 && (-4..=23).contains(&exponent) && mantissa & 3 == 1 && mantissa << shift == hi {
        mantissa &= !1;
    }
    mantissa += mantissa & 1;
    mantissa >>= 1;
    if mantissa >= 2 << MANTISSA_BITS {
        mantissa = 1 << MANTISSA_BITS;
        power2 += 1;
    }
    mantissa &= !(1 << MANTISSA_BITS);
    if power2 >= 0x7ff {
        return None;
    }
    Some(f64::from_bits(mantissa | (power2 as u64) << MANTISSA_BITS))
}

/// Creates an error for the token at the offset.
#[cold]
fn token_error(offset: usize, msg: &'static str) -> Error {
    Error::new(ErrorKind::Unexpected, msg).with_offset(offset)
}

/// Returns `true` if a decimal number without exponent is the shortest
/// representation of its value as `f64` (as formatted by `Debug`).
///
/// The number is given as its digits (without the dot) and the number of
/// fraction digits.  In that case the text can be recovered from the value,
/// so the value is emitted as float.  This is the case if the fraction has
/// no trailing zeros (other than `.0`), there are at most 15 significant
/// digits and the value is zero or at least 1e-4 (below that the shortest
/// representation uses an exponent).  15 digits are guaranteed to roundtrip
/// through `f64`.
#[inline]
fn is_shortest_repr(digits: u64, frac_len: u32) -> bool {
    const MAX: u64 = 1_000_000_000_000_000;
    digits < MAX
        && (frac_len == 1 || !digits.is_multiple_of(10))
        && (frac_len <= 4
            || digits == 0
            || (frac_len <= 19 && digits >= POW10_U64[frac_len as usize - 4]))
}

/// Emits a number.
#[inline]
fn emit_number<'i, O: Out<'i>>(
    out: &mut O,
    number: Number,
    input: &[u8],
    exact_numbers: bool,
    start: usize,
    end: usize,
) -> Result<(), Error> {
    match number {
        Number::U64(val) => out.emit(Event::from(val)),
        Number::I64(val) => out.emit(Event::from(val)),
        Number::F64(val) => out.emit(Event::from(val)),
        Number::Literal(val) if exact_numbers => emit_literal(out, input, val, start, end),
        Number::Literal(val) => out.emit(Event::from(val)),
        Number::BigInt(val) => emit_big_int(out, val),
        Number::U128(val) => out.emit(Atom::Ext(ExtValue::borrowed(&val))),
        Number::I128(val) => out.emit(Atom::Ext(ExtValue::borrowed(&val))),
    }
}

/// Emits a number as number extension value with its text.
///
/// This is not inlined to keep the code of the parser loop small.
#[inline(never)]
fn emit_literal<'i, O: Out<'i>>(
    out: &mut O,
    input: &[u8],
    value: f64,
    start: usize,
    end: usize,
) -> Result<(), Error> {
    // SAFETY: numbers only consist of ASCII characters
    let text = unsafe { str::from_utf8_unchecked(&input[start..end]) };
    let normalized = json_number(text);
    let text = normalized.as_deref().unwrap_or(text);
    let number = ExactNumber::new(text, value);
    out.emit(Atom::Ext(ExtValue::borrowed_value::<ExactNumber>(&number)))
}

/// Returns the text of a number in the syntax of JSON if it differs.
///
/// Numbers can have a leading `+` and leading or trailing decimal points
/// (hexadecimal numbers are integers and never passed on as text).
fn json_number(text: &str) -> Option<String> {
    let (sign, rest) = match text.as_bytes()[0] {
        b'+' => ("", &text[1..]),
        b'-' => ("-", &text[1..]),
        _ => ("", text),
    };
    let (int, frac) = rest.split_once('.').unwrap_or((rest, ""));
    let exp_start = frac.find(['e', 'E']).unwrap_or(frac.len());
    let (frac, exp) = frac.split_at(exp_start);
    if !text.starts_with('+') && !int.is_empty() && (!frac.is_empty() || !rest.contains('.')) {
        return None;
    }
    let int = if int.is_empty() { "0" } else { int };
    let dot = if frac.is_empty() { "" } else { "." };
    Some(format!("{sign}{int}{dot}{frac}{exp}"))
}

/// Emits an integer that does not fit into 64 bits as extension value.
#[cold]
fn emit_big_int<'i, O: Out<'i>>(out: &mut O, text: &str) -> Result<(), Error> {
    // the tokenizer already validated that the value fits
    if text.starts_with('-') {
        let value: i128 = text.parse().unwrap();
        out.emit(Atom::Ext(ExtValue::borrowed(&value)))
    } else {
        let value: u128 = text.parse().unwrap();
        out.emit(Atom::Ext(ExtValue::borrowed(&value)))
    }
}

/// Returns the length of the rest of a line comment (after the slashes)
/// including the line break that ends it.
fn line_comment_len(bytes: &[u8]) -> Option<usize> {
    let mut index = 0;
    while index < bytes.len() {
        match bytes[index] {
            b'\n' | b'\r' => return Some(index + 1),
            // the line and paragraph separators
            0xe2 if matches!(bytes.get(index + 1..index + 3), Some([0x80, 0xa8 | 0xa9])) => {
                return Some(index + 3);
            }
            _ => index += 1,
        }
    }
    None
}

/// Returns the length of the whitespace character at the start of the
/// bytes if it's not ASCII.
///
/// These are the characters of the Unicode category Zs, the line and
/// paragraph separators and the byte order mark.
fn unicode_whitespace(bytes: &[u8]) -> Option<usize> {
    match bytes {
        [0xc2, 0xa0, ..] => Some(2),
        [0xe1, 0x9a, 0x80, ..]
        | [0xe2, 0x80, 0x80..=0x8a | 0xa8 | 0xa9 | 0xaf, ..]
        | [0xe2, 0x81, 0x9f, ..]
        | [0xe3, 0x80, 0x80, ..]
        | [0xef, 0xbb, 0xbf, ..] => Some(3),
        _ => None,
    }
}

/// Returns `true` if the character can be part of an identifier.
///
/// These are the characters of ECMAScript identifiers: `$`, `_` and the
/// characters with the Unicode property `ID_Start` and (except for the
/// first character) `ID_Continue` and the zero width (non-)joiner.
fn is_identifier_char(c: char, first: bool) -> bool {
    matches!(c, '$' | '_')
        || unicode_ident::is_xid_start(c)
        || (!first && (unicode_ident::is_xid_continue(c) || matches!(c, '\u{200c}' | '\u{200d}')))
}

#[cold]
fn invalid_identifier() -> Error {
    Error::new(ErrorKind::Unexpected, "invalid escape in identifier")
}

#[cold]
fn invalid_escape() -> Error {
    Error::new(ErrorKind::Unexpected, "invalid escape in string")
}

#[cold]
fn lone_surrogate() -> Error {
    Error::new(
        ErrorKind::Unexpected,
        "lone surrogate in unicode escape in string",
    )
}

#[cold]
fn number_out_of_range() -> Error {
    Error::new(ErrorKind::OutOfRange, "number out of range")
}

#[cfg(test)]
mod tests {
    use deser_core::de::Recording;

    use super::*;

    const OPTIONS: Options = Options {
        validate_utf8: true,
        exact_numbers: true,
    };

    fn events(value: Recording) -> Vec<Event<'static>> {
        value.events().cloned().collect()
    }

    /// Returns the chunk sizes to feed an input of `len` bytes in.
    ///
    /// Miri is too slow for all sizes, it checks chunks of a byte (which
    /// split the input at every position), odd and aligned sizes and the
    /// whole input.
    fn chunk_sizes(len: usize) -> impl Iterator<Item = usize> {
        (1..=len).filter(move |&size| !cfg!(miri) || matches!(size, 1 | 3 | 8) || size == len)
    }

    /// Parses the input in one go.
    fn parse_complete(input: &str) -> Result<Vec<Event<'static>>, String> {
        let mut out = None::<Recording>;
        let mut parser = Parser::default();
        {
            let mut driver = DeserializeDriver::new(&mut out);
            parser
                .parse(
                    input.as_bytes(),
                    0,
                    true,
                    0,
                    OPTIONS,
                    &mut Borrowing(&mut driver),
                )
                .map_err(|err| err.message().to_string())?;
        }
        Ok(events(out.unwrap()))
    }

    /// Feeds the input to the parser in chunks like a stream would.
    fn parse_chunked(input: &str, size: usize) -> Result<Vec<Event<'static>>, String> {
        let mut out = None::<Recording>;
        let mut parser = Parser::default();
        {
            let mut driver = DeserializeDriver::new(&mut out);
            let mut buffer = Vec::new();
            let mut base = 0;
            let mut rest = input.as_bytes();
            loop {
                let len = size.min(rest.len());
                buffer.extend_from_slice(&rest[..len]);
                rest = &rest[len..];
                let eof = rest.is_empty();
                match parser
                    .parse(&buffer, 0, eof, base, OPTIONS, &mut Copying(&mut driver))
                    .map_err(|err| err.message().to_string())?
                {
                    Progress::Done(_) => break,
                    Progress::NeedMore(consumed) => {
                        assert!(!eof, "more input needed at the end");
                        buffer.drain(..consumed);
                        base += consumed;
                    }
                }
            }
        }
        Ok(events(out.unwrap()))
    }

    #[test]
    fn test_chunks() {
        let long = "x".repeat(300);
        let inputs = [
            r#"{"a": [1, -2, 3.5, 1e10, -0.25e-3, 12345678901234567890123], "b": {"c": null}}"#.to_string(),
            r#"["plain", "esc\"aped\\", "\u00e4\ud83d\ude00", "ä", true, false, null, [], {}, [[]]]"#.to_string(),
            format!(r#"{{"{long}": "{long}\n{long}", "k\u0041": [{{}}, {{"x": [1]}}]}}"#),
            "  42  ".to_string(),
            "\"top\"".to_string(),
            "123".to_string(),
            " [ 1 , 2 ] ".to_string(),
        ];
        for input in inputs {
            let expected = parse_complete(&input).unwrap();
            for size in chunk_sizes(input.len()) {
                assert_eq!(
                    parse_chunked(&input, size).unwrap(),
                    expected,
                    "{input} size {size}"
                );
            }
        }
    }

    #[test]
    fn test_errors_in_chunks() {
        for input in [
            "[1, 2",
            "[1 2]",
            "{\"a\" 1}",
            "[tru]",
            "\"abc",
            "{\"a\": \"\\x\"}",
        ] {
            let expected = parse_complete(input).unwrap_err();
            for size in chunk_sizes(input.len()) {
                assert_eq!(
                    parse_chunked(input, size).unwrap_err(),
                    expected,
                    "{input} size {size}"
                );
            }
        }
    }

    #[test]
    fn test_digit_runs() {
        /// Parses the numbers of a sequence.
        fn parse(text: &str) -> Vec<f64> {
            let mut out = None::<Vec<f64>>;
            let mut driver = DeserializeDriver::new(&mut out);
            Parser::default()
                .parse(
                    text.as_bytes(),
                    0,
                    true,
                    0,
                    OPTIONS,
                    &mut Borrowing(&mut driver),
                )
                .unwrap();
            drop(driver);
            out.unwrap()
        }

        // runs of digits of every length in the integer and the fraction,
        // with and without eight bytes after them
        let digits = "12345678901234567890123";
        // miri is too slow for all combinations
        let step = if cfg!(miri) { 4 } else { 1 };
        for int_len in (1..=digits.len()).step_by(step) {
            for frac_len in (0..=digits.len()).step_by(step) {
                let mut number = digits[..int_len].to_string();
                if frac_len > 0 {
                    number.push('.');
                    number.push_str(&digits[digits.len() - frac_len..]);
                }
                let value: f64 = number.parse().unwrap();
                for text in [
                    format!("[{number}]"),
                    format!("[{number},-{number}e1 , {number}]"),
                    format!("[{number}                ]"),
                ] {
                    let values = parse(&text);
                    assert_eq!(values[0].to_bits(), value.to_bits(), "{text}");
                    assert_eq!(values.last().unwrap().to_bits(), value.to_bits(), "{text}");
                }
            }
        }
    }

    #[test]
    fn test_integers() {
        fn parse(text: &str) -> Result<u64, String> {
            let mut out = None::<u64>;
            let mut driver = DeserializeDriver::new(&mut out);
            Parser::default()
                .parse(
                    text.as_bytes(),
                    0,
                    true,
                    0,
                    OPTIONS,
                    &mut Borrowing(&mut driver),
                )
                .map_err(|err| err.message().to_string())?;
            drop(driver);
            Ok(out.unwrap())
        }

        // every length, around the groups of eight digits and the limit
        let mut value = 0u64;
        for digit in (1..=20).map(|x| x % 10) {
            value = value.wrapping_mul(10).wrapping_add(digit);
            let text = value.to_string();
            assert_eq!(parse(&text), Ok(value), "{text}");
        }
        for value in [
            u64::MAX,
            u64::MAX - 1,
            u64::MAX / 10,
            99_999_999,
            100_000_000,
            EIGHT_DIGITS_LIMIT,
            EIGHT_DIGITS_LIMIT * 100_000_000 + 99_999_999,
            (EIGHT_DIGITS_LIMIT + 1) * 100_000_000,
        ] {
            assert_eq!(parse(&value.to_string()), Ok(value), "{value}");
        }
    }

    #[test]
    fn test_floats_are_rounded_correctly() {
        /// Parses a number as `f64`.
        fn parse(text: &str) -> Result<f64, String> {
            let mut out = None::<f64>;
            let mut driver = DeserializeDriver::new(&mut out);
            let options = Options {
                validate_utf8: false,
                exact_numbers: false,
            };
            Parser::default()
                .parse(
                    text.as_bytes(),
                    0,
                    true,
                    0,
                    options,
                    &mut Borrowing(&mut driver),
                )
                .map_err(|err| err.message().to_string())?;
            drop(driver);
            Ok(out.unwrap())
        }

        let check = |text: &str| match text.parse::<f64>() {
            Ok(value) if value.is_finite() => {
                assert_eq!(parse(text).map(f64::to_bits), Ok(value.to_bits()), "{text}");
            }
            _ => assert_eq!(parse(text), Err("number out of range".into()), "{text}"),
        };
        for text in [
            "2e-23",
            "0.1",
            "9007199254740993",
            "9007199254740993.0",
            "1e23",
            "8.98846567431158e307",
            "1.7976931348623157e308",
            "1.7976931348623159e308",
            "2.2250738585072011e-308",
            "4.9e-324",
            "2.4703282292062328e-324",
            "1e-400",
            "0e999",
            "-0.0e-999",
            "123456789012345678901234567890e-10",
            "0.000000000000000000000000000001234567890123456789",
        ] {
            check(text);
        }

        let mut rng: u64 = 0x2545_f491_4f6c_dd1d;
        let mut next = |n: u64| {
            rng ^= rng << 13;
            rng ^= rng >> 7;
            rng ^= rng << 17;
            rng % n
        };
        // miri is too slow for many iterations
        for _ in 0..if cfg!(miri) { 100 } else { 100_000 } {
            let mut text = String::new();
            if next(2) == 0 {
                text.push('-');
            }
            text.push(char::from(b'1' + next(9) as u8));
            for _ in 0..next(25) {
                text.push(char::from(b'0' + next(10) as u8));
            }
            if next(2) == 0 {
                text.push('.');
                for _ in 0..1 + next(25) {
                    text.push(char::from(b'0' + next(10) as u8));
                }
            }
            if next(2) == 0 {
                text.push_str(&format!("e{}", next(700) as i32 - 350));
            }
            check(&text);
        }
        // significands beyond 53 bits with exponents up to 22 (like
        // coordinates) are corrected with integer arithmetic
        for _ in 0..if cfg!(miri) { 100 } else { 100_000 } {
            let digits = 16 + next(4) as usize;
            let mut text = String::new();
            text.push(char::from(b'1' + next(9) as u8));
            for _ in 1..digits {
                text.push(char::from(b'0' + next(10) as u8));
            }
            if next(2) == 0 {
                text.insert(1 + next(digits as u64 - 1) as usize, '.');
            }
            if next(2) == 0 {
                text.push_str(&format!("e{}", next(30) as i32 - 15));
            }
            check(&text);
        }
        // the halfway points between floats above 2^53 (which are rounded
        // to the even float) and the numbers next to them
        for _ in 0..if cfg!(miri) { 10 } else { 10_000 } {
            let m = (1u64 << 52) + next(1 << 52);
            check(&format!("{}.5", m));
            check(&format!("{}.4999999999", m));
            let half = (2 * m + 1) << 10;
            for value in [half - 1, half, half + 1] {
                check(&format!("{value}e0"));
                check(&format!("{}e-1", u128::from(value) * 10));
            }
        }
    }

    /// Checks that the inputs parse like the equivalent JSON, in one go
    /// and in chunks.
    fn assert_like_json(inputs: &[(&str, &str)]) {
        for (input, json) in inputs {
            let expected = parse_complete(json).unwrap();
            assert_eq!(parse_complete(input), Ok(expected.clone()), "{input}");
            for size in chunk_sizes(input.len()) {
                assert_eq!(
                    parse_chunked(input, size),
                    Ok(expected.clone()),
                    "{input} size {size}"
                );
            }
        }
    }

    /// Checks that the inputs fail with the given errors, in one go and
    /// in chunks.
    fn assert_errors(inputs: &[(&str, &str)]) {
        for (input, msg) in inputs {
            assert_eq!(parse_complete(input).unwrap_err(), *msg, "{input}");
            for size in chunk_sizes(input.len()) {
                assert_eq!(
                    parse_chunked(input, size).unwrap_err(),
                    *msg,
                    "{input} size {size}"
                );
            }
        }
    }

    #[test]
    fn test_comments() {
        assert_like_json(&[
            ("// c\n1", "1"),
            ("/* c */ 1 /* c */", "1"),
            ("1 // c", "1"),
            ("[1, /* a\n * b */ 2 // c\n, 3]", "[1, 2, 3]"),
            ("{/**/\"a\"/**/:/**/1/**/}", "{\"a\": 1}"),
            (
                "[\"// no comment\", \"/* no comment */\"]",
                "[\"// no comment\", \"/* no comment */\"]",
            ),
            ("/* ä */ [/* 😀 */]", "[]"),
        ]);
        assert_errors(&[
            ("[1 /* c", "unexpected end of file"),
            ("[1 / 2]", "expected a comma"),
            ("[/", "unexpected character"),
            ("[1 /", "expected a comma"),
            ("/x", "unexpected character"),
        ]);
    }

    #[test]
    fn test_trailing_commas() {
        assert_like_json(&[
            ("[1,]", "[1]"),
            ("[1, 2 , ]", "[1, 2]"),
            ("{\"a\": 1,}", "{\"a\": 1}"),
            ("[[1,],{\"a\":[],},]", "[[1],{\"a\":[]}]"),
        ]);
        assert_errors(&[
            ("[,]", "unexpected comma"),
            ("[1,,]", "unexpected comma"),
            ("{,}", "expected map key"),
            ("{\"a\": 1,,}", "expected map key"),
        ]);
    }

    #[test]
    fn test_json5() {
        assert_like_json(&[
            // keys
            ("{a: 1, $b_2: 2, _: 3}", r#"{"a": 1, "$b_2": 2, "_": 3}"#),
            (
                "{Infinity: 1, null: 2, true: 3}",
                r#"{"Infinity": 1, "null": 2, "true": 3}"#,
            ),
            ("{ä: 1, a\u{200d}b: 2}", "{\"ä\": 1, \"a\u{200d}b\": 2}"),
            // combining marks and other digits continue identifiers
            (
                "{u\u{308}ber: 1, x\u{665}: 2}",
                "{\"u\u{308}ber\": 1, \"x\u{665}\": 2}",
            ),
            (
                r"{sig\u03A3ma: 1, \u0061b: 2, a\u0062: 3}",
                r#"{"sigΣma": 1, "ab": 2, "ab": 3}"#,
            ),
            ("{'a': 1}", r#"{"a": 1}"#),
            // strings
            ("'a\"b'", r#""a\"b""#),
            ("\"a'b\"", r#""a'b""#),
            (r"'a\'b'", r#""a'b""#),
            (r"'\v\0\x41\a\ä'", r#""\u000b\u0000Aaä""#),
            ("'a\\\nb\\\r\nc\\\rd\\\u{2028}e'", r#""abcde""#),
            ("'a\tb'", r#""a\tb""#),
            // numbers
            (
                "[0x1F, 0XfF, -0x10, +1, +1.5, .5, -.5, 5., 5.e1]",
                "[31, 255, -16, 1, 1.5, 0.5, -0.5, 5.0, 5e1]",
            ),
            (
                "[0xFFFFFFFFFFFFFFFF, -0x8000000000000000]",
                "[18446744073709551615, -9223372036854775808]",
            ),
            (
                "[0x10000000000000000, -0x8000000000000001]",
                "[18446744073709551616, -9223372036854775809]",
            ),
            (
                "[0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, -0x80000000000000000000000000000000]",
                "[340282366920938463463374607431768211455, \
                 -170141183460469231731687303715884105728]",
            ),
            // whitespace and line breaks
            ("\u{feff}[1,\u{a0}2\u{2028}\u{3000}\x0b\x0c]", "[1, 2]"),
            ("[1, // a\u{2028}2, // b\u{2029}3]", "[1, 2, 3]"),
        ]);
        assert_errors(&[
            ("{1: 2}", "expected map key"),
            ("{\u{308}u: 1}", "expected map key"),
            ("{a b: 1}", "expected colon"),
            (r"{\u0031: 1}", "invalid escape in identifier"),
            (r"{a\u0020: 1}", "invalid escape in identifier"),
            (r"{a\x41: 1}", "invalid escape in identifier"),
            (r"{a\uD800: 1}", "invalid escape in identifier"),
            (r"{a\u00: 1}", "invalid hex escape"),
            ("[a]", "unexpected character"),
            ("'a", "unexpected end of string"),
            ("'a\nb'", "unexpected character in string"),
            (r"'\01'", "invalid escape in string"),
            (r"'\1'", "invalid escape in string"),
            (r"'\xZ0'", "invalid hex escape"),
            ("[.]", "expected a digit"),
            ("[0x]", "expected a hex digit"),
            ("[Inf]", "unexpected character"),
            ("\u{2029}x", "unexpected character"),
        ]);
    }

    /// Returns `2^exp` exactly (`powi` may be imprecise, and is in miri).
    fn pow2(exp: u64) -> f64 {
        f64::from_bits((1023 + exp) << 52)
    }

    #[test]
    fn test_json5_hex_floats_are_rounded_correctly() {
        let value = |text: &str| match parse_complete(text).unwrap()[..] {
            [Event::Atom(Atom::F64(value))] => value,
            ref events => panic!("{events:?}"),
        };
        // (2^53 + 1) * 2^80 is half way between 2^133 and the next float
        // (rounded to the even one).  The digits beyond 128 bits are
        // dropped, if one of them is not zero the value is above half way.
        let half = format!("0x20000000000001{}", "0".repeat(20));
        let above = format!("0x20000000000001{}1", "0".repeat(19));
        let next = pow2(133) + pow2(81);
        assert_eq!(value(&half), pow2(133));
        assert_eq!(value(&above), next);
        assert_eq!(value(&format!("-{above}")), -next);
    }

    #[test]
    fn test_json5_large_hex() {
        // hexadecimal integers beyond 128 bits are approximated as floats
        let events = parse_complete(&format!("[0x1{}, -0x1{0}]", "0".repeat(32))).unwrap();
        assert_eq!(
            events[1..3],
            [Event::from(pow2(128)), Event::from(-pow2(128))]
        );
        assert_errors(&[(&format!("0x1{}", "0".repeat(256)), "number out of range")]);
    }

    #[test]
    fn test_line_scan() {
        fn lines(input: &str) -> Vec<&str> {
            let mut rv = Vec::new();
            let mut start = 0;
            let mut scan = crate::scan::LineScan::default();
            while let Some(end) = scan.find_end(input.as_bytes(), start) {
                rv.push(&input[start..end]);
                start = end + 1;
            }
            rv.push(&input[start..]);
            rv
        }

        assert_eq!(lines("1\n2"), ["1", "2"]);
        assert_eq!(lines("1 /* a\nb */\n2"), ["1 /* a\nb */", "2"]);
        assert_eq!(lines("1 // a\n2"), ["1 // a", "2"]);
        assert_eq!(lines("\"/*\"\n2 */"), ["\"/*\"", "2 */"]);
        assert_eq!(lines("\"a\n\"b"), ["\"a", "\"b"]);
        assert_eq!(lines("1 / 2\n3"), ["1 / 2", "3"]);
        assert_eq!(lines("1 /\"a\n\"\n2"), ["1 /\"a", "\"", "2"]);
        assert_eq!(lines("'/*'\n2 */"), ["'/*'", "2 */"]);
        assert_eq!(
            lines("'a\\\nb'\n'c\\\r\nd'\n2"),
            ["'a\\\nb'", "'c\\\r\nd'", "2"]
        );
    }

    #[test]
    fn test_json5_number_text() {
        for (text, json) in [
            ("+1.5", Some("1.5")),
            ("-.5e3", Some("-0.5e3")),
            (".5", Some("0.5")),
            ("5.", Some("5")),
            ("5.e1", Some("5e1")),
            ("+5.E1", Some("5E1")),
            ("1.5e3", None),
            ("-1", None),
        ] {
            assert_eq!(json_number(text).as_deref(), json, "{text}");
        }
    }

    #[test]
    fn test_json5_non_finite() {
        let events = parse_complete("[Infinity, -Infinity, +Infinity, NaN, -NaN]").unwrap();
        let floats: Vec<f64> = events
            .iter()
            .filter_map(|event| match event {
                Event::Atom(Atom::F64(value)) => Some(*value),
                _ => None,
            })
            .collect();
        assert_eq!(floats.len(), 5);
        assert_eq!(
            floats[..3],
            [f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY]
        );
        assert!(floats[3].is_nan() && floats[4].is_nan());
    }
}