1use core::fmt;
8
9use crate::status::PlaintextStatus;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum DecodeError {
15 UnexpectedEof {
17 needed: usize,
19 available: usize,
21 field: Field,
23 },
24 ReservedFlags(u16),
28 InvalidStatus(u8),
31 PayloadOnFailedStatus {
39 status: PlaintextStatus,
41 len: usize,
43 },
44 TrailingBytes(usize),
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52#[non_exhaustive]
53pub enum Field {
54 Version,
56 Flags,
58 FrameLen,
60 Frame,
62 PlaintextCount,
64 PathLen,
66 Path,
68 Status,
70 PayloadLen,
72 Payload,
74}
75
76impl Field {
77 #[must_use]
79 pub const fn name(self) -> &'static str {
80 match self {
81 Self::Version => "version",
82 Self::Flags => "flags",
83 Self::FrameLen => "frame_len",
84 Self::Frame => "frame",
85 Self::PlaintextCount => "pt_count",
86 Self::PathLen => "path_len",
87 Self::Path => "path",
88 Self::Status => "status",
89 Self::PayloadLen => "payload_len",
90 Self::Payload => "payload",
91 }
92 }
93}
94
95impl fmt::Display for Field {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 f.write_str(self.name())
98 }
99}
100
101impl fmt::Display for DecodeError {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 match self {
104 Self::UnexpectedEof {
105 needed,
106 available,
107 field,
108 } => write!(
109 f,
110 "unexpected end of input reading {field}: needed {needed} byte(s), {available} available"
111 ),
112 Self::ReservedFlags(bits) => {
113 write!(f, "reserved flag bits set: {bits:#06x}")
114 }
115 Self::InvalidStatus(byte) => write!(f, "invalid plaintext status: {byte}"),
116 Self::PayloadOnFailedStatus { status, len } => write!(
117 f,
118 "status {status} carries {len} payload byte(s); only ok may carry any"
119 ),
120 Self::TrailingBytes(count) => {
121 write!(f, "{count} trailing byte(s) after the envelope")
122 }
123 }
124 }
125}
126
127impl core::error::Error for DecodeError {}
128
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131#[non_exhaustive]
132pub enum EncodeError {
133 FrameTooLong(usize),
135 PayloadTooLong(usize),
137 PathTooLong(usize),
141 TooManyEntries(usize),
143 PayloadOnFailedStatus {
149 status: PlaintextStatus,
151 len: usize,
153 },
154 BufferTooSmall {
158 needed: usize,
160 available: usize,
162 },
163 LengthOverflow,
165}
166
167impl fmt::Display for EncodeError {
168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169 match self {
170 Self::FrameTooLong(len) => write!(f, "frame of {len} byte(s) exceeds u32"),
171 Self::PayloadTooLong(len) => write!(f, "payload of {len} byte(s) exceeds u32"),
172 Self::PathTooLong(len) => write!(f, "path of {len} component(s) exceeds u8"),
173 Self::TooManyEntries(count) => write!(f, "{count} plaintext entries exceed u16"),
174 Self::PayloadOnFailedStatus { status, len } => write!(
175 f,
176 "status {status} carries {len} payload byte(s); only ok may carry any"
177 ),
178 Self::BufferTooSmall { needed, available } => write!(
179 f,
180 "destination too small: needed {needed} byte(s), {available} available"
181 ),
182 Self::LengthOverflow => {
183 f.write_str("encoded length exceeds this target's address space")
184 }
185 }
186 }
187}
188
189impl core::error::Error for EncodeError {}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194 extern crate alloc;
195 use alloc::string::ToString;
196
197 #[test]
198 fn field_names_are_stable_and_unique() {
199 let all = [
200 Field::Version,
201 Field::Flags,
202 Field::FrameLen,
203 Field::Frame,
204 Field::PlaintextCount,
205 Field::PathLen,
206 Field::Path,
207 Field::Status,
208 Field::PayloadLen,
209 Field::Payload,
210 ];
211 for (i, a) in all.iter().enumerate() {
212 assert!(!a.name().is_empty());
213 assert_eq!(a.to_string(), a.name());
214 for b in all.iter().skip(i.saturating_add(1)) {
215 assert_ne!(a.name(), b.name(), "field names must be unique");
216 }
217 }
218 }
219
220 #[test]
221 fn decode_errors_render_their_detail() {
222 let eof = DecodeError::UnexpectedEof {
223 needed: 4,
224 available: 1,
225 field: Field::FrameLen,
226 };
227 let text = eof.to_string();
228 assert!(text.contains("frame_len"), "{text}");
229 assert!(text.contains('4') && text.contains('1'), "{text}");
230
231 assert!(
232 DecodeError::ReservedFlags(0xFFFC)
233 .to_string()
234 .contains("0xfffc")
235 );
236 assert!(DecodeError::InvalidStatus(9).to_string().contains('9'));
237 assert!(DecodeError::TrailingBytes(3).to_string().contains('3'));
238
239 let paired = DecodeError::PayloadOnFailedStatus {
240 status: PlaintextStatus::Unobserved,
241 len: 12,
242 }
243 .to_string();
244 assert!(
245 paired.contains("unobserved") && paired.contains("12"),
246 "{paired}"
247 );
248 }
249
250 #[test]
251 fn encode_errors_render_their_detail() {
252 assert!(EncodeError::FrameTooLong(5).to_string().contains('5'));
253 assert!(EncodeError::PayloadTooLong(6).to_string().contains('6'));
254 assert!(EncodeError::PathTooLong(7).to_string().contains('7'));
255 assert!(EncodeError::TooManyEntries(8).to_string().contains('8'));
256 let paired = EncodeError::PayloadOnFailedStatus {
257 status: PlaintextStatus::DecryptFailed,
258 len: 9,
259 }
260 .to_string();
261 assert!(
262 paired.contains("decrypt-failed") && paired.contains('9'),
263 "{paired}"
264 );
265 let small = EncodeError::BufferTooSmall {
266 needed: 10,
267 available: 2,
268 };
269 assert!(small.to_string().contains("10") && small.to_string().contains('2'));
270 assert!(
271 EncodeError::LengthOverflow
272 .to_string()
273 .contains("address space")
274 );
275 }
276
277 #[test]
278 fn errors_are_std_errors() {
279 fn assert_error<E: core::error::Error>(_: &E) {}
280 assert_error(&DecodeError::TrailingBytes(1));
281 assert_error(&EncodeError::LengthOverflow);
282 }
283
284 #[test]
285 fn errors_are_debug_and_comparable() {
286 assert_eq!(DecodeError::InvalidStatus(1), DecodeError::InvalidStatus(1));
287 assert_ne!(DecodeError::InvalidStatus(1), DecodeError::InvalidStatus(2));
288 assert_eq!(EncodeError::PathTooLong(1), EncodeError::PathTooLong(1));
289 assert_ne!(EncodeError::PathTooLong(1), EncodeError::FrameTooLong(1));
290 assert!(!alloc::format!("{:?}", Field::Path).is_empty());
291 }
292}