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}
48
49impl fmt::Display for Error {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 match *self {
52 Error::UnexpectedEof => f.write_str("unexpected end of input"),
53 Error::BufferFull => f.write_str("output buffer is full"),
54 Error::VarintOverflow => f.write_str("varint encoded length exceeded the target width"),
55 Error::FrameTooLarge { len, limit } => {
56 write!(f, "frame length {len} exceeds configured limit {limit}")
57 }
58 Error::InvalidLengthPrefix => f.write_str("length prefix is structurally invalid"),
59 Error::DelimiterNotFound => f.write_str("delimiter not found in input"),
60 Error::InvalidEncoding => f.write_str("encoded data violates a structural invariant"),
61 Error::BitOverflow => f.write_str("bit width or value out of range"),
62 }
63 }
64}
65
66#[cfg(feature = "std")]
67impl std::error::Error for Error {}
68
69/// Result alias used throughout the crate.
70pub type Result<T> = core::result::Result<T, Error>;