cbor_tools/
display.rs

1//! This module provides some optional implementations of the `Display` trait.
2//!
3//! When debugging CBOR decoding, it can be interesting to look at the "symbolic"
4//! view of the raw CBOR data. Implementing `Display` for these data structures
5//! allows us to easily examine the low-level CBOR encoding properties.
6//!
7//! See the examples directory for one way this can be used.
8
9use crate::format::{AdnInfo, Element, ImmediateValue, Major};
10
11impl std::fmt::Display for Major {
12    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13        write!(f, "{}({})", self.as_ref(), *self as u8)
14    }
15}
16
17impl std::fmt::Display for ImmediateValue {
18    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        match self {
20            ImmediateValue::Empty => Ok(()),
21            ImmediateValue::Bytes1(b) => write!(f, "{}", hex_fmt::HexFmt(b)),
22            ImmediateValue::Bytes2(b) => write!(f, "{}", hex_fmt::HexFmt(b)),
23            ImmediateValue::Bytes4(b) => write!(f, "{}", hex_fmt::HexFmt(b)),
24            ImmediateValue::Bytes8(b) => write!(f, "{}", hex_fmt::HexFmt(b)),
25        }
26    }
27}
28
29impl std::fmt::Display for Element {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        write!(f, "{} adn=0x{:x}", self.major, self.adn_info.0)?;
32
33        if self.major == Major::Misc {
34            // In major 7, there are a number of special values.
35            match self.adn_info {
36                AdnInfo::FALSE => write!(f, " (FALSE)")?,
37                AdnInfo::TRUE => write!(f, " (TRUE)")?,
38                AdnInfo::NULL => write!(f, " (NULL)")?,
39                AdnInfo::UNDEFINED => write!(f, " (UNDEFINED)")?,
40                AdnInfo::FLOAT16 => write!(f, " (FLOAT16)")?,
41                AdnInfo::FLOAT32 => write!(f, " (FLOAT32)")?,
42                AdnInfo::FLOAT64 => write!(f, " (FLOAT64)")?,
43                AdnInfo::BREAK => write!(f, " (BREAK)")?,
44                _ => write!(f, " (???)")?,
45            }
46        } else {
47            match self.adn_info {
48                AdnInfo(n) if n < 24 => {
49                    write!(f, " (len={})", n)?;
50                }
51                AdnInfo::INDEFINITE => write!(f, " (INDEFINITE)")?,
52                AdnInfo::MORE1 => write!(f, " (1BYTE)")?,
53                AdnInfo::MORE2 => write!(f, " (2BYTE)")?,
54                AdnInfo::MORE4 => write!(f, " (4BYTE)")?,
55                AdnInfo::MORE8 => write!(f, " (8BYTE)")?,
56                _ => write!(f, " (???)")?,
57            };
58        }
59
60        if self.imm != ImmediateValue::Empty {
61            write!(f, " <{}>", self.imm)?;
62        }
63
64        if !self.bytes.is_empty() {
65            write!(f, " [{}]", hex_fmt::HexFmt(&self.bytes))?;
66        }
67        Ok(())
68    }
69}