Skip to main content

matter_kit/tlv/
types.rs

1//! Element types, tag forms and tags — the vocabulary of Core Appendix A.
2
3use crate::error::{Error, ErrorCode, Result, bail};
4
5/// The element type field: the low 5 bits of a control octet (Core §A.7.1).
6///
7/// The variants carry the width the specification packs into the bottom two bits, because
8/// a reader needs it and a writer chooses it.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub enum ElementType {
11    /// Signed integer; the value field is 1, 2, 4 or 8 octets.
12    SignedInt(Width),
13    /// Unsigned integer; the value field is 1, 2, 4 or 8 octets.
14    UnsignedInt(Width),
15    /// Boolean; the value is in the control octet itself.
16    Bool(bool),
17    /// Single-precision float, 4-octet value.
18    Float,
19    /// Double-precision float, 8-octet value.
20    Double,
21    /// UTF-8 string; the length field is 1, 2, 4 or 8 octets.
22    Utf8(Width),
23    /// Octet string; the length field is 1, 2, 4 or 8 octets.
24    Octets(Width),
25    /// The null value.
26    Null,
27    /// Structure: members are uniquely tagged and never anonymous (§A.5.1).
28    Structure,
29    /// Array: members are always anonymous (§A.5.2).
30    Array,
31    /// List: members may carry any tag form, including none (§A.5.3).
32    List,
33    /// End-of-container, control octet `0x18` exactly (§A.10).
34    EndOfContainer,
35}
36
37/// How many octets a length or integer value field occupies.
38///
39/// The specification encodes this as the bottom two bits of the element type for both
40/// integers ("00 — 1 octet … 11 — 8 octets") and strings, so one type serves both.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
42pub enum Width {
43    /// 1 octet.
44    One = 0,
45    /// 2 octets.
46    Two = 1,
47    /// 4 octets.
48    Four = 2,
49    /// 8 octets.
50    Eight = 3,
51}
52
53impl Width {
54    /// The number of octets this width stands for.
55    #[must_use]
56    pub const fn octets(self) -> usize {
57        match self {
58            Self::One => 1,
59            Self::Two => 2,
60            Self::Four => 4,
61            Self::Eight => 8,
62        }
63    }
64
65    const fn from_bits(bits: u8) -> Self {
66        match bits & 0b11 {
67            0 => Self::One,
68            1 => Self::Two,
69            2 => Self::Four,
70            _ => Self::Eight,
71        }
72    }
73
74    /// The narrowest width that can hold `value` as an unsigned integer.
75    #[must_use]
76    pub const fn for_unsigned(value: u64) -> Self {
77        if value <= u8::MAX as u64 {
78            Self::One
79        } else if value <= u16::MAX as u64 {
80            Self::Two
81        } else if value <= u32::MAX as u64 {
82            Self::Four
83        } else {
84            Self::Eight
85        }
86    }
87
88    /// The narrowest width that can hold `value` as a two's-complement signed integer.
89    #[must_use]
90    pub const fn for_signed(value: i64) -> Self {
91        if value >= i8::MIN as i64 && value <= i8::MAX as i64 {
92            Self::One
93        } else if value >= i16::MIN as i64 && value <= i16::MAX as i64 {
94            Self::Two
95        } else if value >= i32::MIN as i64 && value <= i32::MAX as i64 {
96            Self::Four
97        } else {
98            Self::Eight
99        }
100    }
101}
102
103impl ElementType {
104    /// Decodes the low 5 bits of a control octet.
105    ///
106    /// Returns [`ErrorCode::TlvInvalidControl`] for the reserved types `0x19`–`0x1F` and
107    /// for `0x18` — end-of-container — which is handled by the caller because §A.10 makes
108    /// its tag control bits significant.
109    pub(crate) const fn from_bits(bits: u8) -> Result<Self> {
110        let t = bits & 0x1F;
111        Ok(match t {
112            0x00..=0x03 => Self::SignedInt(Width::from_bits(t)),
113            0x04..=0x07 => Self::UnsignedInt(Width::from_bits(t)),
114            0x08 => Self::Bool(false),
115            0x09 => Self::Bool(true),
116            0x0A => Self::Float,
117            0x0B => Self::Double,
118            0x0C..=0x0F => Self::Utf8(Width::from_bits(t)),
119            0x10..=0x13 => Self::Octets(Width::from_bits(t)),
120            0x14 => Self::Null,
121            0x15 => Self::Structure,
122            0x16 => Self::Array,
123            0x17 => Self::List,
124            0x18 => Self::EndOfContainer,
125            // 0x19..=0x1F: "Reserved".
126            _ => return Err(Error::new(ErrorCode::TlvInvalidControl)),
127        })
128    }
129
130    /// The low 5 bits this type encodes as.
131    #[must_use]
132    pub const fn bits(self) -> u8 {
133        match self {
134            // Signed integers are element types 0x00..=0x03: the width *is* the value.
135            Self::SignedInt(w) => w as u8,
136            Self::UnsignedInt(w) => 0x04 | w as u8,
137            Self::Bool(false) => 0x08,
138            Self::Bool(true) => 0x09,
139            Self::Float => 0x0A,
140            Self::Double => 0x0B,
141            Self::Utf8(w) => 0x0C | w as u8,
142            Self::Octets(w) => 0x10 | w as u8,
143            Self::Null => 0x14,
144            Self::Structure => 0x15,
145            Self::Array => 0x16,
146            Self::List => 0x17,
147            Self::EndOfContainer => 0x18,
148        }
149    }
150}
151
152/// Which of the three container types an element opens.
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
154pub enum ContainerKind {
155    /// A structure (§A.5.1).
156    Structure,
157    /// An array (§A.5.2).
158    Array,
159    /// A list (§A.5.3).
160    List,
161}
162
163impl ContainerKind {
164    /// The element type that opens this container.
165    #[must_use]
166    pub const fn element_type(self) -> ElementType {
167        match self {
168            Self::Structure => ElementType::Structure,
169            Self::Array => ElementType::Array,
170            Self::List => ElementType::List,
171        }
172    }
173}
174
175/// The tag control field: the top 3 bits of a control octet (Core §A.7.2).
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
177#[repr(u8)]
178enum TagControl {
179    Anonymous = 0b000,
180    ContextSpecific = 0b001,
181    CommonProfile2 = 0b010,
182    CommonProfile4 = 0b011,
183    ImplicitProfile2 = 0b100,
184    ImplicitProfile4 = 0b101,
185    FullyQualified6 = 0b110,
186    FullyQualified8 = 0b111,
187}
188
189impl TagControl {
190    const fn from_bits(bits: u8) -> Self {
191        match bits >> 5 {
192            0b000 => Self::Anonymous,
193            0b001 => Self::ContextSpecific,
194            0b010 => Self::CommonProfile2,
195            0b011 => Self::CommonProfile4,
196            0b100 => Self::ImplicitProfile2,
197            0b101 => Self::ImplicitProfile4,
198            0b110 => Self::FullyQualified6,
199            // The field is three bits; there is no eighth case.
200            _ => Self::FullyQualified8,
201        }
202    }
203
204    /// How many tag octets follow the control octet.
205    const fn octets(self) -> usize {
206        match self {
207            Self::Anonymous => 0,
208            Self::ContextSpecific => 1,
209            Self::CommonProfile2 | Self::ImplicitProfile2 => 2,
210            Self::CommonProfile4 | Self::ImplicitProfile4 => 4,
211            Self::FullyQualified6 => 6,
212            Self::FullyQualified8 => 8,
213        }
214    }
215}
216
217/// The Matter Common Profile, under which the predefined cross-organisation tags of
218/// §A.2.1 are defined.
219pub const COMMON_PROFILE: u16 = 0x0000;
220
221/// An element's tag (Core §A.2).
222///
223/// A tag is *optional*: an element without one is anonymous. The rest identify the element
224/// either within its containing structure (context-specific) or globally
225/// (profile-specific).
226#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
227pub enum Tag {
228    /// No tag — §A.2.3. The only form allowed for array members and for the outermost
229    /// element of an encoding.
230    Anonymous,
231    /// A context-specific tag: one octet, meaningful only inside its containing structure
232    /// or list (§A.2.2).
233    Context(u8),
234    /// A tag in the Matter Common Profile (§A.8.3).
235    Common(u32),
236    /// A profile-specific tag whose vendor and profile come from the protocol context the
237    /// encoding travels in (§A.8.2).
238    Implicit(u32),
239    /// A fully-qualified profile-specific tag (§A.8.1).
240    FullyQualified {
241        /// The 16-bit Vendor ID.
242        vendor: u16,
243        /// The 16-bit profile number.
244        profile: u16,
245        /// The tag number: 16-bit on the wire when below 65536, else 32-bit.
246        number: u32,
247    },
248}
249
250impl Tag {
251    /// Whether this is [`Tag::Anonymous`].
252    #[must_use]
253    pub const fn is_anonymous(self) -> bool {
254        matches!(self, Self::Anonymous)
255    }
256
257    /// The context-specific tag number, if this is one.
258    #[must_use]
259    pub const fn context(self) -> Option<u8> {
260        match self {
261            Self::Context(n) => Some(n),
262            _ => None,
263        }
264    }
265
266    /// The tag control bits this tag encodes as, given the width its number needs.
267    const fn control(self) -> TagControl {
268        match self {
269            Self::Anonymous => TagControl::Anonymous,
270            Self::Context(_) => TagControl::ContextSpecific,
271            Self::Common(n) => {
272                if n < 0x1_0000 {
273                    TagControl::CommonProfile2
274                } else {
275                    TagControl::CommonProfile4
276                }
277            }
278            Self::Implicit(n) => {
279                if n < 0x1_0000 {
280                    TagControl::ImplicitProfile2
281                } else {
282                    TagControl::ImplicitProfile4
283                }
284            }
285            Self::FullyQualified { number, .. } => {
286                if number < 0x1_0000 {
287                    TagControl::FullyQualified6
288                } else {
289                    TagControl::FullyQualified8
290                }
291            }
292        }
293    }
294
295    /// How many octets this tag occupies on the wire.
296    #[must_use]
297    pub const fn encoded_len(self) -> usize {
298        self.control().octets()
299    }
300
301    /// The top 3 bits of the control octet for this tag.
302    pub(crate) const fn control_bits(self) -> u8 {
303        (self.control() as u8) << 5
304    }
305
306    /// Writes the tag octets into `out`, little-endian, returning how many were written.
307    ///
308    /// `out` must be at least [`Tag::encoded_len`] long.
309    pub(crate) fn encode(self, out: &mut [u8]) -> Result<usize> {
310        let n = self.encoded_len();
311        let Some(dst) = out.get_mut(..n) else {
312            bail!(BufferTooSmall)
313        };
314        match self {
315            Self::Anonymous => {}
316            Self::Context(t) => {
317                let Some(b) = dst.first_mut() else {
318                    bail!(BufferTooSmall)
319                };
320                *b = t;
321            }
322            Self::Common(number) | Self::Implicit(number) => {
323                write_le(dst, u64::from(number), n)?;
324            }
325            Self::FullyQualified {
326                vendor,
327                profile,
328                number,
329            } => {
330                let Some(head) = dst.get_mut(..4) else {
331                    bail!(BufferTooSmall)
332                };
333                write_le(head, u64::from(vendor), 2)?;
334                let Some(prof) = head.get_mut(2..4) else {
335                    bail!(BufferTooSmall)
336                };
337                write_le(prof, u64::from(profile), 2)?;
338                let Some(num) = dst.get_mut(4..) else {
339                    bail!(BufferTooSmall)
340                };
341                // 6-octet form carries 2 tag octets, 8-octet form carries 4.
342                write_le(num, u64::from(number), n.saturating_sub(4))?;
343            }
344        }
345        Ok(n)
346    }
347
348    /// Reads a tag of the form named by `control_bits` from the front of `buf`.
349    ///
350    /// Returns the tag and how many octets it consumed.
351    #[expect(
352        clippy::cast_possible_truncation,
353        reason = "Appendix A's fully-qualified tag takes vendor and profile from two-octet fields"
354    )]
355    pub(crate) fn decode(control_bits: u8, buf: &[u8]) -> Result<(Self, usize)> {
356        let control = TagControl::from_bits(control_bits);
357        let n = control.octets();
358        let Some(src) = buf.get(..n) else {
359            bail!(TlvTruncated)
360        };
361        let tag = match control {
362            TagControl::Anonymous => Self::Anonymous,
363            TagControl::ContextSpecific => {
364                let Some(&b) = src.first() else {
365                    bail!(TlvTruncated)
366                };
367                Self::Context(b)
368            }
369            TagControl::CommonProfile2 | TagControl::CommonProfile4 => {
370                Self::Common(read_le_u32(src)?)
371            }
372            TagControl::ImplicitProfile2 | TagControl::ImplicitProfile4 => {
373                Self::Implicit(read_le_u32(src)?)
374            }
375            TagControl::FullyQualified6 | TagControl::FullyQualified8 => {
376                let Some(vendor) = src.get(..2) else {
377                    bail!(TlvTruncated)
378                };
379                let Some(profile) = src.get(2..4) else {
380                    bail!(TlvTruncated)
381                };
382                let Some(number) = src.get(4..) else {
383                    bail!(TlvTruncated)
384                };
385                Self::FullyQualified {
386                    vendor: read_le_u32(vendor)? as u16,
387                    profile: read_le_u32(profile)? as u16,
388                    number: read_le_u32(number)?,
389                }
390            }
391        };
392        Ok((tag, n))
393    }
394
395    /// Orders two tags by the canonical rules of §A.2.4, which a signature over a
396    /// structure depends on.
397    ///
398    /// The rules are stated in terms of Vendor ID and profile number, so
399    /// [`Tag::Implicit`] — whose vendor and profile come from the protocol context — has
400    /// no defined place among fully-qualified tags. It is ordered after
401    /// [`Tag::Common`] and before [`Tag::FullyQualified`] here; a caller that mixes
402    /// implicit tags with fully-qualified ones in one container and then signs it must
403    /// resolve the implicit ones to their profile first.
404    #[must_use]
405    pub fn canonical_cmp(self, other: Self) -> core::cmp::Ordering {
406        fn key(t: Tag) -> (u8, u16, u16, u32) {
407            match t {
408                // "Anonymous tags SHALL be ordered before all other tags."
409                Tag::Anonymous => (0, 0, 0, 0),
410                // "Context-specific tags SHALL be ordered before profile-specific tags."
411                Tag::Context(n) => (1, 0, 0, u32::from(n)),
412                Tag::Common(n) => (2, COMMON_PROFILE, 0, n),
413                Tag::Implicit(n) => (3, 0, 0, n),
414                Tag::FullyQualified {
415                    vendor,
416                    profile,
417                    number,
418                } => (4, vendor, profile, number),
419            }
420        }
421        key(self).cmp(&key(other))
422    }
423}
424
425/// Writes the low `n` octets of `value`, little-endian.
426pub(crate) fn write_le(out: &mut [u8], value: u64, n: usize) -> Result<()> {
427    let Some(dst) = out.get_mut(..n) else {
428        bail!(BufferTooSmall)
429    };
430    let bytes = value.to_le_bytes();
431    for (i, slot) in dst.iter_mut().enumerate() {
432        // `i < n <= 8` and `bytes` is 8 long, so this index is in range.
433        let Some(&b) = bytes.get(i) else {
434            bail!(BufferTooSmall)
435        };
436        *slot = b;
437    }
438    Ok(())
439}
440
441/// Reads up to 8 little-endian octets as a `u64`.
442pub(crate) fn read_le_u64(src: &[u8]) -> Result<u64> {
443    if src.len() > 8 {
444        bail!(TlvOutOfRange)
445    }
446    let mut out = 0u64;
447    for (i, &b) in src.iter().enumerate() {
448        // `i < 8`, so the shift is in range.
449        let shift = u32::try_from(i)
450            .ok()
451            .and_then(|i| i.checked_mul(8))
452            .ok_or(Error::new(ErrorCode::TlvOutOfRange))?;
453        out |= u64::from(b) << shift;
454    }
455    Ok(out)
456}
457
458fn read_le_u32(src: &[u8]) -> Result<u32> {
459    u32::try_from(read_le_u64(src)?).map_err(|_| Error::new(ErrorCode::TlvOutOfRange))
460}
461
462/// Sign-extends the `n`-octet little-endian two's-complement integer in `src`.
463#[expect(
464    clippy::cast_possible_wrap,
465    reason = "a two's-complement reinterpretation, which is what Appendix A's signed integers are"
466)]
467pub(crate) fn read_le_i64(src: &[u8]) -> Result<i64> {
468    let raw = read_le_u64(src)?;
469    let bits = u32::try_from(src.len())
470        .ok()
471        .and_then(|n| n.checked_mul(8))
472        .ok_or(Error::new(ErrorCode::TlvOutOfRange))?;
473    if bits == 0 || bits >= 64 {
474        // A zero-width integer does not exist in TLV, and a full-width one needs no
475        // extension.
476        return Ok(raw as i64);
477    }
478    let shift = 64u32.saturating_sub(bits);
479    // Shift left then arithmetic-shift right to replicate the sign bit.
480    Ok(((raw << shift) as i64) >> shift)
481}
482
483#[cfg(test)]
484#[allow(clippy::arithmetic_side_effects, clippy::indexing_slicing)]
485mod tests {
486    use super::*;
487
488    #[test]
489    fn element_type_round_trips_through_bits() {
490        for raw in 0u8..=0x18 {
491            let Ok(t) = ElementType::from_bits(raw) else {
492                continue;
493            };
494            assert_eq!(t.bits(), raw, "type {t:?} from 0x{raw:02x}");
495        }
496    }
497
498    #[test]
499    fn reserved_element_types_are_refused() {
500        for raw in 0x19u8..=0x1F {
501            assert_eq!(
502                ElementType::from_bits(raw).unwrap_err().code(),
503                ErrorCode::TlvInvalidControl
504            );
505        }
506    }
507
508    #[test]
509    fn tag_widths_follow_a8() {
510        assert_eq!(Tag::Anonymous.encoded_len(), 0);
511        assert_eq!(Tag::Context(1).encoded_len(), 1);
512        assert_eq!(Tag::Common(1).encoded_len(), 2);
513        assert_eq!(Tag::Common(100_000).encoded_len(), 4);
514        assert_eq!(Tag::Implicit(1).encoded_len(), 2);
515        assert_eq!(Tag::Implicit(0x1_0000).encoded_len(), 4);
516        assert_eq!(
517            Tag::FullyQualified {
518                vendor: 0xFFF1,
519                profile: 0xDEED,
520                number: 1
521            }
522            .encoded_len(),
523            6
524        );
525        assert_eq!(
526            Tag::FullyQualified {
527                vendor: 0xFFF1,
528                profile: 0xDEED,
529                number: 0xAA55_FEED
530            }
531            .encoded_len(),
532            8
533        );
534    }
535
536    #[test]
537    fn sign_extension() {
538        assert_eq!(read_le_i64(&[0xEF]).unwrap(), -17);
539        assert_eq!(read_le_i64(&[0x2A]).unwrap(), 42);
540        assert_eq!(read_le_i64(&[0xF0, 0x67, 0xFD, 0xFF]).unwrap(), -170_000);
541        assert_eq!(
542            read_le_i64(&[0x00, 0x90, 0x2F, 0x50, 0x09, 0x00, 0x00, 0x00]).unwrap(),
543            40_000_000_000
544        );
545    }
546
547    #[test]
548    fn minimal_widths() {
549        assert_eq!(Width::for_unsigned(42), Width::One);
550        assert_eq!(Width::for_unsigned(256), Width::Two);
551        assert_eq!(Width::for_signed(-17), Width::One);
552        assert_eq!(Width::for_signed(-170_000), Width::Four);
553        assert_eq!(Width::for_signed(128), Width::Two, "128 needs a sign bit");
554        assert_eq!(Width::for_signed(-128), Width::One);
555    }
556
557    #[test]
558    fn canonical_order_is_a24() {
559        let mut tags = [
560            Tag::FullyQualified {
561                vendor: 1,
562                profile: 1,
563                number: 1,
564            },
565            Tag::Context(5),
566            Tag::Anonymous,
567            Tag::Context(1),
568            Tag::FullyQualified {
569                vendor: 1,
570                profile: 0,
571                number: 9,
572            },
573        ];
574        tags.sort_by(|a, b| a.canonical_cmp(*b));
575        assert_eq!(tags[0], Tag::Anonymous);
576        assert_eq!(tags[1], Tag::Context(1));
577        assert_eq!(tags[2], Tag::Context(5));
578        // Lower profile number sorts first within the same vendor.
579        assert_eq!(
580            tags[3],
581            Tag::FullyQualified {
582                vendor: 1,
583                profile: 0,
584                number: 9
585            }
586        );
587    }
588}