pack-io 2.1.0

Compact binary wire format with schema evolution and zero-copy deserialization for Rust. The serialization substrate under network-protocol and Hive DB.
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
//! `Serialize` / `Deserialize` implementations for primitive, container, and
//! collection types.
//!
//! ## Wire format (full reference: [`docs/WIRE_FORMAT.md`])
//!
//! - `u8` / `i8` — one byte each (fixed). `i8` is two's-complement.
//! - `u16` / `u32` / `u64` / `u128` / `usize` — LEB128 varint. `usize` is
//!   encoded through `u64`; on a 32-bit target a decoded value outside
//!   `usize::MAX` is rejected with [`SerialError::IntegerOutOfRange`].
//! - `i16` / `i32` / `i64` / `i128` / `isize` — ZigZag mapping followed by
//!   LEB128 varint.
//! - `bool` — one byte (`0x00` / `0x01`); any other byte is rejected.
//! - `f32` / `f64` — IEEE 754 bit pattern, little-endian. NaN, ±Inf,
//!   subnormals, and signed zeros all round-trip bit-for-bit.
//! - `char` — the Unicode scalar value as a `u32` varint; surrogates and
//!   values above `0x10FFFF` are rejected.
//! - `String` / `&str` — varint length prefix, then UTF-8 bytes.
//! - `[T; N]` — `N` consecutive `T` encodings, no length prefix (the length
//!   is in the type).
//! - `Vec<T>` / `&[T]` / `VecDeque<T>` — varint length prefix, then `len`
//!   consecutive `T` encodings.
//! - tuples (arity 1..=12) — fields concatenated in declaration order.
//! - `Option<T>` — one tag byte (`0x00` = `None`, `0x01` = `Some`) followed
//!   by the inner value when present.
//! - `Result<T, E>` — one tag byte (`0x00` = `Ok`, `0x01` = `Err`) followed
//!   by the inner value.
//! - `()` and `PhantomData<T>` — zero bytes.
//! - `NonZero*` — the same bytes as the underlying integer; zero is rejected.
//! - `Duration` — `varint(secs: u64) ++ varint(nanos: u32)`, nanos `< 10^9`.
//! - `Box<T>` (including `Box<str>`, `Box<[T]>`), `Rc<T>`, `Arc<T>`,
//!   `Cow<'_, T>` — transparent:
//!   the same bytes as the value they hold.
//! - `BTreeMap` / `BTreeSet` / `HashMap` / `HashSet` — varint count followed
//!   by the entries sorted lexicographically by their **encoded key bytes**.
//!   This canonical ordering means a `HashMap` and a `BTreeMap` holding the
//!   same logical data encode to the same bytes, regardless of insertion
//!   order or build-flag-dependent hash randomisation.
//!
//! [`docs/WIRE_FORMAT.md`]: https://github.com/jamesgober/pack-io/blob/main/docs/WIRE_FORMAT.md

use alloc::borrow::{Cow, ToOwned};
use alloc::boxed::Box;
use alloc::collections::{BTreeMap, BTreeSet, VecDeque};
use alloc::rc::Rc;
use alloc::string::String;
#[cfg(target_has_atomic = "ptr")]
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::marker::PhantomData;
use core::num::{
    NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize, NonZeroU8,
    NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize,
};
use core::time::Duration;
#[cfg(feature = "std")]
use std::collections::{HashMap, HashSet};
#[cfg(feature = "std")]
use std::hash::{BuildHasher, Hash};

use crate::codec::read_varint_u64_with;
use crate::codec::{
    Decode, Encode, Encoder, decode_elements_counted, guard_element_count, varint_len,
};
use crate::codec::{charge_boxed, charge_elements, initial_capacity};
use crate::error::{Result, SerialError};
use crate::traits::{Deserialize, Serialize};
use crate::varint;

/// `Deserialize::deserialize_many` for an integer encoded as a `u64`
/// varint and converted with `$convert`.
///
/// The canonical flag is read once per collection and the element loop
/// calls a varint reader specialised for it, so a lenient decode of an
/// integer array runs the plain 1.0 varint loop with no per-element check
/// (re-audit PACK-R04). Every element consumes at least one input byte, so
/// the loop needs no accounting for free elements either.
macro_rules! varint_many {
    ($convert:expr) => {
        #[inline]
        fn deserialize_many<D: Decode + ?Sized>(
            decoder: &mut D,
            count: usize,
        ) -> Result<Vec<Self>> {
            let mut out = Vec::with_capacity(initial_capacity::<Self, D>(count, decoder));
            if decoder.config().canonical {
                for _ in 0..count {
                    out.push($convert(read_varint_u64_with::<D, true>(decoder)?)?);
                }
            } else {
                for _ in 0..count {
                    out.push($convert(read_varint_u64_with::<D, false>(decoder)?)?);
                }
            }
            Ok(out)
        }
    };
}

/// `Deserialize::deserialize_array` for a `Copy` primitive: fill a
/// stack array initialised with `$zero`, so `[T; N]` decodes without a
/// temporary heap `Vec`.
macro_rules! stack_array {
    ($zero:expr) => {
        #[inline]
        fn deserialize_array<D: Decode + ?Sized, const N: usize>(
            decoder: &mut D,
        ) -> Result<[Self; N]> {
            let mut out = [$zero; N];
            for slot in &mut out {
                *slot = Self::deserialize(decoder)?;
            }
            Ok(out)
        }
    };
}

// ---------------------------------------------------------------------------
// Unsigned integers
// ---------------------------------------------------------------------------

impl Serialize for u8 {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encoder.write_byte(*self)
    }

    /// Single bulk write — bypasses the per-element loop the default impl
    /// would emit. For an in-memory [`crate::Encoder`] this compiles to a
    /// single `Vec::extend_from_slice`; for `IoEncoder` it is one
    /// `Write::write_all`. Either way it replaces N per-byte calls with a
    /// memcpy.
    #[inline]
    fn serialize_slice<E: Encode + ?Sized>(slice: &[u8], encoder: &mut E) -> Result<()> {
        encoder.write_bytes(slice)
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(1)
    }

    #[inline]
    fn encoded_len_slice(slice: &[u8]) -> Result<usize> {
        Ok(slice.len())
    }
}

impl Deserialize for u8 {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        decoder.read_byte()
    }

    /// Single bulk read. For an in-memory [`crate::Decoder`] this is a
    /// bounds check plus one copy of exactly `count` bytes; a `count` the
    /// input cannot back is refused before anything is allocated. For
    /// `IoDecoder` the buffer grows in bounded chunks as bytes
    /// arrive, so a hostile count over a short stream costs one chunk.
    #[inline]
    fn deserialize_many<D: Decode + ?Sized>(decoder: &mut D, count: usize) -> Result<Vec<u8>> {
        decoder.read_byte_cow(count).map(Cow::into_owned)
    }

    /// `[u8; N]` decodes with one read into a stack array — no heap.
    #[inline]
    fn deserialize_array<D: Decode + ?Sized, const N: usize>(decoder: &mut D) -> Result<[u8; N]> {
        let mut out = [0u8; N];
        decoder.read_into(&mut out)?;
        Ok(out)
    }
}

impl Serialize for u16 {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encoder.write_varint_u64(u64::from(*self))
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(varint_len(u64::from(*self)))
    }
}

impl Deserialize for u16 {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        let value = decoder.read_varint_u64()?;
        u16::try_from(value).map_err(|_| SerialError::IntegerOutOfRange)
    }

    stack_array!(0);

    varint_many!(|v: u64| u16::try_from(v).map_err(|_| SerialError::IntegerOutOfRange));
}

impl Serialize for u32 {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encoder.write_varint_u64(u64::from(*self))
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(varint_len(u64::from(*self)))
    }
}

impl Deserialize for u32 {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        let value = decoder.read_varint_u64()?;
        u32::try_from(value).map_err(|_| SerialError::IntegerOutOfRange)
    }

    stack_array!(0);

    varint_many!(|v: u64| u32::try_from(v).map_err(|_| SerialError::IntegerOutOfRange));
}

impl Serialize for u64 {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encoder.write_varint_u64(*self)
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(varint_len(*self))
    }
}

impl Deserialize for u64 {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        decoder.read_varint_u64()
    }

    stack_array!(0);

    varint_many!(|v: u64| -> Result<u64> { Ok(v) });
}

impl Serialize for u128 {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encoder.write_varint_u128(*self)
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(varint::len_u128(*self))
    }
}

impl Deserialize for u128 {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        decoder.read_varint_u128()
    }

    stack_array!(0);
}

impl Serialize for usize {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encoder.write_varint_u64(*self as u64)
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(varint_len(*self as u64))
    }
}

impl Deserialize for usize {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        let value = decoder.read_varint_u64()?;
        usize::try_from(value).map_err(|_| SerialError::IntegerOutOfRange)
    }

    stack_array!(0);

    varint_many!(|v: u64| usize::try_from(v).map_err(|_| SerialError::IntegerOutOfRange));
}

// ---------------------------------------------------------------------------
// Signed integers — ZigZag + varint
// ---------------------------------------------------------------------------

impl Serialize for i8 {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encoder.write_byte(*self as u8)
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(1)
    }
}

impl Deserialize for i8 {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        Ok(decoder.read_byte()? as i8)
    }

    stack_array!(0);
}

/// `Serialize` / `Deserialize` for a signed integer narrower than 64 bits
/// (or pointer-sized): ZigZag through `i64`, then a `u64` varint.
macro_rules! impl_signed_varint {
    ($($t:ty),+ $(,)?) => {
        $(
            impl Serialize for $t {
                #[inline]
                fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
                    encoder.write_varint_u64(varint::zigzag_encode_i64(*self as i64))
                }

                #[inline]
                fn encoded_len(&self) -> Result<usize> {
                    Ok(varint_len(varint::zigzag_encode_i64(*self as i64)))
                }
            }

            impl Deserialize for $t {
                #[inline]
                fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
                    let value = varint::zigzag_decode_i64(decoder.read_varint_u64()?);
                    <$t>::try_from(value).map_err(|_| SerialError::IntegerOutOfRange)
                }

                varint_many!(|v: u64| {
                    <$t>::try_from(varint::zigzag_decode_i64(v))
                        .map_err(|_| SerialError::IntegerOutOfRange)
                });

                stack_array!(0);
            }
        )+
    };
}

impl_signed_varint!(i16, i32, isize);

impl Serialize for i64 {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encoder.write_varint_u64(varint::zigzag_encode_i64(*self))
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(varint_len(varint::zigzag_encode_i64(*self)))
    }
}

impl Deserialize for i64 {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        Ok(varint::zigzag_decode_i64(decoder.read_varint_u64()?))
    }

    stack_array!(0);

    varint_many!(|v: u64| -> Result<i64> { Ok(varint::zigzag_decode_i64(v)) });
}

impl Serialize for i128 {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encoder.write_varint_u128(varint::zigzag_encode_i128(*self))
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(varint::len_u128(varint::zigzag_encode_i128(*self)))
    }
}

impl Deserialize for i128 {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        Ok(varint::zigzag_decode_i128(decoder.read_varint_u128()?))
    }

    stack_array!(0);
}

// ---------------------------------------------------------------------------
// Bool
// ---------------------------------------------------------------------------

impl Serialize for bool {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encoder.write_byte(u8::from(*self))
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(1)
    }
}

impl Deserialize for bool {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        match decoder.read_byte()? {
            0x00 => Ok(false),
            0x01 => Ok(true),
            other => Err(SerialError::InvalidBool { byte: other }),
        }
    }

    stack_array!(false);
}

// ---------------------------------------------------------------------------
// char — Unicode scalar value as a u32 varint
// ---------------------------------------------------------------------------

impl Serialize for char {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encoder.write_varint_u64(u64::from(u32::from(*self)))
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(varint_len(u64::from(u32::from(*self))))
    }
}

impl Deserialize for char {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        let scalar = u32::deserialize(decoder)?;
        char::from_u32(scalar).ok_or(SerialError::InvalidValue { kind: "char" })
    }

    stack_array!('\0');
}

// ---------------------------------------------------------------------------
// Floats — IEEE 754 bit pattern, little-endian
// ---------------------------------------------------------------------------

impl Serialize for f32 {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encoder.write_bytes(&self.to_bits().to_le_bytes())
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(4)
    }
}

impl Deserialize for f32 {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        let mut buf = [0u8; 4];
        decoder.read_into(&mut buf)?;
        Ok(f32::from_bits(u32::from_le_bytes(buf)))
    }

    stack_array!(0.0);
}

impl Serialize for f64 {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encoder.write_bytes(&self.to_bits().to_le_bytes())
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(8)
    }
}

impl Deserialize for f64 {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        let mut buf = [0u8; 8];
        decoder.read_into(&mut buf)?;
        Ok(f64::from_bits(u64::from_le_bytes(buf)))
    }

    stack_array!(0.0);
}

// ---------------------------------------------------------------------------
// String / &str / Box<str>
// ---------------------------------------------------------------------------

impl Serialize for str {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        let bytes = self.as_bytes();
        encoder.write_varint_u64(bytes.len() as u64)?;
        encoder.write_bytes(bytes)
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(varint_len(self.len() as u64).saturating_add(self.len()))
    }
}

impl Serialize for String {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        Serialize::serialize(self.as_str(), encoder)
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        self.as_str().encoded_len()
    }
}

impl Deserialize for String {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        let bytes = decoder.read_length_prefixed()?;
        String::from_utf8(bytes).map_err(|_| SerialError::InvalidUtf8)
    }
}

impl Deserialize for Box<str> {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        String::deserialize(decoder).map(String::into_boxed_str)
    }
}

// ---------------------------------------------------------------------------
// Slices, Vec<T>, Box<[T]>, VecDeque<T>
// ---------------------------------------------------------------------------

impl<T: Serialize> Serialize for [T] {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encoder.write_varint_u64(self.len() as u64)?;
        // Dispatch to T's `serialize_slice` so byte-slice payloads
        // (T = u8) take the memcpy fast path via the `u8` override.
        T::serialize_slice(self, encoder)
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(varint_len(self.len() as u64).saturating_add(T::encoded_len_slice(self)?))
    }
}

impl<T: Serialize> Serialize for Vec<T> {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        Serialize::serialize(self.as_slice(), encoder)
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        self.as_slice().encoded_len()
    }
}

impl<T: Deserialize> Deserialize for Vec<T> {
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        let declared = decoder.read_varint_u64()?;
        let len = guard_element_count(declared, decoder)?;
        // Every slot is charged against the total budget up front, whatever
        // its encoding costs: `Option<[u8; 4096]>` is one byte on the wire
        // and 4097 in the `Vec`.
        charge_elements::<T, D>(decoder, len)?;
        // Dispatch to T's `deserialize_many` so byte-vec payloads
        // (T = u8) take the memcpy fast path via the `u8` override.
        T::deserialize_many(decoder, len)
    }
}

impl<T: Deserialize> Deserialize for Box<[T]> {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        Vec::<T>::deserialize(decoder).map(Vec::into_boxed_slice)
    }
}

impl<T: Serialize> Serialize for VecDeque<T> {
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encoder.write_varint_u64(self.len() as u64)?;
        let (front, back) = self.as_slices();
        T::serialize_slice(front, encoder)?;
        T::serialize_slice(back, encoder)
    }

    fn encoded_len(&self) -> Result<usize> {
        let (front, back) = self.as_slices();
        Ok(varint_len(self.len() as u64)
            .saturating_add(T::encoded_len_slice(front)?)
            .saturating_add(T::encoded_len_slice(back)?))
    }
}

impl<T: Deserialize> Deserialize for VecDeque<T> {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        Vec::<T>::deserialize(decoder).map(VecDeque::from)
    }
}

// ---------------------------------------------------------------------------
// Fixed-size arrays — [T; N]
// ---------------------------------------------------------------------------

impl<T: Serialize, const N: usize> Serialize for [T; N] {
    /// Routed through `T::serialize_slice`, so `[u8; N]` is one bulk write.
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        T::serialize_slice(self, encoder)
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        T::encoded_len_slice(self)
    }
}

impl<T: Deserialize, const N: usize> Deserialize for [T; N] {
    /// Routed through `T::deserialize_array`, so `[u8; N]` is one read into
    /// a stack array.
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        T::deserialize_array::<D, N>(decoder)
    }
}

// ---------------------------------------------------------------------------
// Tuples — arity 0..=12, PhantomData
// ---------------------------------------------------------------------------

impl Serialize for () {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, _encoder: &mut E) -> Result<()> {
        Ok(())
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(0)
    }
}

impl Deserialize for () {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(_decoder: &mut D) -> Result<Self> {
        Ok(())
    }
}

impl<T: ?Sized> Serialize for PhantomData<T> {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, _encoder: &mut E) -> Result<()> {
        Ok(())
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(0)
    }
}

impl<T: ?Sized> Deserialize for PhantomData<T> {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(_decoder: &mut D) -> Result<Self> {
        Ok(PhantomData)
    }
}

macro_rules! impl_tuple {
    ($($name:ident: $idx:tt),+) => {
        impl<$($name: Serialize),+> Serialize for ($($name,)+) {
            #[inline]
            fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
                $( self.$idx.serialize(encoder)?; )+
                Ok(())
            }

            #[inline]
            fn encoded_len(&self) -> Result<usize> {
                let mut total = 0usize;
                $( total = total.saturating_add(self.$idx.encoded_len()?); )+
                Ok(total)
            }
        }

        impl<$($name: Deserialize),+> Deserialize for ($($name,)+) {
            #[inline]
            fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
                Ok(( $( $name::deserialize(decoder)?, )+ ))
            }
        }
    };
}

impl_tuple!(T0: 0);
impl_tuple!(T0: 0, T1: 1);
impl_tuple!(T0: 0, T1: 1, T2: 2);
impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3);
impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4);
impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5);
impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6);
impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7);
impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8);
impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9);
impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10);
impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10, T11: 11);

// ---------------------------------------------------------------------------
// Option<T>
// ---------------------------------------------------------------------------

impl<T: Serialize> Serialize for Option<T> {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        match self {
            None => encoder.write_byte(0x00),
            Some(value) => {
                encoder.write_byte(0x01)?;
                value.serialize(encoder)
            }
        }
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        match self {
            None => Ok(1),
            Some(value) => Ok(value.encoded_len()?.saturating_add(1)),
        }
    }
}

impl<T: Deserialize> Deserialize for Option<T> {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        match decoder.read_byte()? {
            0x00 => Ok(None),
            0x01 => Ok(Some(T::deserialize(decoder)?)),
            tag => Err(SerialError::InvalidTag {
                kind: "Option",
                tag,
            }),
        }
    }
}

// ---------------------------------------------------------------------------
// Result<T, E>
// ---------------------------------------------------------------------------

impl<T: Serialize, E: Serialize> Serialize for core::result::Result<T, E> {
    #[inline]
    fn serialize<Enc: Encode + ?Sized>(&self, encoder: &mut Enc) -> Result<()> {
        match self {
            Ok(value) => {
                encoder.write_byte(0x00)?;
                value.serialize(encoder)
            }
            Err(err) => {
                encoder.write_byte(0x01)?;
                err.serialize(encoder)
            }
        }
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        let inner = match self {
            Ok(value) => value.encoded_len()?,
            Err(err) => err.encoded_len()?,
        };
        Ok(inner.saturating_add(1))
    }
}

impl<T: Deserialize, E: Deserialize> Deserialize for core::result::Result<T, E> {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        match decoder.read_byte()? {
            0x00 => Ok(Ok(T::deserialize(decoder)?)),
            0x01 => Ok(Err(E::deserialize(decoder)?)),
            tag => Err(SerialError::InvalidTag {
                kind: "Result",
                tag,
            }),
        }
    }
}

// ---------------------------------------------------------------------------
// Transparent wrappers: &T, Rc<T>, Arc<T>, Cow<'_, T>
// ---------------------------------------------------------------------------

impl<T: Serialize + ?Sized> Serialize for &T {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        (**self).serialize(encoder)
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        (**self).encoded_len()
    }
}

impl<T: Serialize + ?Sized> Serialize for Box<T> {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        (**self).serialize(encoder)
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        (**self).encoded_len()
    }
}

/// `Box<T>` encodes exactly like `T`, so a recursive type such as
/// `struct List { next: Option<Box<List>> }` derives directly. Recursion
/// through it is bounded by [`crate::Config::max_depth`] because the
/// recursive type itself is derived.
impl<T: Deserialize> Deserialize for Box<T> {
    /// The heap block (`size_of::<T>()`) is charged against the total
    /// budget, so `Box<Option<[u8; 4096]>>` cannot turn one input byte into
    /// four kilobytes uncounted.
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        charge_boxed::<T, D>(decoder, 0)?;
        T::deserialize(decoder).map(Box::new)
    }
}

/// Transparent `Serialize` plus owned `Deserialize` for a shared-ownership
/// pointer. `Rc<T>` / `Arc<T>` encode exactly like `T`; decoding allocates
/// a fresh pointer (sharing is not preserved across the wire).
macro_rules! impl_shared_pointer {
    ($ptr:ident) => {
        impl<T: Serialize + ?Sized> Serialize for $ptr<T> {
            #[inline]
            fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
                (**self).serialize(encoder)
            }

            #[inline]
            fn encoded_len(&self) -> Result<usize> {
                (**self).encoded_len()
            }
        }

        impl<T: Deserialize> Deserialize for $ptr<T> {
            /// The heap block (`size_of::<T>()` plus the two reference
            /// counts) is charged against the total budget.
            #[inline]
            fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
                charge_boxed::<T, D>(decoder, 2 * core::mem::size_of::<usize>())?;
                T::deserialize(decoder).map($ptr::new)
            }
        }

        impl Deserialize for $ptr<str> {
            #[inline]
            fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
                String::deserialize(decoder).map($ptr::from)
            }
        }

        impl<T: Deserialize> Deserialize for $ptr<[T]> {
            #[inline]
            fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
                Vec::<T>::deserialize(decoder).map($ptr::from)
            }
        }
    };
}

impl_shared_pointer!(Rc);
#[cfg(target_has_atomic = "ptr")]
impl_shared_pointer!(Arc);

impl<B> Serialize for Cow<'_, B>
where
    B: Serialize + ToOwned + ?Sized,
{
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        (**self).serialize(encoder)
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        (**self).encoded_len()
    }
}

/// Owning decode always yields [`Cow::Owned`]. To borrow from the input
/// buffer, decode `Cow<'a, str>` / `Cow<'a, [u8]>` through
/// [`crate::DeserializeView`] instead, which yields [`Cow::Borrowed`].
impl<B> Deserialize for Cow<'_, B>
where
    B: ToOwned + ?Sized,
    B::Owned: Deserialize,
{
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        B::Owned::deserialize(decoder).map(Cow::Owned)
    }
}

// ---------------------------------------------------------------------------
// NonZero integers — same bytes as the underlying integer, zero rejected
// ---------------------------------------------------------------------------

macro_rules! impl_non_zero {
    ($($nz:ident => $prim:ty),+ $(,)?) => {
        $(
            impl Serialize for $nz {
                #[inline]
                fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
                    self.get().serialize(encoder)
                }

                #[inline]
                fn encoded_len(&self) -> Result<usize> {
                    self.get().encoded_len()
                }
            }

            impl Deserialize for $nz {
                #[inline]
                fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
                    let raw = <$prim>::deserialize(decoder)?;
                    $nz::new(raw).ok_or(SerialError::InvalidValue { kind: stringify!($nz) })
                }
            }
        )+
    };
}

impl_non_zero!(
    NonZeroU8 => u8,
    NonZeroU16 => u16,
    NonZeroU32 => u32,
    NonZeroU64 => u64,
    NonZeroU128 => u128,
    NonZeroUsize => usize,
    NonZeroI8 => i8,
    NonZeroI16 => i16,
    NonZeroI32 => i32,
    NonZeroI64 => i64,
    NonZeroI128 => i128,
    NonZeroIsize => isize,
);

// ---------------------------------------------------------------------------
// Duration — varint(secs) ++ varint(subsec nanos)
// ---------------------------------------------------------------------------

impl Serialize for Duration {
    #[inline]
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encoder.write_varint_u64(self.as_secs())?;
        encoder.write_varint_u64(u64::from(self.subsec_nanos()))
    }

    #[inline]
    fn encoded_len(&self) -> Result<usize> {
        Ok(varint_len(self.as_secs()).saturating_add(varint_len(u64::from(self.subsec_nanos()))))
    }
}

impl Deserialize for Duration {
    #[inline]
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        const NANOS_PER_SEC: u32 = 1_000_000_000;
        let secs = decoder.read_varint_u64()?;
        let nanos = u32::deserialize(decoder)?;
        if nanos >= NANOS_PER_SEC {
            return Err(SerialError::InvalidValue { kind: "Duration" });
        }
        Ok(Duration::new(secs, nanos))
    }
}

// ---------------------------------------------------------------------------
// Map and set collections
// ---------------------------------------------------------------------------
//
// Encoding contract: `varint(count) ++ sorted_entries`, where entries are
// sorted lexicographically by their **encoded key bytes**. This means a
// `HashMap` and a `BTreeMap` holding the same logical data encode to the
// same bytes. Hash-randomisation across runs and insertion order are both
// irrelevant to the output — the byte-determinism contract holds.

/// Byte offsets of one encoded entry inside the shared scratch buffer:
/// the key occupies `start..key_end`, the whole entry `start..end`.
#[derive(Clone, Copy)]
struct EntrySpan {
    start: usize,
    key_end: usize,
    end: usize,
}

/// Collects the encoded entries of a map or set so they can be written in
/// canonical (encoded-key-byte) order.
///
/// Every entry is encoded once into a single shared scratch buffer while
/// its byte span is recorded, so a whole map costs two growing allocations
/// (the scratch bytes and the span list) instead of one per entry. When the
/// entries already arrive in canonical order — the common case for a
/// `BTreeMap` whose `Ord` agrees with the encoded-byte order — the scratch
/// buffer is emitted in one write and the sort is skipped.
///
/// Ties on the key bytes (only possible for key types whose encoding is not
/// injective) are broken by the full entry bytes, so the output never
/// depends on iteration order.
///
/// Shared by the native map / set impls and the `serde` adapter, which is
/// how a serde map encodes to the same bytes as the native one.
pub(crate) struct SortedEntries {
    scratch: Encoder,
    spans: Vec<EntrySpan>,
    in_order: bool,
    start: usize,
    key_end: Option<usize>,
    /// Where the entries start in `scratch`: `0` for a private scratch
    /// buffer, the caller's length when encoding in place.
    base: usize,
}

impl SortedEntries {
    /// Room for `count` entries (the span list is bounded by the caller's
    /// already-materialised collection, never by untrusted input).
    pub(crate) fn with_capacity(count: usize) -> Self {
        Self {
            scratch: Encoder::new(),
            spans: Vec::with_capacity(count),
            in_order: true,
            start: 0,
            key_end: None,
            base: 0,
        }
    }

    /// Encode `count` entries straight into `buffer`, after its current
    /// contents and the count prefix: the in-memory encoder's path, which
    /// needs no scratch buffer and, when the entries arrive in order, no
    /// copy at all. Finish with [`SortedEntries::finish_in_buffer`].
    fn in_buffer(buffer: Vec<u8>, count: usize) -> Self {
        let mut scratch = Encoder::into_buffer(buffer);
        // Never fails on an in-memory encoder.
        let _ = scratch.write_varint_u64(count as u64);
        let base = scratch.as_bytes().len();
        Self {
            scratch,
            spans: Vec::with_capacity(count),
            in_order: true,
            start: base,
            key_end: None,
            base,
        }
    }

    /// Put the entries written by [`SortedEntries::in_buffer`] in
    /// canonical order and hand the buffer back. Entries already in order
    /// stay where they are; otherwise the entry region is copied once and
    /// written back sorted.
    fn finish_in_buffer(mut self) -> Vec<u8> {
        let mut buffer = self.scratch.into_inner();
        if self.in_order {
            return buffer;
        }
        let region = buffer.split_off(self.base);
        let base = self.base;
        self.spans.sort_unstable_by(|a, b| {
            region[a.start - base..a.key_end - base]
                .cmp(&region[b.start - base..b.key_end - base])
                .then_with(|| {
                    region[a.start - base..a.end - base].cmp(&region[b.start - base..b.end - base])
                })
        });
        for span in &self.spans {
            buffer.extend_from_slice(&region[span.start - base..span.end - base]);
        }
        buffer
    }

    /// Run `fill` over a [`SortedEntries`] that writes into `buffer` in
    /// place, then order the entries. On error `buffer` is restored to its
    /// original length, as if nothing had been written.
    fn encode_in_buffer<F>(buffer: &mut Vec<u8>, count: usize, fill: F) -> Result<()>
    where
        F: FnOnce(&mut Self) -> Result<()>,
    {
        let original = buffer.len();
        let mut sorted = Self::in_buffer(core::mem::take(buffer), count);
        let outcome = fill(&mut sorted);
        let mut out = sorted.finish_in_buffer();
        if outcome.is_err() {
            out.truncate(original);
        }
        *buffer = out;
        outcome
    }

    /// The scratch encoder the next key / value must be written into.
    pub(crate) fn encoder(&mut self) -> &mut Encoder {
        &mut self.scratch
    }

    /// Mark the start of a new entry.
    pub(crate) fn begin_entry(&mut self) {
        self.start = self.scratch.as_bytes().len();
        self.key_end = None;
    }

    /// Mark the end of the current entry's key. Sets never call this: their
    /// whole entry is the key.
    pub(crate) fn end_key(&mut self) {
        self.key_end = Some(self.scratch.as_bytes().len());
    }

    /// Finish the current entry.
    pub(crate) fn end_entry(&mut self) {
        let end = self.scratch.as_bytes().len();
        let span = EntrySpan {
            start: self.start,
            key_end: self.key_end.unwrap_or(end),
            end,
        };
        if let Some(prev) = self.spans.last() {
            let bytes = self.scratch.as_bytes();
            self.in_order &= bytes[prev.start..prev.key_end] < bytes[span.start..span.key_end];
        }
        self.spans.push(span);
    }

    /// Write `varint(count) ++ entries in canonical order` into `encoder`.
    pub(crate) fn write_to<E: Encode + ?Sized>(mut self, encoder: &mut E) -> Result<()> {
        encoder.write_varint_u64(self.spans.len() as u64)?;
        let bytes = self.scratch.as_bytes();
        if self.in_order {
            return encoder.write_bytes(bytes);
        }
        self.spans.sort_unstable_by(|a, b| {
            bytes[a.start..a.key_end]
                .cmp(&bytes[b.start..b.key_end])
                .then_with(|| bytes[a.start..a.end].cmp(&bytes[b.start..b.end]))
        });
        for span in &self.spans {
            encoder.write_bytes(&bytes[span.start..span.end])?;
        }
        Ok(())
    }
}

/// Encode `count` entries as `varint(count) ++ entries sorted by encoded
/// key bytes` (see [`SortedEntries`]).
fn encode_map_like<K, V, I, E>(count: usize, entries: I, encoder: &mut E) -> Result<()>
where
    K: Serialize,
    V: Serialize,
    I: IntoIterator<Item = (K, V)>,
    E: Encode + ?Sized,
{
    if count == 0 {
        return encoder.write_byte(0);
    }
    let fill = |sorted: &mut SortedEntries| -> Result<()> {
        for (k, v) in entries {
            sorted.begin_entry();
            k.serialize(sorted.encoder())?;
            sorted.end_key();
            v.serialize(sorted.encoder())?;
            sorted.end_entry();
        }
        Ok(())
    };
    if let Some(buffer) = encoder.in_memory_buffer() {
        return SortedEntries::encode_in_buffer(buffer, count, fill);
    }
    let mut sorted = SortedEntries::with_capacity(count);
    fill(&mut sorted)?;
    sorted.write_to(encoder)
}

/// Encode `count` set elements as `varint(count) ++ sorted_elements`.
fn encode_set_like<T, I, E>(count: usize, items: I, encoder: &mut E) -> Result<()>
where
    T: Serialize,
    I: IntoIterator<Item = T>,
    E: Encode + ?Sized,
{
    if count == 0 {
        return encoder.write_byte(0);
    }
    let fill = |sorted: &mut SortedEntries| -> Result<()> {
        for item in items {
            sorted.begin_entry();
            item.serialize(sorted.encoder())?;
            sorted.end_entry();
        }
        Ok(())
    };
    if let Some(buffer) = encoder.in_memory_buffer() {
        return SortedEntries::encode_in_buffer(buffer, count, fill);
    }
    let mut sorted = SortedEntries::with_capacity(count);
    fill(&mut sorted)?;
    sorted.write_to(encoder)
}

/// `encoded_len` of a map: the count prefix plus every entry. Order does
/// not change the length, so no sorting (and no allocation) is needed.
fn map_encoded_len<'a, K, V, I>(count: usize, entries: I) -> Result<usize>
where
    K: Serialize + 'a,
    V: Serialize + 'a,
    I: IntoIterator<Item = (&'a K, &'a V)>,
{
    entries
        .into_iter()
        .try_fold(varint_len(count as u64), |acc, (k, v)| {
            Ok(acc
                .saturating_add(k.encoded_len()?)
                .saturating_add(v.encoded_len()?))
        })
}

/// `encoded_len` of a set: the count prefix plus every element.
fn set_encoded_len<'a, T, I>(count: usize, items: I) -> Result<usize>
where
    T: Serialize + 'a,
    I: IntoIterator<Item = &'a T>,
{
    items
        .into_iter()
        .try_fold(varint_len(count as u64), |acc, item| {
            Ok(acc.saturating_add(item.encoded_len()?))
        })
}

/// Tracks the byte span of the previous key while a map or set decodes in
/// canonical mode, and rejects any key that does not sort strictly after
/// it.
///
/// The spans are offsets into [`Decode::consumed`], which only grows during
/// a decode, so the previous key's bytes stay addressable without copying.
pub(crate) struct KeyOrder {
    reason: &'static str,
    prev: Option<(usize, usize)>,
}

impl KeyOrder {
    /// Start tracking; `reason` is reported in
    /// [`SerialError::NonCanonical`] (`"map key order"` / `"set element
    /// order"`).
    pub(crate) fn new(reason: &'static str) -> Self {
        Self { reason, prev: None }
    }

    /// Offset at which the next key starts.
    ///
    /// # Errors
    ///
    /// [`SerialError::InvalidConfig`] if the decoder cannot expose its
    /// consumed input, so canonical order cannot be checked.
    pub(crate) fn mark<D: Decode + ?Sized>(&self, decoder: &D) -> Result<usize> {
        decoder
            .consumed()
            .map(<[u8]>::len)
            .ok_or(SerialError::InvalidConfig {
                reason: "canonical mode needs a decoder that exposes its consumed input",
            })
    }

    /// Check the key that started at `start` and has just been decoded.
    ///
    /// # Errors
    ///
    /// [`SerialError::NonCanonical`] if the key is not strictly greater
    /// than the previous one.
    pub(crate) fn check<D: Decode + ?Sized>(&mut self, decoder: &D, start: usize) -> Result<()> {
        let consumed = decoder.consumed().unwrap_or_default();
        let end = consumed.len();
        if let Some((prev_start, prev_end)) = self.prev {
            let prev = consumed.get(prev_start..prev_end).unwrap_or_default();
            let current = consumed.get(start..end).unwrap_or_default();
            if current <= prev {
                return Err(SerialError::NonCanonical {
                    reason: self.reason,
                });
            }
        }
        self.prev = Some((start, end));
        Ok(())
    }
}

/// Decode `len` `(K, V)` entries, handing each to `insert`. In canonical
/// mode the encoded keys must be strictly increasing. Entries that consume
/// no input are charged against the total budget (see
/// [`decode_elements_counted`]).
fn decode_entries<K, V, D, F>(decoder: &mut D, len: usize, mut insert: F) -> Result<()>
where
    K: Deserialize,
    V: Deserialize,
    D: Decode + ?Sized,
    F: FnMut(K, V),
{
    if decoder.config().canonical {
        let mut order = KeyOrder::new("map key order");
        decode_elements_counted::<(K, V), D, _>(decoder, len, |decoder| {
            let start = order.mark(decoder)?;
            let k = K::deserialize(decoder)?;
            order.check(decoder, start)?;
            let v = V::deserialize(decoder)?;
            insert(k, v);
            Ok(())
        })
    } else {
        decode_elements_counted::<(K, V), D, _>(decoder, len, |decoder| {
            let k = K::deserialize(decoder)?;
            let v = V::deserialize(decoder)?;
            insert(k, v);
            Ok(())
        })
    }
}

/// Decode `len` set elements, handing each to `insert`. In canonical mode
/// the encoded elements must be strictly increasing. Elements that consume
/// no input are charged against the total budget.
fn decode_elements<T, D, F>(decoder: &mut D, len: usize, mut insert: F) -> Result<()>
where
    T: Deserialize,
    D: Decode + ?Sized,
    F: FnMut(T),
{
    if decoder.config().canonical {
        let mut order = KeyOrder::new("set element order");
        decode_elements_counted::<T, D, _>(decoder, len, |decoder| {
            let start = order.mark(decoder)?;
            let item = T::deserialize(decoder)?;
            order.check(decoder, start)?;
            insert(item);
            Ok(())
        })
    } else {
        decode_elements_counted::<T, D, _>(decoder, len, |decoder| {
            insert(T::deserialize(decoder)?);
            Ok(())
        })
    }
}

impl<K, V> Serialize for BTreeMap<K, V>
where
    K: Serialize,
    V: Serialize,
{
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encode_map_like(self.len(), self.iter(), encoder)
    }

    fn encoded_len(&self) -> Result<usize> {
        map_encoded_len(self.len(), self.iter())
    }
}

impl<K, V> Deserialize for BTreeMap<K, V>
where
    K: Deserialize + Ord,
    V: Deserialize,
{
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        let declared = decoder.read_varint_u64()?;
        let len = guard_element_count(declared, decoder)?;
        charge_elements::<(K, V), D>(decoder, len)?;
        let mut out = BTreeMap::new();
        decode_entries(decoder, len, |k, v| {
            let _ = out.insert(k, v);
        })?;
        Ok(out)
    }
}

impl<T> Serialize for BTreeSet<T>
where
    T: Serialize,
{
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encode_set_like(self.len(), self.iter(), encoder)
    }

    fn encoded_len(&self) -> Result<usize> {
        set_encoded_len(self.len(), self.iter())
    }
}

impl<T> Deserialize for BTreeSet<T>
where
    T: Deserialize + Ord,
{
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        let declared = decoder.read_varint_u64()?;
        let len = guard_element_count(declared, decoder)?;
        charge_elements::<T, D>(decoder, len)?;
        let mut out = BTreeSet::new();
        decode_elements(decoder, len, |item| {
            let _ = out.insert(item);
        })?;
        Ok(out)
    }
}

#[cfg(feature = "std")]
impl<K, V, S> Serialize for HashMap<K, V, S>
where
    K: Serialize,
    V: Serialize,
{
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encode_map_like(self.len(), self.iter(), encoder)
    }

    fn encoded_len(&self) -> Result<usize> {
        map_encoded_len(self.len(), self.iter())
    }
}

#[cfg(feature = "std")]
impl<K, V, S> Deserialize for HashMap<K, V, S>
where
    K: Deserialize + Hash + Eq,
    V: Deserialize,
    S: BuildHasher + Default,
{
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        let declared = decoder.read_varint_u64()?;
        let len = guard_element_count(declared, decoder)?;
        charge_elements::<(K, V), D>(decoder, len)?;
        let capacity = initial_capacity::<(K, V), D>(len, decoder);
        let mut out = HashMap::with_capacity_and_hasher(capacity, S::default());
        decode_entries(decoder, len, |k, v| {
            let _ = out.insert(k, v);
        })?;
        Ok(out)
    }
}

#[cfg(feature = "std")]
impl<T, S> Serialize for HashSet<T, S>
where
    T: Serialize,
{
    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
        encode_set_like(self.len(), self.iter(), encoder)
    }

    fn encoded_len(&self) -> Result<usize> {
        set_encoded_len(self.len(), self.iter())
    }
}

#[cfg(feature = "std")]
impl<T, S> Deserialize for HashSet<T, S>
where
    T: Deserialize + Hash + Eq,
    S: BuildHasher + Default,
{
    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
        let declared = decoder.read_varint_u64()?;
        let len = guard_element_count(declared, decoder)?;
        charge_elements::<T, D>(decoder, len)?;
        let capacity = initial_capacity::<T, D>(len, decoder);
        let mut out = HashSet::with_capacity_and_hasher(capacity, S::default());
        decode_elements(decoder, len, |item| {
            let _ = out.insert(item);
        })?;
        Ok(out)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{decode, encode};
    use alloc::vec;

    fn round_trip<T>(value: T)
    where
        T: Serialize + Deserialize + PartialEq + core::fmt::Debug,
    {
        let bytes = encode(&value).expect("encode");
        let back: T = decode(&bytes).expect("decode");
        assert_eq!(back, value);
    }

    #[test]
    fn u8_round_trips() {
        for v in [0u8, 1, 127, 128, 255] {
            round_trip(v);
        }
    }

    #[test]
    fn u64_round_trips() {
        for v in [0u64, 1, u32::MAX as u64, u64::MAX] {
            round_trip(v);
        }
    }

    #[test]
    fn i64_round_trips() {
        for v in [0i64, -1, 1, i64::MIN, i64::MAX] {
            round_trip(v);
        }
    }

    #[test]
    fn bool_round_trips() {
        round_trip(true);
        round_trip(false);
    }

    #[test]
    fn string_round_trips() {
        for s in ["", "hello", "a longer string with some content"] {
            round_trip(String::from(s));
        }
    }

    #[test]
    fn vec_u8_round_trips() {
        round_trip::<Vec<u8>>(vec![]);
        round_trip::<Vec<u8>>(vec![0u8, 1, 2, 3]);
        round_trip::<Vec<u8>>(vec![0xffu8; 1024]);
    }

    #[test]
    fn vec_u32_round_trips() {
        round_trip::<Vec<u32>>(vec![]);
        round_trip::<Vec<u32>>(vec![1, 2, u32::MAX]);
    }

    #[test]
    fn vec_string_round_trips() {
        round_trip(vec![
            String::from("hello"),
            String::from("world"),
            String::new(),
        ]);
    }

    #[test]
    fn array_round_trips() {
        round_trip([1u32, 2, 3, 4]);
        round_trip([0u8; 0]);
    }

    #[test]
    fn tuple_round_trips() {
        round_trip((1u8, 2u16, 3u32));
        round_trip((String::from("a"), 42u64, -3i32));
    }

    #[test]
    fn option_round_trips() {
        round_trip::<Option<u64>>(None);
        round_trip::<Option<u64>>(Some(42));
        round_trip::<Option<String>>(Some(String::from("hi")));
    }

    #[test]
    fn result_round_trips() {
        round_trip::<core::result::Result<u64, String>>(Ok(7));
        round_trip::<core::result::Result<u64, String>>(Err(String::from("nope")));
    }

    #[test]
    fn invalid_bool_byte_is_rejected() {
        let err = decode::<bool>(&[0x7f]).expect_err("0x7f is not a bool");
        assert!(matches!(err, SerialError::InvalidBool { byte: 0x7f }));
    }

    #[test]
    fn string_with_invalid_utf8_is_rejected() {
        let bytes = [0x02, 0xff, 0xff];
        let err = decode::<String>(&bytes).expect_err("invalid UTF-8 should fail");
        assert!(matches!(err, SerialError::InvalidUtf8));
    }

    #[test]
    fn option_invalid_tag_is_rejected() {
        let err = decode::<Option<u8>>(&[0x02]).expect_err("0x02 is not a valid Option tag");
        assert!(matches!(
            err,
            SerialError::InvalidTag {
                kind: "Option",
                tag: 0x02
            }
        ));
    }

    #[test]
    fn result_invalid_tag_is_rejected() {
        let err =
            decode::<core::result::Result<u8, u8>>(&[0x02]).expect_err("0x02 is not a Result tag");
        assert!(matches!(
            err,
            SerialError::InvalidTag {
                kind: "Result",
                tag: 0x02
            }
        ));
    }

    #[test]
    fn f64_round_trips_including_inf() {
        for v in [
            0.0f64,
            -0.0,
            1.0,
            -1.0,
            f64::MIN,
            f64::MAX,
            f64::INFINITY,
            f64::NEG_INFINITY,
        ] {
            let bytes = encode(&v).unwrap();
            let back: f64 = decode(&bytes).unwrap();
            assert_eq!(back.to_bits(), v.to_bits());
        }
    }

    #[test]
    fn f64_nan_round_trips_bit_for_bit() {
        let v = f64::NAN;
        let bytes = encode(&v).unwrap();
        let back: f64 = decode(&bytes).unwrap();
        assert_eq!(back.to_bits(), v.to_bits());
        assert!(back.is_nan());
    }

    #[test]
    fn btreemap_round_trips() {
        let mut m = BTreeMap::new();
        let _ = m.insert(String::from("a"), 1u32);
        let _ = m.insert(String::from("b"), 2);
        let _ = m.insert(String::from("c"), 3);
        round_trip(m);
    }

    #[test]
    fn btreemap_empty_round_trips() {
        round_trip(BTreeMap::<u32, u32>::new());
    }

    #[test]
    fn btreeset_round_trips() {
        let mut s = BTreeSet::new();
        let _ = s.insert(1u32);
        let _ = s.insert(2);
        let _ = s.insert(3);
        round_trip(s);
    }

    #[cfg(feature = "std")]
    #[test]
    fn hashmap_round_trips() {
        let mut m: HashMap<String, u32> = HashMap::new();
        let _ = m.insert(String::from("alpha"), 1);
        let _ = m.insert(String::from("beta"), 2);
        round_trip(m);
    }

    #[cfg(feature = "std")]
    #[test]
    fn hashset_round_trips() {
        let mut s: HashSet<u32> = HashSet::new();
        let _ = s.insert(1);
        let _ = s.insert(7);
        let _ = s.insert(42);
        round_trip(s);
    }

    #[cfg(feature = "std")]
    #[test]
    fn hashmap_and_btreemap_encode_identically_for_same_data() {
        let mut h: HashMap<String, u32> = HashMap::new();
        let mut b: BTreeMap<String, u32> = BTreeMap::new();
        for (k, v) in [("zeta", 5u32), ("alpha", 1), ("delta", 4), ("beta", 2)] {
            let _ = h.insert(k.into(), v);
            let _ = b.insert(k.into(), v);
        }
        assert_eq!(encode(&h).unwrap(), encode(&b).unwrap());
    }

    #[cfg(feature = "std")]
    #[test]
    fn hashmap_insertion_order_independent() {
        let mut a: HashMap<u32, u32> = HashMap::new();
        let _ = a.insert(1, 10);
        let _ = a.insert(2, 20);
        let _ = a.insert(3, 30);

        let mut b: HashMap<u32, u32> = HashMap::new();
        let _ = b.insert(3, 30);
        let _ = b.insert(1, 10);
        let _ = b.insert(2, 20);

        assert_eq!(encode(&a).unwrap(), encode(&b).unwrap());
    }

    #[test]
    fn collection_with_hostile_element_count_is_rejected() {
        // varint(u64::MAX) is 10 bytes of 0xff... 0x01.
        let bytes: [u8; 10] = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01];
        let err = decode::<Vec<u32>>(&bytes).expect_err("hostile count");
        assert!(matches!(err, SerialError::InvalidLength { .. }));
    }
}