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
use kerberos_asn1::KrbError;
use kerberos_constants::error_codes;
use std::{fmt, io, result};

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

#[derive(Debug)]
pub enum Error
{
	String(String),
	KrbError(KrbError),

	/// Errors due to IO, such as failures in network or file operations.
	IOError(String, io::Error),

	/// Errors related to handling of raw data, such as parsing, encrypting,
	/// etc.
	DataError(String),
}

impl Error
{
	pub fn is_not_found_error(&self) -> bool
	{
		if let Error::IOError(_, ref io_err) = self
		{
			return io_err.kind() == io::ErrorKind::NotFound;
		}
		false
	}

	pub fn is_data_error(&self) -> bool
	{
		if let Error::DataError(_) = self
		{
			return true;
		}
		false
	}
}

impl fmt::Display for Error
{
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
	{
		match self
		{
			Error::String(s) => write!(f, "{}", s),
			Error::DataError(s) => write!(f, "{}", s),
			Error::KrbError(krb_error) =>
			{
				write!(f, "{}", create_krb_error_msg(krb_error))
			},
			Error::IOError(desc, io_error) =>
			{
				write!(f, "{}: {}", desc, io_error)
			},
		}
	}
}

impl From<String> for Error
{
	fn from(error: String) -> Self
	{
		Self::String(error)
	}
}

impl From<&str> for Error
{
	fn from(error: &str) -> Self
	{
		Self::String(error.to_string())
	}
}

impl From<KrbError> for Error
{
	fn from(error: KrbError) -> Self
	{
		Self::KrbError(error)
	}
}

impl From<(&str, io::Error)> for Error
{
	fn from(error: (&str, io::Error)) -> Self
	{
		Self::IOError(error.0.into(), error.1)
	}
}

impl From<(String, io::Error)> for Error
{
	fn from(error: (String, io::Error)) -> Self
	{
		Self::IOError(error.0, error.1)
	}
}

fn create_krb_error_msg(krb_error: &KrbError) -> String
{
	let error_string = error_codes::error_code_to_string(krb_error.error_code);
	format!("Error {}: {}", krb_error.error_code, error_string)
}