Skip to main content

weida_http_codec/
error.rs

1//! Why bytes were rejected, split by the direction that produced them.
2//!
3//! * [`DecodeError`] comes from bytes a peer sent. Exactly one variant,
4//!   [`DecodeError::Incomplete`], is *not* a violation: a head, a chunk line
5//!   or a frame may be split across reads, and asking for more octets is the
6//!   normal answer. [`DecodeError::is_violation`] says which is which, because
7//!   the remedy differs: read again, or refuse the message.
8//! * [`EncodeError`] comes from our own side: a value the wire cannot carry,
9//!   such as a field value holding a line feed, which a recipient would read as
10//!   the start of another field. The encoders refuse rather than escape,
11//!   because HTTP has no escaping mechanism for either.
12//!
13//! The `what` of every variant names the rule that was broken in the words of
14//! the RFC, so a library above can map it onto a status code or an error code
15//! without parsing a message.
16
17use core::fmt;
18
19/// Why bytes could not be decoded.
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum DecodeError {
23    /// More input is needed; `needed` is a lower bound of further octets.
24    ///
25    /// Every proper prefix of a valid input decodes to this variant, so a
26    /// reader that gets it reads more and calls again with the longer buffer.
27    Incomplete {
28        /// At least this many more octets are needed.
29        needed: usize,
30    },
31    /// A declared or searched size exceeds the caller's cap.
32    TooLarge {
33        /// What was too large: `"head"`, `"field count"`, `"chunk line"`,
34        /// `"field section"`, `"frame"`, `"string"`.
35        what: &'static str,
36        /// The size the peer declared, or the octets searched without an end.
37        declared: u64,
38        /// The cap it exceeded.
39        cap: u64,
40    },
41    /// The input breaks a rule of the protocol.
42    Malformed {
43        /// The rule, in the RFC's words: `"whitespace before the colon"`,
44        /// `"obsolete line folding"`, `"version"`, `"transfer coding"`.
45        what: &'static str,
46    },
47}
48
49impl DecodeError {
50    /// `true` for everything but [`DecodeError::Incomplete`]: the input is
51    /// wrong, and reading more will not fix it.
52    #[must_use]
53    pub const fn is_violation(&self) -> bool {
54        !matches!(self, Self::Incomplete { .. })
55    }
56}
57
58impl fmt::Display for DecodeError {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        match self {
61            Self::Incomplete { needed } => write!(f, "incomplete: at least {needed} more octets"),
62            Self::TooLarge {
63                what,
64                declared,
65                cap,
66            } => write!(
67                f,
68                "{what} too large: {declared} octets over the cap of {cap}"
69            ),
70            Self::Malformed { what } => write!(f, "malformed: {what}"),
71        }
72    }
73}
74
75impl std::error::Error for DecodeError {}
76
77/// Why a value could not be encoded.
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79#[non_exhaustive]
80pub enum EncodeError {
81    /// A field name, or a method, that is not a token (RFC 9110 §5.1, §9.1).
82    InvalidName {
83        /// What was invalid: `"field name"`, `"method"`.
84        what: &'static str,
85    },
86    /// A value the wire cannot carry.
87    InvalidValue {
88        /// What was invalid: `"field value"`, `"request target"`, `"status"`,
89        /// `"reason phrase"`, `"version"`.
90        what: &'static str,
91    },
92    /// A value larger than the encoding can express.
93    TooLarge {
94        /// What was too large.
95        what: &'static str,
96        /// Its length or value.
97        len: u64,
98        /// The largest the encoding allows.
99        cap: u64,
100    },
101}
102
103impl fmt::Display for EncodeError {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        match self {
106            Self::InvalidName { what } => write!(f, "invalid {what}: not a token"),
107            Self::InvalidValue { what } => write!(f, "invalid {what}"),
108            Self::TooLarge { what, len, cap } => {
109                write!(f, "{what} too large: {len} over the limit of {cap}")
110            }
111        }
112    }
113}
114
115impl std::error::Error for EncodeError {}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    #[test]
122    fn only_incomplete_is_not_a_violation() {
123        assert!(!DecodeError::Incomplete { needed: 1 }.is_violation());
124        assert!(DecodeError::Malformed { what: "version" }.is_violation());
125        assert!(
126            DecodeError::TooLarge {
127                what: "head",
128                declared: 2,
129                cap: 1
130            }
131            .is_violation()
132        );
133    }
134}