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
extern crate proc_macro;
use TokenStream;
use ;
pub
pub
pub use *;
use impl_from_enum;
use impl_from_struct;
/// This macros provides the implementation of trait [From<T>](std::convert::From) (writed for crate [add_macro](https://docs.rs/add_macro))
///
/// # Examples:
/// ```
/// use add_macro_impl_from::From;
///
/// #[derive(Debug)]
/// enum SimpleError {
/// Wrong,
/// }
///
/// impl std::fmt::Display for SimpleError {
/// fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
/// match &self {
/// Self::Wrong => write!(f, "Something went wrong.. =/"),
/// }
/// }
/// }
///
/// #[derive(Debug)]
/// struct SuperError {
/// source: String,
/// }
///
/// impl std::fmt::Display for SuperError {
/// fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
/// write!(f, "{}", &self.source)
/// }
/// }
///
/// #[derive(Debug, From)]
/// #[from("std::io::Error" = "Self::Io(v)")] // result: impl From<std::io::Error> for Error { fn from(v: std::io::Error) -> Self { Self::Io(v) } }
/// enum Error {
/// Io(std::io::Error),
///
/// #[from]
/// Simple(SimpleError),
///
/// #[from = "SuperError { source: format!(\"Super error: {}\", v.source) }"]
/// Super(SuperError),
///
/// #[from("String")]
/// #[from("&str" = "v.to_owned()")]
/// #[from("i32" = "format!(\"Error code: {v}\")")]
/// Stringify(String),
/// }
///
/// impl std::fmt::Display for Error {
/// fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
/// match &self {
/// Self::Io(e) => write!(f, "{e}"),
/// Self::Simple(e) => write!(f, "{e}"),
/// Self::Super(e) => write!(f, "{e}"),
/// Self::Stringify(e) => write!(f, "{e}"),
/// }
/// }
/// }
///
/// fn main() {
/// let _io_err = Error::from( std::fs::read("fake/path/to/file").unwrap_err() );
///
/// let simple_err = Error::from( SimpleError::Wrong );
/// assert_eq!(format!("{simple_err}"), "Something went wrong.. =/");
///
/// let super_err = Error::from( SuperError { source: "Bad request".to_owned() } );
/// assert_eq!(format!("{super_err}"), "Super error: Bad request");
///
/// let str_err = Error::from( String::from("Something went wrong.. =/") );
/// assert_eq!(format!("{str_err}"), "Something went wrong.. =/");
///
/// let str_err2 = Error::from("Something went wrong.. =/");
/// assert_eq!(format!("{str_err2}"), "Something went wrong.. =/");
///
/// let str_err3 = Error::from(404);
/// assert_eq!(format!("{str_err3}"), "Error code: 404");
/// }
/// ```