serializable_enum::serializable_enum! [] [src]

macro_rules! serializable_enum {
    ($(#[$enum_comment:meta])* pub 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
    pub enum Color {
        /// Red
        Red,
        /// Blue
        Blue,
        /// Green
        Green,
    }
    ColorVistor
}

impl_as_ref_from_str! {
    Color {
        Red => "red",
        Blue => "blue",
        Green => "green",
    }
    Error::Parse
}