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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
use {
    super::{Error, ParseError},
    crate::types::ValueType,
    std::{convert::Infallible, fmt, io},
};

#[derive(Debug)]
pub enum SerializeError {
    Infallible,
    InvalidValue(ValueType, Box<dyn fmt::Debug>),
}

impl From<Infallible> for SerializeError {
    fn from(_value: Infallible) -> Self {
        Self::Infallible
    }
}

pub struct UnexpectedPacket(pub Vec<u8>, pub Option<&'static str>);

impl fmt::Debug for UnexpectedPacket {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(expected) = self.1 {
            f.debug_struct("UnexpectedPacket")
                .field("expected", &expected)
                .field("got", &self.0)
                .finish()
        } else {
            f.debug_tuple("UnexpectedPacket").field(&self.0).finish()
        }
    }
}

#[derive(Debug)]
pub struct InvalidPacket {
    pub packet: Vec<u8>,
    pub r#type: &'static str,
    pub error: &'static str,
}

#[derive(Debug)]
pub enum ProtocolError {
    Parse(ParseError),
    Serialize(SerializeError),
    Io(io::Error),
    OutOfSync,
    UnexpectedPacket(UnexpectedPacket),
    InvalidPacket(InvalidPacket),
    UnknownAuthPlugin(Vec<u8>),
}

impl ProtocolError {
    pub fn eof() -> Self {
        Self::Io(io::Error::new(io::ErrorKind::UnexpectedEof, "EOF"))
    }

    pub fn unexpected_packet(got: Vec<u8>, expected: Option<&'static str>) -> Self {
        Self::UnexpectedPacket(UnexpectedPacket(got, expected))
    }

    pub fn invalid_packet(packet: Vec<u8>, r#type: &'static str, error: &'static str) -> Self {
        Self::InvalidPacket(InvalidPacket {
            packet,
            r#type,
            error,
        })
    }
}

impl From<ParseError> for ProtocolError {
    fn from(value: ParseError) -> Self {
        ProtocolError::Parse(value)
    }
}

impl From<ParseError> for Error {
    fn from(value: ParseError) -> Self {
        ProtocolError::Parse(value).into()
    }
}

impl From<SerializeError> for ProtocolError {
    fn from(value: SerializeError) -> Self {
        ProtocolError::Serialize(value)
    }
}

impl From<SerializeError> for Error {
    fn from(value: SerializeError) -> Self {
        ProtocolError::Serialize(value).into()
    }
}

impl From<io::Error> for ProtocolError {
    fn from(value: io::Error) -> Self {
        ProtocolError::Io(value)
    }
}

impl From<io::Error> for Error {
    fn from(value: io::Error) -> Self {
        ProtocolError::Io(value).into()
    }
}