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
#[macro_export]
macro_rules! unit_enum_from_str {
    ($iterable_type:ty) => {
        impl std::str::FromStr for $iterable_type {
            type Err = $crate::error::Error;

            fn from_str(value: &str) -> $crate::error::Result<$iterable_type> {
                let lowercase_value = value.to_ascii_lowercase();
                <$iterable_type as strum::IntoEnumIterator>::iter()
                    .find(|t| t.to_string().to_ascii_lowercase() == lowercase_value)
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "could not convert \"{}\" to a valid {}, possible values are [{}].",
                            value,
                            stringify!($iterable_type),
                            <$iterable_type as strum::IntoEnumIterator>::iter()
                                .map(|t| t.to_string())
                                .collect::<Vec<_>>()
                                .join(", ")
                        )
                    })
            }
        }
    };
}

#[macro_export]
macro_rules! unit_enum_deserialize {
    ($iterable_type:ty) => {
        impl <'de> serde::de::Deserialize<'de> for $iterable_type {
            fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
                where
                    D: serde::Deserializer<'de> {

                $crate::paste::paste! {

                    struct [<$iterable_type Visitor>];

                    impl serde::de::Visitor<'_> for [<$iterable_type Visitor>] {

                        type Value = $iterable_type;

                        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                            formatter.write_str(&format!(
                                "one of: {}",
                                <$iterable_type as strum::IntoEnumIterator>::iter()
                                    .map(|variant| variant.to_string())
                                    .collect::<Vec<_>>()
                                    .join(", ")
                            ))
                        }

                        fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
                            where
                                E: serde::de::Error, {
                            <$iterable_type as std::str::FromStr>::from_str(v).map_err(|from_str_err| {
                                E::custom(from_str_err.to_string())
                            })
                        }
                    }

                    deserializer.deserialize_str([<$iterable_type Visitor>])
                }
            }
        }
    }
}

pub use {unit_enum_deserialize, unit_enum_from_str};