snops_common/state/
strings.rs

1// https://github.com/serde-rs/serde/issues/1560#issuecomment-506915291
2macro_rules! named_unit_variant {
3    ($variant:ident) => {
4        pub mod $variant {
5            pub fn serialize<S>(serializer: S) -> Result<S::Ok, S::Error>
6            where
7                S: serde::Serializer,
8            {
9                serializer.serialize_str(stringify!($variant))
10            }
11
12            pub fn deserialize<'de, D>(deserializer: D) -> Result<(), D::Error>
13            where
14                D: serde::Deserializer<'de>,
15            {
16                struct V;
17                impl<'de> serde::de::Visitor<'de> for V {
18                    type Value = ();
19                    fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
20                        f.write_str(concat!("\"", stringify!($variant), "\""))
21                    }
22                    fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> {
23                        if value == stringify!($variant) {
24                            Ok(())
25                        } else {
26                            Err(E::invalid_value(serde::de::Unexpected::Str(value), &self))
27                        }
28                    }
29                }
30                deserializer.deserialize_str(V)
31            }
32        }
33    };
34}
35
36named_unit_variant!(top);
37named_unit_variant!(auto);