Skip to main content

matter_kit/tlv/
pretty.rs

1//! Printing TLV the way the specification writes it.
2//!
3//! A hex dump of a failing payload is a puzzle; `{0 = 42, 1 = -17}` is a sentence. This is
4//! the difference between reading a capture and decoding one by hand, and it costs no
5//! allocation — [`Pretty`] is a `Display` wrapper over the bytes.
6
7use core::fmt::{self, Display, Write as _};
8
9use super::reader::{MAX_DEPTH, TlvReader, Value};
10use super::types::{ContainerKind, Tag};
11
12/// Formats a TLV encoding in the notation of Core Appendix A.
13///
14/// ```
15/// use matter_kit::tlv::Pretty;
16///
17/// let bytes = [0x15, 0x20, 0x00, 0x2a, 0x20, 0x01, 0xef, 0x18];
18/// # #[cfg(feature = "std")]
19/// assert_eq!(std::format!("{}", Pretty(&bytes)), "{0 = 42, 1 = -17}");
20/// ```
21///
22/// Malformed input does not fail the format call — it prints what it understood and then
23/// `<!error>`, because a formatter that refuses to print a broken message is useless
24/// exactly when a broken message is what you have.
25#[derive(Debug, Clone, Copy)]
26pub struct Pretty<'a>(pub &'a [u8]);
27
28/// Formats a TLV **fragment** — one or more members of a container, rather than a complete
29/// top-level encoding.
30///
31/// Which tag forms are legal depends on where an element sits, so a fragment carrying a
32/// context-specific tag is valid inside a structure and invalid on its own.
33/// [`Pretty`] reads at the top level and would print `<!error>` for exactly the bytes that
34/// are correct; this reads them the way they will be read.
35///
36/// The counterpart of [`TlvReader::new_in`] and
37/// [`TlvWriter::new_in`](super::TlvWriter::new_in).
38///
39/// ```
40/// use matter_kit::tlv::{ContainerKind, PrettyIn};
41///
42/// // An attribute value destined for an AttributeDataIB's context-2 slot.
43/// let bytes = [0x24, 0x02, 0x2A];
44/// # #[cfg(feature = "std")]
45/// assert_eq!(
46///     std::format!("{}", PrettyIn(&bytes, ContainerKind::Structure)),
47///     "2 = 42U"
48/// );
49/// ```
50#[derive(Debug, Clone, Copy)]
51pub struct PrettyIn<'a>(pub &'a [u8], pub ContainerKind);
52
53impl Display for Pretty<'_> {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        write_tlv(f, TlvReader::new(self.0))
56    }
57}
58
59impl Display for PrettyIn<'_> {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        write_tlv(f, TlvReader::new_in(self.0, self.1))
62    }
63}
64
65/// The shared body of both formatters.
66fn write_tlv(f: &mut fmt::Formatter<'_>, reader: TlvReader<'_>) -> fmt::Result {
67    {
68        let mut r = reader;
69        // Per level: which container is open there, and whether it has printed a member.
70        let mut open = [ContainerKind::Structure; MAX_DEPTH];
71        let mut empty = [true; MAX_DEPTH];
72
73        loop {
74            // The level this element belongs to, read before the cursor moves.
75            let level = r.depth();
76
77            let element = match r.next_element() {
78                Ok(None) => return Ok(()),
79                Ok(Some(e)) => e,
80                Err(_) => return f.write_str("<!error>"),
81            };
82
83            if matches!(element.value, Value::EndOfContainer) {
84                // `depth()` has already been popped, so it now names the closing level.
85                let closing = r.depth();
86                let kind = open
87                    .get(closing)
88                    .copied()
89                    .unwrap_or(ContainerKind::Structure);
90                return_brace(f, kind)?;
91                continue;
92            }
93
94            let level = level.min(MAX_DEPTH.saturating_sub(1));
95            if let Some(slot) = empty.get_mut(level) {
96                if !*slot {
97                    f.write_str(", ")?;
98                }
99                *slot = false;
100            }
101
102            write_tag(f, element.tag)?;
103            write_value(f, &element.value)?;
104
105            if let Value::Container(kind) = element.value {
106                // The cursor is now inside it; record what to close and reset its state.
107                let inner = r.depth().saturating_sub(1).min(MAX_DEPTH.saturating_sub(1));
108                if let Some(slot) = open.get_mut(inner) {
109                    *slot = kind;
110                }
111                if let Some(slot) = empty.get_mut(r.depth().min(MAX_DEPTH.saturating_sub(1))) {
112                    *slot = true;
113                }
114            }
115        }
116    }
117}
118
119fn return_brace(f: &mut fmt::Formatter<'_>, kind: ContainerKind) -> fmt::Result {
120    f.write_char(match kind {
121        ContainerKind::Structure => '}',
122        ContainerKind::Array | ContainerKind::List => ']',
123    })
124}
125
126fn write_tag(f: &mut fmt::Formatter<'_>, tag: Tag) -> fmt::Result {
127    match tag {
128        Tag::Anonymous => Ok(()),
129        Tag::Context(n) => write!(f, "{n} = "),
130        Tag::Common(n) => write!(f, "Matter::{n} = "),
131        Tag::Implicit(n) => write!(f, "implicit:{n} = "),
132        Tag::FullyQualified {
133            vendor,
134            profile,
135            number,
136        } => write!(f, "{vendor}::{profile}:{number} = "),
137    }
138}
139
140fn write_value(f: &mut fmt::Formatter<'_>, value: &Value<'_>) -> fmt::Result {
141    match value {
142        Value::Signed(v) => write!(f, "{v}"),
143        Value::Unsigned(v) => write!(f, "{v}U"),
144        Value::Bool(v) => write!(f, "{v}"),
145        Value::Float(v) => write!(f, "{v}"),
146        Value::Double(v) => write!(f, "{v}"),
147        Value::Utf8(v) => write!(f, "{v:?}"),
148        Value::Octets(v) => {
149            f.write_str("0x")?;
150            for b in *v {
151                write!(f, "{b:02x}")?;
152            }
153            Ok(())
154        }
155        Value::Null => f.write_str("null"),
156        Value::Container(ContainerKind::Structure) => f.write_char('{'),
157        Value::Container(ContainerKind::Array | ContainerKind::List) => f.write_char('['),
158        Value::EndOfContainer => Ok(()),
159    }
160}
161
162#[cfg(all(test, feature = "std"))]
163#[allow(clippy::arithmetic_side_effects, clippy::indexing_slicing)]
164mod tests {
165    use super::*;
166
167    #[test]
168    fn prints_the_spec_examples() {
169        assert_eq!(
170            std::format!(
171                "{}",
172                Pretty(&[0x15, 0x20, 0x00, 0x2a, 0x20, 0x01, 0xef, 0x18])
173            ),
174            "{0 = 42, 1 = -17}"
175        );
176        assert_eq!(std::format!("{}", Pretty(&[0x04, 0x2a])), "42U");
177        assert_eq!(std::format!("{}", Pretty(&[0x14])), "null");
178        assert_eq!(
179            std::format!(
180                "{}",
181                Pretty(&[0x0c, 0x06, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21])
182            ),
183            "\"Hello!\""
184        );
185    }
186
187    #[test]
188    fn containers_close_with_the_brace_they_opened() {
189        assert_eq!(std::format!("{}", Pretty(&[0x15, 0x18])), "{}");
190        assert_eq!(std::format!("{}", Pretty(&[0x16, 0x18])), "[]");
191        assert_eq!(std::format!("{}", Pretty(&[0x17, 0x18])), "[]");
192        // [0, 1, 2, 3, 4]
193        assert_eq!(
194            std::format!(
195                "{}",
196                Pretty(&[
197                    0x16, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04, 0x18
198                ])
199            ),
200            "[0, 1, 2, 3, 4]"
201        );
202    }
203
204    #[test]
205    fn nesting_closes_in_the_right_order() {
206        // { 0 = [ {} ] }
207        let buf = [0x15, 0x36, 0x00, 0x15, 0x18, 0x18, 0x18];
208        assert_eq!(std::format!("{}", Pretty(&buf)), "{0 = [{}]}");
209    }
210
211    #[test]
212    fn a_broken_encoding_prints_what_it_understood() {
213        let s = std::format!("{}", Pretty(&[0x15, 0x24, 0x00, 0x2a, 0x0c, 0x06, 0x48]));
214        assert!(s.contains("<!error>"), "{s}");
215        assert!(s.starts_with('{'), "{s}");
216    }
217}