wire_codec/error.rs
1//! Error type returned by codec and framing operations.
2//!
3//! All fallible APIs in this crate return [`Result<T>`][`crate::Result`], which is
4//! [`core::result::Result<T, Error>`]. The [`Error`] enum is `#[non_exhaustive]`
5//! so future variants can be added without breaking semver.
6
7use core::fmt;
8
9/// Errors returned by codec and framing operations.
10///
11/// # Example
12///
13/// ```
14/// use wire_codec::{Error, ReadBuf};
15///
16/// let mut buf = ReadBuf::new(&[0x01]);
17/// // Only one byte available but we ask for two.
18/// let result = buf.read_u16_be();
19/// assert!(matches!(result, Err(Error::UnexpectedEof)));
20/// ```
21#[non_exhaustive]
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Error {
24 /// Reader ran out of bytes before the requested value could be decoded.
25 UnexpectedEof,
26 /// Writer ran out of capacity before the requested value could be encoded.
27 BufferFull,
28 /// A varint exceeded the maximum encoded length for its target width.
29 VarintOverflow,
30 /// A frame's declared length exceeds the configured limit for the framer.
31 FrameTooLarge {
32 /// Frame length advertised by the protocol.
33 len: usize,
34 /// Configured upper bound enforced by the framer.
35 limit: usize,
36 },
37 /// A length prefix was structurally invalid (e.g. width zero, or a width
38 /// larger than the codec supports).
39 InvalidLengthPrefix,
40 /// A delimiter byte sequence was not found within the available input.
41 DelimiterNotFound,
42 /// Decoded data violated a structural invariant required by the codec.
43 InvalidEncoding,
44 /// A bit-level write requested more bits than the target type can hold,
45 /// or a value did not fit in the requested bit width.
46 BitOverflow,
47 /// A delimited-framer constructor was given an empty delimiter, which
48 /// cannot uniquely separate frames.
49 EmptyDelimiter,
50}
51
52impl fmt::Display for Error {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 match *self {
55 Error::UnexpectedEof => f.write_str("unexpected end of input"),
56 Error::BufferFull => f.write_str("output buffer is full"),
57 Error::VarintOverflow => f.write_str("varint encoded length exceeded the target width"),
58 Error::FrameTooLarge { len, limit } => {
59 write!(f, "frame length {len} exceeds configured limit {limit}")
60 }
61 Error::InvalidLengthPrefix => f.write_str("length prefix is structurally invalid"),
62 Error::DelimiterNotFound => f.write_str("delimiter not found in input"),
63 Error::InvalidEncoding => f.write_str("encoded data violates a structural invariant"),
64 Error::BitOverflow => f.write_str("bit width or value out of range"),
65 Error::EmptyDelimiter => f.write_str("delimiter must be non-empty"),
66 }
67 }
68}
69
70#[cfg(feature = "std")]
71impl std::error::Error for Error {}
72
73/// Result alias used throughout the crate.
74pub type Result<T> = core::result::Result<T, Error>;