Skip to main content

SerialError

Enum SerialError 

Source
#[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
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

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

§needed: usize

Number of bytes the codec required to make progress.

§remaining: usize

Number of bytes still available in the input when the read failed.

§

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

§declared: u64

The length declared by the prefix, in bytes.

§remaining: usize

Bytes remaining in the input when the prefix was read.

§

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

§byte: u8

The offending byte. Kept so the caller can log a sanitised summary ({:02x}) without echoing the surrounding payload.

§

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

§kind: &'static str

Name of the type that owns this tag ("Option", "Result").

§tag: u8

The offending tag byte.

§

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

§kind: &'static str

Name of the enum that was being decoded.

§index: u64

The offending varint variant index.

§

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.

Fields

§remaining: usize

Number of bytes left over after the value was decoded.

§

Io

Available on crate feature 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

§kind: ErrorKind

Classification of the underlying I/O failure.

§message: String

Human-readable rendering of the original std::io::Error.

§

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.

Fields

§max_depth: usize

The configured limit that was hit.

§

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).

Fields

§reason: &'static str

The canonical-form rule the input violated.

§

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.

Fields

§version: u64

The offending version number.

§

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.

Fields

§kind: &'static str

Name of the target type ("char", "NonZeroU32", "Duration", …).

§

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.

Fields

§reason: &'static str

Which knob was rejected and why.

§

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.

Fields

§message: Cow<'static, str>

Human-readable description of the failure.

Implementations§

Source§

impl SerialError

Source

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

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for SerialError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for SerialError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for SerialError

Source§

impl Error for SerialError

Available on crate feature std only.
1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0:

use the Display impl or to_string()

1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl Error for SerialError

Available on crate feature serde only.
Source§

fn custom<T: Display>(msg: T) -> Self

Used when a Serialize implementation encounters any error while serializing a type. Read more
Source§

impl Error for SerialError

Available on crate feature serde only.
Source§

fn custom<T: Display>(msg: T) -> Self

Raised when there is general error when deserializing a type. Read more
Source§

fn invalid_type(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self

Raised when a Deserialize receives a type different from what it was expecting. Read more
Source§

fn invalid_value(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self

Raised when a Deserialize receives a value of the right type but that is wrong for some other reason. Read more
Source§

fn invalid_length(len: usize, exp: &dyn Expected) -> Self

Raised when deserializing a sequence or map and the input data contains too many or too few elements. Read more
Source§

fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self

Raised when a Deserialize enum type received a variant with an unrecognized name.
Source§

fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self

Raised when a Deserialize struct type received a field with an unrecognized name.
Source§

fn missing_field(field: &'static str) -> Self

Raised when a 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

Raised when a Deserialize struct type received more than one of the same field.
Source§

impl PartialEq for SerialError

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for SerialError

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.