pack_io/error.rs
1//! Error type for the codec.
2//!
3//! `pack-io` uses a single, `#[non_exhaustive]` error enum that covers every
4//! failure mode of both encode and decode. The built-in encode paths are
5//! infallible on the in-memory [`crate::Encoder`]; encoding stays fallible at
6//! the type level so streaming encoders can surface `Write` failures and user
7//! impls can reject values they cannot represent.
8//!
9//! The variants are kept small and concrete: each one names a single failure
10//! mode and carries the smallest amount of context needed to act on it. None
11//! of them include the malformed bytes themselves — error messages from the
12//! codec never echo untrusted input back into a log line.
13
14use alloc::borrow::Cow;
15use core::fmt;
16
17/// Every error returned by the codec.
18///
19/// `#[non_exhaustive]` so additional variants can be added in a MINOR release
20/// without breaking downstream `match` arms. Callers MUST include a wildcard
21/// arm.
22///
23/// # Examples
24///
25/// ```
26/// use pack_io::{decode, SerialError};
27///
28/// // A length prefix that runs off the end of the buffer is rejected, not
29/// // accepted-and-corrected.
30/// let bad: &[u8] = &[0xff, 0xff, 0xff, 0xff, 0x0f]; // varint = u32::MAX
31/// match decode::<String>(bad) {
32/// Ok(_) => unreachable!("hostile length should not decode"),
33/// Err(SerialError::InvalidLength { .. })
34/// | Err(SerialError::UnexpectedEof { .. }) => {} // expected
35/// Err(other) => panic!("unexpected error variant: {other}"),
36/// }
37/// ```
38#[non_exhaustive]
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub enum SerialError {
41 /// The decoder needed more bytes than the input contained.
42 ///
43 /// `needed` is the number of additional bytes the codec required to make
44 /// progress; `remaining` is what was actually left in the buffer.
45 UnexpectedEof {
46 /// Number of bytes the codec required to make progress.
47 needed: usize,
48 /// Number of bytes still available in the input when the read failed.
49 remaining: usize,
50 },
51
52 /// A length prefix declared a value larger than the buffer can hold.
53 ///
54 /// This is the primary defence against a hostile length-prefix attack:
55 /// the decoder refuses to allocate or read past the available input.
56 /// It is also returned when collection elements that occupy no input
57 /// bytes (`Box<()>`, structs whose fields are all `skip`, …) would need
58 /// more memory than [`crate::Config::max_alloc`] allows across the whole
59 /// decode; `declared` is then that memory in bytes.
60 InvalidLength {
61 /// The length declared by the prefix, in bytes.
62 declared: u64,
63 /// Bytes remaining in the input when the prefix was read.
64 remaining: usize,
65 },
66
67 /// A LEB128 varint exceeded the maximum legal byte count for its target
68 /// width (10 bytes for `u64`, 5 for `u32`, 19 for `u128`, etc.).
69 VarintOverflow,
70
71 /// A decoded varint did not fit in the requested integer width
72 /// (e.g. `u64` decoded successfully but the target was `u32`).
73 IntegerOutOfRange,
74
75 /// A boolean byte was neither `0x00` nor `0x01`.
76 InvalidBool {
77 /// The offending byte. Kept so the caller can log a sanitised summary
78 /// (`{:02x}`) without echoing the surrounding payload.
79 byte: u8,
80 },
81
82 /// A length-prefixed byte run was not valid UTF-8 when decoding a
83 /// `String`.
84 InvalidUtf8,
85
86 /// A tag byte for `Option` (`0x00` / `0x01`) or `Result` (`0x00` / `0x01`)
87 /// was outside the legal range.
88 InvalidTag {
89 /// Name of the type that owns this tag (`"Option"`, `"Result"`).
90 kind: &'static str,
91 /// The offending tag byte.
92 tag: u8,
93 },
94
95 /// A decoded enum variant index did not correspond to any known variant
96 /// of the target type. Produced by the `#[derive(Deserialize)]` /
97 /// `#[derive(DeserializeView)]` enum deserialisers in `pack-io-derive`.
98 ///
99 /// `kind` is the enum's type name; `index` is the offending varint
100 /// value (read as `u64` so any overflow case is representable).
101 UnknownVariant {
102 /// Name of the enum that was being decoded.
103 kind: &'static str,
104 /// The offending varint variant index.
105 index: u64,
106 },
107
108 /// The input buffer contained trailing bytes after a strict decode
109 /// completed. Returned by the whole-buffer entry points
110 /// ([`crate::decode`], [`crate::decode_view`], `decode_from` (feature `std`) and
111 /// their `_with_config` siblings), which require the payload to be fully
112 /// consumed.
113 TrailingBytes {
114 /// Number of bytes left over after the value was decoded.
115 remaining: usize,
116 },
117
118 /// An underlying `std::io::Write` / `std::io::Read` operation failed
119 /// while a streaming codec was in flight. Returned only by the
120 /// `std`-gated I/O integration (`IoEncoder`, `IoDecoder`,
121 /// `encode_into`, `decode_from`).
122 ///
123 /// The error kind and a stringified message are captured so the variant
124 /// remains `Clone + Eq`. The original `std::io::Error` is not preserved
125 /// — log the captured `message` field for diagnostics.
126 #[cfg(feature = "std")]
127 Io {
128 /// Classification of the underlying I/O failure.
129 kind: std::io::ErrorKind,
130 /// Human-readable rendering of the original `std::io::Error`.
131 message: alloc::string::String,
132 },
133
134 /// Decoding nested deeper than [`crate::Config::max_depth`] levels.
135 ///
136 /// Every derived `Deserialize` / `DeserializeView` impl counts as one
137 /// level, so a hostile payload for a recursive type (for example
138 /// `struct Node { children: Vec<Node> }`) cannot drive the decoder into
139 /// a stack overflow. Raise the limit with
140 /// [`crate::Config::with_max_depth`] if legitimate data is deeper than
141 /// the default; otherwise treat the input as hostile.
142 DepthLimitExceeded {
143 /// The configured limit that was hit.
144 max_depth: usize,
145 },
146
147 /// The input used a valid but non-canonical encoding while the decoder
148 /// was in canonical mode ([`crate::Config::with_canonical`]).
149 ///
150 /// Canonical mode rejects every input that is not the exact byte string
151 /// the encoder would produce for the decoded value, so that a hash or
152 /// signature over the bytes identifies the value. `reason` names the
153 /// rule that was broken: `"varint"` (a varint with redundant zero high
154 /// bytes), `"map key order"` / `"set element order"` (entries not in
155 /// strictly increasing encoded-key order, which also covers
156 /// duplicates), `"versioned struct version"` (a versioned struct
157 /// written at a version other than the decoding type's own),
158 /// `"versioned body"` (unread bytes inside a versioned struct body), or
159 /// `"retired field"` (a retired field's slot holding anything but the
160 /// encoding of its default).
161 NonCanonical {
162 /// The canonical-form rule the input violated.
163 reason: &'static str,
164 },
165
166 /// A versioned struct carried a schema version the format reserves.
167 ///
168 /// Version `0` is reserved by the wire format so that an accidental
169 /// all-zero buffer is never mistaken for a versioned payload
170 /// (`docs/WIRE_FORMAT.md` §3.8). Treat the input as corrupt.
171 InvalidVersion {
172 /// The offending version number.
173 version: u64,
174 },
175
176 /// A decoded value was well-formed on the wire but violates the target
177 /// type's own invariant — a `char` outside the Unicode scalar range, a
178 /// zero for a `NonZero*` integer, or a `Duration` whose nanosecond part
179 /// is one second or more.
180 InvalidValue {
181 /// Name of the target type (`"char"`, `"NonZeroU32"`, `"Duration"`, …).
182 kind: &'static str,
183 },
184
185 /// A [`crate::Config`] knob was set to a value the codec cannot honour
186 /// (for example `max_alloc == 0` or `max_depth == 0`), or canonical mode
187 /// on a decoder that cannot check it (a streaming decoder). Returned at
188 /// construction time, before any byte is read.
189 InvalidConfig {
190 /// Which knob was rejected and why.
191 reason: &'static str,
192 },
193
194 /// An error raised by user code: a hand-written `Serialize` /
195 /// `Deserialize` impl, a `#[pack_io(with = "...")]` helper, or a
196 /// `serde` type routed through the `serde` adapter.
197 ///
198 /// Build it with [`SerialError::custom`]. The message is the caller's
199 /// responsibility; as with every other variant, never put untrusted
200 /// payload bytes or secrets into it.
201 Custom {
202 /// Human-readable description of the failure.
203 message: Cow<'static, str>,
204 },
205}
206
207impl fmt::Display for SerialError {
208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209 match self {
210 Self::UnexpectedEof { needed, remaining } => write!(
211 f,
212 "unexpected end of input: needed {needed} more byte(s), {remaining} remaining"
213 ),
214 Self::InvalidLength {
215 declared,
216 remaining,
217 } => write!(
218 f,
219 "length prefix exceeds remaining buffer: declared {declared}, remaining {remaining}"
220 ),
221 Self::VarintOverflow => {
222 f.write_str("varint exceeds the maximum byte count for its target width")
223 }
224 Self::IntegerOutOfRange => {
225 f.write_str("decoded integer does not fit in the requested width")
226 }
227 Self::InvalidBool { byte } => write!(f, "invalid boolean byte: 0x{byte:02x}"),
228 Self::InvalidUtf8 => f.write_str("length-prefixed bytes were not valid UTF-8"),
229 Self::InvalidTag { kind, tag } => write!(f, "invalid {kind} tag: 0x{tag:02x}"),
230 Self::UnknownVariant { kind, index } => {
231 write!(f, "unknown {kind} variant index: {index}")
232 }
233 Self::TrailingBytes { remaining } => {
234 write!(
235 f,
236 "trailing input after strict decode: {remaining} byte(s) unread"
237 )
238 }
239 Self::DepthLimitExceeded { max_depth } => {
240 write!(
241 f,
242 "nesting depth exceeds the configured limit of {max_depth}"
243 )
244 }
245 Self::NonCanonical { reason } => {
246 write!(
247 f,
248 "non-canonical encoding rejected in canonical mode: {reason}"
249 )
250 }
251 Self::InvalidVersion { version } => {
252 write!(
253 f,
254 "invalid schema version {version} (version 0 is reserved)"
255 )
256 }
257 Self::InvalidValue { kind } => {
258 write!(f, "decoded value is not a valid {kind}")
259 }
260 Self::InvalidConfig { reason } => write!(f, "invalid decoder configuration: {reason}"),
261 Self::Custom { message } => f.write_str(message),
262 #[cfg(feature = "std")]
263 Self::Io { kind, message } => write!(f, "I/O error ({kind:?}): {message}"),
264 }
265 }
266}
267
268impl SerialError {
269 /// Build a [`SerialError::Custom`] from any message.
270 ///
271 /// Accepts a `&'static str` (no allocation) or an owned `String`. Use it
272 /// from hand-written `Serialize` / `Deserialize` impls to reject values
273 /// the built-in variants do not describe.
274 ///
275 /// # Examples
276 ///
277 /// ```
278 /// use pack_io::{Decode, Deserialize, Result, SerialError};
279 ///
280 /// /// A percentage stored as one byte; anything above 100 is corrupt.
281 /// struct Percent(u8);
282 ///
283 /// impl Deserialize for Percent {
284 /// fn deserialize<D: Decode + ?Sized>(dec: &mut D) -> Result<Self> {
285 /// let raw = u8::deserialize(dec)?;
286 /// if raw > 100 {
287 /// return Err(SerialError::custom("percentage above 100"));
288 /// }
289 /// Ok(Percent(raw))
290 /// }
291 /// }
292 ///
293 /// let err = pack_io::decode::<Percent>(&[101]).err().unwrap();
294 /// assert_eq!(err.to_string(), "percentage above 100");
295 /// ```
296 #[must_use]
297 pub fn custom(message: impl Into<Cow<'static, str>>) -> Self {
298 Self::Custom {
299 message: message.into(),
300 }
301 }
302}
303
304#[cfg(feature = "std")]
305impl std::error::Error for SerialError {}
306
307// The `serde` adapter needs `SerialError` to satisfy serde's error traits.
308// With pack-io's `std` feature on, the `std::error::Error` impl above covers
309// serde's `StdError` bound (pack-io's `std` feature turns on `serde/std`).
310// Without it, serde's own `StdError` trait is implemented instead.
311#[cfg(all(feature = "serde", not(feature = "std")))]
312impl serde::ser::StdError for SerialError {}
313
314#[cfg(feature = "serde")]
315impl serde::ser::Error for SerialError {
316 fn custom<T: fmt::Display>(msg: T) -> Self {
317 use alloc::string::ToString;
318 Self::custom(msg.to_string())
319 }
320}
321
322#[cfg(feature = "serde")]
323impl serde::de::Error for SerialError {
324 fn custom<T: fmt::Display>(msg: T) -> Self {
325 use alloc::string::ToString;
326 Self::custom(msg.to_string())
327 }
328}
329
330/// Convenience alias for `Result<T, SerialError>`.
331///
332/// Used throughout the codec so the trait surface stays terse. Crates that
333/// implement `Serialize` / `Deserialize` for their own types are encouraged to
334/// use it as well; nothing in the public API requires it.
335///
336/// # Examples
337///
338/// ```
339/// use pack_io::Result;
340///
341/// fn parse_header(_bytes: &[u8]) -> Result<u32> {
342/// Ok(0)
343/// }
344/// ```
345pub type Result<T> = core::result::Result<T, SerialError>;
346
347#[cfg(test)]
348mod tests {
349 use super::*;
350 use alloc::format;
351 use alloc::string::ToString;
352
353 #[test]
354 fn display_unexpected_eof_reports_counts() {
355 let err = SerialError::UnexpectedEof {
356 needed: 4,
357 remaining: 1,
358 };
359 let msg = err.to_string();
360 assert!(msg.contains("needed 4"));
361 assert!(msg.contains("1 remaining"));
362 }
363
364 #[test]
365 fn display_invalid_length_reports_declared_and_remaining() {
366 let err = SerialError::InvalidLength {
367 declared: 1 << 20,
368 remaining: 16,
369 };
370 let msg = err.to_string();
371 assert!(msg.contains("1048576"));
372 assert!(msg.contains("16"));
373 }
374
375 #[test]
376 fn display_invalid_bool_is_hex_with_zero_pad() {
377 let err = SerialError::InvalidBool { byte: 0x2a };
378 assert_eq!(err.to_string(), "invalid boolean byte: 0x2a");
379 }
380
381 #[test]
382 fn display_invalid_tag_carries_kind_and_byte() {
383 let err = SerialError::InvalidTag {
384 kind: "Option",
385 tag: 0x7f,
386 };
387 assert!(err.to_string().contains("Option"));
388 assert!(err.to_string().contains("0x7f"));
389 }
390
391 #[test]
392 fn equality_distinguishes_variants() {
393 let a = SerialError::VarintOverflow;
394 let b = SerialError::VarintOverflow;
395 let c = SerialError::IntegerOutOfRange;
396 assert_eq!(a, b);
397 assert_ne!(a, c);
398 }
399
400 #[test]
401 fn clone_preserves_variant() {
402 let err = SerialError::TrailingBytes { remaining: 8 };
403 let cloned = err.clone();
404 assert_eq!(err, cloned);
405 }
406
407 #[test]
408 fn test_display_of_variants_added_in_1_1() {
409 let cases = [
410 (
411 SerialError::DepthLimitExceeded { max_depth: 7 },
412 "nesting depth exceeds the configured limit of 7",
413 ),
414 (
415 SerialError::NonCanonical { reason: "varint" },
416 "non-canonical encoding rejected in canonical mode: varint",
417 ),
418 (
419 SerialError::InvalidVersion { version: 0 },
420 "invalid schema version 0 (version 0 is reserved)",
421 ),
422 (
423 SerialError::InvalidValue { kind: "char" },
424 "decoded value is not a valid char",
425 ),
426 (
427 SerialError::InvalidConfig { reason: "x" },
428 "invalid decoder configuration: x",
429 ),
430 (SerialError::custom("boom"), "boom"),
431 (
432 SerialError::UnknownVariant {
433 kind: "E",
434 index: 9,
435 },
436 "unknown E variant index: 9",
437 ),
438 ];
439 for (err, expected) in cases {
440 assert_eq!(err.to_string(), expected);
441 }
442 }
443
444 #[test]
445 fn test_custom_accepts_static_and_owned_messages() {
446 let a = SerialError::custom("static");
447 let b = SerialError::custom(alloc::string::String::from("static"));
448 assert_eq!(a, b);
449 assert!(matches!(
450 a,
451 SerialError::Custom {
452 message: Cow::Borrowed("static")
453 }
454 ));
455 }
456
457 #[test]
458 fn debug_format_does_not_panic() {
459 // We never put untrusted bytes into Debug, so it's safe to print.
460 let _ = format!("{:?}", SerialError::InvalidUtf8);
461 }
462}