reallyme-buffa 0.1.1

ReallyMe fork: A pure Rust Protocol Buffers implementation with first-class editions 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
// Modified by ReallyMe Technologies Limited.
//! Generic wire codec for `map<K, V>` fields.
//!
//! Generated code used to inline ~40 lines of entry encode/size/merge per
//! map field. The shape only varies by the key/value proto types, so the
//! variation is captured here as zero-sized **codec** types (one per proto
//! scalar type — proto types, not Rust types, because e.g. `int32` /
//! `sint32` / `sfixed32` all map to `i32` with different encodings) plus
//! generic per-field helpers. Generated call sites name the codecs by
//! turbofish and let the map's own key/value types drive inference:
//!
//! ```ignore
//! size += ::buffa::map_codec::field_len::<Str, Int32, _>(&self.stock, 1u32);
//! ::buffa::map_codec::write_field::<Str, Int32, _>(&self.stock, 5u32, buf);
//! ::buffa::map_codec::merge_entry::<Str, Int32, _>(&mut self.stock, buf, ctx)?;
//! ```
//!
//! The trailing `_` is the container type ([`MapStorage`]); it is inferred from
//! the map argument but must be written explicitly, because a partial turbofish
//! on a three-generic function is a hard error.
//!
//! Everything monomorphizes to the same code the previous inline expansion
//! produced; the fixed-width fast path (`len() * const`) is preserved via
//! [`MapCodec::FIXED_LEN`], which folds at compile time.
//!
//! Message-typed values are the one asymmetry: their encoded size is
//! two-pass (a [`SizeCache`] slot is reserved during `compute_size` and
//! consumed during `write_to`, in identical iteration order). They get
//! dedicated [`message_field_len`] / [`write_message_field`] helpers, and
//! implement only [`MapValueDecode`] (via [`Msg`]) for the merge path.
//!
//! Every encoder has an `_omitting_defaults` twin, which generated code calls
//! under `map_entries_omit_defaults`: it leaves a key or value at its default
//! out of the entry, as prost does.

use crate::bytes::Buf;
use crate::encode_sink::EncodeSink;
use crate::encoding::{check_wire_type, decode_varint, encode_varint, varint_len, Tag, WireType};
use crate::error::DecodeError;
use crate::types;
use crate::{DecodeContext, EnumValue, Enumeration, Message, SizeCache};
use core::hash::Hash;

/// The default owned `HashMap` type generated `map<K, V>` fields use.
///
/// On `std` builds this resolves to `std::collections::HashMap<K, V,
/// foldhash::fast::RandomState>`; on `no_std` builds it is
/// `hashbrown::HashMap<K, V>` (which defaults to the same `foldhash` hasher).
/// This alias is the recommended way to name a generated map field's type in
/// downstream code, so that the concrete hasher and container stay an
/// implementation detail.
///
/// Re-exported at the crate root as `buffa::Map`, alongside [`MapStorage`]:
/// `use buffa::Map;`.
///
/// # Construction
///
/// Use [`Map::default`] to construct an empty map. The inherent
/// `HashMap::new()` and `HashMap::with_capacity()` are only defined for the
/// std default hasher, so they are unavailable on `Map` under `std` (and would
/// be non-portable across the `std`/`no_std` boundary). For literals, use
/// `[(k, v), ..].into_iter().collect()` rather than `Map::from([...])` —
/// `From<[_; N]>` is likewise hasher-pinned in std. To preallocate, use
/// `std::collections::HashMap::with_capacity_and_hasher(n, Default::default())`.
///
/// # Hasher and HashDoS
///
/// `foldhash::fast` is per-instance seeded — each `Map::default()` derives a
/// fresh seed from the stack pointer mixed with a thread-local counter,
/// layered on a process-wide seed. On `std` that process-wide seed mixes
/// ASLR addresses with the wall clock and an allocator address. The seed is
/// **not** drawn from a CSPRNG (unlike `std::hash::RandomState`, which seeds
/// SipHash from `getrandom`), and `foldhash::fast` does not advertise
/// HashDoS resistance. Treat this default as **not hardened** against
/// adversarial hash flooding.
///
/// On `no_std` it is weaker than that, in a way worth stating plainly.
/// buffa gates `foldhash/std` behind its own `std` feature, and without it
/// foldhash drops the clock and allocator contributions: the process-wide
/// seed is then derived from three pointers alone — a stack address, a
/// function address, and the address of a static. On a hosted target ASLR
/// still varies those per process. On a bare-metal target such as
/// `thumbv7em-none-eabihf`, which buffa supports and CI checks, there is no
/// ASLR: all three are fixed at link time, so the seed is effectively a
/// compile-time constant and a colliding key set can be computed once from
/// the firmware image and reused against every device running it. If you
/// decode `map` fields with attacker-controlled keys in a `no_std` build,
/// prefer one of the alternatives below rather than this default.
///
/// This is the same trade-off Google's `protobuf-v4`/upb makes (Wyhash).
/// Consumers decoding `map` fields with attacker-controlled keys who need a
/// hardened bound should select `MapRepr::BTreeMap` (no hashing, O(log n)
/// worst case) or supply a SipHash-backed map via `MapRepr::Custom`. The
/// [`MapStorage`] impl is generic over the hasher, so
/// `std::collections::HashMap<K, V, std::hash::RandomState>` works without a
/// newtype — only a foreign *container* type (e.g. `IndexMap`) needs one.
pub type Map<K, V> = crate::__private::HashMap<K, V>;

/// The owned collection backing a proto `map<K, V>` field.
///
/// The default is the `__private::HashMap` alias above; `buffa_build`'s
/// `map_type` knob can instead select the buffa-provided
/// [`BTreeMap`](alloc::collections::BTreeMap) (deterministic iteration order,
/// no extra dependency) or a custom map. The runtime helpers in this
/// module need only three operations from the container — count entries,
/// borrow-iterate entries, and insert one entry — so this trait captures that
/// minimal surface and lets the helpers stay generic over *which* map a field
/// uses rather than hard-coding `__private::HashMap`.
///
/// The wire format is identical regardless of the container; only the in-memory
/// owned type changes, and view types are unaffected.
///
/// It is re-exported at the crate root, so downstream code can write
/// `use buffa::MapStorage;` (the longer `buffa::map_codec::MapStorage` path also
/// works).
///
/// # Sealing
///
/// Unlike [`MapCodec`] / [`MapValueDecode`], this trait is **not** sealed.
/// Those traits guard wire-format invariants the type system cannot express, so
/// they must stay closed. `MapStorage` carries no wire invariant: a buggy impl
/// can at worst iterate in an unusual order (already permitted for proto maps)
/// or drop the consumer's own entries. Leaving it open lets a downstream crate
/// wrap a foreign map (e.g. `indexmap::IndexMap`) in a crate-local newtype and
/// implement `MapStorage` on it, exactly as the orphan rule requires. The
/// wire-format seal is orthogonal and unaffected.
///
/// # Contract
///
/// - [`storage_insert`](Self::storage_insert) is **last-write-wins**, matching
///   proto map-merge semantics (a later entry for an existing key replaces the
///   earlier value).
/// - [`storage_iter`](Self::storage_iter) and [`storage_len`](Self::storage_len)
///   must agree: the iterator yields exactly `storage_len()` entries.
///
/// The key/value types are **associated types** ([`Key`](Self::Key) /
/// [`Value`](Self::Value)), not trait parameters, and the per-collection key
/// bound (`Eq + Hash` for `HashMap`, `Ord` for `BTreeMap`) lives on each impl.
/// The generic helpers bound only `C: MapStorage<Key = …, Value = …>` and never
/// name a key bound themselves. Because the key/value are associated, a type
/// implements `MapStorage` at most once, so the container — and its key and
/// value types — resolve unambiguously everywhere the trait is used as a bound.
///
/// # Requirements (for a *custom* map)
///
/// This is the canonical list of what a custom map must provide. A custom map is
/// always a **crate-local newtype** (the orphan rule blocks implementing the
/// buffa-owned reflection / serde traits on a foreign map), and must implement:
///
/// - `MapStorage` itself (this trait), naming its `Key` / `Value`.
/// - `Default` + `Clone` + `PartialEq` + `Debug` — the generated owned message
///   derives these, so its map field must support them.
/// - [`FromIterator<(Key, Value)>`] — the view→owned conversion `.collect()`s
///   entries into the owned map.
/// - `buffa_descriptor`'s `ReflectMap` under the reflection / vtable path — not
///   derivable, but a `BTreeMap`/`HashMap`-backed newtype can delegate to the
///   inner map's impl. This requirement is `std`-only (vtable reflection
///   requires `std`), so a `no_std` build never needs it.
/// - `arbitrary::Arbitrary` under the `arbitrary` feature (derivable on a
///   newtype). Not needed on a map field whose key or value is a custom string
///   type or whose value is a non-default bytes type: generated code builds
///   that field through `MapStorage` and `Default`.
/// - `serde::Serialize` / `Deserialize` under a JSON-enabled build. The proto3
///   JSON codec drives serialization through this trait, so **every** proto map
///   key/value type is supported regardless of the container — there is no
///   string-key or scalar-value restriction. (When a newtype wraps the inner map
///   in a single field, a derived `Serialize` / `Deserialize` already routes
///   transparently to the inner map; the with-modules call this trait's methods
///   directly rather than the newtype's serde, so even that is only needed when
///   the field type bypasses a with-module.)
///
/// The buffa-provided `HashMap` and `BTreeMap` already satisfy all of these, so
/// selecting `BTreeMap` needs no consumer code.
///
/// This trait is used only as a generic bound; it is **not object-safe** (the
/// [`storage_iter`](Self::storage_iter) RPITIT precludes `dyn MapStorage`).
#[rustversion::attr(
    since(1.78),
    diagnostic::on_unimplemented(
        message = "`{Self}` cannot be used as a buffa custom map type",
        note = "buffa owns `MapStorage`, so a foreign type can't implement it directly (orphan rule). \
                Wrap it in a crate-local newtype and implement `MapStorage` on the newtype. \
                See the `custom-types` example in the buffa repository for a template."
    )
)]
pub trait MapStorage {
    /// The map key type.
    type Key;
    /// The map value type.
    type Value;
    /// Number of entries.
    fn storage_len(&self) -> usize;
    /// Insert one entry (last-write-wins, matching proto map-merge semantics).
    fn storage_insert(&mut self, key: Self::Key, value: Self::Value);
    /// Remove all entries (the field's cleared / default state), retaining
    /// capacity where the underlying type allows. Invoked by the generated
    /// message `clear()`.
    fn storage_clear(&mut self);
    /// Erase a key discarded before insertion, including after a later parse error.
    /// A wipe-owning container overrides this; ordinary containers keep the default.
    /// Implementations must not panic or allocate.
    /// Called by binary and JSON map decoders when the `zeroize` feature is
    /// enabled, including the table codec's partial and discarded entries.
    /// With that feature disabled, temporary slots use ordinary Rust drop.
    fn storage_erase_key(_key: &mut Self::Key) {}
    /// Erase a value discarded before insertion. Implementations must not panic or allocate.
    /// Like `storage_erase_key`, this hook runs only with the `zeroize` feature.
    fn storage_erase_value(_value: &mut Self::Value) {}
    /// Borrow-iterate entries in the container's native order.
    fn storage_iter<'a>(&'a self) -> impl Iterator<Item = (&'a Self::Key, &'a Self::Value)>
    where
        Self::Key: 'a,
        Self::Value: 'a;
}

/// Implements [`MapStorage`] for both the `std` and `no_std` `HashMap` types,
/// generic over the hasher `S`. The buffa default `S` is `foldhash` on both
/// paths (see [`Map`]); the `S` parameter lets `MapRepr::Custom` users reach
/// any `BuildHasher` without a newtype. The `S: Default` bound is required so
/// generated owned messages can `Default`-construct the field — the read-only
/// `ReflectMap` impl in `buffa-descriptor` relaxes to `S: BuildHasher`.
macro_rules! map_storage_hashmap {
    ($($ty:tt)*) => {
        impl<K: Eq + Hash, V, S: core::hash::BuildHasher + Default> MapStorage for $($ty)*<K, V, S> {
            type Key = K;
            type Value = V;
            #[inline]
            fn storage_len(&self) -> usize {
                self.len()
            }
            #[inline]
            fn storage_insert(&mut self, key: K, value: V) {
                self.insert(key, value);
            }
            #[inline]
            fn storage_clear(&mut self) {
                self.clear();
            }
            #[inline]
            fn storage_iter<'a>(&'a self) -> impl Iterator<Item = (&'a K, &'a V)>
            where
                K: 'a,
                V: 'a,
            {
                self.iter()
            }
        }
    };
}
#[cfg(feature = "std")]
map_storage_hashmap!(std::collections::HashMap);
#[cfg(not(feature = "std"))]
map_storage_hashmap!(hashbrown::HashMap);

impl<K: Ord, V> MapStorage for crate::alloc::collections::BTreeMap<K, V> {
    type Key = K;
    type Value = V;
    #[inline]
    fn storage_len(&self) -> usize {
        self.len()
    }
    #[inline]
    fn storage_insert(&mut self, key: K, value: V) {
        self.insert(key, value);
    }
    #[inline]
    fn storage_clear(&mut self) {
        self.clear();
    }
    #[inline]
    fn storage_iter<'a>(&'a self) -> impl Iterator<Item = (&'a K, &'a V)>
    where
        K: 'a,
        V: 'a,
    {
        self.iter()
    }
}

mod sealed {
    /// Seals [`MapValueDecode`](super::MapValueDecode) / [`MapCodec`](super::MapCodec).
    ///
    /// The traits carry invariants the type system cannot enforce —
    /// `WIRE_TYPE` must match the payload `merge` reads and `encode`
    /// writes, and a wrong `FIXED_LEN` would make [`field_len`](super::field_len)
    /// disagree with [`write_field`](super::write_field), corrupting output.
    /// The proto scalar set is closed, so only buffa's own codecs implement
    /// them.
    pub trait Sealed {}
}

/// Decode side of a map key/value codec.
///
/// Implemented by every codec, including [`Msg`] for message-typed values
/// (whose *encode* side is two-pass and lives in [`message_field_len`] /
/// [`write_message_field`] instead of [`MapCodec`]).
pub trait MapValueDecode: sealed::Sealed {
    /// The Rust type this codec reads into.
    type Value: Default;
    /// The wire type every payload of this codec carries.
    const WIRE_TYPE: WireType;
    /// Whether [`merge`](Self::merge) can report
    /// [`MapValueDecodeStatus::Unknown`].
    ///
    /// This is false for ordinary scalar/message codecs and true for closed
    /// enum codecs. [`merge_entry_with_unknowns`] uses it to avoid buffering
    /// map-entry payloads unless a value can actually force whole-entry
    /// unknown-field preservation.
    const MAY_RETURN_UNKNOWN: bool = false;

    /// Merge one payload from `buf` into `value`.
    ///
    /// Returns [`MapValueDecodeStatus::Known`] in the normal case, or
    /// [`MapValueDecodeStatus::Unknown`] when this codec is a closed enum and
    /// the payload's numeric value is not a declared variant — letting the
    /// caller route the whole map entry to unknown fields instead of inserting
    /// it.
    ///
    /// `ctx` carries the remaining recursion and unknown-field budgets
    /// (used by message values; scalar codecs ignore it).
    ///
    /// # Errors
    ///
    /// Returns a [`DecodeError`] on malformed payloads.
    fn merge(
        value: &mut Self::Value,
        buf: &mut impl Buf,
        ctx: DecodeContext<'_>,
    ) -> Result<MapValueDecodeStatus, DecodeError>;
}

/// Result of decoding one map-entry key/value payload.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum MapValueDecodeStatus {
    /// The payload decoded to a normal map key/value.
    Known,
    /// The payload was an unknown value for a closed enum.
    ///
    /// Proto2 map semantics require the whole outer map-entry record to be
    /// treated as unknown in this case, not inserted with a default value.
    Unknown,
}

/// Full (encode + size + decode) map key/value codec for non-message types.
pub trait MapCodec: MapValueDecode {
    /// `Some(n)` when every payload encodes to exactly `n` bytes
    /// (fixed-width scalars and `bool`). Lets [`field_len`] fold the whole
    /// field to `len() * entry_size` at compile time.
    ///
    /// Must equal the length [`encode`](Self::encode) actually writes for
    /// every value — [`field_len`] sizes the buffer with it. (One reason the
    /// traits are sealed.)
    const FIXED_LEN: Option<u64> = None;

    /// Encoded payload length in bytes (no tag).
    ///
    /// `u64`, like all size arithmetic feeding `compute_size` accumulators:
    /// a huge `bytes`/`string` payload must surface as an exact over-limit
    /// total at the encode entry points' 2 GiB check, never wrap.
    fn encoded_len(value: &Self::Value) -> u64;

    /// Write the payload (no tag) to `buf`.
    fn encode(value: &Self::Value, buf: &mut impl EncodeSink);

    /// Whether `value` is what a missing key or value field decodes to, which
    /// the `*_omitting_defaults` encoders leave out of an entry: zero, `false`,
    /// empty, an open enum's 0, or a closed enum's default (its first value).
    /// Compared with `==`, as prost does, so `-0.0` counts as a float's default
    /// and decodes back as `0.0`.
    fn is_default(value: &Self::Value) -> bool;
}

/// Stamp a varint/fixed scalar codec from the existing `types::` functions.
macro_rules! scalar_codec {
    ($(#[$doc:meta])* $name:ident, $value:ty, $wire:expr, $fixed:expr,
     len: $len:expr, encode: $encode:expr, decode: $decode:expr) => {
        $(#[$doc])*
        pub struct $name;

        impl sealed::Sealed for $name {}

        impl MapValueDecode for $name {
            type Value = $value;
            const WIRE_TYPE: WireType = $wire;

            #[inline]
            fn merge(
                value: &mut Self::Value,
                buf: &mut impl Buf,
                _ctx: DecodeContext<'_>,
            ) -> Result<MapValueDecodeStatus, DecodeError> {
                *value = $decode(buf)?;
                Ok(MapValueDecodeStatus::Known)
            }
        }

        impl MapCodec for $name {
            const FIXED_LEN: Option<u64> = $fixed;

            #[inline]
            #[allow(clippy::redundant_closure_call)]
            fn encoded_len(value: &Self::Value) -> u64 {
                ($len)(value) as u64
            }

            #[inline]
            #[allow(clippy::redundant_closure_call)]
            fn encode(value: &Self::Value, buf: &mut impl EncodeSink) {
                ($encode)(value, buf)
            }

            #[inline]
            #[allow(clippy::float_cmp)]
            fn is_default(value: &Self::Value) -> bool {
                *value == <$value as Default>::default()
            }
        }
    };
}

scalar_codec!(
    /// `int32` codec.
    Int32, i32, WireType::Varint, None,
    len: |v: &i32| types::int32_encoded_len(*v),
    encode: |v: &i32, buf: &mut _| types::encode_int32(*v, buf),
    decode: types::decode_int32
);
scalar_codec!(
    /// `int64` codec.
    Int64, i64, WireType::Varint, None,
    len: |v: &i64| types::int64_encoded_len(*v),
    encode: |v: &i64, buf: &mut _| types::encode_int64(*v, buf),
    decode: types::decode_int64
);
scalar_codec!(
    /// `uint32` codec.
    Uint32, u32, WireType::Varint, None,
    len: |v: &u32| types::uint32_encoded_len(*v),
    encode: |v: &u32, buf: &mut _| types::encode_uint32(*v, buf),
    decode: types::decode_uint32
);
scalar_codec!(
    /// `uint64` codec.
    Uint64, u64, WireType::Varint, None,
    len: |v: &u64| types::uint64_encoded_len(*v),
    encode: |v: &u64, buf: &mut _| types::encode_uint64(*v, buf),
    decode: types::decode_uint64
);
scalar_codec!(
    /// `sint32` (zigzag) codec.
    Sint32, i32, WireType::Varint, None,
    len: |v: &i32| types::sint32_encoded_len(*v),
    encode: |v: &i32, buf: &mut _| types::encode_sint32(*v, buf),
    decode: types::decode_sint32
);
scalar_codec!(
    /// `sint64` (zigzag) codec.
    Sint64, i64, WireType::Varint, None,
    len: |v: &i64| types::sint64_encoded_len(*v),
    encode: |v: &i64, buf: &mut _| types::encode_sint64(*v, buf),
    decode: types::decode_sint64
);
scalar_codec!(
    /// `bool` codec.
    Bool, bool, WireType::Varint, Some(types::BOOL_ENCODED_LEN as u64),
    len: |_: &bool| types::BOOL_ENCODED_LEN,
    encode: |v: &bool, buf: &mut _| types::encode_bool(*v, buf),
    decode: types::decode_bool
);
scalar_codec!(
    /// `fixed32` codec.
    Fixed32, u32, WireType::Fixed32, Some(types::FIXED32_ENCODED_LEN as u64),
    len: |_: &u32| types::FIXED32_ENCODED_LEN,
    encode: |v: &u32, buf: &mut _| types::encode_fixed32(*v, buf),
    decode: types::decode_fixed32
);
scalar_codec!(
    /// `fixed64` codec.
    Fixed64, u64, WireType::Fixed64, Some(types::FIXED64_ENCODED_LEN as u64),
    len: |_: &u64| types::FIXED64_ENCODED_LEN,
    encode: |v: &u64, buf: &mut _| types::encode_fixed64(*v, buf),
    decode: types::decode_fixed64
);
scalar_codec!(
    /// `sfixed32` codec.
    Sfixed32, i32, WireType::Fixed32, Some(types::FIXED32_ENCODED_LEN as u64),
    len: |_: &i32| types::FIXED32_ENCODED_LEN,
    encode: |v: &i32, buf: &mut _| types::encode_sfixed32(*v, buf),
    decode: types::decode_sfixed32
);
scalar_codec!(
    /// `sfixed64` codec.
    Sfixed64, i64, WireType::Fixed64, Some(types::FIXED64_ENCODED_LEN as u64),
    len: |_: &i64| types::FIXED64_ENCODED_LEN,
    encode: |v: &i64, buf: &mut _| types::encode_sfixed64(*v, buf),
    decode: types::decode_sfixed64
);
scalar_codec!(
    /// `float` codec.
    Float, f32, WireType::Fixed32, Some(types::FIXED32_ENCODED_LEN as u64),
    len: |_: &f32| types::FIXED32_ENCODED_LEN,
    encode: |v: &f32, buf: &mut _| types::encode_float(*v, buf),
    decode: types::decode_float
);
scalar_codec!(
    /// `double` codec.
    Double, f64, WireType::Fixed64, Some(types::FIXED64_ENCODED_LEN as u64),
    len: |_: &f64| types::FIXED64_ENCODED_LEN,
    encode: |v: &f64, buf: &mut _| types::encode_double(*v, buf),
    decode: types::decode_double
);
scalar_codec!(
    /// `string` codec.
    Str, crate::alloc::string::String, WireType::LengthDelimited, None,
    len: |v: &crate::alloc::string::String| types::string_encoded_len(v),
    encode: |v: &crate::alloc::string::String, buf: &mut _| types::encode_string(v, buf),
    decode: types::decode_string
);
scalar_codec!(
    /// `bytes` codec (`Vec<u8>` representation).
    BytesVec, crate::alloc::vec::Vec<u8>, WireType::LengthDelimited, None,
    len: |v: &crate::alloc::vec::Vec<u8>| types::bytes_encoded_len(v),
    encode: |v: &crate::alloc::vec::Vec<u8>, buf: &mut _| types::encode_bytes(v, buf),
    decode: types::decode_bytes
);
scalar_codec!(
    /// `bytes` codec (`bytes::Bytes` representation, via the `bytes_fields`
    /// codegen option; zero-copy when the source buffer is `Bytes`-backed).
    BytesBuf, crate::bytes::Bytes, WireType::LengthDelimited, None,
    len: |v: &crate::bytes::Bytes| types::bytes_encoded_len(v),
    // Shared-aware: splices into segmented sinks by refcount.
    encode: |v: &crate::bytes::Bytes, buf: &mut _| types::encode_shared_bytes(v, buf),
    decode: types::decode_bytes_to_bytes
);

/// `bytes` codec for a custom [`ProtoBytes`](crate::types::ProtoBytes) map-value
/// representation (via `bytes_type_custom`). Decodes through
/// [`decode_length_delimited`](crate::types::ProtoBytes::decode_length_delimited),
/// whose default delegates to `from_wire`; encodes the borrowed
/// `&[u8]`. Generic over the value type, so the codec itself stays sealed in
/// buffa while the concrete representation is a downstream (crate-local) type.
pub struct ProtoBytesMap<B>(core::marker::PhantomData<B>);

impl<B: crate::types::ProtoBytes> sealed::Sealed for ProtoBytesMap<B> {}

impl<B: crate::types::ProtoBytes> MapValueDecode for ProtoBytesMap<B> {
    type Value = B;
    const WIRE_TYPE: WireType = WireType::LengthDelimited;

    #[inline]
    fn merge(
        value: &mut Self::Value,
        buf: &mut impl Buf,
        _ctx: DecodeContext<'_>,
    ) -> Result<MapValueDecodeStatus, DecodeError> {
        *value = crate::types::decode_bytes_to::<B>(buf)?;
        Ok(MapValueDecodeStatus::Known)
    }
}

impl<B: crate::types::ProtoBytes> MapCodec for ProtoBytesMap<B> {
    #[inline]
    fn encoded_len(value: &Self::Value) -> u64 {
        types::bytes_encoded_len(value.as_ref()) as u64
    }

    #[inline]
    fn encode(value: &Self::Value, buf: &mut impl EncodeSink) {
        // Shared-aware: a `Bytes`-backed map value splices into segmented
        // sinks by refcount, like top-level bytes fields.
        types::encode_shared_bytes(value, buf);
    }

    #[inline]
    fn is_default(value: &Self::Value) -> bool {
        value.as_ref().is_empty()
    }
}

/// `string` codec for a custom [`ProtoString`](crate::types::ProtoString)
/// map key or value representation (via `string_type_custom`). Decodes through
/// [`decode_length_delimited`](crate::types::ProtoString::decode_length_delimited)
/// (UTF-8 validation included), whose default delegates to `from_wire`.
/// Encodes the borrowed `&str`. Generic over the type, so the codec
/// itself stays sealed in buffa while the concrete representation is a
/// downstream (crate-local) type.
///
/// Unlike [`ProtoBytesMap`], which is value-only (proto forbids `bytes` map
/// keys), this codec serves **both** map slots — `string` is a legal key and
/// value type. Used as a *key*, the type additionally needs the container's
/// `Eq + Hash` (`HashMap`) or `Ord` (`BTreeMap`) bound; that is enforced at the
/// generated map field type via the [`MapStorage`] impls, not here.
pub struct ProtoStringMap<S>(core::marker::PhantomData<S>);

impl<S: crate::types::ProtoString> sealed::Sealed for ProtoStringMap<S> {}

impl<S: crate::types::ProtoString> MapValueDecode for ProtoStringMap<S> {
    type Value = S;
    const WIRE_TYPE: WireType = WireType::LengthDelimited;

    #[inline]
    fn merge(
        value: &mut Self::Value,
        buf: &mut impl Buf,
        _ctx: DecodeContext<'_>,
    ) -> Result<MapValueDecodeStatus, DecodeError> {
        *value = crate::types::decode_string_to::<S>(buf)?;
        Ok(MapValueDecodeStatus::Known)
    }
}

impl<S: crate::types::ProtoString> MapCodec for ProtoStringMap<S> {
    #[inline]
    fn encoded_len(value: &Self::Value) -> u64 {
        types::string_encoded_len(value.as_ref()) as u64
    }

    #[inline]
    fn encode(value: &Self::Value, buf: &mut impl EncodeSink) {
        types::encode_string(value.as_ref(), buf);
    }

    #[inline]
    fn is_default(value: &Self::Value) -> bool {
        value.as_ref().is_empty()
    }
}

/// Open-enum codec: values decode into [`EnumValue<E>`], preserving unknown
/// numbers.
pub struct OpenEnum<E>(core::marker::PhantomData<E>);

impl<E: Enumeration> sealed::Sealed for OpenEnum<E> {}

impl<E: Enumeration> MapValueDecode for OpenEnum<E> {
    type Value = EnumValue<E>;
    const WIRE_TYPE: WireType = WireType::Varint;

    #[inline]
    fn merge(
        value: &mut Self::Value,
        buf: &mut impl Buf,
        _ctx: DecodeContext<'_>,
    ) -> Result<MapValueDecodeStatus, DecodeError> {
        *value = EnumValue::from(types::decode_int32(buf)?);
        Ok(MapValueDecodeStatus::Known)
    }
}

impl<E: Enumeration> MapCodec for OpenEnum<E> {
    #[inline]
    fn encoded_len(value: &Self::Value) -> u64 {
        types::int32_encoded_len(value.to_i32()) as u64
    }

    #[inline]
    fn encode(value: &Self::Value, buf: &mut impl EncodeSink) {
        types::encode_int32(value.to_i32(), buf);
    }

    #[inline]
    fn is_default(value: &Self::Value) -> bool {
        value.to_i32() == 0
    }
}

/// Closed-enum codec: values decode into the bare enum `E`.
///
/// Unknown numeric values report [`MapValueDecodeStatus::Unknown`], letting
/// [`merge_entry_with_unknowns`] route the whole map-entry record to unknown
/// fields instead of inserting a default-valued entry.
pub struct ClosedEnum<E>(core::marker::PhantomData<E>);

impl<E: Enumeration + Default> sealed::Sealed for ClosedEnum<E> {}

impl<E: Enumeration + Default> MapValueDecode for ClosedEnum<E> {
    type Value = E;
    const WIRE_TYPE: WireType = WireType::Varint;
    const MAY_RETURN_UNKNOWN: bool = true;

    #[inline]
    fn merge(
        value: &mut Self::Value,
        buf: &mut impl Buf,
        _ctx: DecodeContext<'_>,
    ) -> Result<MapValueDecodeStatus, DecodeError> {
        let raw = types::decode_int32(buf)?;
        if let Some(v) = E::from_i32(raw) {
            *value = v;
            Ok(MapValueDecodeStatus::Known)
        } else {
            Ok(MapValueDecodeStatus::Unknown)
        }
    }
}

impl<E: Enumeration + Default> MapCodec for ClosedEnum<E> {
    #[inline]
    fn encoded_len(value: &Self::Value) -> u64 {
        types::int32_encoded_len(value.to_i32()) as u64
    }

    #[inline]
    fn encode(value: &Self::Value, buf: &mut impl EncodeSink) {
        types::encode_int32(value.to_i32(), buf);
    }

    #[inline]
    fn is_default(value: &Self::Value) -> bool {
        *value == E::default()
    }
}

/// Message-value codec (decode side only — encode is two-pass via
/// [`message_field_len`] / [`write_message_field`]).
pub struct Msg<M>(core::marker::PhantomData<M>);

impl<M: Message + Default> sealed::Sealed for Msg<M> {}

impl<M: Message + Default> MapValueDecode for Msg<M> {
    type Value = M;
    const WIRE_TYPE: WireType = WireType::LengthDelimited;

    #[inline]
    fn merge(
        value: &mut Self::Value,
        buf: &mut impl Buf,
        ctx: DecodeContext<'_>,
    ) -> Result<MapValueDecodeStatus, DecodeError> {
        Message::merge_length_delimited(value, buf, ctx)?;
        Ok(MapValueDecodeStatus::Known)
    }
}

/// Key tag (field 1) and value tag (field 2) are both single-byte for every
/// wire type, so each entry carries exactly two tag bytes.
const ENTRY_TAG_LEN: u64 = 2;

#[inline]
fn entry_len<KC: MapCodec, VC: MapCodec>(k: &KC::Value, v: &VC::Value) -> u64 {
    ENTRY_TAG_LEN + KC::encoded_len(k) + VC::encoded_len(v)
}

/// Total encoded length of a scalar-valued map field, including each entry's
/// outer tag and length prefix.
///
/// `outer_tag_len` is the encoded length of the field's outer tag (a codegen
/// constant). When both codecs are fixed-width the per-entry size is a
/// compile-time constant and the loop folds to `len() * entry`.
pub fn field_len<KC: MapCodec, VC: MapCodec, C>(map: &C, outer_tag_len: u64) -> u64
where
    C: MapStorage<Key = KC::Value, Value = VC::Value>,
{
    if let (Some(kf), Some(vf)) = (KC::FIXED_LEN, VC::FIXED_LEN) {
        let entry = ENTRY_TAG_LEN + kf + vf;
        return map.storage_len() as u64 * (outer_tag_len + varint_len(entry) as u64 + entry);
    }
    let mut size = 0u64;
    for (k, v) in map.storage_iter() {
        let entry = entry_len::<KC, VC>(k, v);
        size += outer_tag_len + varint_len(entry) as u64 + entry;
    }
    size
}

/// Write a scalar-valued map field: one `field_number`-tagged,
/// length-prefixed entry per element.
pub fn write_field<KC: MapCodec, VC: MapCodec, C>(
    map: &C,
    field_number: u32,
    buf: &mut impl EncodeSink,
) where
    C: MapStorage<Key = KC::Value, Value = VC::Value>,
{
    for (k, v) in map.storage_iter() {
        let entry = entry_len::<KC, VC>(k, v);
        Tag::new(field_number, WireType::LengthDelimited).encode(buf);
        encode_varint(entry, buf);
        Tag::new(1, KC::WIRE_TYPE).encode(buf);
        KC::encode(k, buf);
        Tag::new(2, VC::WIRE_TYPE).encode(buf);
        VC::encode(v, buf);
    }
}

/// Total encoded length of a message-valued map field.
///
/// Reserves one [`SizeCache`] slot per entry (in map iteration order);
/// [`write_message_field`] consumes the slots in the same order — both
/// helpers iterate the same map, so the orders match by construction.
pub fn message_field_len<KC: MapCodec, M: Message, C>(
    map: &C,
    outer_tag_len: u64,
    cache: &mut SizeCache,
) -> u64
where
    C: MapStorage<Key = KC::Value, Value = M>,
{
    let mut size = 0u64;
    for (k, v) in map.storage_iter() {
        let slot = cache.reserve();
        let inner = v.compute_size(cache);
        cache.set(slot, inner);
        let entry =
            ENTRY_TAG_LEN + KC::encoded_len(k) + varint_len(inner as u64) as u64 + inner as u64;
        size += outer_tag_len + varint_len(entry) as u64 + entry;
    }
    size
}

/// Write a message-valued map field, consuming the [`SizeCache`] slots
/// reserved by [`message_field_len`].
pub fn write_message_field<KC: MapCodec, M: Message, C>(
    map: &C,
    field_number: u32,
    cache: &mut SizeCache,
    buf: &mut impl EncodeSink,
) where
    C: MapStorage<Key = KC::Value, Value = M>,
{
    for (k, v) in map.storage_iter() {
        let inner = cache.consume_next();
        let entry =
            ENTRY_TAG_LEN + KC::encoded_len(k) + varint_len(inner as u64) as u64 + inner as u64;
        Tag::new(field_number, WireType::LengthDelimited).encode(buf);
        encode_varint(entry, buf);
        Tag::new(1, KC::WIRE_TYPE).encode(buf);
        KC::encode(k, buf);
        Tag::new(2, WireType::LengthDelimited).encode(buf);
        encode_varint(inner as u64, buf);
        v.write_to(cache, buf);
    }
}

/// Tag length of an entry's key (field 1) or value (field 2), one byte for
/// every wire type.
const ENTRY_FIELD_TAG_LEN: u64 = 1;

/// Which of an entry's fields the `_omitting_defaults` encoders leave out,
/// decided once for the size and the write of the entry.
struct Omitted {
    key: bool,
    value: bool,
}

impl Omitted {
    #[inline]
    fn of<KC: MapCodec, VC: MapCodec>(k: &KC::Value, v: &VC::Value) -> Self {
        Self {
            key: KC::is_default(k),
            value: VC::is_default(v),
        }
    }

    /// Encoded length of the entry's fields, the length prefix excluded.
    #[inline]
    fn entry_len<KC: MapCodec, VC: MapCodec>(&self, k: &KC::Value, v: &VC::Value) -> u64 {
        let value = if self.value {
            0
        } else {
            ENTRY_FIELD_TAG_LEN + VC::encoded_len(v)
        };
        sparse_key_len::<KC>(self.key, k) + value
    }
}

/// Encoded length of an entry's key field, nothing when it is left out.
#[inline]
fn sparse_key_len<KC: MapCodec>(omitted: bool, k: &KC::Value) -> u64 {
    if omitted {
        0
    } else {
        ENTRY_FIELD_TAG_LEN + KC::encoded_len(k)
    }
}

/// Encoded length of an entry's message value field, nothing for a value that
/// encodes to nothing.
#[inline]
fn sparse_message_len(inner: u32) -> u64 {
    if inner == 0 {
        0
    } else {
        ENTRY_FIELD_TAG_LEN + varint_len(inner as u64) as u64 + inner as u64
    }
}

/// [`field_len`] for entries that leave a default key or value out, as
/// [`write_field_omitting_defaults`] writes them.
pub fn field_len_omitting_defaults<KC: MapCodec, VC: MapCodec, C>(
    map: &C,
    outer_tag_len: u64,
) -> u64
where
    C: MapStorage<Key = KC::Value, Value = VC::Value>,
{
    let mut size = 0u64;
    for (k, v) in map.storage_iter() {
        let entry = Omitted::of::<KC, VC>(k, v).entry_len::<KC, VC>(k, v);
        size += outer_tag_len + varint_len(entry) as u64 + entry;
    }
    size
}

/// [`write_field`], leaving a key or value at its default out of its entry, as
/// prost does. The entry decodes to the same key and value, except that a
/// `-0.0` float decodes as `0.0`.
pub fn write_field_omitting_defaults<KC: MapCodec, VC: MapCodec, C>(
    map: &C,
    field_number: u32,
    buf: &mut impl EncodeSink,
) where
    C: MapStorage<Key = KC::Value, Value = VC::Value>,
{
    for (k, v) in map.storage_iter() {
        let omitted = Omitted::of::<KC, VC>(k, v);
        Tag::new(field_number, WireType::LengthDelimited).encode(buf);
        encode_varint(omitted.entry_len::<KC, VC>(k, v), buf);
        if !omitted.key {
            Tag::new(1, KC::WIRE_TYPE).encode(buf);
            KC::encode(k, buf);
        }
        if !omitted.value {
            Tag::new(2, VC::WIRE_TYPE).encode(buf);
            VC::encode(v, buf);
        }
    }
}

/// [`message_field_len`] for entries that leave a default key or a message
/// that encodes to nothing out, as [`write_message_field_omitting_defaults`]
/// writes them.
pub fn message_field_len_omitting_defaults<KC: MapCodec, M: Message, C>(
    map: &C,
    outer_tag_len: u64,
    cache: &mut SizeCache,
) -> u64
where
    C: MapStorage<Key = KC::Value, Value = M>,
{
    let mut size = 0u64;
    for (k, v) in map.storage_iter() {
        let slot = cache.reserve();
        let inner = v.compute_size(cache);
        cache.set(slot, inner);
        let entry = sparse_key_len::<KC>(KC::is_default(k), k) + sparse_message_len(inner);
        size += outer_tag_len + varint_len(entry) as u64 + entry;
    }
    size
}

/// [`write_message_field`], leaving a default key or a message that encodes to
/// nothing out of its entry. prost leaves out a message equal to its default
/// instead, which can still encode a field, such as a `required` one.
pub fn write_message_field_omitting_defaults<KC: MapCodec, M: Message, C>(
    map: &C,
    field_number: u32,
    cache: &mut SizeCache,
    buf: &mut impl EncodeSink,
) where
    C: MapStorage<Key = KC::Value, Value = M>,
{
    for (k, v) in map.storage_iter() {
        let inner = cache.consume_next();
        let key_omitted = KC::is_default(k);
        Tag::new(field_number, WireType::LengthDelimited).encode(buf);
        encode_varint(
            sparse_key_len::<KC>(key_omitted, k) + sparse_message_len(inner),
            buf,
        );
        if !key_omitted {
            Tag::new(1, KC::WIRE_TYPE).encode(buf);
            KC::encode(k, buf);
        }
        if inner != 0 {
            Tag::new(2, WireType::LengthDelimited).encode(buf);
            encode_varint(inner as u64, buf);
        }
        // Writes nothing for an empty value, but consumes the slots its
        // `compute_size` reserved.
        v.write_to(cache, buf);
    }
}

fn merge_entry_contents<KC, VC>(
    key: &mut KC::Value,
    val: &mut VC::Value,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
) -> Result<MapValueDecodeStatus, DecodeError>
where
    KC: MapValueDecode,
    VC: MapValueDecode,
{
    // Track the *value* field's status with last-wins semantics: only the
    // final field-2 occurrence decides whether the entry is unknown, matching
    // the protobuf reference implementation. Map keys are never closed enums,
    // so the key codec always returns `Known` and is ignored here.
    let mut val_status = MapValueDecodeStatus::Known;
    while buf.has_remaining() {
        let entry_tag = Tag::decode(buf)?;
        match entry_tag.field_number() {
            1 => {
                check_wire_type(entry_tag, KC::WIRE_TYPE)?;
                KC::merge(key, buf, ctx)?;
            }
            2 => {
                check_wire_type(entry_tag, VC::WIRE_TYPE)?;
                val_status = VC::merge(val, buf, ctx)?;
                if matches!(val_status, MapValueDecodeStatus::Unknown) {
                    ctx.check_unknown_field()?;
                }
            }
            _ => {
                crate::encoding::skip_unknown_field(entry_tag, buf, ctx)?;
            }
        }
    }
    Ok(val_status)
}

/// Decode one length-prefixed map entry from `buf`.
///
/// Closed-enum entries with unknown values are skipped. Use
/// [`merge_entry_with_unknowns`] when generated code has a parent
/// `UnknownFields` set available and needs to preserve those skipped entries.
pub fn merge_entry<KC, VC, C>(
    map: &mut C,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
) -> Result<(), DecodeError>
where
    KC: MapValueDecode,
    VC: MapValueDecode,
    C: MapStorage<Key = KC::Value, Value = VC::Value>,
{
    merge_entry_with_unknowns::<KC, VC, C>(map, buf, ctx, None)
}

/// Decode one length-prefixed map entry from `buf`, inserting it unless the
/// value is an unknown closed-enum number — in which case the whole entry is
/// optionally preserved as an unknown-field record.
///
/// Implements proto map-entry semantics: missing key/value fields take
/// their type defaults, repeated occurrences of a scalar key or value within
/// one entry last-win while repeated occurrences of a message value merge,
/// and unknown entry fields are skipped.
///
/// If the *final* value-field occurrence in the entry is an unknown
/// closed-enum number, the entry is not inserted. When `unknown_fields` is
/// `Some((field_number, fields))`, the whole original map-entry payload is
/// preserved verbatim as a length-delimited unknown field with the outer map
/// field number.
///
/// # Errors
///
/// Returns a [`DecodeError`] on malformed lengths, payloads, or wire-type
/// mismatches inside the entry.
pub fn merge_entry_with_unknowns<KC, VC, C>(
    map: &mut C,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
    unknown_fields: Option<(u32, &mut crate::UnknownFields)>,
) -> Result<(), DecodeError>
where
    KC: MapValueDecode,
    VC: MapValueDecode,
    C: MapStorage<Key = KC::Value, Value = VC::Value>,
{
    let entry_len = decode_varint(buf)?;
    let entry_len = usize::try_from(entry_len).map_err(|_| DecodeError::MessageTooLarge)?;
    if buf.remaining() < entry_len {
        return Err(DecodeError::UnexpectedEof);
    }
    // An entry amplifies exactly as a repeated element does, and by the same
    // route: a message value omitted from the wire still materializes a whole
    // `VC::Value` in the map, and a few bytes of key buy a distinct slot. Charge
    // both halves before decoding either, so a doomed entry costs the check
    // rather than the work.
    ctx.register_element_memory(
        core::mem::size_of::<KC::Value>() + core::mem::size_of::<VC::Value>(),
    )?;
    let mut key = crate::erasing::Erasing::new(KC::Value::default(), C::storage_erase_key);
    let mut val = crate::erasing::Erasing::new(VC::Value::default(), C::storage_erase_value);

    if unknown_fields.is_some() && (KC::MAY_RETURN_UNKNOWN || VC::MAY_RETURN_UNKNOWN) {
        // Fast path for contiguous bufs (the common `&[u8]` / `Bytes` case):
        // decode from a borrowed slice and only allocate when the entry
        // actually turns out to be unknown.
        if buf.chunk().len() >= entry_len {
            let preserved = {
                let entry_slice = &buf.chunk()[..entry_len];
                let mut entry_cur = entry_slice;
                let status =
                    merge_entry_contents::<KC, VC>(&mut key, &mut val, &mut entry_cur, ctx)?;
                matches!(status, MapValueDecodeStatus::Unknown).then(|| entry_slice.to_vec())
            };
            buf.advance(entry_len);
            match preserved {
                None => map.storage_insert(key.into_inner(), val.into_inner()),
                Some(payload) => {
                    if let Some((field_number, unknown_fields)) = unknown_fields {
                        ctx.register_unknown_field()?;
                        unknown_fields.push(crate::UnknownField {
                            number: field_number,
                            data: crate::UnknownFieldData::LengthDelimited(payload),
                        });
                    }
                }
            }
            return Ok(());
        }
        // Non-contiguous fallback: buffer the payload up front so it can be
        // preserved verbatim if decoding reports `Unknown`.
        let entry_payload = buf.copy_to_bytes(entry_len);
        let mut entry_cur = entry_payload.clone();
        let status = merge_entry_contents::<KC, VC>(&mut key, &mut val, &mut entry_cur, ctx)?;
        if matches!(status, MapValueDecodeStatus::Known) {
            map.storage_insert(key.into_inner(), val.into_inner());
        } else if let Some((field_number, unknown_fields)) = unknown_fields {
            ctx.register_unknown_field()?;
            unknown_fields.push(crate::UnknownField {
                number: field_number,
                data: crate::UnknownFieldData::LengthDelimited(entry_payload.to_vec()),
            });
        }
        return Ok(());
    }

    let entry_limit = buf.remaining() - entry_len;
    let mut val_status = MapValueDecodeStatus::Known;
    while buf.remaining() > entry_limit {
        let entry_tag = Tag::decode(buf)?;
        match entry_tag.field_number() {
            1 => {
                check_wire_type(entry_tag, KC::WIRE_TYPE)?;
                KC::merge(&mut key, buf, ctx)?;
            }
            2 => {
                check_wire_type(entry_tag, VC::WIRE_TYPE)?;
                val_status = VC::merge(&mut val, buf, ctx)?;
                if matches!(val_status, MapValueDecodeStatus::Unknown) {
                    ctx.check_unknown_field()?;
                }
            }
            _ => {
                crate::encoding::skip_unknown_field(entry_tag, buf, ctx)?;
            }
        }
    }
    if buf.remaining() != entry_limit {
        let remaining = buf.remaining();
        if remaining > entry_limit {
            buf.advance(remaining - entry_limit);
        } else {
            return Err(DecodeError::UnexpectedEof);
        }
    }
    if matches!(val_status, MapValueDecodeStatus::Known) {
        map.storage_insert(key.into_inner(), val.into_inner());
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::alloc::string::String;
    use crate::alloc::vec::Vec;
    use crate::encoding::skip_field_depth;

    fn encode_field<KC: MapCodec, VC: MapCodec>(
        map: &Map<KC::Value, VC::Value>,
        field_number: u32,
        outer_tag_len: u64,
    ) -> Vec<u8>
    where
        KC::Value: Eq + Hash,
    {
        let len = field_len::<KC, VC, _>(map, outer_tag_len);
        let mut buf = Vec::new();
        write_field::<KC, VC, _>(map, field_number, &mut buf);
        assert_eq!(buf.len() as u64, len, "field_len must match written bytes");
        buf
    }

    fn decode_field<KC, VC>(mut wire: &[u8]) -> Map<KC::Value, VC::Value>
    where
        KC: MapValueDecode,
        KC::Value: Eq + Hash,
        VC: MapValueDecode,
    {
        let mut map = Map::default();
        let limit = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
        while !wire.is_empty() {
            let tag = Tag::decode(&mut wire).unwrap();
            assert_eq!(tag.wire_type(), WireType::LengthDelimited);
            let ctx = DecodeContext::new(crate::RECURSION_LIMIT, &limit);
            merge_entry::<KC, VC, _>(&mut map, &mut wire, ctx).unwrap();
        }
        map
    }

    /// A closed enum whose default, its first value `A`, is not 0. protoc
    /// rejects it as a map value; a descriptor built another way can have it.
    #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
    #[repr(i32)]
    enum FirstIsOne {
        #[default]
        A = 1,
        B = 0,
    }

    impl Enumeration for FirstIsOne {
        fn from_i32(value: i32) -> Option<Self> {
            match value {
                1 => Some(Self::A),
                0 => Some(Self::B),
                _ => None,
            }
        }
        fn to_i32(&self) -> i32 {
            *self as i32
        }
        fn proto_name(&self) -> &'static str {
            match self {
                Self::A => "A",
                Self::B => "B",
            }
        }
    }

    #[test]
    fn string_int32_round_trip() {
        let mut map: Map<String, i32> = Map::default();
        map.insert("a".into(), 1);
        map.insert("bee".into(), -7);
        let wire = encode_field::<Str, Int32>(&map, 5, 1);
        let back = decode_field::<Str, Int32>(&wire);
        assert_eq!(back, map);
    }

    #[test]
    fn proto_string_map_codec_matches_str() {
        // `ProtoStringMap<String>` (the custom-string codec, monomorphized on the
        // built-in `String`) must produce byte-identical output to the canonical
        // `Str` codec and round-trip through it — proving the custom-string map
        // key/value path is wire-compatible with the default.
        let mut map: Map<String, i32> = Map::default();
        map.insert("a".into(), 1);
        map.insert("bee".into(), -7);

        let str_wire = encode_field::<Str, Int32>(&map, 5, 1);
        let custom_wire = encode_field::<ProtoStringMap<String>, Int32>(&map, 5, 1);
        // Map iteration order is unspecified, so compare via decode, not bytes.
        assert_eq!(
            decode_field::<ProtoStringMap<String>, Int32>(&str_wire),
            map
        );
        assert_eq!(decode_field::<Str, Int32>(&custom_wire), map);

        // As a value codec too: `map<int32, string>`.
        let mut vmap: Map<i32, String> = Map::default();
        vmap.insert(1, "x".into());
        let vwire = encode_field::<Int32, ProtoStringMap<String>>(&vmap, 3, 1);
        assert_eq!(decode_field::<Int32, ProtoStringMap<String>>(&vwire), vmap);
    }

    #[test]
    fn fixed_fixed_len_fold_matches_written_bytes() {
        let mut map: Map<u32, f64> = Map::default();
        map.insert(1, 0.5);
        map.insert(9, -2.25);
        map.insert(1000, 0.0);
        // Both codecs fixed-width → field_len takes the folded path; the
        // assert inside encode_field proves it equals the written bytes.
        let wire = encode_field::<Fixed32, Double>(&map, 3, 1);
        let back = decode_field::<Fixed32, Double>(&wire);
        assert_eq!(back, map);
    }

    /// Entries that leave the default key and value out, against the bytes
    /// prost writes for them, decoding back to the same map.
    #[test]
    fn omitting_defaults_leaves_default_fields_out() {
        let encode = |key: &str, value: i32| {
            let mut map: Map<String, i32> = Map::default();
            map.insert(key.into(), value);
            let len = field_len_omitting_defaults::<Str, Int32, _>(&map, 1);
            let mut buf = Vec::new();
            write_field_omitting_defaults::<Str, Int32, _>(&map, 5, &mut buf);
            assert_eq!(buf.len() as u64, len, "the size matches the written bytes");
            assert_eq!(decode_field::<Str, Int32>(&buf), map);
            buf
        };
        // tag 5, length 0: neither field
        assert_eq!(encode("", 0), [0x2a, 0x00]);
        // the key only
        assert_eq!(encode("a", 0), [0x2a, 0x03, 0x0a, 0x01, b'a']);
        // the value only
        assert_eq!(encode("", 7), [0x2a, 0x02, 0x10, 0x07]);
        assert_eq!(
            encode("a", 7),
            encode_field::<Str, Int32>(
                &{
                    let mut map = Map::default();
                    map.insert(String::from("a"), 7);
                    map
                },
                5,
                1
            )
        );
        // `-0.0` is a float's default to `==`, as to prost
        let mut floats: Map<u32, f64> = Map::default();
        floats.insert(1, -0.0);
        let mut buf = Vec::new();
        write_field_omitting_defaults::<Uint32, Double, _>(&floats, 2, &mut buf);
        assert_eq!(buf, [0x12, 0x02, 0x08, 0x01]);
    }

    /// A closed enum value is left out when it is the enum's default, which
    /// need not be 0, as prost leaves it out.
    #[test]
    fn omitting_defaults_compares_a_closed_enum_with_its_default() {
        type Codec = ClosedEnum<FirstIsOne>;
        let encode = |value: FirstIsOne| {
            let mut map: Map<u32, FirstIsOne> = Map::default();
            map.insert(1, value);
            let len = field_len_omitting_defaults::<Uint32, Codec, _>(&map, 1);
            let mut buf = Vec::new();
            write_field_omitting_defaults::<Uint32, Codec, _>(&map, 2, &mut buf);
            assert_eq!(buf.len() as u64, len, "the size matches the written bytes");
            assert_eq!(decode_field::<Uint32, Codec>(&buf), map);
            buf
        };
        // key 1, the default `A` left out
        assert_eq!(encode(FirstIsOne::A), [0x12, 0x02, 0x08, 0x01]);
        // key 1, `B` written although it is 0
        assert_eq!(encode(FirstIsOne::B), [0x12, 0x04, 0x08, 0x01, 0x10, 0x00]);
    }

    /// `is_default` holds for exactly the value a missing entry field decodes
    /// to, for every codec.
    #[test]
    fn is_default_is_the_decoded_default() {
        fn check<C: MapCodec>(default: C::Value, others: &[C::Value]) {
            // An entry with neither field: key 0, the value's default.
            let decoded = decode_field::<Int32, C>(&[0x0a, 0x00]);
            assert!(C::is_default(&decoded[&0]));
            assert!(C::is_default(&default));
            for other in others {
                assert!(!C::is_default(other));
            }
        }
        #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
        #[repr(i32)]
        enum E {
            #[default]
            A = 0,
            B = 1,
        }
        impl Enumeration for E {
            fn from_i32(value: i32) -> Option<Self> {
                match value {
                    0 => Some(E::A),
                    1 => Some(E::B),
                    _ => None,
                }
            }
            fn to_i32(&self) -> i32 {
                *self as i32
            }
            fn proto_name(&self) -> &'static str {
                match self {
                    E::A => "A",
                    E::B => "B",
                }
            }
        }
        check::<Int32>(0, &[1, -1]);
        check::<Int64>(0, &[1, i64::MIN]);
        check::<Uint32>(0, &[1]);
        check::<Uint64>(0, &[u64::MAX]);
        check::<Sint32>(0, &[-1]);
        check::<Sint64>(0, &[-1]);
        check::<Fixed32>(0, &[1]);
        check::<Fixed64>(0, &[1]);
        check::<Sfixed32>(0, &[-1]);
        check::<Sfixed64>(0, &[-1]);
        check::<Bool>(false, &[true]);
        check::<Float>(0.0, &[1.0, f32::NAN, f32::MIN_POSITIVE]);
        check::<Float>(-0.0, &[]);
        check::<Double>(0.0, &[1.0, f64::NAN, f64::MIN_POSITIVE]);
        check::<Double>(-0.0, &[]);
        check::<Str>(String::new(), &["a".into()]);
        check::<BytesVec>(Vec::new(), &[vec![0]]);
        check::<BytesBuf>(
            crate::bytes::Bytes::new(),
            &[crate::bytes::Bytes::from_static(&[0])],
        );
        check::<ProtoStringMap<String>>(String::new(), &[" ".into()]);
        check::<ProtoBytesMap<Vec<u8>>>(Vec::new(), &[vec![0]]);
        check::<OpenEnum<E>>(
            EnumValue::from(0),
            &[EnumValue::from(1), EnumValue::Unknown(7)],
        );
        check::<ClosedEnum<E>>(E::A, &[E::B]);
        // A missing closed enum decodes as its first value, an open one as 0.
        check::<ClosedEnum<FirstIsOne>>(FirstIsOne::A, &[FirstIsOne::B]);
        check::<OpenEnum<FirstIsOne>>(EnumValue::from(0), &[EnumValue::from(1)]);
    }

    #[test]
    fn missing_key_and_value_take_defaults() {
        // Entry with no fields at all: length prefix 0.
        let wire = [0x00u8];
        let mut map: Map<String, i32> = Map::default();
        let limit = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
        merge_entry::<Str, Int32, _>(&mut map, &mut &wire[..], DecodeContext::new(10, &limit))
            .unwrap();
        assert_eq!(map.get(""), Some(&0));
    }

    #[test]
    fn unknown_entry_field_is_skipped() {
        // key "a" (field 1), unknown varint field 3, value 7 (field 2).
        let mut entry = Vec::new();
        Tag::new(1, WireType::LengthDelimited).encode(&mut entry);
        types::encode_string("a", &mut entry);
        Tag::new(3, WireType::Varint).encode(&mut entry);
        encode_varint(99, &mut entry);
        Tag::new(2, WireType::Varint).encode(&mut entry);
        types::encode_int32(7, &mut entry);
        let mut wire = Vec::new();
        encode_varint(entry.len() as u64, &mut wire);
        wire.extend_from_slice(&entry);

        let mut map: Map<String, i32> = Map::default();
        let limit = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
        merge_entry::<Str, Int32, _>(
            &mut map,
            &mut wire.as_slice(),
            DecodeContext::new(10, &limit),
        )
        .unwrap();
        assert_eq!(map.get("a"), Some(&7));
    }

    #[test]
    fn entry_wire_type_mismatch_errors() {
        // Field 1 claims Fixed64 for a string key.
        let mut entry = Vec::new();
        Tag::new(1, WireType::Fixed64).encode(&mut entry);
        entry.extend_from_slice(&[0u8; 8]);
        let mut wire = Vec::new();
        encode_varint(entry.len() as u64, &mut wire);
        wire.extend_from_slice(&entry);

        let mut map: Map<String, i32> = Map::default();
        let limit = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
        let err = merge_entry::<Str, Int32, _>(
            &mut map,
            &mut wire.as_slice(),
            DecodeContext::new(10, &limit),
        )
        .unwrap_err();
        assert!(matches!(err, DecodeError::WireTypeMismatch { .. }));
    }

    #[test]
    fn truncated_entry_errors() {
        // Length prefix promises 5 bytes; only 1 available.
        let wire = [0x05u8, 0x08];
        let mut map: Map<String, i32> = Map::default();
        let limit = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
        let err =
            merge_entry::<Str, Int32, _>(&mut map, &mut &wire[..], DecodeContext::new(10, &limit))
                .unwrap_err();
        assert!(matches!(err, DecodeError::UnexpectedEof));
    }

    #[test]
    fn message_map_two_pass_round_trip() {
        use crate::{DefaultInstance, SizeCache};

        #[derive(Clone, PartialEq, Eq, Debug, Default)]
        struct FlatMsg {
            value: i32,
        }

        impl DefaultInstance for FlatMsg {
            fn default_instance() -> &'static Self {
                static INST: crate::__private::OnceBox<FlatMsg> = crate::__private::OnceBox::new();
                INST.get_or_init(|| crate::alloc::boxed::Box::new(FlatMsg::default()))
            }
        }

        impl Message for FlatMsg {
            fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
                if self.value != 0 {
                    1 + types::int32_encoded_len(self.value) as u32
                } else {
                    0
                }
            }
            fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
                if self.value != 0 {
                    Tag::new(1, WireType::Varint).encode(buf);
                    types::encode_int32(self.value, buf);
                }
            }
            fn merge_field(
                &mut self,
                tag: Tag,
                buf: &mut impl Buf,
                ctx: DecodeContext<'_>,
            ) -> Result<(), DecodeError> {
                match tag.field_number() {
                    1 => self.value = types::decode_int32(buf)?,
                    _ => skip_field_depth(tag, buf, ctx.depth())?,
                }
                Ok(())
            }
            fn clear(&mut self) {
                *self = Self::default();
            }
        }

        let mut map: Map<i32, FlatMsg> = Map::default();
        map.insert(1, FlatMsg { value: 0 }); // empty payload entry
        map.insert(2, FlatMsg { value: -3 }); // multi-byte varint payload
        map.insert(9, FlatMsg { value: 7 });

        // Two-pass: message_field_len reserves SizeCache slots in map
        // iteration order; write_message_field consumes them in the same
        // order. The size must equal the written bytes exactly.
        let mut cache = SizeCache::default();
        let len = message_field_len::<Int32, FlatMsg, _>(&map, 1, &mut cache);
        let mut wire = Vec::new();
        write_message_field::<Int32, FlatMsg, _>(&map, 4, &mut cache, &mut wire);
        assert_eq!(wire.len() as u64, len, "size pass must match write pass");

        let back = decode_field::<Int32, Msg<FlatMsg>>(&wire);
        assert_eq!(back, map);

        // Omitting defaults: the empty message and the zero key go, the
        // slots stay in step.
        let mut cache = SizeCache::default();
        let mut sparse: Map<i32, FlatMsg> = Map::default();
        sparse.insert(0, FlatMsg { value: 5 });
        sparse.insert(1, FlatMsg { value: 0 });
        sparse.insert(2, FlatMsg { value: -3 });
        let len = message_field_len_omitting_defaults::<Int32, FlatMsg, _>(&sparse, 1, &mut cache);
        let mut wire = Vec::new();
        write_message_field_omitting_defaults::<Int32, FlatMsg, _>(
            &sparse, 4, &mut cache, &mut wire,
        );
        assert_eq!(wire.len() as u64, len, "size pass must match write pass");
        assert_eq!(decode_field::<Int32, Msg<FlatMsg>>(&wire), sparse);
        let entries: Vec<Vec<u8>> = {
            let mut rest = wire.as_slice();
            let mut out = Vec::new();
            while !rest.is_empty() {
                Tag::decode(&mut rest).unwrap();
                let len = decode_varint(&mut rest).unwrap() as usize;
                out.push(rest[..len].to_vec());
                rest = &rest[len..];
            }
            out
        };
        // key 0 left out, value 5; key 1, the empty value left out
        assert!(
            entries.contains(&vec![0x12, 0x02, 0x08, 0x05]),
            "{entries:?}"
        );
        assert!(entries.contains(&vec![0x08, 0x01]), "{entries:?}");

        // A value that reserves a slot of its own, after an empty one: the
        // slots stay in step.
        #[derive(Clone, PartialEq, Eq, Debug, Default)]
        struct Outer {
            inner: Option<FlatMsg>,
        }

        impl DefaultInstance for Outer {
            fn default_instance() -> &'static Self {
                static INST: crate::__private::OnceBox<Outer> = crate::__private::OnceBox::new();
                INST.get_or_init(|| crate::alloc::boxed::Box::new(Outer::default()))
            }
        }

        impl Message for Outer {
            fn compute_size(&self, cache: &mut SizeCache) -> u32 {
                let Some(inner) = &self.inner else {
                    return 0;
                };
                let slot = cache.reserve();
                let len = inner.compute_size(cache);
                cache.set(slot, len);
                1 + varint_len(len as u64) as u32 + len
            }
            fn write_to(&self, cache: &mut SizeCache, buf: &mut impl EncodeSink) {
                if let Some(inner) = &self.inner {
                    let len = cache.consume_next();
                    Tag::new(1, WireType::LengthDelimited).encode(buf);
                    encode_varint(len as u64, buf);
                    inner.write_to(cache, buf);
                }
            }
            fn merge_field(
                &mut self,
                tag: Tag,
                buf: &mut impl Buf,
                ctx: DecodeContext<'_>,
            ) -> Result<(), DecodeError> {
                match tag.field_number() {
                    1 => Message::merge_length_delimited(
                        self.inner.get_or_insert_with(FlatMsg::default),
                        buf,
                        ctx,
                    )?,
                    _ => skip_field_depth(tag, buf, ctx.depth())?,
                }
                Ok(())
            }
            fn clear(&mut self) {
                *self = Self::default();
            }
        }

        let mut nested = crate::alloc::collections::BTreeMap::new();
        nested.insert(1, Outer::default());
        nested.insert(
            2,
            Outer {
                inner: Some(FlatMsg { value: 7 }),
            },
        );
        let mut cache = SizeCache::default();
        let len = message_field_len_omitting_defaults::<Int32, Outer, _>(&nested, 1, &mut cache);
        let mut wire = Vec::new();
        write_message_field_omitting_defaults::<Int32, Outer, _>(&nested, 4, &mut cache, &mut wire);
        assert_eq!(wire.len() as u64, len, "size pass must match write pass");
        #[rustfmt::skip]
        assert_eq!(wire, [
            0x22, 0x02, 0x08, 0x01, // key 1, the empty value left out
            0x22, 0x08, 0x08, 0x02, 0x12, 0x04, 0x0a, 0x02, 0x08, 0x07, // key 2
        ]);
    }

    #[test]
    fn open_enum_value_preserves_unknown() {
        #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
        #[repr(i32)]
        enum E {
            #[default]
            A = 0,
        }
        impl Enumeration for E {
            fn from_i32(value: i32) -> Option<Self> {
                (value == 0).then_some(E::A)
            }
            fn to_i32(&self) -> i32 {
                *self as i32
            }
            fn proto_name(&self) -> &'static str {
                "A"
            }
            fn from_proto_name(name: &str) -> Option<Self> {
                (name == "A").then_some(E::A)
            }
        }

        let mut map: Map<i32, EnumValue<E>> = Map::default();
        map.insert(1, EnumValue::Unknown(42));
        let wire = encode_field::<Int32, OpenEnum<E>>(&map, 2, 1);
        let back = decode_field::<Int32, OpenEnum<E>>(&wire);
        assert_eq!(back.get(&1), Some(&EnumValue::Unknown(42)));

        // Closed codec drops the whole map entry instead of inserting the
        // default enum value.
        let back = decode_field::<Int32, ClosedEnum<E>>(&wire);
        assert!(!back.contains_key(&1));
    }

    #[test]
    fn closed_enum_unknown_preserves_whole_entry_when_requested() {
        #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
        #[repr(i32)]
        enum E {
            #[default]
            A = 0,
            B = 1,
        }
        impl Enumeration for E {
            fn from_i32(value: i32) -> Option<Self> {
                match value {
                    0 => Some(E::A),
                    1 => Some(E::B),
                    _ => None,
                }
            }
            fn to_i32(&self) -> i32 {
                *self as i32
            }
            fn proto_name(&self) -> &'static str {
                match self {
                    E::A => "A",
                    E::B => "B",
                }
            }
        }

        let mut entry = Vec::new();
        Tag::new(1, WireType::Varint).encode(&mut entry);
        types::encode_int32(7, &mut entry);
        Tag::new(2, WireType::Varint).encode(&mut entry);
        types::encode_int32(99, &mut entry);

        let mut wire = Vec::new();
        encode_varint(entry.len() as u64, &mut wire);
        wire.extend_from_slice(&entry);

        let mut map: Map<i32, E> = Map::default();
        let mut unknown_fields = crate::UnknownFields::new();
        let limit = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
        merge_entry_with_unknowns::<Int32, ClosedEnum<E>, _>(
            &mut map,
            &mut wire.as_slice(),
            DecodeContext::new(10, &limit),
            Some((5, &mut unknown_fields)),
        )
        .unwrap();

        assert!(map.is_empty());
        let unknowns: Vec<_> = unknown_fields.iter().collect();
        assert_eq!(unknowns.len(), 1);
        assert_eq!(unknowns[0].number, 5);
        assert!(matches!(
            &unknowns[0].data,
            crate::UnknownFieldData::LengthDelimited(payload) if payload == &entry
        ));

        // Non-contiguous Buf takes the buffering fallback and produces the
        // same outcome. Split *inside* the entry payload so that after the
        // length prefix is consumed, the first chunk is shorter than
        // `entry_len` and the contiguous fast path is bypassed.
        let mut map: Map<i32, E> = Map::default();
        let mut unknown_fields = crate::UnknownFields::new();
        let (a, b) = wire.split_at(3);
        let mut chained = bytes::Buf::chain(a, b);
        merge_entry_with_unknowns::<Int32, ClosedEnum<E>, _>(
            &mut map,
            &mut chained,
            DecodeContext::new(10, &limit),
            Some((5, &mut unknown_fields)),
        )
        .unwrap();
        assert!(map.is_empty());
        let unknowns: Vec<_> = unknown_fields.iter().collect();
        assert_eq!(unknowns.len(), 1);
        assert!(matches!(
            &unknowns[0].data,
            crate::UnknownFieldData::LengthDelimited(payload) if payload == &entry
        ));

        // Last-wins: an unknown value followed by a known one inserts the
        // known value and records nothing in unknown fields.
        let mut entry = Vec::new();
        Tag::new(1, WireType::Varint).encode(&mut entry);
        types::encode_int32(7, &mut entry);
        Tag::new(2, WireType::Varint).encode(&mut entry);
        types::encode_int32(99, &mut entry);
        Tag::new(2, WireType::Varint).encode(&mut entry);
        types::encode_int32(1, &mut entry);

        let mut wire = Vec::new();
        encode_varint(entry.len() as u64, &mut wire);
        wire.extend_from_slice(&entry);

        let mut map: Map<i32, E> = Map::default();
        let mut unknown_fields = crate::UnknownFields::new();
        merge_entry_with_unknowns::<Int32, ClosedEnum<E>, _>(
            &mut map,
            &mut wire.as_slice(),
            DecodeContext::new(10, &limit),
            Some((5, &mut unknown_fields)),
        )
        .unwrap();
        assert_eq!(map.get(&7), Some(&E::B));
        assert_eq!(unknown_fields.iter().count(), 0);
    }
}