Last active
October 24, 2018 23:48
-
-
Save hadronized/b01f4c0e0a324dd7f05eb44aeccd7d50 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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