Skip to main content

matter_kit/tlv/
reader.rs

1//! A zero-copy, non-recursive, allocation-free TLV reader.
2//!
3//! The reader is a cursor over a byte slice that yields one [`Element`] at a time.
4//! Containers are reported as their opening element followed by their members and an
5//! [`Value::EndOfContainer`], so reading is a loop rather than a recursion — a hostile
6//! encoding cannot grow the stack, only exhaust a fixed depth budget.
7//!
8//! Everything borrowed from the input is borrowed, not copied: a `&str` or `&[u8]` value
9//! points into the original buffer.
10
11use super::types::{ContainerKind, ElementType, Tag, Width, read_le_i64, read_le_u64};
12use crate::error::{Error, ErrorCode, Result, bail};
13
14/// How deeply containers may nest before the reader refuses to go further.
15///
16/// The specification sets no limit ("Container types can be nested to any depth"), but a
17/// reader must, or a 1 KB message of nothing but `15` octets costs a kilobyte of reader
18/// state. Matter's own encodings are shallow — the deepest interaction-model payload nests
19/// about eight levels — so 16 is roomy without being exploitable.
20pub const MAX_DEPTH: usize = 16;
21
22/// A decoded element value (Core §A.11).
23///
24/// Container variants carry no members: they mark the *start* of a container, whose
25/// members follow as further elements until [`Value::EndOfContainer`].
26#[derive(Debug, Clone, Copy, PartialEq)]
27#[non_exhaustive]
28pub enum Value<'a> {
29    /// A signed integer, sign-extended from its encoded width.
30    Signed(i64),
31    /// An unsigned integer, zero-extended from its encoded width.
32    Unsigned(u64),
33    /// A boolean, whose value lives in the control octet.
34    Bool(bool),
35    /// A single-precision float.
36    Float(f32),
37    /// A double-precision float.
38    Double(f64),
39    /// A UTF-8 string, validated on read (§A.11.2).
40    Utf8(&'a str),
41    /// An octet string.
42    Octets(&'a [u8]),
43    /// The null value.
44    Null,
45    /// The start of a container.
46    Container(ContainerKind),
47    /// The end of the innermost open container.
48    EndOfContainer,
49}
50
51impl Value<'_> {
52    /// Whether this is TLV null.
53    ///
54    /// Matter's `X` quality makes null a *value*, distinct from an absent field: §11.9.6.6's
55    /// `LastNetworkingStatus` is null when nothing has been attempted and `0` when the last
56    /// attempt succeeded, which are different claims. A decoder that treated the two alike
57    /// would report success for a device that has never tried.
58    #[must_use]
59    pub const fn is_null(self) -> bool {
60        matches!(self, Self::Null)
61    }
62
63    /// The container this value opens, if it opens one.
64    #[must_use]
65    pub const fn container(self) -> Option<ContainerKind> {
66        match self {
67            Self::Container(k) => Some(k),
68            _ => None,
69        }
70    }
71}
72
73/// A tag and the value it labels.
74#[derive(Debug, Clone, Copy, PartialEq)]
75pub struct Element<'a> {
76    /// The element's tag; [`Tag::Anonymous`] when it has none.
77    pub tag: Tag,
78    /// The element's value.
79    pub value: Value<'a>,
80}
81
82impl<'a> Element<'a> {
83    /// The value as an unsigned integer, or [`ErrorCode::TlvWrongType`].
84    pub fn unsigned(&self) -> Result<u64> {
85        match self.value {
86            Value::Unsigned(v) => Ok(v),
87            _ => Err(Error::new(ErrorCode::TlvWrongType)),
88        }
89    }
90
91    /// The value as a signed integer, or [`ErrorCode::TlvWrongType`].
92    pub fn signed(&self) -> Result<i64> {
93        match self.value {
94            Value::Signed(v) => Ok(v),
95            _ => Err(Error::new(ErrorCode::TlvWrongType)),
96        }
97    }
98
99    /// The value as a boolean, or [`ErrorCode::TlvWrongType`].
100    pub fn bool(&self) -> Result<bool> {
101        match self.value {
102            Value::Bool(v) => Ok(v),
103            _ => Err(Error::new(ErrorCode::TlvWrongType)),
104        }
105    }
106
107    /// The value as a string, or [`ErrorCode::TlvWrongType`].
108    pub fn utf8(&self) -> Result<&'a str> {
109        match self.value {
110            Value::Utf8(v) => Ok(v),
111            _ => Err(Error::new(ErrorCode::TlvWrongType)),
112        }
113    }
114
115    /// The value as an octet string, or [`ErrorCode::TlvWrongType`].
116    pub fn octets(&self) -> Result<&'a [u8]> {
117        match self.value {
118            Value::Octets(v) => Ok(v),
119            _ => Err(Error::new(ErrorCode::TlvWrongType)),
120        }
121    }
122}
123
124/// A cursor over a TLV encoding.
125#[derive(Debug, Clone)]
126pub struct TlvReader<'a> {
127    buf: &'a [u8],
128    pos: usize,
129    stack: [ContainerKind; MAX_DEPTH],
130    depth: usize,
131    /// Set once the single top-level element of §A.1 has been fully read, so that a
132    /// second one is reported rather than silently accepted.
133    top_level_done: bool,
134    /// Whether this cursor reads a container's *members* rather than one element.
135    ///
136    /// §A.1's "single top-level element" is a rule about an encoding, and a members fragment
137    /// is not one — it is the inside of a container whose punctuation is somewhere else. A
138    /// reader that applied the rule anyway would accept the first member and refuse the
139    /// second, which is a spectacularly confusing way to fail.
140    many: bool,
141    /// Whether [`TlvReader::new_in`] made this cursor start inside a container.
142    started_inside: bool,
143}
144
145impl<'a> TlvReader<'a> {
146    /// Starts reading at the beginning of `buf`.
147    #[must_use]
148    pub const fn new(buf: &'a [u8]) -> Self {
149        Self {
150            buf,
151            pos: 0,
152            stack: [ContainerKind::Structure; MAX_DEPTH],
153            depth: 0,
154            top_level_done: false,
155            many: false,
156            started_inside: false,
157        }
158    }
159
160    /// Starts reading as though the cursor were already inside `container`.
161    ///
162    /// Which tag forms are legal depends on where an element sits (§A.2.2, §A.5.1,
163    /// §A.5.2), so a fragment that will be spliced into a structure has to be checked
164    /// against a structure's rules, not against the top level's. A context-specific tag
165    /// is invalid at the top level and required inside a structure — validating such a
166    /// fragment with [`TlvReader::new`] would reject exactly the bytes that are correct.
167    ///
168    /// This is what [`TlvWriter::raw_element`](super::TlvWriter::raw_element) uses.
169    #[must_use]
170    pub const fn new_in(buf: &'a [u8], container: ContainerKind) -> Self {
171        Self {
172            buf,
173            pos: 0,
174            stack: [container; MAX_DEPTH],
175            depth: 1,
176            top_level_done: false,
177            many: false,
178            started_inside: true,
179        }
180    }
181
182    /// A cursor over the *members* of a container — many elements, not one.
183    ///
184    /// [`TlvReader::new_in`] reads a fragment that will be spliced in as a single element, and
185    /// holds it to §A.1's "single top-level element". This reads the inside of a container
186    /// whose opening and closing octets live somewhere else, so the rule does not apply:
187    /// [`TlvList`](super::TlvList) keeps a list's members that way, and a reader that refused
188    /// the second one would be applying a rule about encodings to something that is not one.
189    ///
190    /// The members must **not** include the end-of-container: that octet closes a container
191    /// this cursor was never told it is inside, and meeting it is
192    /// [`ErrorCode::TlvContainerMismatch`].
193    #[must_use]
194    pub const fn new_members(buf: &'a [u8], container: ContainerKind) -> Self {
195        Self {
196            buf,
197            pos: 0,
198            stack: [container; MAX_DEPTH],
199            depth: 1,
200            top_level_done: false,
201            many: true,
202            started_inside: true,
203        }
204    }
205
206    /// How many octets have been consumed.
207    #[must_use]
208    pub const fn position(&self) -> usize {
209        self.pos
210    }
211
212    /// How many containers are currently open.
213    #[must_use]
214    pub const fn depth(&self) -> usize {
215        self.depth
216    }
217
218    /// The octets not yet consumed.
219    #[must_use]
220    pub fn remaining(&self) -> &'a [u8] {
221        self.buf.get(self.pos..).unwrap_or(&[])
222    }
223
224    /// Whether the cursor is at the end of the buffer.
225    #[must_use]
226    pub const fn is_empty(&self) -> bool {
227        self.pos >= self.buf.len()
228    }
229
230    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
231        let end = self
232            .pos
233            .checked_add(n)
234            .ok_or(Error::new(ErrorCode::TlvTruncated))?;
235        let Some(slice) = self.buf.get(self.pos..end) else {
236            bail!(TlvTruncated)
237        };
238        self.pos = end;
239        Ok(slice)
240    }
241
242    /// The depth the cursor started at: 0 normally, 1 for [`TlvReader::new_in`].
243    const fn base_depth(&self) -> usize {
244        // `new_in` is the only way to start inside a container, and it starts at 1.
245        if self.started_inside { 1 } else { 0 }
246    }
247
248    /// The container the cursor is directly inside, or `None` at the top level.
249    fn current_container(&self) -> Option<ContainerKind> {
250        self.depth
251            .checked_sub(1)
252            .and_then(|i| self.stack.get(i))
253            .copied()
254    }
255
256    /// Enforces §A.2.2, §A.5.1 and §A.5.2: which tag forms a container admits.
257    fn check_tag(&self, tag: Tag) -> Result<()> {
258        match self.current_container() {
259            // "All valid TLV encodings consist of a single top-level element", and a
260            // context-specific tag "cannot appear as the outermost element of a TLV
261            // encoding" (§A.2.2). Profile-specific tags are fine at the top level —
262            // Table 129's last row is exactly that.
263            None => {
264                if tag.context().is_some() {
265                    bail!(TlvInvalidTag)
266                }
267            }
268            // "Member elements without tags (anonymous elements) are not allowed in
269            // structures" (§A.5.1).
270            Some(ContainerKind::Structure) => {
271                if tag.is_anonymous() {
272                    bail!(TlvInvalidTag)
273                }
274            }
275            // "All member elements of an array SHALL be anonymous elements" (§A.5.2).
276            Some(ContainerKind::Array) => {
277                if !tag.is_anonymous() {
278                    bail!(TlvInvalidTag)
279                }
280            }
281            // "The members of a list may be encoded with any form of tag" (§A.5.3).
282            Some(ContainerKind::List) => {}
283        }
284        Ok(())
285    }
286
287    /// Reads the next element.
288    ///
289    /// Returns `Ok(None)` at the end of the buffer. An unterminated container is *not* an
290    /// error here — it is one in [`TlvReader::finish`], which is what a caller that has
291    /// read a whole encoding should call.
292    pub fn next_element(&mut self) -> Result<Option<Element<'a>>> {
293        if self.is_empty() {
294            return Ok(None);
295        }
296        if self.top_level_done && !self.many && self.depth == self.base_depth() {
297            // §A.1: "All valid TLV encodings consist of a single top-level element."
298            bail!(TlvContainerMismatch)
299        }
300
301        let control = {
302            let b = self.take(1)?;
303            let Some(&c) = b.first() else {
304                bail!(TlvTruncated)
305            };
306            c
307        };
308        let element_type = ElementType::from_bits(control)?;
309
310        // §A.10: end-of-container is control octet 0x18 exactly — "The tag control bits
311        // within the control octet SHALL be set to zero".
312        if matches!(element_type, ElementType::EndOfContainer) {
313            if control != 0x18 {
314                bail!(TlvInvalidControl)
315            }
316            let Some(new_depth) = self.depth.checked_sub(1) else {
317                bail!(TlvContainerMismatch)
318            };
319            if new_depth < self.base_depth() {
320                // Closing the container this cursor was told it is inside would leave the
321                // fragment, which is not something a fragment may do.
322                bail!(TlvContainerMismatch)
323            }
324            self.depth = new_depth;
325            if self.depth == self.base_depth() {
326                self.top_level_done = true;
327            }
328            return Ok(Some(Element {
329                tag: Tag::Anonymous,
330                value: Value::EndOfContainer,
331            }));
332        }
333
334        let (tag, tag_len) = Tag::decode(control, self.remaining())?;
335        self.pos = self
336            .pos
337            .checked_add(tag_len)
338            .ok_or(Error::new(ErrorCode::TlvTruncated))?;
339        self.check_tag(tag)?;
340
341        let value = match element_type {
342            ElementType::SignedInt(w) => Value::Signed(read_le_i64(self.take(w.octets())?)?),
343            ElementType::UnsignedInt(w) => Value::Unsigned(read_le_u64(self.take(w.octets())?)?),
344            ElementType::Bool(v) => Value::Bool(v),
345            ElementType::Float => {
346                let raw = read_le_u64(self.take(4)?)?;
347                let Ok(bits) = u32::try_from(raw) else {
348                    bail!(TlvOutOfRange)
349                };
350                Value::Float(f32::from_bits(bits))
351            }
352            ElementType::Double => Value::Double(f64::from_bits(read_le_u64(self.take(8)?)?)),
353            ElementType::Utf8(w) => {
354                let bytes = self.take_string(w)?;
355                match core::str::from_utf8(bytes) {
356                    Ok(s) => Value::Utf8(s),
357                    Err(_) => bail!(TlvInvalidUtf8),
358                }
359            }
360            ElementType::Octets(w) => Value::Octets(self.take_string(w)?),
361            ElementType::Null => Value::Null,
362            ElementType::Structure | ElementType::Array | ElementType::List => {
363                let kind = match element_type {
364                    ElementType::Structure => ContainerKind::Structure,
365                    ElementType::Array => ContainerKind::Array,
366                    _ => ContainerKind::List,
367                };
368                let Some(slot) = self.stack.get_mut(self.depth) else {
369                    bail!(TlvDepthExceeded)
370                };
371                *slot = kind;
372                self.depth = self
373                    .depth
374                    .checked_add(1)
375                    .ok_or(Error::new(ErrorCode::TlvDepthExceeded))?;
376                Value::Container(kind)
377            }
378            // Handled above.
379            ElementType::EndOfContainer => bail!(TlvInvalidControl),
380        };
381
382        if self.depth == self.base_depth() {
383            self.top_level_done = true;
384        }
385        Ok(Some(Element { tag, value }))
386    }
387
388    /// Reads a string's length field and then its value octets.
389    fn take_string(&mut self, w: Width) -> Result<&'a [u8]> {
390        let len = read_le_u64(self.take(w.octets())?)?;
391        let Ok(len) = usize::try_from(len) else {
392            // A length that does not fit a `usize` cannot be satisfied by a buffer that
393            // does, so this is truncation rather than an out-of-range value.
394            bail!(TlvTruncated)
395        };
396        self.take(len)
397    }
398
399    /// Skips the container the cursor has just entered, leaving it positioned after that
400    /// container's end-of-container element.
401    ///
402    /// Call this immediately after a [`Value::Container`] element. It is iterative, so
403    /// nesting costs no stack.
404    pub fn skip_container(&mut self) -> Result<()> {
405        let Some(target) = self.depth.checked_sub(1) else {
406            bail!(TlvContainerMismatch)
407        };
408        while self.depth > target {
409            if self.next_element()?.is_none() {
410                bail!(TlvContainerMismatch)
411            }
412        }
413        Ok(())
414    }
415
416    /// The octets between `start` and the cursor — one element with its tag, when `start`
417    /// was taken immediately before reading it.
418    ///
419    /// This is how a payload whose schema belongs to somebody else is carried: an attribute's
420    /// value has a cluster's type, not the interaction model's, so the interaction model keeps
421    /// the encoded element and hands it on with
422    /// [`TlvWriter::raw_element`](super::TlvWriter::raw_element) rather than interpreting it.
423    ///
424    /// Returns [`ErrorCode::TlvTruncated`] if `start` is past the cursor, which can only
425    /// happen if a caller passed a position from a different reader.
426    pub fn slice_from(&self, start: usize) -> Result<&'a [u8]> {
427        self.buf
428            .get(start..self.pos)
429            .ok_or(Error::new(ErrorCode::TlvTruncated))
430    }
431
432    /// Skips whatever the given element is: a no-op for a primitive, a whole subtree for
433    /// a container.
434    pub fn skip_value(&mut self, element: &Element<'a>) -> Result<()> {
435        if element.value.container().is_some() {
436            self.skip_container()?;
437        }
438        Ok(())
439    }
440
441    /// Checks that the encoding is complete and well-formed: every container closed, and
442    /// exactly one top-level element present.
443    pub fn finish(&self) -> Result<()> {
444        if self.depth != self.base_depth() {
445            bail!(TlvContainerMismatch)
446        }
447        if !self.top_level_done {
448            bail!(TlvTruncated)
449        }
450        if !self.is_empty() {
451            // Trailing octets after the single top-level element.
452            bail!(TlvContainerMismatch)
453        }
454        Ok(())
455    }
456
457    /// Reads the whole encoding, checking it is well-formed, and returns how many
458    /// elements it contained.
459    ///
460    /// This is what a fuzz target and a "is this valid TLV?" caller want.
461    pub fn validate(buf: &'a [u8]) -> Result<usize> {
462        let mut r = Self::new(buf);
463        let mut count = 0usize;
464        while r.next_element()?.is_some() {
465            count = count.saturating_add(1);
466        }
467        r.finish()?;
468        Ok(count)
469    }
470}
471
472#[cfg(test)]
473#[allow(clippy::arithmetic_side_effects, clippy::indexing_slicing)]
474mod tests {
475    use super::*;
476
477    fn one(buf: &[u8]) -> Element<'_> {
478        let mut r = TlvReader::new(buf);
479        r.next_element().expect("read").expect("an element")
480    }
481
482    #[test]
483    fn primitives_from_table_127() {
484        assert_eq!(one(&[0x08]).value, Value::Bool(false));
485        assert_eq!(one(&[0x09]).value, Value::Bool(true));
486        assert_eq!(one(&[0x00, 0x2a]).value, Value::Signed(42));
487        assert_eq!(one(&[0x00, 0xef]).value, Value::Signed(-17));
488        assert_eq!(one(&[0x04, 0x2a]).value, Value::Unsigned(42));
489        assert_eq!(one(&[0x01, 0x2a, 0x00]).value, Value::Signed(42));
490        assert_eq!(
491            one(&[0x02, 0xf0, 0x67, 0xfd, 0xff]).value,
492            Value::Signed(-170_000)
493        );
494        assert_eq!(
495            one(&[0x03, 0x00, 0x90, 0x2f, 0x50, 0x09, 0x00, 0x00, 0x00]).value,
496            Value::Signed(40_000_000_000)
497        );
498        assert_eq!(
499            one(&[0x0c, 0x06, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21]).value,
500            Value::Utf8("Hello!")
501        );
502        assert_eq!(
503            one(&[0x0c, 0x07, 0x54, 0x73, 0x63, 0x68, 0xc3, 0xbc, 0x73]).value,
504            Value::Utf8("Tschüs")
505        );
506        assert_eq!(
507            one(&[0x10, 0x05, 0x00, 0x01, 0x02, 0x03, 0x04]).value,
508            Value::Octets(&[0, 1, 2, 3, 4])
509        );
510        assert_eq!(one(&[0x14]).value, Value::Null);
511        assert_eq!(
512            one(&[0x0a, 0x00, 0x00, 0x00, 0x00]).value,
513            Value::Float(0.0)
514        );
515        assert_eq!(
516            one(&[0x0a, 0x33, 0x33, 0x8f, 0x41]).value,
517            Value::Float(17.9)
518        );
519        assert_eq!(
520            one(&[0x0a, 0x00, 0x00, 0x80, 0x7f]).value,
521            Value::Float(f32::INFINITY)
522        );
523        assert_eq!(
524            one(&[0x0b, 0x66, 0x66, 0x66, 0x66, 0x66, 0xe6, 0x31, 0x40]).value,
525            Value::Double(17.9)
526        );
527    }
528
529    #[test]
530    fn tags_from_table_129() {
531        assert_eq!(one(&[0x04, 0x2a]).tag, Tag::Anonymous);
532        // A context tag cannot be outermost (§A.2.2), so Table 129's second row is read
533        // where such a tag is legal: inside a structure.
534        {
535            let buf = [0x15, 0x24, 0x01, 0x2a, 0x18];
536            let mut r = TlvReader::new(&buf);
537            let _open = r.next_element().expect("read").expect("an element");
538            let member = r.next_element().expect("read").expect("an element");
539            assert_eq!(member.tag, Tag::Context(1));
540            assert_eq!(member.unsigned().expect("unsigned"), 42);
541        }
542        assert_eq!(one(&[0x44, 0x01, 0x00, 0x2a]).tag, Tag::Common(1));
543        assert_eq!(
544            one(&[0x64, 0xa0, 0x86, 0x01, 0x00, 0x2a]).tag,
545            Tag::Common(100_000)
546        );
547        assert_eq!(
548            one(&[0xc4, 0xf1, 0xff, 0xed, 0xde, 0x01, 0x00, 0x2a]).tag,
549            Tag::FullyQualified {
550                vendor: 0xFFF1,
551                profile: 0xDEED,
552                number: 1
553            }
554        );
555        assert_eq!(
556            one(&[0xe4, 0xf1, 0xff, 0xed, 0xde, 0xed, 0xfe, 0x55, 0xaa, 0x2a]).tag,
557            Tag::FullyQualified {
558                vendor: 0xFFF1,
559                profile: 0xDEED,
560                number: 0xAA55_FEED
561            }
562        );
563    }
564
565    #[test]
566    fn containers_from_table_128() {
567        assert_eq!(TlvReader::validate(&[0x15, 0x18]).unwrap(), 2);
568        assert_eq!(TlvReader::validate(&[0x16, 0x18]).unwrap(), 2);
569        assert_eq!(TlvReader::validate(&[0x17, 0x18]).unwrap(), 2);
570        // {0 = 42, 1 = -17}
571        assert_eq!(
572            TlvReader::validate(&[0x15, 0x20, 0x00, 0x2a, 0x20, 0x01, 0xef, 0x18]).unwrap(),
573            4
574        );
575        // [0, 1, 2, 3, 4]
576        assert_eq!(
577            TlvReader::validate(&[
578                0x16, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04, 0x18
579            ])
580            .unwrap(),
581            7
582        );
583        // List with a mix of anonymous and context tags.
584        assert_eq!(
585            TlvReader::validate(&[
586                0x17, 0x00, 0x01, 0x20, 0x00, 0x2a, 0x00, 0x02, 0x00, 0x03, 0x20, 0x00, 0xef, 0x18
587            ])
588            .unwrap(),
589            7
590        );
591        // Array with a mix of element types, including an empty structure.
592        assert_eq!(
593            TlvReader::validate(&[
594                0x16, 0x00, 0x2a, 0x02, 0xf0, 0x67, 0xfd, 0xff, 0x15, 0x18, 0x0a, 0x33, 0x33, 0x8f,
595                0x41, 0x0c, 0x06, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21, 0x18
596            ])
597            .unwrap(),
598            // array, 42, -170000, {, }, 17.9, "Hello!", ] — eight elements.
599            8
600        );
601        // Structure with fully-qualified tags, inside and out.
602        assert_eq!(
603            TlvReader::validate(&[
604                0xd5, 0xf1, 0xff, 0xed, 0xde, 0x01, 0x00, 0xc4, 0xf1, 0xff, 0xed, 0xde, 0x55, 0xaa,
605                0x2a, 0x18
606            ])
607            .unwrap(),
608            3
609        );
610    }
611
612    #[test]
613    fn structure_members_may_not_be_anonymous() {
614        // §A.5.1.
615        assert_eq!(
616            TlvReader::validate(&[0x15, 0x04, 0x2a, 0x18])
617                .unwrap_err()
618                .code(),
619            ErrorCode::TlvInvalidTag
620        );
621    }
622
623    #[test]
624    fn array_members_must_be_anonymous() {
625        // §A.5.2.
626        assert_eq!(
627            TlvReader::validate(&[0x16, 0x24, 0x01, 0x2a, 0x18])
628                .unwrap_err()
629                .code(),
630            ErrorCode::TlvInvalidTag
631        );
632    }
633
634    #[test]
635    fn context_tag_may_not_be_outermost() {
636        // §A.2.2.
637        assert_eq!(
638            TlvReader::validate(&[0x24, 0x01, 0x2a]).unwrap_err().code(),
639            ErrorCode::TlvInvalidTag
640        );
641    }
642
643    #[test]
644    fn end_of_container_must_have_zero_tag_control() {
645        // §A.10: 0x18 exactly. 0x38 is end-of-container with a context tag control.
646        assert_eq!(
647            TlvReader::validate(&[0x15, 0x38, 0x01]).unwrap_err().code(),
648            ErrorCode::TlvInvalidControl
649        );
650    }
651
652    #[test]
653    fn unbalanced_containers_are_refused() {
654        assert_eq!(
655            TlvReader::validate(&[0x15]).unwrap_err().code(),
656            ErrorCode::TlvContainerMismatch
657        );
658        assert_eq!(
659            TlvReader::validate(&[0x18]).unwrap_err().code(),
660            ErrorCode::TlvContainerMismatch
661        );
662    }
663
664    #[test]
665    fn only_one_top_level_element() {
666        // §A.1.
667        assert_eq!(
668            TlvReader::validate(&[0x04, 0x2a, 0x04, 0x2b])
669                .unwrap_err()
670                .code(),
671            ErrorCode::TlvContainerMismatch
672        );
673    }
674
675    #[test]
676    fn truncation_is_an_error_not_a_panic() {
677        for cut in 1..8 {
678            let full = [0x0c, 0x06, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21];
679            let _ = TlvReader::validate(&full[..cut]);
680        }
681        assert_eq!(
682            TlvReader::validate(&[0x0c, 0x06, 0x48]).unwrap_err().code(),
683            ErrorCode::TlvTruncated
684        );
685    }
686
687    #[test]
688    fn invalid_utf8_is_refused() {
689        assert_eq!(
690            TlvReader::validate(&[0x0c, 0x02, 0xff, 0xfe])
691                .unwrap_err()
692                .code(),
693            ErrorCode::TlvInvalidUtf8
694        );
695    }
696
697    #[test]
698    fn depth_is_bounded() {
699        // Arrays, because an array's members are anonymous (§A.5.2) and a structure's
700        // may not be (§A.5.1) — nesting bare structures is invalid for a different
701        // reason and would not test the depth budget.
702        fn nested(levels: usize) -> heapless::Vec<u8, 128> {
703            let mut v = heapless::Vec::new();
704            for _ in 0..levels {
705                let _ = v.push(0x16);
706            }
707            for _ in 0..levels {
708                let _ = v.push(0x18);
709            }
710            v
711        }
712        assert!(
713            TlvReader::validate(&nested(MAX_DEPTH)).is_ok(),
714            "MAX_DEPTH levels must be readable"
715        );
716        assert_eq!(
717            TlvReader::validate(&nested(MAX_DEPTH + 1))
718                .unwrap_err()
719                .code(),
720            ErrorCode::TlvDepthExceeded
721        );
722    }
723
724    #[test]
725    fn skip_container_lands_after_the_end() {
726        let buf = [0x15, 0x24, 0x00, 0x2a, 0x24, 0x01, 0xef, 0x18];
727        let mut r = TlvReader::new(&buf);
728        let e = r.next_element().unwrap().unwrap();
729        assert_eq!(e.value, Value::Container(ContainerKind::Structure));
730        r.skip_container().unwrap();
731        assert!(r.is_empty());
732        r.finish().unwrap();
733    }
734
735    #[test]
736    fn a_huge_declared_length_is_truncation() {
737        // An 8-octet length of u64::MAX with nothing behind it.
738        let buf = [0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
739        assert_eq!(
740            TlvReader::validate(&buf).unwrap_err().code(),
741            ErrorCode::TlvTruncated
742        );
743    }
744}