azure_sdk_core/
enumerations.rs

1#[derive(Debug)]
2pub enum ParsingError {
3    ElementNotFound(String),
4}
5
6/// use as
7/// ```create_enum!(SecondCollection, (Pollo, "Pollo"), (Bianco, "Bianco"), (Giallo, "Giallo"));```
8#[macro_export]
9macro_rules! create_enum {
10    ($en:ident, $(($na:ident, $x:expr)), *) => (
11        #[derive(Debug, PartialEq, PartialOrd, Clone, Copy, Serialize, Deserialize)]
12        pub enum $en {
13            $(
14                $na,
15            )*
16        }
17
18        impl ::std::convert::Into<&'static str> for $en {
19            fn into(self) -> &'static str {
20                match self {
21                    $(
22                        $en::$na => $x,
23                    )*
24                }
25            }
26        }
27
28        impl $crate::parsing::FromStringOptional<$en> for $en {
29            fn from_str_optional(s : &str) -> Result<$en, $crate::errors::TraversingError> {
30                match s.parse::<$en>() {
31                    Err(e) => Err($crate::errors::TraversingError::ParsingError(e)),
32                    Ok(v) => Ok(v)
33                }
34            }
35        }
36
37        impl ::std::str::FromStr for $en {
38            type Err = $crate::enumerations::ParsingError;
39
40            fn from_str(s: &str) -> Result<$en, $crate::enumerations::ParsingError> {
41                match s {
42                    $(
43                        $x => Ok($en::$na),
44                    )*
45                    _ => Err($crate::enumerations::ParsingError::ElementNotFound(s.to_owned())),
46                }
47            }
48        }
49
50        impl ::std::convert::AsRef<str> for $en {
51            fn as_ref(&self) -> &str {
52                 match *self {
53                    $(
54                        $en::$na => $x,
55                    )*
56                }
57            }
58        }
59
60        impl ::std::fmt::Display for $en {
61            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
62                match *self {
63                    $(
64                        $en::$na => write!(f, "{}", $x),
65                    )*
66                }
67            }
68        }
69    )
70}
71
72#[cfg(test)]
73mod test {
74    create_enum!(Colors, (Black, "Black"), (White, "White"), (Red, "Red"));
75    create_enum!(ColorsMonochrome, (Black, "Black"), (White, "White"));
76
77    #[test]
78    fn test_color_parse_1() {
79        let color = "Black".parse::<Colors>().unwrap();
80        assert_eq!(Colors::Black, color);
81    }
82
83    #[test]
84    fn test_color_parse_2() {
85        let color = "White".parse::<ColorsMonochrome>().unwrap();
86        assert_eq!(ColorsMonochrome::White, color);
87    }
88
89    #[test]
90    #[should_panic(expected = "ElementNotFound(\"Red\")")]
91    fn test_color_parse_err_1() {
92        "Red".parse::<ColorsMonochrome>().unwrap();
93    }
94}