Skip to content

Instantly share code, notes, and snippets.

@hadronized
Last active October 24, 2018 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hadronized/b01f4c0e0a324dd7f05eb44aeccd7d50 to your computer and use it in GitHub Desktop.
Save hadronized/b01f4c0e0a324dd7f05eb44aeccd7d50 to your computer and use it in GitHub Desktop.
use serde::de::{Deserialize, Deserializer, Error, Visitor};
use std::fmt;
use serde_json::de::from_str;
#[derive(Clone, Debug, Eq, PartialEq)]
enum YourFancyEnum {
Foo,
Bar,
Zoo,
Quux,
Unknown(String)
}
impl<'de> Deserialize<'de> for YourFancyEnum {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
struct V;
impl<'de> Visitor<'de> for V {
type Value = YourFancyEnum;
fn expecting(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
formatter.write_str("Foo, Bar, Zoo, Quux or any unknown string")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E> where E: Error {
match &s[..] {
"Foo" => Ok(YourFancyEnum::Foo),
"Bar" => Ok(YourFancyEnum::Bar),
"Zoo" => Ok(YourFancyEnum::Zoo),
"Quux" => Ok(YourFancyEnum::Quux),
_ => Ok(YourFancyEnum::Unknown(s.to_owned()))
}
}
}
deserializer.deserialize_str(V)
}
}
fn main() {
println!("{:?}", from_str::<YourFancyEnum>(r#""Foo""#));
println!("{:?}", from_str::<YourFancyEnum>(r#""Bar""#));
println!("{:?}", from_str::<YourFancyEnum>(r#""Zoo""#));
println!("{:?}", from_str::<YourFancyEnum>(r#""Quux""#));
println!("{:?}", from_str::<YourFancyEnum>(r#""Warghl""#));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment