This crate provides a procedural macro to automatically derive serde's Serialize
and Deserialize
traits for enum types that should be encoded as a single string.
toml
[dependencies]
serde = "1.0"
serde_string_enum = "0.1"
unicase = "2.6.0"
This crate defines two pairs of macros:
SerializeLabeledStringEnum
/ DeserializeLabeledStringEnum
- Uses the #[string = ...]
attribute on each enum variant to perform string conversions.SerializeStringEnum
/ DeserializeStringEnum
- Uses the enum type's Display
and FromStr
implementations to perform string conversions.default
- std
, unicase
std
- Depend on the Rust standard library.alloc
- Depend on the alloc library without the Rust standard library.unicase
- Depend on the unicase crate for Unicode-insensitive matching. ```
extern crate alloc;
use serdestringenum::{ DeserializeLabeledStringEnum, SerializeLabeledStringEnum, };
enum Type { #[string = "Grass"] Grass, #[string = "Fire"] #[alias = "Flame"] Fire, #[string = "Water"] Water, }
fn main() -> serdejson::Result<()> { let j = serdejson::tostring(&Type::Grass)?; asserteq!(j, "\"Grass\""); let t: Type = serdejson::fromstr(&j)?; assert_eq!(t, Type::Grass);
// Alias strings.
let t: Type = serde_json::from_str("\"Flame\"")?;
assert_eq!(t, Type::Fire);
// Case-insensitive conversion also works.
if cfg!(feature = "unicase") {
let t: Type = serde_json::from_str("\"water\"")?;
assert_eq!(t, Type::Water);
}
Ok(())
} ```
``` use core::{ fmt::Display, str::FromStr, }; use serdestringenum::{ DeserializeStringEnum, SerializeStringEnum, };
enum Move { Stay, Forward(u8), Left(u8), }
impl Display for Move { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Self::Stay => write!(f, "S"), Self::Forward(n) => write!(f, "F{n}"), Self::Left(n) => write!(f, "L{n}"), } } }
impl FromStr for Move {
type Err = String;
fn fromstr(s: &str) -> Result
fn main() -> serdejson::Result<()> { let j = serdejson::tostring(&Move::Forward(10))?; asserteq!(j, "\"F10\""); let m: Move = serdejson::fromstr(&j)?; assert_eq!(m, Move::Forward(10));
let moves: Vec<Move> = serde_json::from_str("[\"S\",\"F2\",\"S\",\"L4\"]")?;
assert_eq!(
moves,
vec![Move::Stay, Move::Forward(2), Move::Stay, Move::Left(4)]
);
Ok(())
} ```