Macro serializable_enum::serializable_enum
[−]
[src]
macro_rules! serializable_enum { { $(#[$enum_meta:meta])+ pub enum $name:ident { $($(#[$enum_variant_comment:meta])+ $variant:ident),+ $(,)* } $visitor:ident } => { ... }; { $(#[$enum_meta:meta])+ enum $name:ident { $($(#[$enum_variant_comment:meta])+ $variant:ident),+ $(,)* } $visitor:ident } => { ... }; }
Implements deserialization and serialization for an enum of the form:
pub enum Color { Red, Blue, }
to serialize Color::Red
to "red"
. This overrides serde's default behavior of {"Red":[]}
.
One must pass an identifier to use as the type's Visitor.
Relies on the type implementing FromStr
to call parse
when deserializing.
Relies on AsRef
implementation when serializing.
Example
#[macro_use] extern crate serializable_enum; extern crate serde; // your error type #[derive(Debug)] pub enum Error { Parse(String), } // You will need display implemented (you should already have this). impl ::std::fmt::Display for Error { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "{:?}", self) } } serializable_enum! { /// Color #[derive(Debug, PartialEq)] pub enum Color { /// Red Red, /// Blue Blue, /// Green Green, } ColorVistor } impl_as_ref_from_str! { Color { Red => "red", Blue => "blue", Green => "green", } Error::Parse } // also works with non-pub enums serializable_enum! { /// ContentFormat #[derive(Debug)] enum ContentFormat { /// Markdown Markdown, /// Html Html, } ContentFormatVisitor } impl_as_ref_from_str! { ContentFormat { Markdown => "md", Html => "html", } Error::Parse }