areq_h1/
error.rs

1use {
2    http::Version,
3    std::{
4        error, fmt,
5        io::{self, ErrorKind},
6    },
7};
8
9#[derive(Debug)]
10pub enum Error {
11    Io(io::Error),
12    Parse(httparse::Error),
13    TooLargeInput,
14    UnsupportedVersion(Version),
15    Closed,
16}
17
18impl Error {
19    #[inline]
20    pub fn invalid_input() -> Self {
21        Self::Io(ErrorKind::InvalidInput.into())
22    }
23
24    #[inline]
25    pub fn unexpected_eof() -> Self {
26        Self::Io(ErrorKind::UnexpectedEof.into())
27    }
28
29    #[inline]
30    pub fn try_into_io(self) -> Result<io::Error, Self> {
31        match self {
32            Self::Io(e) => Ok(e),
33            e => Err(e),
34        }
35    }
36}
37
38impl From<io::Error> for Error {
39    #[inline]
40    fn from(v: io::Error) -> Self {
41        Self::Io(v)
42    }
43}
44
45impl From<httparse::Error> for Error {
46    #[inline]
47    fn from(v: httparse::Error) -> Self {
48        Self::Parse(v)
49    }
50}
51
52impl From<Error> for io::Error {
53    #[inline]
54    fn from(e: Error) -> Self {
55        e.try_into_io().unwrap_or_else(Self::other)
56    }
57}
58
59impl fmt::Display for Error {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        match self {
62            Self::Io(e) => write!(f, "io error: {e}"),
63            Self::Parse(e) => write!(f, "parse error: {e}"),
64            Self::TooLargeInput => write!(f, "too large input"),
65            Self::UnsupportedVersion(v) => write!(f, "unsupported http version: {v:?}"),
66            Self::Closed => write!(f, "connection closed"),
67        }
68    }
69}
70
71impl error::Error for Error {
72    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
73        match self {
74            Self::Io(e) => Some(e),
75            Self::Parse(e) => Some(e),
76            Self::TooLargeInput => None,
77            Self::UnsupportedVersion(_) => None,
78            Self::Closed => None,
79        }
80    }
81}