azul_css_parser/macros.rs
1/// Implement `Display` for an enum.
2///
3/// Example usage:
4/// ```
5/// enum Foo<'a> {
6/// Bar(&'a str)
7/// Baz(i32)
8/// }
9///
10/// impl_display!{ Foo<'a>, {
11/// Bar(s) => s,
12/// Baz(i) => format!("{}", i)
13/// }}
14/// ```
15macro_rules! impl_display {
16 // For a type with a lifetime
17 ($enum:ident<$lt:lifetime>, {$($variant:pat => $fmt_string:expr),+$(,)* }) => {
18
19 impl<$lt> ::std::fmt::Display for $enum<$lt> {
20 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
21 use self::$enum::*;
22 match &self {
23 $(
24 $variant => write!(f, "{}", $fmt_string),
25 )+
26 }
27 }
28 }
29
30 };
31
32 // For a type without a lifetime
33 ($enum:ident, {$($variant:pat => $fmt_string:expr),+$(,)* }) => {
34
35 impl ::std::fmt::Display for $enum {
36 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
37 use self::$enum::*;
38 match &self {
39 $(
40 $variant => write!(f, "{}", $fmt_string),
41 )+
42 }
43 }
44 }
45
46 };
47}
48
49/// Implements `Debug` to use `Display` instead - assumes the that the type has implemented `Display`
50macro_rules! impl_debug_as_display {
51 // For a type with a lifetime
52 ($enum:ident<$lt:lifetime>) => {
53
54 impl<$lt> ::std::fmt::Debug for $enum<$lt> {
55 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
56 write!(f, "{}", self)
57 }
58 }
59
60 };
61
62 // For a type without a lifetime
63 ($enum:ident) => {
64
65 impl ::std::fmt::Debug for $enum {
66 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
67 write!(f, "{}", self)
68 }
69 }
70
71 };
72}
73
74/// Implement the `From` trait for any type.
75/// Example usage:
76/// ```
77/// enum MyError<'a> {
78/// Bar(BarError<'a>)
79/// Foo(FooError<'a>)
80/// }
81///
82/// impl_from!(BarError<'a>, Error::Bar);
83/// impl_from!(BarError<'a>, Error::Bar);
84///
85/// ```
86macro_rules! impl_from {
87 // From a type with a lifetime to a type which also has a lifetime
88 ($a:ident<$c:lifetime>, $b:ident::$enum_type:ident) => {
89 impl<$c> From<$a<$c>> for $b<$c> {
90 fn from(e: $a<$c>) -> Self {
91 $b::$enum_type(e)
92 }
93 }
94 };
95
96 // From a type without a lifetime to a type which also does not have a lifetime
97 ($a:ident, $b:ident::$enum_type:ident) => {
98 impl From<$a> for $b {
99 fn from(e: $a) -> Self {
100 $b::$enum_type(e)
101 }
102 }
103 };
104}