beve 8.0.0

Rust implementation of the BEVE (Binary Efficient Versatile Encoding) specification with serde support
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
use half::{bf16, f16};
use serde::Deserialize;
use serde::de::value::{BoolDeserializer, BorrowedStrDeserializer};
use serde::de::{self, Visitor};
use serde::forward_to_deserialize_any;

use crate::error::{Error, Result};
use crate::header::*;
use crate::size::read_size;
use simdutf8::basic::from_utf8;

#[inline]
fn decode_utf8<'de>(bytes: &'de [u8], context: &'static str) -> Result<&'de str> {
    from_utf8(bytes).map_err(|_| Error::InvalidType(context))
}

#[inline]
pub(crate) fn byte_count_to_bytes(code: u8) -> Result<usize> {
    match code {
        0 => Ok(1),
        1 => Ok(2),
        2 => Ok(4),
        3 => Ok(8),
        4 => Ok(16),
        _ => Err(Error::Unsupported("byte width > 16 not supported")),
    }
}

#[derive(Clone, Copy)]
pub(crate) enum HalfKind {
    Bf16,
    F16,
}

impl HalfKind {
    #[inline]
    fn to_f32(self, bits: u16) -> f32 {
        match self {
            HalfKind::Bf16 => bf16::from_bits(bits).to_f32(),
            HalfKind::F16 => f16::from_bits(bits).to_f32(),
        }
    }

    #[inline]
    fn to_f64(self, bits: u16) -> f64 {
        self.to_f32(bits) as f64
    }
}

/// Ceiling on an allocation sized from a length on the wire that no bytes have
/// vouched for yet.
///
/// Such a length is untrusted input, and `Vec` answers an impossible request by
/// aborting the process rather than returning an error -- which no decoder can
/// turn back into an `Err`, and no caller can catch. Every buffer bounded by
/// this still grows to whatever data actually arrives; only the reserve taken up
/// front is capped. 8 MiB is past the size where taking it up front still
/// matters.
pub(crate) const MAX_PREALLOC_BYTES: usize = 8 * 1024 * 1024;

/// What the slice decoder's bulk complex-array marker found on the wire.
enum ComplexArrayPayload<'de> {
    /// The array's class already matches the destination: its payload, borrowed.
    Borrowed(&'de [u8]),
    /// A different class, converted into the destination width.
    Owned(Vec<u8>),
    /// Header consumed, and only the element-wise path can convert this pair.
    /// The caller drives the ordinary complex-array sequence access from here,
    /// which is exactly the state that access expects to start in.
    ElementWise {
        len: usize,
        src_class: u8,
        src_byte_code: u8,
    },
}

/// How a bulk complex-array marker should take a complex array off the wire,
/// given the component class the header names and the one the field wants.
///
/// The two decoders read bytes differently -- one borrows out of a slice, the
/// other pulls from a reader -- but they choose between these three routes by
/// one rule, and this is the only place it is written down. While each carried
/// its own copy of it they drifted, over what even counts as an array.
pub(crate) enum ComplexArrayPlan {
    /// The classes match: take `payload_len` bytes of payload as they are.
    AsIs { payload_len: usize },
    /// The classes differ but the pair converts in bulk: take `payload_len`
    /// bytes -- sized by the *source* width -- and hand them to
    /// [`widen_complex_components`].
    Widen { payload_len: usize },
    /// Only the element-wise path converts this pair. The payload stays unread
    /// so that path can walk it component by component, range-checking as it
    /// goes.
    ElementWise,
}

/// Plan the decode of a complex array of `len` `[re, im]` values whose
/// components are `(src_class, src_byte_code)` into a field wanting
/// `(dst_class, dst_byte_code)` components of `dst_scalar_size` bytes.
///
/// Sizes nothing from the destination width unless the classes match: a source
/// component is as wide as its own class says, which for a half float is not the
/// generic `1 << byte_code` (see [`complex_component_bytes`]).
pub(crate) fn complex_array_plan(
    src_class: u8,
    src_byte_code: u8,
    len: usize,
    dst_class: u8,
    dst_byte_code: u8,
    dst_scalar_size: usize,
) -> Result<ComplexArrayPlan> {
    if src_class == dst_class && src_byte_code == dst_byte_code {
        return Ok(ComplexArrayPlan::AsIs {
            payload_len: complex_payload_len(len, dst_scalar_size)?,
        });
    }
    if !complex_widening_supported(src_class, src_byte_code, dst_class, dst_byte_code) {
        return Ok(ComplexArrayPlan::ElementWise);
    }
    let src_width = complex_component_bytes(src_class, src_byte_code)
        .ok_or(Error::Unsupported("unsupported complex component width"))?;
    Ok(ComplexArrayPlan::Widen {
        payload_len: complex_payload_len(len, src_width)?,
    })
}

/// Bytes a complex array of `len` values occupies at `component_bytes` per
/// component: two components (re, im) per value.
fn complex_payload_len(len: usize, component_bytes: usize) -> Result<usize> {
    len.checked_mul(2)
        .and_then(|n| n.checked_mul(component_bytes))
        .ok_or(Error::InvalidSize)
}

/// Whether [`widen_complex_components`] converts this class pair.
///
/// [`complex_array_plan`] picks a route before either decoder has read the
/// payload, and the streaming one cannot rewind if that choice was wrong, so the
/// answer has to be available up front. Stated as a rule rather than a second
/// copy of the pair list below; `widening_predicate_matches_the_converter` pins
/// the two together over every possible pair.
pub(crate) fn complex_widening_supported(
    src_class: u8,
    src_bc: u8,
    dst_class: u8,
    dst_bc: u8,
) -> bool {
    if dst_class != NUM_FLOAT || !matches!(dst_bc, 2 | 3) {
        return false;
    }
    if src_class == dst_class && src_bc == dst_bc {
        return false; // same class: the caller takes the payload as-is
    }
    match src_class {
        NUM_SIGNED | NUM_UNSIGNED => src_bc <= 4,
        NUM_FLOAT => src_bc <= 3,
        _ => false,
    }
}

/// Convert a little-endian complex payload of `(src_class, src_bc)` components
/// into little-endian components of the float width `dst_bc` names.
///
/// Mirrors `NumDe::deserialize_f32`/`deserialize_f64`, which accept every
/// numeric class, so a bulk decode and an element-wise decode of the same bytes
/// produce the same values. That equality is the whole contract of the
/// `#[serde(with = ...)]` markers: they are a throughput change, never a
/// semantic one.
///
/// Only float destinations convert. The element-wise path range-checks every
/// component on the way into an integer and rejects floats outright; a bulk loop
/// that wrapped or saturated instead would disagree with it, so those callers
/// get `None` and fall back to the element-wise path rather than a fast wrong
/// answer.
pub(crate) fn widen_complex_components(
    src: &[u8],
    src_class: u8,
    src_bc: u8,
    dst_class: u8,
    dst_bc: u8,
) -> Option<Vec<u8>> {
    // Not merely an early-out: `dst_bc` 2 means f32 under NUM_FLOAT but i32/u32
    // under the integer classes, so without this the match below would happily
    // write floats into an integer destination.
    if dst_class != NUM_FLOAT {
        return None;
    }
    // Read each component at the source width, convert, write it back at the
    // destination width. Pairing is irrelevant: a complex payload is just `2n`
    // contiguous components, and re/im convert identically.
    macro_rules! convert {
        ($src_ty:ty, $dst_ty:ty, $f:expr) => {{
            const SW: usize = core::mem::size_of::<$src_ty>();
            const DW: usize = core::mem::size_of::<$dst_ty>();
            // The source width is stated twice: here by the arm's own type, and
            // by `complex_component_bytes` where the caller sizes the read. They
            // agree today; if an arm ever pairs a class with the wrong type,
            // refuse the payload rather than dropping the trailing partial
            // component and returning a silently short `Vec`.
            debug_assert_eq!(Some(SW), complex_component_bytes(src_class, src_bc));
            if !src.len().is_multiple_of(SW) {
                return None;
            }
            let mut out = vec![0u8; src.len() / SW * DW];
            for (o, i) in out.chunks_exact_mut(DW).zip(src.chunks_exact(SW)) {
                let v = <$src_ty>::from_le_bytes(i.try_into().expect("component width"));
                let d: $dst_ty = $f(v);
                o.copy_from_slice(&d.to_le_bytes());
            }
            out
        }};
    }

    // `dst_bc` is a NUM_FLOAT byte code: 2 is f32, 3 is f64. The same-class case
    // never arrives here; the caller borrows that payload instead of copying it.
    Some(match (dst_bc, src_class, src_bc) {
        (2, NUM_SIGNED, 0) => convert!(i8, f32, |v| v as f32),
        (2, NUM_SIGNED, 1) => convert!(i16, f32, |v| v as f32),
        (2, NUM_SIGNED, 2) => convert!(i32, f32, |v| v as f32),
        (2, NUM_SIGNED, 3) => convert!(i64, f32, |v| v as f32),
        (2, NUM_SIGNED, 4) => convert!(i128, f32, |v| v as f32),
        (2, NUM_UNSIGNED, 0) => convert!(u8, f32, |v| v as f32),
        (2, NUM_UNSIGNED, 1) => convert!(u16, f32, |v| v as f32),
        (2, NUM_UNSIGNED, 2) => convert!(u32, f32, |v| v as f32),
        (2, NUM_UNSIGNED, 3) => convert!(u64, f32, |v| v as f32),
        (2, NUM_UNSIGNED, 4) => convert!(u128, f32, |v| v as f32),
        (2, NUM_FLOAT, 0) => convert!(u16, f32, |b| HalfKind::Bf16.to_f32(b)),
        (2, NUM_FLOAT, 1) => convert!(u16, f32, |b| HalfKind::F16.to_f32(b)),
        (2, NUM_FLOAT, 3) => convert!(f64, f32, |v| v as f32),

        (3, NUM_SIGNED, 0) => convert!(i8, f64, |v| v as f64),
        (3, NUM_SIGNED, 1) => convert!(i16, f64, |v| v as f64),
        (3, NUM_SIGNED, 2) => convert!(i32, f64, |v| v as f64),
        (3, NUM_SIGNED, 3) => convert!(i64, f64, |v| v as f64),
        (3, NUM_SIGNED, 4) => convert!(i128, f64, |v| v as f64),
        (3, NUM_UNSIGNED, 0) => convert!(u8, f64, |v| v as f64),
        (3, NUM_UNSIGNED, 1) => convert!(u16, f64, |v| v as f64),
        (3, NUM_UNSIGNED, 2) => convert!(u32, f64, |v| v as f64),
        (3, NUM_UNSIGNED, 3) => convert!(u64, f64, |v| v as f64),
        (3, NUM_UNSIGNED, 4) => convert!(u128, f64, |v| v as f64),
        (3, NUM_FLOAT, 0) => convert!(u16, f64, |b| HalfKind::Bf16.to_f64(b)),
        (3, NUM_FLOAT, 1) => convert!(u16, f64, |b| HalfKind::F16.to_f64(b)),
        (3, NUM_FLOAT, 2) => convert!(f32, f64, |v| v as f64),

        _ => return None,
    })
}

#[inline]
fn make_seq_unsigned<'de>(
    de: &mut Deserializer<'de>,
    len: usize,
    byte_code: u8,
) -> Result<SeqAccessUnsigned<'de>> {
    let elem_size = byte_count_to_bytes(byte_code)?;
    let total = elem_size.checked_mul(len).ok_or(Error::InvalidSize)?;
    let data = de.read_exact(total)?;
    Ok(SeqAccessUnsigned {
        data,
        remaining: len,
        elem_size,
        offset: 0,
    })
}

#[inline]
fn make_seq_signed<'de>(
    de: &mut Deserializer<'de>,
    len: usize,
    byte_code: u8,
) -> Result<SeqAccessSigned<'de>> {
    let elem_size = byte_count_to_bytes(byte_code)?;
    let total = elem_size.checked_mul(len).ok_or(Error::InvalidSize)?;
    let data = de.read_exact(total)?;
    Ok(SeqAccessSigned {
        data,
        remaining: len,
        elem_size,
        offset: 0,
    })
}

#[inline]
fn make_seq_half<'de>(
    de: &mut Deserializer<'de>,
    len: usize,
    kind: HalfKind,
) -> Result<SeqAccessHalf<'de>> {
    let total = len.checked_mul(2).ok_or(Error::InvalidSize)?;
    let data = de.read_exact(total)?;
    Ok(SeqAccessHalf {
        data,
        remaining: len,
        offset: 0,
        kind,
    })
}

#[inline]
fn make_seq_float32<'de>(de: &mut Deserializer<'de>, len: usize) -> Result<SeqAccessFloat32<'de>> {
    let total = 4usize.checked_mul(len).ok_or(Error::InvalidSize)?;
    let data = de.read_exact(total)?;
    Ok(SeqAccessFloat32 {
        data,
        remaining: len,
        offset: 0,
    })
}

#[inline]
fn make_seq_float64<'de>(de: &mut Deserializer<'de>, len: usize) -> Result<SeqAccessFloat64<'de>> {
    let total = 8usize.checked_mul(len).ok_or(Error::InvalidSize)?;
    let data = de.read_exact(total)?;
    Ok(SeqAccessFloat64 {
        data,
        remaining: len,
        offset: 0,
    })
}

pub struct Deserializer<'de> {
    input: &'de [u8],
    pos: usize,
}

impl<'de> Deserializer<'de> {
    /// Create a `Deserializer` that starts reading from byte offset `pos`
    /// within `input`. Used by `from_field` to deserialize at an arbitrary
    /// position after JSON-Pointer navigation.
    pub(crate) fn from_slice_at(input: &'de [u8], pos: usize) -> Self {
        Self { input, pos }
    }
}

/// Deserialize a value from a BEVE byte slice.
///
/// Supports zero-copy deserialization: types containing `&'de str` fields
/// borrow directly from the input buffer instead of allocating.
///
/// # Example
///
/// ```rust
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Info<'a> {
///     name: &'a str,
///     count: u32,
/// }
///
/// let bytes = beve::to_vec(&("hello", 42u32)).unwrap();
/// ```
pub fn from_slice<'de, T: Deserialize<'de>>(bytes: &'de [u8]) -> Result<T> {
    let mut de = Deserializer {
        input: bytes,
        pos: 0,
    };
    de.skip_delimiters();
    let t = T::deserialize(&mut de)?;
    if de.pos != de.input.len() {
        // trailing bytes allowed? We'll ignore for now
    }
    Ok(t)
}

/// Validate that `bytes` contains exactly one well-formed BEVE value.
///
/// This performs structural validation only and does not materialize a target type.
/// The full input must be consumed by a single value; trailing bytes are rejected.
///
/// # Example
///
/// ```rust
/// let bytes = beve::to_vec(&vec![1u32, 2, 3]).unwrap();
/// beve::validate_slice(&bytes).unwrap();
/// ```
pub fn validate_slice(bytes: &[u8]) -> Result<()> {
    let mut de = Deserializer {
        input: bytes,
        pos: 0,
    };
    let _ = <de::IgnoredAny as serde::Deserialize>::deserialize(&mut de)?;
    if de.pos != de.input.len() {
        return Err(Error::InvalidType("unexpected trailing BEVE data"));
    }
    Ok(())
}

impl<'de> Deserializer<'de> {
    #[inline]
    fn remaining(&self) -> usize {
        self.input.len().saturating_sub(self.pos)
    }

    #[inline]
    fn peek_byte(&self) -> Result<u8> {
        self.input.get(self.pos).copied().ok_or(Error::Eof)
    }

    /// Skip any leading data delimiter bytes (extension 0).
    fn skip_delimiters(&mut self) {
        while self.pos < self.input.len()
            && self.input[self.pos] == make_extension_header(EXT_DELIMITER)
        {
            self.pos += 1;
        }
    }

    #[inline]
    fn read_byte(&mut self) -> Result<u8> {
        if self.pos >= self.input.len() {
            Err(Error::Eof)
        } else {
            let b = self.input[self.pos];
            self.pos += 1;
            Ok(b)
        }
    }

    #[inline]
    fn read_exact<'a>(&'a mut self, n: usize) -> Result<&'de [u8]> {
        if self.remaining() < n {
            return Err(Error::Eof);
        }
        let s = &self.input[self.pos..self.pos + n];
        self.pos += n;
        Ok(s)
    }

    /// If the value here is a typed numeric array matching `(class, byte_code)`,
    /// consume its header and return the borrowed little-endian payload; otherwise
    /// leave the cursor untouched and return `None` (the caller falls back to the
    /// element-wise path). `elem_size` is the true element width. Used by the bulk
    /// `#[serde(with = ...)]` decode markers.
    fn typed_array_payload(
        &mut self,
        class: u8,
        byte_code: u8,
        elem_size: usize,
    ) -> Result<Option<&'de [u8]>> {
        let header = self.peek_byte()?;
        if parse_type(header) == TYPE_TYPED_ARRAY
            && parse_subtype(header) == class
            && parse_byte_count_code(header) == byte_code
        {
            self.read_byte()?;
            let len = read_size(self.input, &mut self.pos)? as usize;
            let payload = len.checked_mul(elem_size).ok_or(Error::InvalidSize)?;
            Ok(Some(self.read_exact(payload)?))
        } else {
            Ok(None)
        }
    }

    /// Complex-array twin of [`typed_array_payload`](Self::typed_array_payload):
    /// `scalar_size` is the per-scalar width (the payload is `len * 2 *
    /// scalar_size` for `len` `[re, im]` values).
    ///
    /// An array whose class already matches lends its payload out borrowed. A
    /// *different* class is widened into the destination when the destination is
    /// a float, because the element-wise path accepts every numeric class there
    /// and the two must agree; see [`widen_complex_components`].
    ///
    /// `None` covers the two shapes this fast path declines, both with the
    /// cursor left where it started so the caller can fall back to
    /// `deserialize_any`: a value that is not a complex extension at all (the
    /// generic empty array an empty `Vec` encodes as), and a *single* complex
    /// value, which is a complex extension but not an array. `deserialize_any`
    /// presents that one as a 2-element sequence of scalars, and rejecting it is
    /// its job, not this one's.
    fn complex_array_payload(
        &mut self,
        class: u8,
        byte_code: u8,
        scalar_size: usize,
    ) -> Result<Option<ComplexArrayPayload<'de>>> {
        let header = self.peek_byte()?;
        if parse_type(header) != TYPE_EXTENSION || parse_extension_id(header) != EXT_COMPLEX {
            return Ok(None);
        }
        let rewind = self.pos;
        self.read_byte()?; // extension header
        let ch = self.read_byte()?; // complex header byte
        let is_array = (ch & 0x01) != 0;
        let src_class = (ch >> 3) & 0x03;
        let src_byte_code = (ch >> 5) & 0x07;
        if !is_array {
            self.pos = rewind;
            return Ok(None);
        }
        let len = read_size(self.input, &mut self.pos)? as usize;

        match complex_array_plan(src_class, src_byte_code, len, class, byte_code, scalar_size)? {
            ComplexArrayPlan::AsIs { payload_len } => Ok(Some(ComplexArrayPayload::Borrowed(
                self.read_exact(payload_len)?,
            ))),
            ComplexArrayPlan::Widen { payload_len } => {
                let widened = widen_complex_components(
                    self.peek_exact(payload_len)?,
                    src_class,
                    src_byte_code,
                    class,
                    byte_code,
                )
                .ok_or(Error::Unsupported(
                    "complex widening plan and converter disagree",
                ))?;
                self.pos += payload_len;
                Ok(Some(ComplexArrayPayload::Owned(widened)))
            }
            // Leave the payload unread: the element-wise access reads it itself,
            // component by component, and range-checks as it goes.
            ComplexArrayPlan::ElementWise => Ok(Some(ComplexArrayPayload::ElementWise {
                len,
                src_class,
                src_byte_code,
            })),
        }
    }

    /// Borrow the next `n` bytes without advancing. Lets a bulk decode inspect a
    /// payload it may decide not to consume.
    #[inline]
    fn peek_exact(&self, n: usize) -> Result<&'de [u8]> {
        if self.remaining() < n {
            return Err(Error::Eof);
        }
        Ok(&self.input[self.pos..self.pos + n])
    }

    fn parse_bool(&mut self, header: u8) -> Result<bool> {
        bool_value(header)
    }

    fn parse_signed(&mut self, code: u8) -> Result<i128> {
        let nbytes = match code {
            0 => 1,
            1 => 2,
            2 => 4,
            3 => 8,
            4 => 16,
            _ => return Err(Error::Unsupported("signed width > 128")),
        };
        let s = self.read_exact(nbytes)?;
        let mut buf = [0u8; 16];
        buf[..nbytes].copy_from_slice(s);
        // Sign-extend if the highest bit of the most significant byte is set
        if nbytes < 16 && (s[nbytes - 1] & 0x80) != 0 {
            for b in &mut buf[nbytes..] {
                *b = 0xFF;
            }
        }
        Ok(i128::from_le_bytes(buf))
    }

    fn parse_unsigned(&mut self, code: u8) -> Result<u128> {
        let nbytes = match code {
            0 => 1,
            1 => 2,
            2 => 4,
            3 => 8,
            4 => 16,
            _ => return Err(Error::Unsupported("unsigned width > 128")),
        };
        let s = self.read_exact(nbytes)?;
        let mut buf = [0u8; 16];
        buf[..nbytes].copy_from_slice(s);
        Ok(u128::from_le_bytes(buf))
    }

    fn parse_bf16_bits(&mut self) -> Result<u16> {
        let s = self.read_exact(2)?;
        Ok(u16::from_le_bytes([s[0], s[1]]))
    }

    fn parse_f16_bits(&mut self) -> Result<u16> {
        let s = self.read_exact(2)?;
        Ok(u16::from_le_bytes([s[0], s[1]]))
    }

    fn parse_f32(&mut self) -> Result<f32> {
        Ok(f32::from_le_bytes(self.read_exact(4)?.try_into().unwrap()))
    }
    fn parse_f64(&mut self) -> Result<f64> {
        Ok(f64::from_le_bytes(self.read_exact(8)?.try_into().unwrap()))
    }

    fn deserialize_half_newtype<V: Visitor<'de>>(
        &mut self,
        visitor: V,
        kind: HalfKind,
    ) -> Result<V::Value> {
        let header = self.peek_byte()?;
        if parse_type(header) == TYPE_NUMBER && parse_subtype(header) == NUM_FLOAT {
            let byte_code = parse_byte_count_code(header);
            let matches = match kind {
                HalfKind::Bf16 => byte_code == 0,
                HalfKind::F16 => byte_code == 1,
            };
            if matches {
                self.read_byte()?; // consume header
                let bits = match kind {
                    HalfKind::Bf16 => self.parse_bf16_bits()?,
                    HalfKind::F16 => self.parse_f16_bits()?,
                };
                let deser = HalfBitsDeserializer { kind, bits };
                return visitor.visit_newtype_struct(deser);
            }
        }
        serde::Deserializer::deserialize_any(self, visitor)
    }

    fn parse_string_borrowed(&mut self) -> Result<&'de str> {
        let len = read_size(self.input, &mut self.pos)? as usize;
        let s = self.read_exact(len)?;
        decode_utf8(s, "invalid utf-8")
    }

    fn read_enum_tag(&mut self) -> Result<EnumTag<'de>> {
        let header = self.read_byte()?;
        match parse_type(header) {
            TYPE_NUMBER => {
                let subtype = parse_subtype(header);
                let bc = parse_byte_count_code(header);
                match subtype {
                    NUM_UNSIGNED => Ok(EnumTag::Index(self.parse_unsigned(bc)? as u64)),
                    NUM_SIGNED => {
                        let v = self.parse_signed(bc)?;
                        if v < 0 {
                            Err(Error::InvalidType("negative enum index"))
                        } else {
                            Ok(EnumTag::Index(v as u64))
                        }
                    }
                    _ => Err(Error::InvalidType("enum tag must be integer")),
                }
            }
            TYPE_STRING => {
                let name = self.parse_string_borrowed()?;
                Ok(EnumTag::Name(name))
            }
            _ => Err(Error::InvalidType("unsupported enum tag")),
        }
    }

    fn deserialize_value<V: Visitor<'de>>(&mut self, visitor: V) -> Result<V::Value> {
        let header = self.read_byte()?;
        let ty = parse_type(header);
        match ty {
            TYPE_NULL_BOOL => {
                if header == 0 {
                    visitor.visit_unit()
                } else {
                    visitor.visit_bool(self.parse_bool(header)?)
                }
            }
            TYPE_NUMBER => {
                let class = parse_subtype(header);
                let bc = parse_byte_count_code(header);
                match class {
                    NUM_FLOAT => match bc {
                        0 => {
                            let bits = self.parse_bf16_bits()?;
                            let v = bf16::from_bits(bits).to_f32();
                            visitor.visit_f32(v)
                        }
                        1 => {
                            let bits = self.parse_f16_bits()?;
                            let v = f16::from_bits(bits).to_f32();
                            visitor.visit_f32(v)
                        }
                        2 => visitor.visit_f32(self.parse_f32()?),
                        3 => visitor.visit_f64(self.parse_f64()?),
                        4 => Err(Error::Unsupported("float128 not supported")),
                        _ => Err(Error::InvalidHeader(header)),
                    },
                    NUM_SIGNED => {
                        let v = self.parse_signed(bc)?;
                        // Choose the smallest fitting type for the visitor
                        if v >= i8::MIN as i128 && v <= i8::MAX as i128 {
                            visitor.visit_i8(v as i8)
                        } else if v >= i16::MIN as i128 && v <= i16::MAX as i128 {
                            visitor.visit_i16(v as i16)
                        } else if v >= i32::MIN as i128 && v <= i32::MAX as i128 {
                            visitor.visit_i32(v as i32)
                        } else if v >= i64::MIN as i128 && v <= i64::MAX as i128 {
                            visitor.visit_i64(v as i64)
                        } else {
                            visitor.visit_i128(v)
                        }
                    }
                    NUM_UNSIGNED => {
                        let v = self.parse_unsigned(bc)?;
                        if v <= u8::MAX as u128 {
                            visitor.visit_u8(v as u8)
                        } else if v <= u16::MAX as u128 {
                            visitor.visit_u16(v as u16)
                        } else if v <= u32::MAX as u128 {
                            visitor.visit_u32(v as u32)
                        } else if v <= u64::MAX as u128 {
                            visitor.visit_u64(v as u64)
                        } else {
                            visitor.visit_u128(v)
                        }
                    }
                    _ => Err(Error::InvalidHeader(header)),
                }
            }
            TYPE_STRING => {
                let s = self.parse_string_borrowed()?;
                visitor.visit_borrowed_str(s)
            }
            TYPE_OBJECT => {
                let key_type = parse_subtype(header);
                let bc = parse_byte_count_code(header);
                let count = read_size(self.input, &mut self.pos)? as usize;
                match key_type {
                    KEY_STRING => {
                        let access = MapAccessString {
                            de: self,
                            remaining: count,
                        };
                        visitor.visit_map(access)
                    }
                    KEY_SIGNED => {
                        let access = MapAccessSigned {
                            de: self,
                            remaining: count,
                            byte_code: bc,
                        };
                        visitor.visit_map(access)
                    }
                    KEY_UNSIGNED => {
                        let access = MapAccessUnsigned {
                            de: self,
                            remaining: count,
                            byte_code: bc,
                        };
                        visitor.visit_map(access)
                    }
                    _ => Err(Error::InvalidHeader(header)),
                }
            }
            TYPE_TYPED_ARRAY => {
                let cat = parse_subtype(header);
                let bc = parse_byte_count_code(header);
                let len = read_size(self.input, &mut self.pos)? as usize;
                match cat {
                    ARRAY_FLOAT => match bc {
                        0 => visitor.visit_seq(make_seq_half(self, len, HalfKind::Bf16)?),
                        1 => visitor.visit_seq(make_seq_half(self, len, HalfKind::F16)?),
                        2 => visitor.visit_seq(make_seq_float32(self, len)?),
                        3 => visitor.visit_seq(make_seq_float64(self, len)?),
                        _ => Err(Error::Unsupported(
                            "typed float arrays supported only for bf16/f16/f32/f64",
                        )),
                    },
                    ARRAY_SIGNED => visitor.visit_seq(make_seq_signed(self, len, bc)?),
                    ARRAY_UNSIGNED => visitor.visit_seq(make_seq_unsigned(self, len, bc)?),
                    ARRAY_BOOL_OR_STRING => {
                        if (header & 0b0010_0000) == 0 {
                            // boolean array
                            let packed_len = len.div_ceil(8);
                            let data = self.read_exact(packed_len)?;
                            visitor.visit_seq(SeqAccessBool {
                                data,
                                remaining: len,
                                byte_idx: 0,
                                bit_idx: 0,
                            })
                        } else {
                            // string array
                            visitor.visit_seq(SeqAccessString {
                                de: self,
                                remaining: len,
                            })
                        }
                    }
                    _ => Err(Error::InvalidHeader(header)),
                }
            }
            TYPE_GENERIC_ARRAY => {
                let len = read_size(self.input, &mut self.pos)? as usize;
                visitor.visit_seq(SeqAccessGeneric {
                    de: self,
                    remaining: len,
                })
            }
            TYPE_EXTENSION => {
                let ext = parse_extension_id(header);
                match ext {
                    EXT_TYPE_TAG => {
                        let tag = self.read_enum_tag()?;
                        let access = EnumAccess { de: self, tag };
                        visitor.visit_enum(access)
                    }
                    EXT_COMPLEX => {
                        let ch = self.read_byte()?; // complex header
                        let is_array = (ch & 0x01) != 0;
                        let class = (ch >> 3) & 0x03;
                        let bc = (ch >> 5) & 0x07;
                        if !is_array {
                            // single complex -> present as 2-element sequence
                            visitor.visit_seq(ComplexPairAccess {
                                de: self,
                                class,
                                byte_code: bc,
                                state: 0,
                            })
                        } else {
                            let len = read_size(self.input, &mut self.pos)? as usize;
                            visitor.visit_seq(SeqAccessComplexArray {
                                de: self,
                                remaining: len,
                                class,
                                byte_code: bc,
                            })
                        }
                    }
                    EXT_MATRICES => {
                        // Present as a map with keys: layout, extents, value
                        let mheader = self.read_byte()?; // layout bit in bit0
                        visitor.visit_map(MatrixAccess {
                            de: self,
                            step: 0,
                            mheader,
                        })
                    }
                    _ => Err(Error::Unsupported("extension type not supported")),
                }
            }
            _ => Err(Error::InvalidHeader(header)),
        }
    }
}

impl<'de> serde::Deserializer<'de> for &mut Deserializer<'de> {
    type Error = Error;

    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_value(visitor)
    }

    fn deserialize_bool<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        let header = self.read_byte()?;
        if is_bool(header) {
            visitor.visit_bool(self.parse_bool(header)?)
        } else {
            Err(Error::InvalidType("expected bool"))
        }
    }

    fn deserialize_i8<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_i16<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_i32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_i64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_i128<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_u8<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_u16<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_u32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_u64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_u128<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_f32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_f64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_char<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_str<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_string<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_bytes<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        let header = self.peek_byte()?;
        let ty = parse_type(header);
        if ty == TYPE_TYPED_ARRAY
            && parse_subtype(header) == ARRAY_UNSIGNED
            && parse_byte_count_code(header) == 0
        {
            self.read_byte()?;
            let len = read_size(self.input, &mut self.pos)? as usize;
            let data = self.read_exact(len)?;
            return visitor.visit_borrowed_bytes(data);
        }
        // Empty sequences serialize as generic arrays; treat as empty bytes
        if ty == TYPE_GENERIC_ARRAY {
            self.read_byte()?;
            let len = read_size(self.input, &mut self.pos)? as usize;
            if len == 0 {
                return visitor.visit_borrowed_bytes(&[]);
            }
            // Non-empty generic array: fall through via visit_seq
            return visitor.visit_seq(SeqAccessGeneric {
                de: self,
                remaining: len,
            });
        }
        self.deserialize_any(visitor)
    }
    fn deserialize_byte_buf<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        let header = self.peek_byte()?;
        let ty = parse_type(header);
        if ty == TYPE_TYPED_ARRAY
            && parse_subtype(header) == ARRAY_UNSIGNED
            && parse_byte_count_code(header) == 0
        {
            self.read_byte()?;
            let len = read_size(self.input, &mut self.pos)? as usize;
            let data = self.read_exact(len)?;
            return visitor.visit_borrowed_bytes(data);
        }
        if ty == TYPE_GENERIC_ARRAY {
            self.read_byte()?;
            let len = read_size(self.input, &mut self.pos)? as usize;
            if len == 0 {
                return visitor.visit_borrowed_bytes(&[]);
            }
            return visitor.visit_seq(SeqAccessGeneric {
                de: self,
                remaining: len,
            });
        }
        self.deserialize_any(visitor)
    }

    fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        let header = self.peek_byte()?;
        if header == 0 {
            self.read_byte()?;
            visitor.visit_none()
        } else {
            visitor.visit_some(self)
        }
    }

    fn deserialize_unit<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        let header = self.read_byte()?;
        if header == 0 {
            visitor.visit_unit()
        } else {
            Err(Error::InvalidType("expected null/unit"))
        }
    }

    fn deserialize_unit_struct<V: Visitor<'de>>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> Result<V::Value> {
        self.deserialize_unit(visitor)
    }

    fn deserialize_newtype_struct<V: Visitor<'de>>(
        self,
        name: &'static str,
        visitor: V,
    ) -> Result<V::Value> {
        match name {
            "bf16" => self.deserialize_half_newtype(visitor, HalfKind::Bf16),
            "f16" => self.deserialize_half_newtype(visitor, HalfKind::F16),
            _ => {
                // Bulk-array `#[serde(with = ...)]` markers: hand the raw payload
                // to the visitor (which memcpys it into the result `Vec`). A
                // non-matching wire shape (e.g. the generic empty array an empty
                // `Vec` encodes as) falls back to the element-wise path.
                if let Some((class, byte_code, elem_size)) = crate::ext::typed_array_tag(name) {
                    return match self.typed_array_payload(class, byte_code, elem_size)? {
                        Some(bytes) => visitor.visit_borrowed_bytes(bytes),
                        None => self.deserialize_any(visitor),
                    };
                }
                if let Some((class, byte_code, scalar_size)) = crate::ext::complex_array_tag(name) {
                    return match self.complex_array_payload(class, byte_code, scalar_size)? {
                        Some(ComplexArrayPayload::Borrowed(bytes)) => {
                            visitor.visit_borrowed_bytes(bytes)
                        }
                        // A converted payload is owned, so it cannot be borrowed
                        // for `'de`; the visitor copies out of it either way.
                        Some(ComplexArrayPayload::Owned(bytes)) => visitor.visit_byte_buf(bytes),
                        Some(ComplexArrayPayload::ElementWise {
                            len,
                            src_class,
                            src_byte_code,
                        }) => visitor.visit_seq(SeqAccessComplexArray {
                            de: self,
                            remaining: len,
                            class: src_class,
                            byte_code: src_byte_code,
                        }),
                        None => self.deserialize_any(visitor),
                    };
                }
                self.deserialize_any(visitor)
            }
        }
    }

    fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_tuple<V: Visitor<'de>>(self, _len: usize, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_tuple_struct<V: Visitor<'de>>(
        self,
        _name: &'static str,
        _len: usize,
        visitor: V,
    ) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }

    fn deserialize_map<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_struct<V: Visitor<'de>>(
        self,
        _name: &'static str,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }

    fn deserialize_enum<V: Visitor<'de>>(
        self,
        _name: &'static str,
        _variants: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value> {
        // Only an *externally* tagged enum reaches this method. Serde's derive
        // lowers `#[serde(tag)]`, `#[serde(tag, content)]` and
        // `#[serde(untagged)]` to ordinary maps and bare values before the
        // deserializer sees them, so there is no ambiguity between a variant
        // object and a struct here.
        let header = self.peek_byte()?;
        let ty = parse_type(header);
        match ty {
            // BEVE Version 2: `{ "VariantName": <payload> }`, an ordinary
            // single-key object, which is what `serde_json` writes too.
            TYPE_OBJECT if parse_subtype(header) == KEY_STRING => {
                let _ = self.read_byte()?; // consume object header
                let count = read_size(self.input, &mut self.pos)? as usize;
                if count != 1 {
                    return Err(Error::InvalidType(
                        "an externally tagged variant must be a single-key object",
                    ));
                }
                let name = self.parse_string_borrowed()?;
                let access = EnumAccess {
                    de: self,
                    tag: EnumTag::Name(name),
                };
                visitor.visit_enum(access)
            }
            // BEVE Version 1 legacy: the deprecated type-tag extension. Kept on
            // read so existing documents still load; never written.
            TYPE_EXTENSION => {
                let _ = self.read_byte()?; // consume extension header
                let ext = parse_extension_id(header);
                match ext {
                    EXT_TYPE_TAG => {
                        let tag = self.read_enum_tag()?;
                        let access = EnumAccess { de: self, tag };
                        visitor.visit_enum(access)
                    }
                    _ => Err(Error::InvalidHeader(header)),
                }
            }
            // BEVE Version 1 legacy: a bare positional index, which is what the
            // removed `EnumEncoding::Number` wrote for a unit variant.
            TYPE_NUMBER => {
                let header = self.read_byte()?; // consume number header
                let subtype = parse_subtype(header);
                let idx: u64 = match subtype {
                    NUM_UNSIGNED => self.parse_unsigned(parse_byte_count_code(header))? as u64,
                    NUM_SIGNED => {
                        let v = self.parse_signed(parse_byte_count_code(header))?;
                        if v < 0 {
                            return Err(Error::InvalidType("negative enum index"));
                        }
                        v as u64
                    }
                    _ => return Err(Error::InvalidType("enum index must be integer")),
                };
                visitor.visit_enum(EnumIndexAccess { idx })
            }
            TYPE_STRING => {
                let _ = self.read_byte()?; // consume string header
                let s = self.parse_string_borrowed()?;
                visitor.visit_enum(EnumStrAccess { name: s })
            }
            _ => self.deserialize_any(visitor),
        }
    }

    fn deserialize_identifier<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_ignored_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }

    /// BEVE is a binary format, so types that offer a compact non-textual form
    /// take it. This has to be stated: serde's default is `true`, and a reader
    /// disagreeing with the writer means the crate cannot read its own output
    /// for any type that branches on it, such as `std::net::IpAddr`.
    fn is_human_readable(&self) -> bool {
        false
    }
}

// =============== SeqAccess implementations ===============

struct SeqAccessGeneric<'a, 'de> {
    de: &'a mut Deserializer<'de>,
    remaining: usize,
}
impl<'de, 'a> de::SeqAccess<'de> for SeqAccessGeneric<'a, 'de> {
    type Error = Error;
    fn next_element_seed<T: de::DeserializeSeed<'de>>(
        &mut self,
        seed: T,
    ) -> Result<Option<T::Value>> {
        if self.remaining == 0 {
            return Ok(None);
        }
        self.remaining -= 1;
        let val = seed.deserialize(&mut *self.de)?;
        Ok(Some(val))
    }
    fn size_hint(&self) -> Option<usize> {
        Some(self.remaining)
    }
}

/// Widen `elem_size` little-endian bytes to `u128`. `chunk.len()` must equal
/// `elem_size` (1/2/4/8/16, the only values `byte_count_to_bytes` yields).
///
/// Narrow widths (1/2/4) read at native width, where the old 16-byte buffer
/// round-trip was pure overhead — this is where the big wins are. The 8/16-byte
/// widths keep the buffer path: there it is already a single wide load, so a
/// native read only adds a length-check branch with nothing to gain.
#[inline(always)]
pub(crate) fn le_unsigned(chunk: &[u8], elem_size: usize) -> u128 {
    match elem_size {
        1 => chunk[0] as u128,
        2 => u16::from_le_bytes(chunk.try_into().unwrap()) as u128,
        4 => u32::from_le_bytes(chunk.try_into().unwrap()) as u128,
        _ => {
            let mut buf = [0u8; 16];
            buf[..elem_size].copy_from_slice(chunk);
            u128::from_le_bytes(buf)
        }
    }
}

/// Signed twin of [`le_unsigned`]: widen `elem_size` little-endian bytes to
/// `i128`. Native-width reads sign-extend with a single `as` cast, replacing the
/// per-element conditional sign-fill the buffer path used — the dominant cost of
/// the old signed path, so every width benefits (the 16-byte case needs no
/// extension).
#[inline(always)]
pub(crate) fn le_signed(chunk: &[u8], elem_size: usize) -> i128 {
    match elem_size {
        1 => (chunk[0] as i8) as i128,
        2 => i16::from_le_bytes(chunk.try_into().unwrap()) as i128,
        4 => i32::from_le_bytes(chunk.try_into().unwrap()) as i128,
        8 => i64::from_le_bytes(chunk.try_into().unwrap()) as i128,
        16 => i128::from_le_bytes(chunk.try_into().unwrap()),
        // Unreachable for BEVE widths; kept correct for robustness.
        _ => {
            let mut buf = [0u8; 16];
            buf[..elem_size].copy_from_slice(chunk);
            if elem_size < 16 && (chunk[elem_size - 1] & 0x80) != 0 {
                for b in &mut buf[elem_size..] {
                    *b = 0xFF;
                }
            }
            i128::from_le_bytes(buf)
        }
    }
}

struct SeqAccessUnsigned<'de> {
    data: &'de [u8],
    remaining: usize,
    elem_size: usize,
    offset: usize,
}
impl<'de> de::SeqAccess<'de> for SeqAccessUnsigned<'de> {
    type Error = Error;
    fn next_element_seed<T: de::DeserializeSeed<'de>>(
        &mut self,
        seed: T,
    ) -> Result<Option<T::Value>> {
        if self.remaining == 0 {
            return Ok(None);
        }
        self.remaining -= 1;
        debug_assert!(self.offset + self.elem_size <= self.data.len());
        let chunk = &self.data[self.offset..self.offset + self.elem_size];
        self.offset += self.elem_size;
        let v = le_unsigned(chunk, self.elem_size);
        seed.deserialize(NumDe::Unsigned(v)).map(Some)
    }
    fn size_hint(&self) -> Option<usize> {
        Some(self.remaining)
    }
}

struct SeqAccessSigned<'de> {
    data: &'de [u8],
    remaining: usize,
    elem_size: usize,
    offset: usize,
}
impl<'de> de::SeqAccess<'de> for SeqAccessSigned<'de> {
    type Error = Error;
    fn next_element_seed<T: de::DeserializeSeed<'de>>(
        &mut self,
        seed: T,
    ) -> Result<Option<T::Value>> {
        if self.remaining == 0 {
            return Ok(None);
        }
        self.remaining -= 1;
        debug_assert!(self.offset + self.elem_size <= self.data.len());
        let chunk = &self.data[self.offset..self.offset + self.elem_size];
        self.offset += self.elem_size;
        let v = le_signed(chunk, self.elem_size);
        seed.deserialize(NumDe::Signed(v)).map(Some)
    }
    fn size_hint(&self) -> Option<usize> {
        Some(self.remaining)
    }
}

struct SeqAccessHalf<'de> {
    data: &'de [u8],
    remaining: usize,
    offset: usize,
    kind: HalfKind,
}
impl<'de> de::SeqAccess<'de> for SeqAccessHalf<'de> {
    type Error = Error;
    fn next_element_seed<T: de::DeserializeSeed<'de>>(
        &mut self,
        seed: T,
    ) -> Result<Option<T::Value>> {
        if self.remaining == 0 {
            return Ok(None);
        }
        self.remaining -= 1;
        debug_assert!(self.offset + 2 <= self.data.len());
        let chunk = &self.data[self.offset..self.offset + 2];
        self.offset += 2;
        let bits = u16::from_le_bytes([chunk[0], chunk[1]]);
        let deser = NumDe::Half(self.kind, bits);
        seed.deserialize(deser).map(Some)
    }
    fn size_hint(&self) -> Option<usize> {
        Some(self.remaining)
    }
}

struct SeqAccessFloat32<'de> {
    data: &'de [u8],
    remaining: usize,
    offset: usize,
}
impl<'de> de::SeqAccess<'de> for SeqAccessFloat32<'de> {
    type Error = Error;
    fn next_element_seed<T: de::DeserializeSeed<'de>>(
        &mut self,
        seed: T,
    ) -> Result<Option<T::Value>> {
        if self.remaining == 0 {
            return Ok(None);
        }
        self.remaining -= 1;
        debug_assert!(self.offset + 4 <= self.data.len());
        let mut buf = [0u8; 4];
        buf.copy_from_slice(&self.data[self.offset..self.offset + 4]);
        self.offset += 4;
        let v = f32::from_le_bytes(buf);
        let deser = NumDe::F32(v);
        seed.deserialize(deser).map(Some)
    }
    fn size_hint(&self) -> Option<usize> {
        Some(self.remaining)
    }
}

struct SeqAccessFloat64<'de> {
    data: &'de [u8],
    remaining: usize,
    offset: usize,
}
impl<'de> de::SeqAccess<'de> for SeqAccessFloat64<'de> {
    type Error = Error;
    fn next_element_seed<T: de::DeserializeSeed<'de>>(
        &mut self,
        seed: T,
    ) -> Result<Option<T::Value>> {
        if self.remaining == 0 {
            return Ok(None);
        }
        self.remaining -= 1;
        debug_assert!(self.offset + 8 <= self.data.len());
        let mut buf = [0u8; 8];
        buf.copy_from_slice(&self.data[self.offset..self.offset + 8]);
        self.offset += 8;
        let v = f64::from_le_bytes(buf);
        let deser = NumDe::F64(v);
        seed.deserialize(deser).map(Some)
    }
    fn size_hint(&self) -> Option<usize> {
        Some(self.remaining)
    }
}

struct SeqAccessBool<'de> {
    data: &'de [u8],
    remaining: usize,
    byte_idx: usize,
    bit_idx: u8,
}
impl<'de> de::SeqAccess<'de> for SeqAccessBool<'de> {
    type Error = Error;
    fn next_element_seed<T: de::DeserializeSeed<'de>>(
        &mut self,
        seed: T,
    ) -> Result<Option<T::Value>> {
        if self.remaining == 0 {
            return Ok(None);
        }
        let current = self.data[self.byte_idx];
        // LSB-first: bit 0 maps to the first element in the byte
        let bit = (current >> self.bit_idx) & 1;
        self.bit_idx += 1;
        if self.bit_idx == 8 {
            self.bit_idx = 0;
            self.byte_idx += 1;
        }
        self.remaining -= 1;
        seed.deserialize(BoolDeserializer::new(bit != 0)).map(Some)
    }
    fn size_hint(&self) -> Option<usize> {
        Some(self.remaining)
    }
}

struct SeqAccessString<'a, 'de> {
    de: &'a mut Deserializer<'de>,
    remaining: usize,
}
impl<'de, 'a> de::SeqAccess<'de> for SeqAccessString<'a, 'de> {
    type Error = Error;
    fn next_element_seed<T: de::DeserializeSeed<'de>>(
        &mut self,
        seed: T,
    ) -> Result<Option<T::Value>> {
        if self.remaining == 0 {
            return Ok(None);
        }
        let s = self.de.parse_string_borrowed()?;
        self.remaining -= 1;
        seed.deserialize(BorrowedStrDeserializer::new(s)).map(Some)
    }
    fn size_hint(&self) -> Option<usize> {
        Some(self.remaining)
    }
}

// =============== MapAccess implementations ===============

struct MapAccessString<'a, 'de> {
    de: &'a mut Deserializer<'de>,
    remaining: usize,
}
impl<'de, 'a> de::MapAccess<'de> for MapAccessString<'a, 'de> {
    type Error = Error;
    fn next_key_seed<K: de::DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>> {
        if self.remaining == 0 {
            return Ok(None);
        }
        let key_len = read_size(self.de.input, &mut self.de.pos)? as usize;
        let key_bytes = self.de.read_exact(key_len)?;
        let key = decode_utf8(key_bytes, "invalid utf-8 in key")?;
        seed.deserialize(BorrowedStrDeserializer::new(key))
            .map(Some)
    }
    fn next_value_seed<V: de::DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value> {
        self.remaining -= 1;
        seed.deserialize(&mut *self.de)
    }
}

// =============== Complex Extension Helpers ===============

struct ComplexPairAccess<'a, 'de> {
    de: &'a mut Deserializer<'de>,
    class: u8,
    byte_code: u8,
    state: u8,
}
impl<'de, 'a> de::SeqAccess<'de> for ComplexPairAccess<'a, 'de> {
    type Error = Error;
    fn next_element_seed<T: de::DeserializeSeed<'de>>(
        &mut self,
        seed: T,
    ) -> Result<Option<T::Value>> {
        if self.state >= 2 {
            return Ok(None);
        }
        self.state += 1;
        let deser = match self.class {
            NUM_FLOAT => match self.byte_code {
                0 => NumDe::Half(HalfKind::Bf16, self.de.parse_bf16_bits()?),
                1 => NumDe::Half(HalfKind::F16, self.de.parse_f16_bits()?),
                2 => NumDe::F32(self.de.parse_f32()?),
                3 => NumDe::F64(self.de.parse_f64()?),
                _ => return Err(Error::Unsupported("unsupported complex float width")),
            },
            NUM_SIGNED => NumDe::Signed(self.de.parse_signed(self.byte_code)?),
            NUM_UNSIGNED => NumDe::Unsigned(self.de.parse_unsigned(self.byte_code)?),
            _ => return Err(Error::Unsupported("unsupported complex number class")),
        };
        seed.deserialize(deser).map(Some)
    }
    fn size_hint(&self) -> Option<usize> {
        Some((2 - self.state) as usize)
    }
}

struct SeqAccessComplexArray<'a, 'de> {
    de: &'a mut Deserializer<'de>,
    remaining: usize,
    class: u8,
    byte_code: u8,
}
impl<'de, 'a> de::SeqAccess<'de> for SeqAccessComplexArray<'a, 'de> {
    type Error = Error;
    fn next_element_seed<T: de::DeserializeSeed<'de>>(
        &mut self,
        seed: T,
    ) -> Result<Option<T::Value>> {
        if self.remaining == 0 {
            return Ok(None);
        }
        self.remaining -= 1;
        let delem = ComplexElemDe {
            de: self.de,
            class: self.class,
            byte_code: self.byte_code,
        };
        seed.deserialize(delem).map(Some)
    }
    fn size_hint(&self) -> Option<usize> {
        Some(self.remaining)
    }
}

struct ComplexElemDe<'a, 'de> {
    de: &'a mut Deserializer<'de>,
    class: u8,
    byte_code: u8,
}
impl<'de, 'a> de::Deserializer<'de> for ComplexElemDe<'a, 'de> {
    type Error = Error;
    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        visitor.visit_seq(ComplexPairAccess {
            de: self.de,
            class: self.class,
            byte_code: self.byte_code,
            state: 0,
        })
    }
    fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    fn deserialize_tuple<V: Visitor<'de>>(self, _len: usize, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    forward_to_deserialize_any! {
        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit unit_struct newtype_struct tuple_struct map struct enum identifier ignored_any
    }
}

// =============== Matrix Extension Helper ===============

struct MatrixAccess<'a, 'de> {
    de: &'a mut Deserializer<'de>,
    step: u8,
    mheader: u8,
}
impl<'de, 'a> de::MapAccess<'de> for MatrixAccess<'a, 'de> {
    type Error = Error;
    fn next_key_seed<K: de::DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>> {
        let key = match self.step {
            0 => "layout",
            1 => "extents",
            2 => "value",
            _ => return Ok(None),
        };
        self.step += 1;
        seed.deserialize(BorrowedStrDeserializer::new(key))
            .map(Some)
    }
    fn next_value_seed<V: de::DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value> {
        match self.step - 1 {
            0 => {
                let layout = if (self.mheader & 0x01) == 0 {
                    "layout_right"
                } else {
                    "layout_left"
                };
                seed.deserialize(BorrowedStrDeserializer::new(layout))
            }
            1 => {
                // extents as typed integer array (signed or unsigned)
                let h = self.de.read_byte()?;
                let len = read_size(self.de.input, &mut self.de.pos)? as usize;
                match h {
                    // Unsigned arrays
                    0x14 => seed.deserialize(SeqArrayDeUnsigned {
                        de: self.de,
                        len,
                        byte_code: 0,
                    }),
                    0x34 => seed.deserialize(SeqArrayDeUnsigned {
                        de: self.de,
                        len,
                        byte_code: 1,
                    }),
                    0x54 => seed.deserialize(SeqArrayDeUnsigned {
                        de: self.de,
                        len,
                        byte_code: 2,
                    }),
                    0x74 => seed.deserialize(SeqArrayDeUnsigned {
                        de: self.de,
                        len,
                        byte_code: 3,
                    }),
                    // Signed arrays
                    0x0c => seed.deserialize(SeqArrayDeSigned {
                        de: self.de,
                        len,
                        byte_code: 0,
                    }),
                    0x2c => seed.deserialize(SeqArrayDeSigned {
                        de: self.de,
                        len,
                        byte_code: 1,
                    }),
                    0x4c => seed.deserialize(SeqArrayDeSigned {
                        de: self.de,
                        len,
                        byte_code: 2,
                    }),
                    0x6c => seed.deserialize(SeqArrayDeSigned {
                        de: self.de,
                        len,
                        byte_code: 3,
                    }),
                    _ => Err(Error::InvalidHeader(h)),
                }
            }
            2 => {
                // value: just delegate to underlying deserializer at current position
                seed.deserialize(&mut *self.de)
            }
            _ => unreachable!(),
        }
    }
}

struct SeqArrayDeUnsigned<'a, 'de> {
    de: &'a mut Deserializer<'de>,
    len: usize,
    byte_code: u8,
}
impl<'de, 'a> de::Deserializer<'de> for SeqArrayDeUnsigned<'a, 'de> {
    type Error = Error;
    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        let access = make_seq_unsigned(self.de, self.len, self.byte_code)?;
        visitor.visit_seq(access)
    }
    fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    forward_to_deserialize_any! { bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit unit_struct newtype_struct tuple tuple_struct map struct enum identifier ignored_any }
}

struct SeqArrayDeSigned<'a, 'de> {
    de: &'a mut Deserializer<'de>,
    len: usize,
    byte_code: u8,
}
impl<'de, 'a> de::Deserializer<'de> for SeqArrayDeSigned<'a, 'de> {
    type Error = Error;
    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        let access = make_seq_signed(self.de, self.len, self.byte_code)?;
        visitor.visit_seq(access)
    }
    fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        self.deserialize_any(visitor)
    }
    forward_to_deserialize_any! { bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit unit_struct newtype_struct tuple tuple_struct map struct enum identifier ignored_any }
}

struct MapAccessSigned<'a, 'de> {
    de: &'a mut Deserializer<'de>,
    remaining: usize,
    byte_code: u8,
}
impl<'de, 'a> de::MapAccess<'de> for MapAccessSigned<'a, 'de> {
    type Error = Error;
    fn next_key_seed<K: de::DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>> {
        if self.remaining == 0 {
            return Ok(None);
        }
        let v = self.de.parse_signed(self.byte_code)?;
        seed.deserialize(NumDe::Signed(v)).map(Some)
    }
    fn next_value_seed<V: de::DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value> {
        self.remaining -= 1;
        seed.deserialize(&mut *self.de)
    }
}

struct MapAccessUnsigned<'a, 'de> {
    de: &'a mut Deserializer<'de>,
    remaining: usize,
    byte_code: u8,
}
impl<'de, 'a> de::MapAccess<'de> for MapAccessUnsigned<'a, 'de> {
    type Error = Error;
    fn next_key_seed<K: de::DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>> {
        if self.remaining == 0 {
            return Ok(None);
        }
        let v = self.de.parse_unsigned(self.byte_code)?;
        seed.deserialize(NumDe::Unsigned(v)).map(Some)
    }
    fn next_value_seed<V: de::DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value> {
        self.remaining -= 1;
        seed.deserialize(&mut *self.de)
    }
}

// =============== EnumAccess ===============

enum EnumTag<'de> {
    Index(u64),
    Name(&'de str),
}

/// Access for a variant whose wire form is followed by exactly one value.
///
/// Both forms that reach here carry a payload, so the count never has to be
/// guessed. A Version 2 variant is a single-key object whose header declared
/// `count == 1`. Version 1's type-tag extension always paired the tag with a
/// value too, including for a unit variant, which was written as the tag plus an
/// explicit `null`. The forms that genuinely carry no payload, a bare positional
/// index and a bare name, go to [`VariantAccessNoValue`] instead and never
/// construct this.
///
/// That is why `unit_variant` can consume unconditionally. Guessing from "are
/// there bytes left" would read a sibling as a payload.
struct EnumAccess<'a, 'de> {
    de: &'a mut Deserializer<'de>,
    tag: EnumTag<'de>,
}
impl<'de, 'a> de::EnumAccess<'de> for EnumAccess<'a, 'de> {
    type Error = Error;
    type Variant = VariantAccess<'a, 'de>;

    fn variant_seed<V: de::DeserializeSeed<'de>>(
        self,
        seed: V,
    ) -> Result<(V::Value, Self::Variant)> {
        match self.tag {
            EnumTag::Index(idx) => {
                let idx_de = NumDe::Unsigned(idx as u128);
                let v = seed.deserialize(idx_de)?;
                Ok((v, VariantAccess { de: self.de }))
            }
            EnumTag::Name(name) => {
                let v = seed.deserialize(BorrowedStrDeserializer::<Error>::new(name))?;
                Ok((v, VariantAccess { de: self.de }))
            }
        }
    }
}

struct VariantAccess<'a, 'de> {
    de: &'a mut Deserializer<'de>,
}
impl<'de, 'a> de::VariantAccess<'de> for VariantAccess<'a, 'de> {
    type Error = Error;
    fn unit_variant(self) -> Result<()> {
        // A value always follows here (see the note on `EnumAccess`), so discard
        // exactly one and let a truncated or malformed payload surface:
        // swallowing the error would leave the cursor mid-value and corrupt
        // every later read.
        serde::de::Deserializer::deserialize_ignored_any(self.de, de::IgnoredAny)?;
        Ok(())
    }
    fn newtype_variant_seed<T: de::DeserializeSeed<'de>>(self, seed: T) -> Result<T::Value> {
        seed.deserialize(self.de)
    }
    fn tuple_variant<V: Visitor<'de>>(self, _len: usize, visitor: V) -> Result<V::Value> {
        de::Deserializer::deserialize_any(self.de, visitor)
    }
    fn struct_variant<V: Visitor<'de>>(
        self,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value> {
        de::Deserializer::deserialize_any(self.de, visitor)
    }
}

pub(crate) struct EnumIndexAccess {
    pub(crate) idx: u64,
}
impl<'de> de::EnumAccess<'de> for EnumIndexAccess {
    type Error = Error;
    type Variant = VariantAccessNoValue;
    fn variant_seed<V: de::DeserializeSeed<'de>>(
        self,
        seed: V,
    ) -> Result<(V::Value, Self::Variant)> {
        let v = seed.deserialize(NumDe::Unsigned(self.idx as u128))?;
        Ok((v, VariantAccessNoValue))
    }
}

struct EnumStrAccess<'de> {
    name: &'de str,
}
impl<'de> de::EnumAccess<'de> for EnumStrAccess<'de> {
    type Error = Error;
    type Variant = VariantAccessNoValue;
    fn variant_seed<V: de::DeserializeSeed<'de>>(
        self,
        seed: V,
    ) -> Result<(V::Value, Self::Variant)> {
        let v = seed.deserialize(BorrowedStrDeserializer::<Error>::new(self.name))?;
        Ok((v, VariantAccessNoValue))
    }
}

pub(crate) struct VariantAccessNoValue;
impl<'de> de::VariantAccess<'de> for VariantAccessNoValue {
    type Error = Error;
    fn unit_variant(self) -> Result<()> {
        Ok(())
    }
    fn newtype_variant_seed<T: de::DeserializeSeed<'de>>(self, _seed: T) -> Result<T::Value> {
        Err(Error::InvalidType("enum value not present"))
    }
    fn tuple_variant<V: Visitor<'de>>(self, _len: usize, _visitor: V) -> Result<V::Value> {
        Err(Error::InvalidType("enum value not present"))
    }
    fn struct_variant<V: Visitor<'de>>(
        self,
        _fields: &'static [&'static str],
        _visitor: V,
    ) -> Result<V::Value> {
        Err(Error::InvalidType("enum value not present"))
    }
}

// =============== Primitive Value Deserializers ===============

pub(crate) enum NumDe {
    Unsigned(u128),
    Signed(i128),
    F32(f32),
    F64(f64),
    Half(HalfKind, u16),
}
impl<'de> de::Deserializer<'de> for NumDe {
    type Error = Error;
    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        match self {
            NumDe::Unsigned(u) => {
                if u <= u8::MAX as u128 {
                    visitor.visit_u8(u as u8)
                } else if u <= u16::MAX as u128 {
                    visitor.visit_u16(u as u16)
                } else if u <= u32::MAX as u128 {
                    visitor.visit_u32(u as u32)
                } else if u <= u64::MAX as u128 {
                    visitor.visit_u64(u as u64)
                } else {
                    visitor.visit_u128(u)
                }
            }
            NumDe::Signed(i) => {
                if i >= i8::MIN as i128 && i <= i8::MAX as i128 {
                    visitor.visit_i8(i as i8)
                } else if i >= i16::MIN as i128 && i <= i16::MAX as i128 {
                    visitor.visit_i16(i as i16)
                } else if i >= i32::MIN as i128 && i <= i32::MAX as i128 {
                    visitor.visit_i32(i as i32)
                } else if i >= i64::MIN as i128 && i <= i64::MAX as i128 {
                    visitor.visit_i64(i as i64)
                } else {
                    visitor.visit_i128(i)
                }
            }
            NumDe::F32(f) => visitor.visit_f32(f),
            NumDe::F64(f) => visitor.visit_f64(f),
            NumDe::Half(kind, bits) => visitor.visit_f32(kind.to_f32(bits)),
        }
    }
    fn deserialize_u8<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        match self {
            NumDe::Unsigned(u) if u <= u8::MAX as u128 => visitor.visit_u8(u as u8),
            NumDe::Signed(i) if i >= 0 && i <= u8::MAX as i128 => visitor.visit_u8(i as u8),
            _ => Err(Error::Mismatch("expected u8")),
        }
    }
    fn deserialize_u16<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        match self {
            NumDe::Unsigned(u) if u <= u16::MAX as u128 => visitor.visit_u16(u as u16),
            NumDe::Signed(i) if i >= 0 && i <= u16::MAX as i128 => visitor.visit_u16(i as u16),
            NumDe::Half(_, bits) => visitor.visit_u16(bits),
            _ => Err(Error::Mismatch("expected u16")),
        }
    }
    fn deserialize_u32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        match self {
            NumDe::Unsigned(u) if u <= u32::MAX as u128 => visitor.visit_u32(u as u32),
            NumDe::Signed(i) if i >= 0 && i <= u32::MAX as i128 => visitor.visit_u32(i as u32),
            _ => Err(Error::Mismatch("expected u32")),
        }
    }
    fn deserialize_u64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        match self {
            NumDe::Unsigned(u) if u <= u64::MAX as u128 => visitor.visit_u64(u as u64),
            NumDe::Signed(i) if i >= 0 && i <= u64::MAX as i128 => visitor.visit_u64(i as u64),
            _ => Err(Error::Mismatch("expected u64")),
        }
    }
    fn deserialize_u128<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        match self {
            NumDe::Unsigned(u) => visitor.visit_u128(u),
            NumDe::Signed(i) if i >= 0 => visitor.visit_u128(i as u128),
            _ => Err(Error::Mismatch("expected u128")),
        }
    }
    fn deserialize_i8<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        match self {
            NumDe::Signed(i) if i >= i8::MIN as i128 && i <= i8::MAX as i128 => {
                visitor.visit_i8(i as i8)
            }
            NumDe::Unsigned(u) if u <= i8::MAX as u128 => visitor.visit_i8(u as i8),
            _ => Err(Error::Mismatch("expected i8")),
        }
    }
    fn deserialize_i16<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        match self {
            NumDe::Signed(i) if i >= i16::MIN as i128 && i <= i16::MAX as i128 => {
                visitor.visit_i16(i as i16)
            }
            NumDe::Unsigned(u) if u <= i16::MAX as u128 => visitor.visit_i16(u as i16),
            _ => Err(Error::Mismatch("expected i16")),
        }
    }
    fn deserialize_i32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        match self {
            NumDe::Signed(i) if i >= i32::MIN as i128 && i <= i32::MAX as i128 => {
                visitor.visit_i32(i as i32)
            }
            NumDe::Unsigned(u) if u <= i32::MAX as u128 => visitor.visit_i32(u as i32),
            _ => Err(Error::Mismatch("expected i32")),
        }
    }
    fn deserialize_i64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        match self {
            NumDe::Signed(i) if i >= i64::MIN as i128 && i <= i64::MAX as i128 => {
                visitor.visit_i64(i as i64)
            }
            NumDe::Unsigned(u) if u <= i64::MAX as u128 => visitor.visit_i64(u as i64),
            _ => Err(Error::Mismatch("expected i64")),
        }
    }
    fn deserialize_i128<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        match self {
            NumDe::Signed(i) => visitor.visit_i128(i),
            NumDe::Unsigned(u) if u <= i128::MAX as u128 => visitor.visit_i128(u as i128),
            _ => Err(Error::Mismatch("expected i128")),
        }
    }
    fn deserialize_f32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        match self {
            NumDe::F32(f) => visitor.visit_f32(f),
            NumDe::F64(f) => visitor.visit_f32(f as f32),
            NumDe::Signed(i) => visitor.visit_f32(i as f32),
            NumDe::Unsigned(u) => visitor.visit_f32(u as f32),
            NumDe::Half(kind, bits) => visitor.visit_f32(kind.to_f32(bits)),
        }
    }
    fn deserialize_f64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        match self {
            NumDe::F64(f) => visitor.visit_f64(f),
            NumDe::F32(f) => visitor.visit_f64(f as f64),
            NumDe::Signed(i) => visitor.visit_f64(i as f64),
            NumDe::Unsigned(u) => visitor.visit_f64(u as f64),
            NumDe::Half(kind, bits) => visitor.visit_f64(kind.to_f64(bits)),
        }
    }

    fn deserialize_newtype_struct<V: Visitor<'de>>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> Result<V::Value> {
        match self {
            NumDe::Half(kind, bits) => {
                let deser = HalfBitsDeserializer { kind, bits };
                visitor.visit_newtype_struct(deser)
            }
            _ => self.deserialize_any(visitor),
        }
    }

    forward_to_deserialize_any! {
        bool char str string bytes byte_buf option unit unit_struct seq tuple tuple_struct map struct enum identifier ignored_any
    }
}

pub(crate) struct HalfBitsDeserializer {
    pub(crate) kind: HalfKind,
    pub(crate) bits: u16,
}
impl<'de> de::Deserializer<'de> for HalfBitsDeserializer {
    type Error = Error;

    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        visitor.visit_f32(self.kind.to_f32(self.bits))
    }

    fn deserialize_u16<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        visitor.visit_u16(self.bits)
    }

    fn deserialize_f32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        visitor.visit_f32(self.kind.to_f32(self.bits))
    }

    fn deserialize_f64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
        visitor.visit_f64(self.kind.to_f64(self.bits))
    }

    fn deserialize_newtype_struct<V: Visitor<'de>>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> Result<V::Value> {
        visitor.visit_newtype_struct(self)
    }

    forward_to_deserialize_any! {
        bool i8 i16 i32 i64 i128 u8 u32 u64 u128 char str string bytes byte_buf option unit unit_struct seq tuple tuple_struct map struct enum identifier ignored_any
    }

    fn is_human_readable(&self) -> bool {
        false
    }
}

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

    /// `complex_array_plan` asks `complex_widening_supported` whether to bulk-read
    /// a payload, and the decoder then calls `widen_complex_components` on what it
    /// read. If those two ever disagree, a decode that should have gone
    /// element-wise instead consumes the payload and errors out with no way back
    /// (the streaming decoder cannot rewind). Nothing about the pair list forces
    /// them to agree, so this walks every encodable combination.
    #[test]
    fn widening_predicate_matches_the_converter() {
        for src_class in 0u8..4 {
            for src_bc in 0u8..8 {
                for dst_class in 0u8..4 {
                    for dst_bc in 0u8..8 {
                        let predicted =
                            complex_widening_supported(src_class, src_bc, dst_class, dst_bc);
                        let converts =
                            widen_complex_components(&[], src_class, src_bc, dst_class, dst_bc)
                                .is_some();
                        assert_eq!(
                            predicted, converts,
                            "disagreement at src=({src_class},{src_bc}) dst=({dst_class},{dst_bc})"
                        );
                    }
                }
            }
        }
    }

    /// The converter writes the destination width for every component it reads,
    /// so an output buffer is `len * 2 * size_of::<dst>()` however wide the
    /// source was. A half-float source is the one that catches a generic
    /// `1 << byte_code` width rule (see `header::complex_component_bytes`).
    #[test]
    fn widened_output_is_sized_by_the_destination_not_the_source() {
        // Compared as bytes rather than decoded back, which also pins the output
        // to little-endian: `bytes_to_vec` byte-swaps on a big-endian target on
        // the assumption that every payload reaching it is LE, so a converter
        // writing native order would be wrong only there.
        let le = |v: &[f32]| -> Vec<u8> { v.iter().flat_map(|f| f.to_le_bytes()).collect() };

        // Four i16 components (two complex values) -> four f32 components.
        let src = [1i16, 2, 3, 4]
            .iter()
            .flat_map(|v| v.to_le_bytes())
            .collect::<Vec<u8>>();
        let out = widen_complex_components(&src, NUM_SIGNED, 1, NUM_FLOAT, 2).expect("supported");
        assert_eq!(out, le(&[1.0, 2.0, 3.0, 4.0]));

        // bf16 components are 2 bytes at byte_code 0, where `1 << 0` would say 1.
        let bits = half::bf16::from_f32(-1.5).to_bits();
        let src: Vec<u8> = (0..4).flat_map(|_| bits.to_le_bytes()).collect();
        let out = widen_complex_components(&src, NUM_FLOAT, 0, NUM_FLOAT, 2).expect("supported");
        assert_eq!(out, le(&[-1.5; 4]));
    }
}