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
use tokio_util::codec::LinesCodecError;

/// Error type returned by this library
#[derive(Debug)]
pub enum TorError {
    /// Authentication error
    AuthenticationError(String),

    /// General protocol error
    ProtocolError(String),

    /// I/O Error
    IOError(std::io::Error),
}

impl std::fmt::Display for TorError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::AuthenticationError(error) => write!(f, "Authentication Error: {}", error),
            Self::ProtocolError(error) => write!(f, "Protocol Error: {}", error),
            Self::IOError(error) => write!(f, "IO Error: {}", error),
        }
    }
}

impl std::error::Error for TorError {}

impl TorError {
    pub fn authentication_error(msg: &str) -> TorError {
        TorError::AuthenticationError(msg.to_string())
    }

    pub fn protocol_error(msg: &str) -> TorError {
        TorError::ProtocolError(msg.to_string())
    }
}

impl From<std::io::Error> for TorError {
    fn from(error: std::io::Error) -> TorError {
        TorError::IOError(error)
    }
}

impl From<LinesCodecError> for TorError {
    fn from(error: LinesCodecError) -> TorError {
        match error {
            LinesCodecError::MaxLineLengthExceeded => TorError::ProtocolError(error.to_string()),
            LinesCodecError::Io(error) => error.into(),
        }
    }
}