1use core::fmt;
4
5#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum DecodeError {
15 UnknownKey(String),
17 MissingField(&'static str),
19 WrongArity { expected: u64, found: u64 },
21 IndefiniteLength,
23 DuplicateKey,
25 NonMinimalHead,
28 UnsortedMapKeys,
31 UnexpectedType {
33 expected: &'static str,
34 found: String,
35 },
36 InvalidLength {
38 field: &'static str,
39 expected: usize,
40 found: usize,
41 },
42 BadLiteral {
44 expected: &'static str,
45 found: String,
46 },
47 TrailingBytes { consumed: usize, total: usize },
49 Constraint(&'static str),
51 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 pub fn from_minicbor(err: minicbor::decode::Error) -> Self {
112 DecodeError::Malformed(err.to_string())
113 }
114}
115
116#[derive(Debug, Clone, PartialEq, Eq)]
122pub enum EncodeError {
123 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}