Skip to content

Instantly share code, notes, and snippets.

@jwilm
Created May 13, 2016 18:48
Show Gist options
  • Save jwilm/ddd5162b9edde15868ca0d201698be62 to your computer and use it in GitHub Desktop.
Save jwilm/ddd5162b9edde15868ca0d201698be62 to your computer and use it in GitHub Desktop.
Macro for implementing Deserialize on simple enums relying on FromStr
#[macro_export]
macro_rules! impl_deserialize_fromstr {
($tyname:ident) => {
impl ::serde::de::Deserialize for $tyname {
/// Deserialize this value given this `Deserializer`.
fn deserialize<D>(deserializer: &mut D) -> ::std::result::Result<Self, D::Error>
where D: ::serde::de::Deserializer
{
struct VariantVisitor<__D> {
_marker: ::std::marker::PhantomData<__D>,
}
impl<__D> ::serde::de::Visitor for VariantVisitor<__D>
where __D: ::serde::de::Deserializer
{
type Value = $tyname;
fn visit_str<E>(&mut self, value: &str) -> ::std::result::Result<$tyname, E>
where E: ::serde::de::Error
{
::std::str::FromStr::from_str(value).map_err(E::invalid_value)
}
}
deserializer.deserialize_str(VariantVisitor::<D>{
_marker: ::std::marker::PhantomData
})
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment