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