Skip to main content

wire_mesh_wire/
error.rs

1//! Error types for the wire codec.
2
3use core::fmt;
4
5/// Failure to decode a wire value.
6///
7/// Decoding is strict by design: it rejects unknown map keys, wrong map
8/// arity, indefinite-length items (RFC 8949 4.2 core deterministic encoding
9/// requires definite lengths), non-minimal head widths, map keys out of CDE
10/// order (including duplicates), floats, tags, non-32-byte device-ids, bad
11/// enum literals, and trailing bytes after a top-level item — so any input
12/// that decodes also re-encodes to the identical bytes.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum DecodeError {
15    /// A map key that no CDDL rule in the corresponding family defines.
16    UnknownKey(String),
17    /// A mandatory field of a map is absent.
18    MissingField(&'static str),
19    /// A map or array head declared a different arity than the rule allows.
20    WrongArity { expected: u64, found: u64 },
21    /// An indefinite-length item where CDE requires a definite one.
22    IndefiniteLength,
23    /// A duplicate key within a single map.
24    DuplicateKey,
25    /// A head (integer, string, bytes, map, or array) not in shortest CBOR
26    /// form, which RFC 8949 4.2.1 core deterministic encoding requires.
27    NonMinimalHead,
28    /// Map keys not in RFC 8949 4.2.1 core deterministic order
29    /// (encoded-length first, then bytewise).
30    UnsortedMapKeys,
31    /// A value of the wrong CBOR type or shape for the field.
32    UnexpectedType {
33        expected: &'static str,
34        found: String,
35    },
36    /// A fixed-size field (e.g. `device-id`) of the wrong byte length.
37    InvalidLength {
38        field: &'static str,
39        expected: usize,
40        found: usize,
41    },
42    /// An enum literal that is not part of the closed union.
43    BadLiteral {
44        expected: &'static str,
45        found: String,
46    },
47    /// Bytes remained after the top-level item.
48    TrailingBytes { consumed: usize, total: usize },
49    /// A bool/uint/int constraint from the CDDL failed on the decoded value.
50    Constraint(&'static str),
51    /// Anything else, including malformed CBOR from the underlying decoder.
52    Malformed(String),
53}
54
55impl fmt::Display for DecodeError {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        match self {
58            DecodeError::UnknownKey(k) => write!(f, "unknown map key {k:?}"),
59            DecodeError::MissingField(name) => write!(f, "missing mandatory field {name:?}"),
60            DecodeError::WrongArity { expected, found } => {
61                write!(f, "expected {expected} items, found {found}")
62            }
63            DecodeError::IndefiniteLength => {
64                write!(
65                    f,
66                    "indefinite-length item rejected (CDE requires definite lengths)"
67                )
68            }
69            DecodeError::DuplicateKey => write!(f, "duplicate map key"),
70            DecodeError::NonMinimalHead => {
71                write!(
72                    f,
73                    "head not in shortest form (CDE requires minimal-width encodings)"
74                )
75            }
76            DecodeError::UnsortedMapKeys => {
77                write!(
78                    f,
79                    "map keys not in CDE order (encoded-length first, then bytewise)"
80                )
81            }
82            DecodeError::UnexpectedType { expected, found } => {
83                write!(f, "expected {expected}, found {found}")
84            }
85            DecodeError::InvalidLength {
86                field,
87                expected,
88                found,
89            } => {
90                write!(f, "field {field} must be {expected} bytes, found {found}")
91            }
92            DecodeError::BadLiteral { expected, found } => {
93                write!(f, "expected literal {expected}, found {found}")
94            }
95            DecodeError::TrailingBytes { consumed, total } => {
96                write!(
97                    f,
98                    "{consumed} of {total} bytes consumed, trailing bytes remain"
99                )
100            }
101            DecodeError::Constraint(what) => write!(f, "constraint violated: {what}"),
102            DecodeError::Malformed(msg) => write!(f, "malformed CBOR: {msg}"),
103        }
104    }
105}
106
107impl std::error::Error for DecodeError {}
108
109impl DecodeError {
110    /// Map an underlying `minicbor` decode error into a [`DecodeError`].
111    pub fn from_minicbor(err: minicbor::decode::Error) -> Self {
112        DecodeError::Malformed(err.to_string())
113    }
114}
115
116/// Failure to encode a wire value.
117///
118/// Encoding a well-formed wire value cannot fail in practice (the types make
119/// invalid states unrepresentable); this type exists so the codec's entry
120/// points can surface writer errors without panicking.
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub enum EncodeError {
123    /// The underlying writer failed.
124    Write(String),
125}
126
127impl fmt::Display for EncodeError {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        match self {
130            EncodeError::Write(msg) => write!(f, "write failed: {msg}"),
131        }
132    }
133}
134
135impl std::error::Error for EncodeError {}
136
137impl From<minicbor::encode::Error<std::io::Error>> for EncodeError {
138    fn from(err: minicbor::encode::Error<std::io::Error>) -> Self {
139        EncodeError::Write(err.to_string())
140    }
141}