#[non_exhaustive]pub enum SerialError {
Show 16 variants
UnexpectedEof {
needed: usize,
remaining: usize,
},
InvalidLength {
declared: u64,
remaining: usize,
},
VarintOverflow,
IntegerOutOfRange,
InvalidBool {
byte: u8,
},
InvalidUtf8,
InvalidTag {
kind: &'static str,
tag: u8,
},
UnknownVariant {
kind: &'static str,
index: u64,
},
TrailingBytes {
remaining: usize,
},
Io {
kind: ErrorKind,
message: String,
},
DepthLimitExceeded {
max_depth: usize,
},
NonCanonical {
reason: &'static str,
},
InvalidVersion {
version: u64,
},
InvalidValue {
kind: &'static str,
},
InvalidConfig {
reason: &'static str,
},
Custom {
message: Cow<'static, str>,
},
}Expand description
Every error returned by the codec.
#[non_exhaustive] so additional variants can be added in a MINOR release
without breaking downstream match arms. Callers MUST include a wildcard
arm.
§Examples
use pack_io::{decode, SerialError};
// A length prefix that runs off the end of the buffer is rejected, not
// accepted-and-corrected.
let bad: &[u8] = &[0xff, 0xff, 0xff, 0xff, 0x0f]; // varint = u32::MAX
match decode::<String>(bad) {
Ok(_) => unreachable!("hostile length should not decode"),
Err(SerialError::InvalidLength { .. })
| Err(SerialError::UnexpectedEof { .. }) => {} // expected
Err(other) => panic!("unexpected error variant: {other}"),
}Variants (Non-exhaustive)§
This enum is marked as non-exhaustive
UnexpectedEof
The decoder needed more bytes than the input contained.
needed is the number of additional bytes the codec required to make
progress; remaining is what was actually left in the buffer.
Fields
InvalidLength
A length prefix declared a value larger than the buffer can hold.
This is the primary defence against a hostile length-prefix attack:
the decoder refuses to allocate or read past the available input.
It is also returned when collection elements that occupy no input
bytes (Box<()>, structs whose fields are all skip, …) would need
more memory than crate::Config::max_alloc allows across the whole
decode; declared is then that memory in bytes.
Fields
VarintOverflow
A LEB128 varint exceeded the maximum legal byte count for its target
width (10 bytes for u64, 5 for u32, 19 for u128, etc.).
IntegerOutOfRange
A decoded varint did not fit in the requested integer width
(e.g. u64 decoded successfully but the target was u32).
InvalidBool
A boolean byte was neither 0x00 nor 0x01.
Fields
InvalidUtf8
A length-prefixed byte run was not valid UTF-8 when decoding a
String.
InvalidTag
A tag byte for Option (0x00 / 0x01) or Result (0x00 / 0x01)
was outside the legal range.
Fields
UnknownVariant
A decoded enum variant index did not correspond to any known variant
of the target type. Produced by the #[derive(Deserialize)] /
#[derive(DeserializeView)] enum deserialisers in pack-io-derive.
kind is the enum’s type name; index is the offending varint
value (read as u64 so any overflow case is representable).
Fields
TrailingBytes
The input buffer contained trailing bytes after a strict decode
completed. Returned by the whole-buffer entry points
(crate::decode, crate::decode_view, decode_from (feature std) and
their _with_config siblings), which require the payload to be fully
consumed.
Io
std only.An underlying std::io::Write / std::io::Read operation failed
while a streaming codec was in flight. Returned only by the
std-gated I/O integration (IoEncoder, IoDecoder,
encode_into, decode_from).
The error kind and a stringified message are captured so the variant
remains Clone + Eq. The original std::io::Error is not preserved
— log the captured message field for diagnostics.
Fields
DepthLimitExceeded
Decoding nested deeper than crate::Config::max_depth levels.
Every derived Deserialize / DeserializeView impl counts as one
level, so a hostile payload for a recursive type (for example
struct Node { children: Vec<Node> }) cannot drive the decoder into
a stack overflow. Raise the limit with
crate::Config::with_max_depth if legitimate data is deeper than
the default; otherwise treat the input as hostile.
NonCanonical
The input used a valid but non-canonical encoding while the decoder
was in canonical mode (crate::Config::with_canonical).
Canonical mode rejects every input that is not the exact byte string
the encoder would produce for the decoded value, so that a hash or
signature over the bytes identifies the value. reason names the
rule that was broken: "varint" (a varint with redundant zero high
bytes), "map key order" / "set element order" (entries not in
strictly increasing encoded-key order, which also covers
duplicates), "versioned struct version" (a versioned struct
written at a version other than the decoding type’s own),
"versioned body" (unread bytes inside a versioned struct body), or
"retired field" (a retired field’s slot holding anything but the
encoding of its default).
InvalidVersion
A versioned struct carried a schema version the format reserves.
Version 0 is reserved by the wire format so that an accidental
all-zero buffer is never mistaken for a versioned payload
(docs/WIRE_FORMAT.md §3.8). Treat the input as corrupt.
InvalidValue
A decoded value was well-formed on the wire but violates the target
type’s own invariant — a char outside the Unicode scalar range, a
zero for a NonZero* integer, or a Duration whose nanosecond part
is one second or more.
InvalidConfig
A crate::Config knob was set to a value the codec cannot honour
(for example max_alloc == 0 or max_depth == 0), or canonical mode
on a decoder that cannot check it (a streaming decoder). Returned at
construction time, before any byte is read.
Custom
An error raised by user code: a hand-written Serialize /
Deserialize impl, a #[pack_io(with = "...")] helper, or a
serde type routed through the serde adapter.
Build it with SerialError::custom. The message is the caller’s
responsibility; as with every other variant, never put untrusted
payload bytes or secrets into it.
Implementations§
Source§impl SerialError
impl SerialError
Sourcepub fn custom(message: impl Into<Cow<'static, str>>) -> Self
pub fn custom(message: impl Into<Cow<'static, str>>) -> Self
Build a SerialError::Custom from any message.
Accepts a &'static str (no allocation) or an owned String. Use it
from hand-written Serialize / Deserialize impls to reject values
the built-in variants do not describe.
§Examples
use pack_io::{Decode, Deserialize, Result, SerialError};
/// A percentage stored as one byte; anything above 100 is corrupt.
struct Percent(u8);
impl Deserialize for Percent {
fn deserialize<D: Decode + ?Sized>(dec: &mut D) -> Result<Self> {
let raw = u8::deserialize(dec)?;
if raw > 100 {
return Err(SerialError::custom("percentage above 100"));
}
Ok(Percent(raw))
}
}
let err = pack_io::decode::<Percent>(&[101]).err().unwrap();
assert_eq!(err.to_string(), "percentage above 100");Trait Implementations§
Source§impl Clone for SerialError
impl Clone for SerialError
Source§impl Debug for SerialError
impl Debug for SerialError
Source§impl Display for SerialError
impl Display for SerialError
impl Eq for SerialError
Source§impl Error for SerialError
Available on crate feature std only.
impl Error for SerialError
std only.1.30.0 · Source§fn source(&self) -> Option<&(dyn Error + 'static)>
fn source(&self) -> Option<&(dyn Error + 'static)>
1.0.0 · Source§fn description(&self) -> &str
fn description(&self) -> &str
use the Display impl or to_string()
Source§impl Error for SerialError
Available on crate feature serde only.
impl Error for SerialError
serde only.Source§impl Error for SerialError
Available on crate feature serde only.
impl Error for SerialError
serde only.Source§fn custom<T: Display>(msg: T) -> Self
fn custom<T: Display>(msg: T) -> Self
Source§fn invalid_type(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self
fn invalid_type(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self
Deserialize receives a type different from what it was
expecting. Read moreSource§fn invalid_value(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self
fn invalid_value(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self
Deserialize receives a value of the right type but that
is wrong for some other reason. Read moreSource§fn invalid_length(len: usize, exp: &dyn Expected) -> Self
fn invalid_length(len: usize, exp: &dyn Expected) -> Self
Source§fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self
fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self
Deserialize enum type received a variant with an
unrecognized name.Source§fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self
fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self
Deserialize struct type received a field with an
unrecognized name.Source§fn missing_field(field: &'static str) -> Self
fn missing_field(field: &'static str) -> Self
Deserialize struct type expected to receive a required
field with a particular name but that field was not present in the
input.Source§fn duplicate_field(field: &'static str) -> Self
fn duplicate_field(field: &'static str) -> Self
Deserialize struct type received more than one of the
same field.