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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
use std::{
    error,
    fmt::{self},
    num::ParseIntError,
    result,
    str::Utf8Error,
};

use crate::runtime::io::Error as IoError;
use async_native_tls::Error as TlsError;

macro_rules! err {
    ($kind:expr, $($arg:tt)*) => {{
		use crate::error::Error;

        let kind = $kind;
        let message = format!($($arg)*);
        return Err(Error::new( kind, message ));
    }};
}

#[derive(Debug)]
pub enum ErrorKind {
    Tls(TlsError),
    Io(IoError),
    ParseInt(ParseIntError),
    ParseString(Utf8Error),
    ServerError(String),
    NotConnected,
    ShouldNotBeConnected,
    IncorrectStateForCommand,
    MessageIsDeleted,
    FeatureUnsupported,
    ServerFailedToGreet,
    InvalidResponse,
    ResponseTooLarge,
    MissingRequest,
    ParseCommand,
    UnexpectedResponse,
    ConnectionClosed,
}

#[derive(Debug)]
pub struct Error {
    message: String,
    kind: ErrorKind,
}

impl Error {
    pub fn new<S>(error_kind: ErrorKind, message: S) -> Self
    where
        String: From<S>,
    {
        Self {
            message: message.into(),
            kind: error_kind,
        }
    }

    pub fn message(&self) -> &str {
        &self.message
    }

    pub fn kind(&self) -> &ErrorKind {
        &self.kind
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        &self.message
    }

    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self.kind() {
            _ => None,
        }
    }
}

impl Into<String> for Error {
    fn into(self) -> String {
        self.message
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl From<TlsError> for Error {
    fn from(tls_error: async_native_tls::Error) -> Self {
        Self::new(
            ErrorKind::Tls(tls_error),
            "Error creating secure connection",
        )
    }
}

impl From<IoError> for Error {
    fn from(io_error: IoError) -> Self {
        Self::new(ErrorKind::Io(io_error), "Error with connection to server")
    }
}

impl From<ParseIntError> for Error {
    fn from(parse_int_error: ParseIntError) -> Self {
        Self::new(ErrorKind::ParseInt(parse_int_error), "Failed to parse int")
    }
}

impl From<Utf8Error> for Error {
    fn from(error: Utf8Error) -> Self {
        Self::new(ErrorKind::ParseString(error), "Failed to parse string")
    }
}

pub(crate) use err;

pub type Result<T> = result::Result<T, Error>;