riven/consts/
macros.rs

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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#![macro_use]

/// Macro for deriving `Serialize` and `Deserialize` for string enums with an
/// `UNKNOWN(String)` variant.
///
/// Enum should have `#[derive(EnumString, EnumVariantNames, IntoStaticStr)]` included.
///
/// Also implements `AsRef<str>`, `Display`, and `From<&str>`.
macro_rules! serde_strum_unknown {
    ($name:ident) => {
        impl AsRef<str> for $name {
            fn as_ref(&self) -> &str {
                match self {
                    Self::UNKNOWN(string) => &*string,
                    known => known.into(),
                }
            }
        }
        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
                self.as_ref().fmt(f)
            }
        }
        impl serde::ser::Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: serde::ser::Serializer,
            {
                serializer.serialize_str(self.as_ref())
            }
        }

        impl From<&str> for $name {
            fn from(item: &str) -> Self {
                item.parse().unwrap()
            }
        }
        impl<'de> serde::de::Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::de::Deserializer<'de>,
            {
                #[cfg(not(feature = "deny-unknown-enum-variants-strings"))]
                {
                    <&str>::deserialize(deserializer).map(Into::into)
                }
                #[cfg(feature = "deny-unknown-enum-variants-strings")]
                {
                    <&str>::deserialize(deserializer)
                        .map(Into::into)
                        .and_then(|item| match item {
                            Self::UNKNOWN(unknown) => {
                                if unknown.is_empty() {
                                    // https://github.com/RiotGames/developer-relations/issues/898
                                    Ok(Self::UNKNOWN(unknown))
                                } else {
                                    Err(serde::de::Error::unknown_variant(
                                        &*unknown,
                                        <Self as strum::VariantNames>::VARIANTS,
                                    ))
                                }
                            }
                            other => Ok(other),
                        })
                }
            }
        }
    };
}

macro_rules! arr {
    (
        $( #[$attr:meta] )*
        $v:vis $id:ident $name:ident: [$ty:ty; _] = $value:expr
    ) => {
        $( #[$attr] )*
        $v $id $name: [$ty; $value.len()] = $value;
    }
}

/// Macro for newtype "enums" with integer values.
///
/// For serde, use the following:
/// ```ignore
/// #[derive(Serialize, Deserialize)]
/// #[serde(from = "$repr", into = "$repr")]
/// ```
macro_rules! newtype_enum {
    {
        $( #[$attr:meta] )*
        $v:vis newtype_enum $name:ident($repr:ty) {
            $(
                $( #[$var_attr:meta] )*
                $var_name:ident = $var_val:expr,
            )*
        }
    } => {
        $( #[$attr] )*
        #[derive(Copy, Clone)]
        #[derive(Hash, PartialEq, Eq, PartialOrd, Ord)]
        #[repr(transparent)]
        $v struct $name($v $repr);
        impl $name {
            $(
                $( #[$var_attr] )*
                $v const $var_name: Self = Self($var_val);
            )*
        }

        impl $name {
            arr!{
                #[doc = "Array containing all known variants."]
                pub const ALL_KNOWN: [Self; _] = [
                    $( Self::$var_name, )*
                ]
            }

            #[doc = "If this is one of the known variants."]
            $v const fn is_known(self) -> bool {
                match self {
                    $(
                        Self::$var_name => true,
                    )*
                    _ => false,
                }
            }
        }

        impl std::convert::From<$name> for $repr {
            fn from(value: $name ) -> Self {
                value.0
            }
        }
        impl serde::ser::Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: serde::ser::Serializer,
            {
                <$repr>::serialize(&self.0, serializer)
            }
        }

        impl std::convert::From<$repr> for $name {
            fn from(value: $repr ) -> Self {
                Self(value)
            }
        }
        impl<'de> serde::de::Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::de::Deserializer<'de>
            {
                #[cfg(not(feature = "deny-unknown-enum-variants-integers"))]
                {
                    <$repr>::deserialize(deserializer).map(Into::into)
                }
                #[cfg(feature = "deny-unknown-enum-variants-integers")]
                {
                    <$repr>::deserialize(deserializer).map(Into::into)
                        .and_then(|item: Self| {
                            // Exception for id zero: https://github.com/RiotGames/developer-relations/issues/898
                            if 0 != item.0 && !item.is_known() {
                                Err(serde::de::Error::custom(format!(
                                    "Unknown integer enum variant: {} (\"deny-unknown-enum-variants-integers\" feature is enabled).\nExpected one of the following: {:?}",
                                    item, Self::ALL_KNOWN
                                )))
                            }
                            else {
                                Ok(item)
                            }
                        })
                }
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                self.0.fmt(f)
            }
        }
        impl std::fmt::Debug for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}({}{})", stringify!($name), self.0, if self.is_known() { "" } else { "?" })
            }
        }
    }
}