1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use crate::ascii::AsciiError;
use safe_http::{InvalidHeaderName, InvalidHeaderValue, InvalidMethod, InvalidStatusCode};
use safe_uri::ParseUriError;
use std::{error, fmt, num::ParseIntError};

#[derive(Debug, Clone)]
pub(crate) enum Error {
    Ascii(AsciiError),
    HeaderName(InvalidHeaderName),
    HeaderValue(InvalidHeaderValue),
    Message(&'static str),
    Method(InvalidMethod),
    Uri(ParseUriError),
    StatusCodeParse(ParseIntError),
    StatusCode(InvalidStatusCode),
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        use Error::*;
        Some(match self {
            Message(_) => return None,
            Ascii(s) => s,
            HeaderName(s) => s,
            HeaderValue(s) => s,
            Method(s) => s,
            Uri(s) => s,
            StatusCodeParse(s) => s,
            StatusCode(s) => s,
        })
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use Error::*;
        match self {
            Ascii(_) => f.write_str("invalid ASCII"),
            HeaderName(_) => f.write_str("invalid header name"),
            HeaderValue(_) => f.write_str("invalid header value"),
            Message(m) => f.write_str(m),
            Method(_) => f.write_str("invalid method"),
            Uri(_) => f.write_str("failed to parse URI"),
            StatusCode(_) | StatusCodeParse(_) => f.write_str("failed status code"),
        }
    }
}

#[derive(Debug, Clone)]
pub struct ParseRequestError(pub(crate) Error);

impl error::Error for ParseRequestError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        Some(&self.0)
    }
}

impl fmt::Display for ParseRequestError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("failed to parse HTTP request")
    }
}

#[derive(Debug, Clone)]
pub struct ParseResponseError(pub(crate) Error);

impl error::Error for ParseResponseError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        Some(&self.0)
    }
}

impl fmt::Display for ParseResponseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("failed to parse HTTP response")
    }
}