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    /// The first container with no members under a context-specific tag, if there is one.
472    ///
473    /// **What you write, somebody stricter will read.** An optional structure encoded with
474    /// nothing in it is legal Appendix A, accepted by this crate's decoder, and refused by every
475    /// released CHIP SDK — so the rule kept here is stricter than the specification's: an
476    /// optional structure that would be empty is not written at all.
477    ///
478    /// It cannot live in [`TlvWriter`](crate::tlv::TlvWriter), because §4.14.1.2 gives empty a
479    /// meaning: an empty `PBKDFParamResponse.pbkdf_parameters [4]` encodes "the initiator
480    /// already has them", which is a claim rather than an absence. So the rule is checked *over*
481    /// the writer, on encoded output, and the caller knows its own exceptions.
482    ///
483    /// Two narrowings, and both matter. **Only structures** — an empty array or list is a value,
484    /// and a node that wrote nothing has to be able to say so. **Only context-specific tags** —
485    /// an anonymous empty structure is an element of the list containing it, not an absent field.
486    ///
487    /// ```
488    /// use matter_kit::tlv::{ContainerKind, Tag, TlvReader, TlvWriter};
489    ///
490    /// let mut buf = [0u8; 32];
491    /// let mut w = TlvWriter::new(&mut buf);
492    /// w.start(Tag::Anonymous, ContainerKind::Structure).unwrap();
493    /// w.start(Tag::Context(4), ContainerKind::Structure).unwrap();   // optional, and empty
494    /// w.end_container().unwrap();
495    /// w.end_container().unwrap();
496    /// let encoded = w.finish().unwrap();
497    ///
498    /// assert_eq!(TlvReader::first_empty_optional(encoded).unwrap(), Some(Tag::Context(4)));
499    /// ```
500    ///
501    /// Errors only when `buf` is not well-formed TLV; [`TlvReader::validate`] is the check that
502    /// makes that complaint.
503    pub fn first_empty_optional(buf: &'a [u8]) -> Result<Option<Tag>> {
504        let mut r = Self::new(buf);
505        // The tag of each container currently open, innermost last, and whether anything has
506        // been written inside it yet.
507        let mut open: heapless::Vec<(Tag, bool, crate::tlv::ContainerKind), 16> =
508            heapless::Vec::new();
509        while let Some(element) = r.next_element()? {
510            match element.value {
511                Value::Container(kind) => {
512                    if let Some((_, seen, _)) = open.last_mut() {
513                        *seen = true;
514                    }
515                    if open.push((element.tag, false, kind)).is_err() {
516                        // Deeper than Appendix A's own nesting limit, which `next_element` has
517                        // already refused — so this is unreachable, and saying so is cheaper
518                        // than a second error code nobody can produce.
519                        bail!(TlvContainerMismatch)
520                    }
521                }
522                Value::EndOfContainer => {
523                    let Some((tag, seen, kind)) = open.pop() else {
524                        bail!(TlvContainerMismatch)
525                    };
526                    let empty_structure =
527                        !seen && matches!(kind, crate::tlv::ContainerKind::Structure);
528                    if empty_structure && matches!(tag, Tag::Context(_)) {
529                        return Ok(Some(tag));
530                    }
531                }
532                _ => {
533                    if let Some((_, seen, _)) = open.last_mut() {
534                        *seen = true;
535                    }
536                }
537            }
538        }
539        r.finish()?;
540        Ok(None)
541    }
542}
543
544#[cfg(test)]
545#[allow(clippy::arithmetic_side_effects, clippy::indexing_slicing)]
546mod tests {
547    use super::*;
548
549    fn one(buf: &[u8]) -> Element<'_> {
550        let mut r = TlvReader::new(buf);
551        r.next_element().expect("read").expect("an element")
552    }
553
554    #[test]
555    fn primitives_from_table_127() {
556        assert_eq!(one(&[0x08]).value, Value::Bool(false));
557        assert_eq!(one(&[0x09]).value, Value::Bool(true));
558        assert_eq!(one(&[0x00, 0x2a]).value, Value::Signed(42));
559        assert_eq!(one(&[0x00, 0xef]).value, Value::Signed(-17));
560        assert_eq!(one(&[0x04, 0x2a]).value, Value::Unsigned(42));
561        assert_eq!(one(&[0x01, 0x2a, 0x00]).value, Value::Signed(42));
562        assert_eq!(
563            one(&[0x02, 0xf0, 0x67, 0xfd, 0xff]).value,
564            Value::Signed(-170_000)
565        );
566        assert_eq!(
567            one(&[0x03, 0x00, 0x90, 0x2f, 0x50, 0x09, 0x00, 0x00, 0x00]).value,
568            Value::Signed(40_000_000_000)
569        );
570        assert_eq!(
571            one(&[0x0c, 0x06, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21]).value,
572            Value::Utf8("Hello!")
573        );
574        assert_eq!(
575            one(&[0x0c, 0x07, 0x54, 0x73, 0x63, 0x68, 0xc3, 0xbc, 0x73]).value,
576            Value::Utf8("Tschüs")
577        );
578        assert_eq!(
579            one(&[0x10, 0x05, 0x00, 0x01, 0x02, 0x03, 0x04]).value,
580            Value::Octets(&[0, 1, 2, 3, 4])
581        );
582        assert_eq!(one(&[0x14]).value, Value::Null);
583        assert_eq!(
584            one(&[0x0a, 0x00, 0x00, 0x00, 0x00]).value,
585            Value::Float(0.0)
586        );
587        assert_eq!(
588            one(&[0x0a, 0x33, 0x33, 0x8f, 0x41]).value,
589            Value::Float(17.9)
590        );
591        assert_eq!(
592            one(&[0x0a, 0x00, 0x00, 0x80, 0x7f]).value,
593            Value::Float(f32::INFINITY)
594        );
595        assert_eq!(
596            one(&[0x0b, 0x66, 0x66, 0x66, 0x66, 0x66, 0xe6, 0x31, 0x40]).value,
597            Value::Double(17.9)
598        );
599    }
600
601    #[test]
602    fn tags_from_table_129() {
603        assert_eq!(one(&[0x04, 0x2a]).tag, Tag::Anonymous);
604        // A context tag cannot be outermost (§A.2.2), so Table 129's second row is read
605        // where such a tag is legal: inside a structure.
606        {
607            let buf = [0x15, 0x24, 0x01, 0x2a, 0x18];
608            let mut r = TlvReader::new(&buf);
609            let _open = r.next_element().expect("read").expect("an element");
610            let member = r.next_element().expect("read").expect("an element");
611            assert_eq!(member.tag, Tag::Context(1));
612            assert_eq!(member.unsigned().expect("unsigned"), 42);
613        }
614        assert_eq!(one(&[0x44, 0x01, 0x00, 0x2a]).tag, Tag::Common(1));
615        assert_eq!(
616            one(&[0x64, 0xa0, 0x86, 0x01, 0x00, 0x2a]).tag,
617            Tag::Common(100_000)
618        );
619        assert_eq!(
620            one(&[0xc4, 0xf1, 0xff, 0xed, 0xde, 0x01, 0x00, 0x2a]).tag,
621            Tag::FullyQualified {
622                vendor: 0xFFF1,
623                profile: 0xDEED,
624                number: 1
625            }
626        );
627        assert_eq!(
628            one(&[0xe4, 0xf1, 0xff, 0xed, 0xde, 0xed, 0xfe, 0x55, 0xaa, 0x2a]).tag,
629            Tag::FullyQualified {
630                vendor: 0xFFF1,
631                profile: 0xDEED,
632                number: 0xAA55_FEED
633            }
634        );
635    }
636
637    #[test]
638    fn containers_from_table_128() {
639        assert_eq!(TlvReader::validate(&[0x15, 0x18]).unwrap(), 2);
640        assert_eq!(TlvReader::validate(&[0x16, 0x18]).unwrap(), 2);
641        assert_eq!(TlvReader::validate(&[0x17, 0x18]).unwrap(), 2);
642        // {0 = 42, 1 = -17}
643        assert_eq!(
644            TlvReader::validate(&[0x15, 0x20, 0x00, 0x2a, 0x20, 0x01, 0xef, 0x18]).unwrap(),
645            4
646        );
647        // [0, 1, 2, 3, 4]
648        assert_eq!(
649            TlvReader::validate(&[
650                0x16, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04, 0x18
651            ])
652            .unwrap(),
653            7
654        );
655        // List with a mix of anonymous and context tags.
656        assert_eq!(
657            TlvReader::validate(&[
658                0x17, 0x00, 0x01, 0x20, 0x00, 0x2a, 0x00, 0x02, 0x00, 0x03, 0x20, 0x00, 0xef, 0x18
659            ])
660            .unwrap(),
661            7
662        );
663        // Array with a mix of element types, including an empty structure.
664        assert_eq!(
665            TlvReader::validate(&[
666                0x16, 0x00, 0x2a, 0x02, 0xf0, 0x67, 0xfd, 0xff, 0x15, 0x18, 0x0a, 0x33, 0x33, 0x8f,
667                0x41, 0x0c, 0x06, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21, 0x18
668            ])
669            .unwrap(),
670            // array, 42, -170000, {, }, 17.9, "Hello!", ] — eight elements.
671            8
672        );
673        // Structure with fully-qualified tags, inside and out.
674        assert_eq!(
675            TlvReader::validate(&[
676                0xd5, 0xf1, 0xff, 0xed, 0xde, 0x01, 0x00, 0xc4, 0xf1, 0xff, 0xed, 0xde, 0x55, 0xaa,
677                0x2a, 0x18
678            ])
679            .unwrap(),
680            3
681        );
682    }
683
684    #[test]
685    fn structure_members_may_not_be_anonymous() {
686        // §A.5.1.
687        assert_eq!(
688            TlvReader::validate(&[0x15, 0x04, 0x2a, 0x18])
689                .unwrap_err()
690                .code(),
691            ErrorCode::TlvInvalidTag
692        );
693    }
694
695    #[test]
696    fn array_members_must_be_anonymous() {
697        // §A.5.2.
698        assert_eq!(
699            TlvReader::validate(&[0x16, 0x24, 0x01, 0x2a, 0x18])
700                .unwrap_err()
701                .code(),
702            ErrorCode::TlvInvalidTag
703        );
704    }
705
706    #[test]
707    fn context_tag_may_not_be_outermost() {
708        // §A.2.2.
709        assert_eq!(
710            TlvReader::validate(&[0x24, 0x01, 0x2a]).unwrap_err().code(),
711            ErrorCode::TlvInvalidTag
712        );
713    }
714
715    #[test]
716    fn end_of_container_must_have_zero_tag_control() {
717        // §A.10: 0x18 exactly. 0x38 is end-of-container with a context tag control.
718        assert_eq!(
719            TlvReader::validate(&[0x15, 0x38, 0x01]).unwrap_err().code(),
720            ErrorCode::TlvInvalidControl
721        );
722    }
723
724    #[test]
725    fn unbalanced_containers_are_refused() {
726        assert_eq!(
727            TlvReader::validate(&[0x15]).unwrap_err().code(),
728            ErrorCode::TlvContainerMismatch
729        );
730        assert_eq!(
731            TlvReader::validate(&[0x18]).unwrap_err().code(),
732            ErrorCode::TlvContainerMismatch
733        );
734    }
735
736    #[test]
737    fn only_one_top_level_element() {
738        // §A.1.
739        assert_eq!(
740            TlvReader::validate(&[0x04, 0x2a, 0x04, 0x2b])
741                .unwrap_err()
742                .code(),
743            ErrorCode::TlvContainerMismatch
744        );
745    }
746
747    #[test]
748    fn truncation_is_an_error_not_a_panic() {
749        for cut in 1..8 {
750            let full = [0x0c, 0x06, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21];
751            let _ = TlvReader::validate(&full[..cut]);
752        }
753        assert_eq!(
754            TlvReader::validate(&[0x0c, 0x06, 0x48]).unwrap_err().code(),
755            ErrorCode::TlvTruncated
756        );
757    }
758
759    #[test]
760    fn invalid_utf8_is_refused() {
761        assert_eq!(
762            TlvReader::validate(&[0x0c, 0x02, 0xff, 0xfe])
763                .unwrap_err()
764                .code(),
765            ErrorCode::TlvInvalidUtf8
766        );
767    }
768
769    #[test]
770    fn depth_is_bounded() {
771        // Arrays, because an array's members are anonymous (§A.5.2) and a structure's
772        // may not be (§A.5.1) — nesting bare structures is invalid for a different
773        // reason and would not test the depth budget.
774        fn nested(levels: usize) -> heapless::Vec<u8, 128> {
775            let mut v = heapless::Vec::new();
776            for _ in 0..levels {
777                let _ = v.push(0x16);
778            }
779            for _ in 0..levels {
780                let _ = v.push(0x18);
781            }
782            v
783        }
784        assert!(
785            TlvReader::validate(&nested(MAX_DEPTH)).is_ok(),
786            "MAX_DEPTH levels must be readable"
787        );
788        assert_eq!(
789            TlvReader::validate(&nested(MAX_DEPTH + 1))
790                .unwrap_err()
791                .code(),
792            ErrorCode::TlvDepthExceeded
793        );
794    }
795
796    #[test]
797    fn skip_container_lands_after_the_end() {
798        let buf = [0x15, 0x24, 0x00, 0x2a, 0x24, 0x01, 0xef, 0x18];
799        let mut r = TlvReader::new(&buf);
800        let e = r.next_element().unwrap().unwrap();
801        assert_eq!(e.value, Value::Container(ContainerKind::Structure));
802        r.skip_container().unwrap();
803        assert!(r.is_empty());
804        r.finish().unwrap();
805    }
806
807    #[test]
808    fn a_huge_declared_length_is_truncation() {
809        // An 8-octet length of u64::MAX with nothing behind it.
810        let buf = [0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
811        assert_eq!(
812            TlvReader::validate(&buf).unwrap_err().code(),
813            ErrorCode::TlvTruncated
814        );
815    }
816}