1use std::fmt::{self, Debug, Display, Formatter};
2use std::io::ErrorKind::UnexpectedEof;
3use std::sync::mpsc::RecvError;
4
5pub type Result<T> = std::result::Result<T, Error>;
6
7#[derive(Clone, Eq, PartialEq, Hash)]
10pub struct Error {
11 pub inner: String,
12}
13
14impl Error {
15 pub fn error(&self) -> String {
18 self.inner.clone()
19 }
20
21 pub fn warp<E>(e: E, info: &str) -> Self
24 where
25 E: std::fmt::Display,
26 {
27 Self {
28 inner: format!("{}{}", info, e),
29 }
30 }
31
32 pub fn to_string(&self) -> String {
35 self.inner.clone()
36 }
37}
38
39#[macro_export]
43macro_rules! err {
44 ($($arg:tt)*) => {{
45 $crate::error::Error{
46 inner: format!($($arg)*)
47 }
48 }}
49}
50
51#[inline]
54pub fn new(text: String) -> Error {
55 Error { inner: text }
56}
57
58pub trait FromError<T>: Sized {
59 fn from_err(_: T) -> Error;
60}
61
62impl Display for Error {
63 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
64 std::fmt::Display::fmt(&self.inner, f)
65 }
66}
67
68impl Debug for Error {
69 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
70 std::fmt::Debug::fmt(&self.inner, f)
71 }
72}
73
74impl From<std::io::Error> for Error {
75 #[inline]
76 fn from(err: std::io::Error) -> Self {
77 if err.kind().eq(&UnexpectedEof) {
78 return err!("Eof");
79 }
80 if err.kind().eq(&std::io::ErrorKind::UnexpectedEof) {
81 return err!("UnexpectedEof");
82 }
83 new(err.to_string())
84 }
85}
86
87impl std::error::Error for Error {}
88
89impl From<&str> for Error {
90 fn from(arg: &str) -> Self {
91 return new(arg.to_string());
92 }
93}
94
95impl From<std::string::String> for Error {
96 fn from(arg: String) -> Self {
97 return new(arg);
98 }
99}
100
101impl From<&dyn std::error::Error> for Error {
102 fn from(arg: &dyn std::error::Error) -> Self {
103 return new(arg.to_string());
104 }
105}
106
107impl From<Box<dyn std::error::Error>> for Error {
108 fn from(arg: Box<dyn std::error::Error>) -> Self {
109 return new(arg.to_string());
110 }
111}
112
113impl From<&Box<dyn std::error::Error>> for Error {
114 fn from(arg: &Box<dyn std::error::Error>) -> Self {
115 return new(arg.to_string());
116 }
117}
118
119impl From<std::sync::mpsc::RecvError> for Error {
120 fn from(e: RecvError) -> Self {
121 return new(e.to_string());
122 }
123}
124
125impl<T> From<std::sync::mpsc::SendError<T>> for Error {
126 fn from(e: std::sync::mpsc::SendError<T>) -> Self {
127 return new(e.to_string());
128 }
129}
130
131#[cfg(test)]
132mod test {
133
134 #[test]
135 fn test_error() {
136 let e = err!("e");
137 assert_eq!(e.to_string(), "e");
138 }
139}