Skip to main content

odradek_protocol/
wire.rs

1//! Primitive codecs for the Kafka wire format.
2//!
3//! Fixed-width integers are big-endian and provided directly by [`bytes`];
4//! this module adds the Kafka-specific primitives: unsigned varints
5//! (protobuf-style LEB128), zigzag-encoded signed varints, length-prefixed
6//! strings/bytes in both classic and compact ("flexible version") forms, and
7//! tagged fields.
8//!
9//! Decoders take `&mut impl Buf` and never panic on malformed input; every
10//! failure is a [`DecodeError`]. Encoders take `&mut impl BufMut` and only
11//! fail when a value cannot be represented (see [`EncodeError`]).
12//!
13//! The one decoder here that allocates per wire element —
14//! [`get_tagged_fields`] — spends against a [`Budget`]; see
15//! [`crate::budget`] for the bound that puts on it.
16
17use bytes::{Buf, BufMut, Bytes};
18
19use crate::budget::{Budget, Limits};
20use crate::error::{DecodeError, EncodeError};
21
22/// Ensure `buf` has at least `needed` readable bytes.
23fn ensure(buf: &impl Buf, needed: usize) -> Result<(), DecodeError> {
24    if buf.remaining() < needed {
25        Err(DecodeError::Truncated {
26            needed: needed - buf.remaining(),
27        })
28    } else {
29        Ok(())
30    }
31}
32
33fn len_from(raw: i64) -> Result<usize, DecodeError> {
34    usize::try_from(raw).map_err(|_| DecodeError::InvalidLength(raw))
35}
36
37/// Convert a compact length (already offset by -1) to `usize`, rejecting
38/// values that cannot fit in memory on this platform.
39fn compact_len(raw: u64) -> Result<usize, DecodeError> {
40    usize::try_from(raw)
41        .map_err(|_| DecodeError::InvalidLength(i64::try_from(raw).unwrap_or(i64::MAX)))
42}
43
44// ---------------------------------------------------------------------------
45// Fixed-width values
46// ---------------------------------------------------------------------------
47//
48// `Buf`'s own getters panic when the buffer is short; codecs must never do
49// that on wire input, so every fixed-width read goes through these.
50
51macro_rules! checked_get {
52    ($(#[$doc:meta] $name:ident -> $ty:ty [$len:expr] via $method:ident;)+) => {
53        $(
54            #[$doc]
55            pub fn $name(buf: &mut impl Buf) -> Result<$ty, DecodeError> {
56                ensure(buf, $len)?;
57                Ok(buf.$method())
58            }
59        )+
60    };
61}
62
63checked_get! {
64    /// Decode an `INT8`.
65    get_i8 -> i8 [1] via get_i8;
66    /// Decode an `INT16` (big-endian).
67    get_i16 -> i16 [2] via get_i16;
68    /// Decode a `UINT16` (big-endian).
69    get_u16 -> u16 [2] via get_u16;
70    /// Decode an `INT32` (big-endian).
71    get_i32 -> i32 [4] via get_i32;
72    /// Decode a `UINT32` (big-endian).
73    get_u32 -> u32 [4] via get_u32;
74    /// Decode an `INT64` (big-endian).
75    get_i64 -> i64 [8] via get_i64;
76    /// Decode a `FLOAT64` (big-endian IEEE 754).
77    get_f64 -> f64 [8] via get_f64;
78}
79
80/// Decode a `BOOLEAN` (any non-zero byte is true).
81pub fn get_bool(buf: &mut impl Buf) -> Result<bool, DecodeError> {
82    ensure(buf, 1)?;
83    Ok(buf.get_u8() != 0)
84}
85
86// ---------------------------------------------------------------------------
87// Varints
88// ---------------------------------------------------------------------------
89
90/// Encode an `UNSIGNED_VARINT` (LEB128, low 7 bits first).
91pub fn put_unsigned_varint(buf: &mut impl BufMut, mut value: u64) {
92    loop {
93        let mut byte = (value & 0x7f) as u8;
94        value >>= 7;
95        if value != 0 {
96            byte |= 0x80;
97        }
98        buf.put_u8(byte);
99        if value == 0 {
100            return;
101        }
102    }
103}
104
105/// Decode an `UNSIGNED_VARINT`. At most 10 bytes; rejects encodings that
106/// overflow 64 bits.
107pub fn get_unsigned_varint(buf: &mut impl Buf) -> Result<u64, DecodeError> {
108    let mut value = 0u64;
109    let mut shift = 0u32;
110    loop {
111        ensure(buf, 1)?;
112        let byte = buf.get_u8();
113        if shift == 63 && byte & 0xfe != 0 {
114            return Err(DecodeError::VarintOverflow);
115        }
116        value |= u64::from(byte & 0x7f) << shift;
117        if byte & 0x80 == 0 {
118            return Ok(value);
119        }
120        shift += 7;
121        if shift > 63 {
122            return Err(DecodeError::VarintOverflow);
123        }
124    }
125}
126
127/// Encode a signed `VARINT`/`VARLONG` using zigzag encoding.
128pub fn put_varint(buf: &mut impl BufMut, value: i64) {
129    put_unsigned_varint(buf, zigzag_encode(value));
130}
131
132/// Decode a signed `VARINT`/`VARLONG` using zigzag encoding.
133pub fn get_varint(buf: &mut impl Buf) -> Result<i64, DecodeError> {
134    Ok(zigzag_decode(get_unsigned_varint(buf)?))
135}
136
137fn zigzag_encode(value: i64) -> u64 {
138    ((value << 1) ^ (value >> 63)) as u64
139}
140
141fn zigzag_decode(value: u64) -> i64 {
142    ((value >> 1) as i64) ^ -((value & 1) as i64)
143}
144
145/// Number of bytes [`put_varint`] emits for `value`. Lets an encoder
146/// size a body before writing it instead of measuring a side buffer.
147pub(crate) fn varint_len(value: i64) -> usize {
148    unsigned_varint_len(zigzag_encode(value))
149}
150
151/// Number of bytes [`put_unsigned_varint`] emits for `value`.
152pub fn unsigned_varint_len(value: u64) -> usize {
153    // 1 byte per started 7-bit group; value 0 still takes one byte.
154    let bits = 64 - value.leading_zeros() as usize;
155    bits.div_ceil(7).max(1)
156}
157
158// ---------------------------------------------------------------------------
159// Strings
160// ---------------------------------------------------------------------------
161
162/// Encode a classic `STRING` (i16 length prefix).
163pub fn put_string(buf: &mut impl BufMut, value: &str) -> Result<(), EncodeError> {
164    let len = i16::try_from(value.len()).map_err(|_| EncodeError::TooLong {
165        len: value.len(),
166        max: i16::MAX as usize,
167    })?;
168    buf.put_i16(len);
169    buf.put_slice(value.as_bytes());
170    Ok(())
171}
172
173/// Encode a classic `NULLABLE_STRING` (length -1 marks null).
174pub fn put_nullable_string(buf: &mut impl BufMut, value: Option<&str>) -> Result<(), EncodeError> {
175    match value {
176        Some(s) => put_string(buf, s),
177        None => {
178            buf.put_i16(-1);
179            Ok(())
180        }
181    }
182}
183
184/// Decode a classic `STRING`; a null marker is an error here.
185pub fn get_string(buf: &mut impl Buf) -> Result<String, DecodeError> {
186    get_nullable_string(buf)?.ok_or(DecodeError::InvalidLength(-1))
187}
188
189/// Decode a classic `NULLABLE_STRING`.
190pub fn get_nullable_string(buf: &mut impl Buf) -> Result<Option<String>, DecodeError> {
191    ensure(buf, 2)?;
192    let raw = buf.get_i16();
193    if raw == -1 {
194        return Ok(None);
195    }
196    let len = len_from(raw.into())?;
197    read_utf8(buf, len).map(Some)
198}
199
200/// Encode a `COMPACT_STRING` (unsigned varint of length + 1).
201pub fn put_compact_string(buf: &mut impl BufMut, value: &str) {
202    put_unsigned_varint(buf, value.len() as u64 + 1);
203    buf.put_slice(value.as_bytes());
204}
205
206/// Encode a `COMPACT_NULLABLE_STRING` (0 marks null).
207pub fn put_compact_nullable_string(buf: &mut impl BufMut, value: Option<&str>) {
208    match value {
209        Some(s) => put_compact_string(buf, s),
210        None => put_unsigned_varint(buf, 0),
211    }
212}
213
214/// Decode a `COMPACT_STRING`; a null marker is an error here.
215pub fn get_compact_string(buf: &mut impl Buf) -> Result<String, DecodeError> {
216    get_compact_nullable_string(buf)?.ok_or(DecodeError::InvalidLength(-1))
217}
218
219/// Decode a `COMPACT_NULLABLE_STRING`.
220pub fn get_compact_nullable_string(buf: &mut impl Buf) -> Result<Option<String>, DecodeError> {
221    match get_unsigned_varint(buf)? {
222        0 => Ok(None),
223        n => read_utf8(buf, compact_len(n - 1)?).map(Some),
224    }
225}
226
227fn read_utf8(buf: &mut impl Buf, len: usize) -> Result<String, DecodeError> {
228    ensure(buf, len)?;
229    let bytes = buf.copy_to_bytes(len);
230    String::from_utf8(bytes.into()).map_err(|_| DecodeError::InvalidUtf8)
231}
232
233// ---------------------------------------------------------------------------
234// Bytes
235// ---------------------------------------------------------------------------
236
237/// Encode classic `BYTES` (i32 length prefix).
238pub fn put_bytes(buf: &mut impl BufMut, value: &[u8]) -> Result<(), EncodeError> {
239    let len = i32::try_from(value.len()).map_err(|_| EncodeError::TooLong {
240        len: value.len(),
241        max: i32::MAX as usize,
242    })?;
243    buf.put_i32(len);
244    buf.put_slice(value);
245    Ok(())
246}
247
248/// Encode classic `NULLABLE_BYTES` (length -1 marks null).
249pub fn put_nullable_bytes(buf: &mut impl BufMut, value: Option<&[u8]>) -> Result<(), EncodeError> {
250    match value {
251        Some(b) => put_bytes(buf, b),
252        None => {
253            buf.put_i32(-1);
254            Ok(())
255        }
256    }
257}
258
259/// Decode classic `NULLABLE_BYTES`.
260pub fn get_nullable_bytes(buf: &mut impl Buf) -> Result<Option<Bytes>, DecodeError> {
261    ensure(buf, 4)?;
262    let raw = buf.get_i32();
263    if raw == -1 {
264        return Ok(None);
265    }
266    let len = len_from(raw.into())?;
267    ensure(buf, len)?;
268    Ok(Some(buf.copy_to_bytes(len)))
269}
270
271/// Encode `COMPACT_BYTES` (unsigned varint of length + 1).
272pub fn put_compact_bytes(buf: &mut impl BufMut, value: &[u8]) {
273    put_unsigned_varint(buf, value.len() as u64 + 1);
274    buf.put_slice(value);
275}
276
277/// Encode `COMPACT_NULLABLE_BYTES` (0 marks null).
278pub fn put_compact_nullable_bytes(buf: &mut impl BufMut, value: Option<&[u8]>) {
279    match value {
280        Some(b) => put_compact_bytes(buf, b),
281        None => put_unsigned_varint(buf, 0),
282    }
283}
284
285/// Decode `COMPACT_NULLABLE_BYTES`.
286pub fn get_compact_nullable_bytes(buf: &mut impl Buf) -> Result<Option<Bytes>, DecodeError> {
287    match get_unsigned_varint(buf)? {
288        0 => Ok(None),
289        n => {
290            let len = compact_len(n - 1)?;
291            ensure(buf, len)?;
292            Ok(Some(buf.copy_to_bytes(len)))
293        }
294    }
295}
296
297// ---------------------------------------------------------------------------
298// Array length prefixes
299// ---------------------------------------------------------------------------
300
301/// Encode a classic `ARRAY` length prefix (`None` marks a null array).
302pub fn put_array_len(buf: &mut impl BufMut, len: Option<usize>) -> Result<(), EncodeError> {
303    match len {
304        Some(n) => {
305            let n = i32::try_from(n).map_err(|_| EncodeError::TooLong {
306                len: n,
307                max: i32::MAX as usize,
308            })?;
309            buf.put_i32(n);
310        }
311        None => buf.put_i32(-1),
312    }
313    Ok(())
314}
315
316/// Decode a classic `ARRAY` length prefix (`None` marks a null array).
317pub fn get_array_len(buf: &mut impl Buf) -> Result<Option<usize>, DecodeError> {
318    ensure(buf, 4)?;
319    let raw = buf.get_i32();
320    if raw == -1 {
321        return Ok(None);
322    }
323    len_from(raw.into()).map(Some)
324}
325
326/// Encode a `COMPACT_ARRAY` length prefix (varint of length + 1, 0 is null).
327pub fn put_compact_array_len(buf: &mut impl BufMut, len: Option<usize>) {
328    match len {
329        Some(n) => put_unsigned_varint(buf, n as u64 + 1),
330        None => put_unsigned_varint(buf, 0),
331    }
332}
333
334/// Decode a `COMPACT_ARRAY` length prefix (`None` marks a null array).
335pub fn get_compact_array_len(buf: &mut impl Buf) -> Result<Option<usize>, DecodeError> {
336    match get_unsigned_varint(buf)? {
337        0 => Ok(None),
338        n => compact_len(n - 1).map(Some),
339    }
340}
341
342// ---------------------------------------------------------------------------
343// UUID
344// ---------------------------------------------------------------------------
345
346/// Encode a `UUID` (16 raw bytes, big-endian field order as sent by Kafka).
347pub fn put_uuid(buf: &mut impl BufMut, value: [u8; 16]) {
348    buf.put_slice(&value);
349}
350
351/// Decode a `UUID`.
352pub fn get_uuid(buf: &mut impl Buf) -> Result<[u8; 16], DecodeError> {
353    ensure(buf, 16)?;
354    let mut out = [0u8; 16];
355    buf.copy_to_slice(&mut out);
356    Ok(out)
357}
358
359// ---------------------------------------------------------------------------
360// Tagged fields (KIP-482 flexible versions)
361// ---------------------------------------------------------------------------
362
363/// A single tagged field, kept as raw bytes so unknown tags round-trip
364/// losslessly — required for proxying and for acceptance testing against
365/// implementations newer than this crate.
366#[derive(Debug, Clone, PartialEq, Eq)]
367pub struct RawTaggedField {
368    pub tag: u32,
369    pub data: Bytes,
370}
371
372/// Encode a tagged-field section. Fields must be sorted by tag per the spec;
373/// this function encodes in the order given.
374pub fn put_tagged_fields(buf: &mut impl BufMut, fields: &[RawTaggedField]) {
375    put_unsigned_varint(buf, fields.len() as u64);
376    for field in fields {
377        put_unsigned_varint(buf, u64::from(field.tag));
378        put_unsigned_varint(buf, field.data.len() as u64);
379        buf.put_slice(&field.data);
380    }
381}
382
383/// Decode a tagged-field section, preserving unknown tags as raw bytes.
384///
385/// Allocation is bounded by a [`Budget`] derived from `buf`'s remaining
386/// length; see [`get_tagged_fields_with_budget`] to share one budget
387/// across a whole message.
388pub fn get_tagged_fields(buf: &mut impl Buf) -> Result<Vec<RawTaggedField>, DecodeError> {
389    let mut budget = Limits::default().budget(buf.remaining());
390    get_tagged_fields_with_budget(buf, &mut budget)
391}
392
393/// Decode a tagged-field section, charging `budget` for what it keeps.
394///
395/// Tags must be **strictly ascending**, which the spec requires and the
396/// Java implementation enforces. Accepting anything else is a
397/// parser-differential primitive: a section carrying tag 0 twice would
398/// decode to whichever copy came last, with the first vanishing — not
399/// even preserved in `unknown_tagged_fields` — so the bytes this crate
400/// re-encoded would not be the bytes it was handed, and two
401/// implementations reading the same frame would disagree about its
402/// contents.
403pub fn get_tagged_fields_with_budget(
404    buf: &mut impl Buf,
405    budget: &mut Budget,
406) -> Result<Vec<RawTaggedField>, DecodeError> {
407    let count = get_unsigned_varint(buf)?;
408    let mut fields: Vec<RawTaggedField> = Vec::new();
409    let mut previous: Option<u32> = None;
410    for _ in 0..count {
411        // No progress check here: a tag costs at least its own varint
412        // plus a length varint, so this loop always consumes input.
413        let tag =
414            u32::try_from(get_unsigned_varint(buf)?).map_err(|_| DecodeError::VarintOverflow)?;
415        if let Some(previous) = previous {
416            if tag <= previous {
417                return Err(DecodeError::TaggedFieldOrder { previous, tag });
418            }
419        }
420        previous = Some(tag);
421        let len = len_from(i64::try_from(get_unsigned_varint(buf)?).unwrap_or(-1))?;
422        ensure(buf, len)?;
423        budget.push(
424            &mut fields,
425            RawTaggedField {
426                tag,
427                data: buf.copy_to_bytes(len),
428            },
429        )?;
430    }
431    Ok(fields)
432}
433
434#[cfg(test)]
435mod tests {
436    use super::*;
437    use bytes::BytesMut;
438
439    #[track_caller]
440    fn roundtrip_unsigned(value: u64) {
441        let mut buf = BytesMut::new();
442        put_unsigned_varint(&mut buf, value);
443        assert_eq!(buf.len(), unsigned_varint_len(value), "length of {value}");
444        let mut read = buf.freeze();
445        assert_eq!(get_unsigned_varint(&mut read), Ok(value));
446        assert!(!read.has_remaining());
447    }
448
449    #[test]
450    fn unsigned_varint_roundtrip() {
451        for value in [0, 1, 127, 128, 300, 16383, 16384, u32::MAX as u64, u64::MAX] {
452            roundtrip_unsigned(value);
453        }
454    }
455
456    #[test]
457    fn unsigned_varint_known_encoding() {
458        let mut buf = BytesMut::new();
459        put_unsigned_varint(&mut buf, 300);
460        assert_eq!(&buf[..], &[0xac, 0x02]);
461    }
462
463    #[test]
464    fn unsigned_varint_overflow_rejected() {
465        // 11 continuation bytes can never be a valid u64.
466        let mut buf = Bytes::from_static(&[0x80; 11]);
467        assert_eq!(
468            get_unsigned_varint(&mut buf),
469            Err(DecodeError::VarintOverflow)
470        );
471        // 10th byte with value bits above the 64th bit.
472        let mut buf =
473            Bytes::from_static(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02]);
474        assert_eq!(
475            get_unsigned_varint(&mut buf),
476            Err(DecodeError::VarintOverflow)
477        );
478    }
479
480    #[test]
481    fn unsigned_varint_truncated() {
482        let mut buf = Bytes::from_static(&[0x80]);
483        assert_eq!(
484            get_unsigned_varint(&mut buf),
485            Err(DecodeError::Truncated { needed: 1 })
486        );
487    }
488
489    #[test]
490    fn zigzag_known_values() {
491        for (plain, encoded) in [(0i64, 0u64), (-1, 1), (1, 2), (-2, 3), (2, 4)] {
492            assert_eq!(zigzag_encode(plain), encoded);
493            assert_eq!(zigzag_decode(encoded), plain);
494        }
495        assert_eq!(zigzag_decode(zigzag_encode(i64::MIN)), i64::MIN);
496        assert_eq!(zigzag_decode(zigzag_encode(i64::MAX)), i64::MAX);
497    }
498
499    #[test]
500    fn signed_varint_roundtrip() {
501        for value in [0i64, -1, 1, -300, 300, i32::MIN as i64, i64::MAX, i64::MIN] {
502            let mut buf = BytesMut::new();
503            put_varint(&mut buf, value);
504            assert_eq!(get_varint(&mut buf.freeze()), Ok(value));
505        }
506    }
507
508    #[test]
509    fn string_roundtrip() {
510        let mut buf = BytesMut::new();
511        put_string(&mut buf, "hello").unwrap();
512        assert_eq!(&buf[..], b"\x00\x05hello");
513        assert_eq!(get_string(&mut buf.freeze()).unwrap(), "hello");
514    }
515
516    #[test]
517    fn nullable_string_null() {
518        let mut buf = BytesMut::new();
519        put_nullable_string(&mut buf, None).unwrap();
520        assert_eq!(&buf[..], &[0xff, 0xff]);
521        assert_eq!(get_nullable_string(&mut buf.freeze()), Ok(None));
522    }
523
524    #[test]
525    fn compact_string_roundtrip() {
526        let mut buf = BytesMut::new();
527        put_compact_string(&mut buf, "topic-a");
528        assert_eq!(buf[0], 8); // len + 1
529        assert_eq!(get_compact_string(&mut buf.freeze()).unwrap(), "topic-a");
530
531        let mut buf = BytesMut::new();
532        put_compact_nullable_string(&mut buf, None);
533        assert_eq!(&buf[..], &[0x00]);
534        assert_eq!(get_compact_nullable_string(&mut buf.freeze()), Ok(None));
535    }
536
537    #[test]
538    fn invalid_utf8_rejected() {
539        let mut buf = Bytes::from_static(&[0x00, 0x02, 0xff, 0xfe]);
540        assert_eq!(get_string(&mut buf), Err(DecodeError::InvalidUtf8));
541    }
542
543    #[test]
544    fn bytes_roundtrip() {
545        let payload = &[1u8, 2, 3][..];
546        let mut buf = BytesMut::new();
547        put_bytes(&mut buf, payload).unwrap();
548        assert_eq!(
549            get_nullable_bytes(&mut buf.freeze()).unwrap().as_deref(),
550            Some(payload)
551        );
552
553        let mut buf = BytesMut::new();
554        put_nullable_bytes(&mut buf, None).unwrap();
555        assert_eq!(get_nullable_bytes(&mut buf.freeze()), Ok(None));
556
557        let mut buf = BytesMut::new();
558        put_compact_bytes(&mut buf, payload);
559        assert_eq!(
560            get_compact_nullable_bytes(&mut buf.freeze())
561                .unwrap()
562                .as_deref(),
563            Some(payload)
564        );
565    }
566
567    #[test]
568    fn array_len_roundtrip() {
569        for len in [None, Some(0), Some(5), Some(100_000)] {
570            let mut buf = BytesMut::new();
571            put_array_len(&mut buf, len).unwrap();
572            assert_eq!(get_array_len(&mut buf.freeze()), Ok(len));
573
574            let mut buf = BytesMut::new();
575            put_compact_array_len(&mut buf, len);
576            assert_eq!(get_compact_array_len(&mut buf.freeze()), Ok(len));
577        }
578    }
579
580    #[test]
581    fn negative_array_len_rejected() {
582        let mut buf = Bytes::from_static(&[0xff, 0xff, 0xff, 0xfe]); // -2
583        assert_eq!(get_array_len(&mut buf), Err(DecodeError::InvalidLength(-2)));
584    }
585
586    #[test]
587    fn uuid_roundtrip() {
588        let id: [u8; 16] = *b"0123456789abcdef";
589        let mut buf = BytesMut::new();
590        put_uuid(&mut buf, id);
591        assert_eq!(get_uuid(&mut buf.freeze()), Ok(id));
592    }
593
594    #[test]
595    fn tagged_fields_roundtrip() {
596        let fields = vec![
597            RawTaggedField {
598                tag: 0,
599                data: Bytes::from_static(b"abc"),
600            },
601            RawTaggedField {
602                tag: 7,
603                data: Bytes::new(),
604            },
605        ];
606        let mut buf = BytesMut::new();
607        put_tagged_fields(&mut buf, &fields);
608        assert_eq!(get_tagged_fields(&mut buf.freeze()), Ok(fields));
609
610        // Empty section is a single zero byte.
611        let mut buf = BytesMut::new();
612        put_tagged_fields(&mut buf, &[]);
613        assert_eq!(&buf[..], &[0x00]);
614    }
615
616    /// Build a tagged-field section from `(tag, data)` pairs verbatim,
617    /// bypassing the ordering `put_tagged_fields` callers observe.
618    fn raw_section(fields: &[(u32, &[u8])]) -> Bytes {
619        let mut buf = BytesMut::new();
620        put_unsigned_varint(&mut buf, fields.len() as u64);
621        for (tag, data) in fields {
622            put_unsigned_varint(&mut buf, u64::from(*tag));
623            put_unsigned_varint(&mut buf, data.len() as u64);
624            buf.put_slice(data);
625        }
626        buf.freeze()
627    }
628
629    #[test]
630    fn tagged_fields_must_ascend() {
631        assert_eq!(
632            get_tagged_fields(&mut raw_section(&[(7, b"a"), (2, b"b")])),
633            Err(DecodeError::TaggedFieldOrder {
634                previous: 7,
635                tag: 2
636            })
637        );
638    }
639
640    #[test]
641    fn duplicate_tags_are_rejected() {
642        // Unknown tag twice: the second would shadow the first in any
643        // consumer that indexes by tag.
644        assert_eq!(
645            get_tagged_fields(&mut raw_section(&[(99, b"first"), (99, b"second")])),
646            Err(DecodeError::TaggedFieldOrder {
647                previous: 99,
648                tag: 99
649            })
650        );
651        // Adjacent distinct tags are still fine.
652        assert!(get_tagged_fields(&mut raw_section(&[(0, b"a"), (1, b"b")])).is_ok());
653    }
654
655    #[test]
656    fn tagged_fields_are_bounded_by_input_size() {
657        // 4096 empty tags: 2 bytes each on the wire, 40 in memory.
658        // Unbounded, that is a 20x amplification; the budget stops it.
659        let fields: Vec<(u32, &[u8])> = (0..4096u32).map(|tag| (tag, &[][..])).collect();
660        let section = raw_section(&fields);
661        let mut tight = Limits::default()
662            .with_min_alloc_bytes(0)
663            .with_alloc_factor(4)
664            .budget(section.len());
665        assert!(matches!(
666            get_tagged_fields_with_budget(&mut section.clone(), &mut tight),
667            Err(DecodeError::AllocationLimit { .. })
668        ));
669        assert!(tight.used() <= tight.limit());
670        // Raising the factor decodes the same bytes: the limit is a
671        // policy, not a wire rule.
672        let mut roomy = Limits::default()
673            .with_alloc_factor(64)
674            .budget(section.len());
675        assert_eq!(
676            get_tagged_fields_with_budget(&mut section.clone(), &mut roomy)
677                .expect("decodes")
678                .len(),
679            4096
680        );
681    }
682}