Created
November 26, 2017 22:46
-
-
Save kybishop/2fa9e9d32728167bed5b1bc0b9becd97 to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
use std::convert::TryFrom; | |
use std; | |
#[derive(Debug)] | |
pub enum Charity { | |
ACLU, | |
EFF, | |
FSF, | |
} | |
impl<S: AsRef<str>> TryFrom<S> for Charity { | |
type Error = &'static str; | |
fn try_from(string: S) -> Result<Self, Self::Error> { | |
match string.as_ref() { | |
"The ACLU" => Ok(Charity::ACLU), | |
"The EFF" => Ok(Charity::EFF), | |
"The FSF" => Ok(Charity::FSF), | |
// LATER(kjb) Better error message that includes all valid charities | |
_ => Err("Unknown charity"), | |
} | |
} | |
} | |
impl ::std::fmt::Display for Charity { | |
fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { | |
match *self { | |
Charity::ACLU => write!(fmt, "ACLU"), | |
Charity::EFF => write!(fmt, "EFF"), | |
Charity::FSF => write!(fmt, "FSF"), | |
} | |
} | |
} | |
struct CharityVisitor; | |
impl<'de> serde::de::Visitor<'de> for CharityVisitor { | |
type Value = Charity; | |
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { | |
write!(formatter, "a string of a valid charity") | |
} | |
fn visit_str<E>(self, value: &str) -> Result<Charity, E> | |
where | |
E: serde::de::Error, | |
{ | |
Charity::try_from(value).map_err(|err| E::custom(err.to_string())) | |
} | |
} | |
impl<'de> serde::de::Deserialize<'de> for Charity { | |
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> | |
where | |
D: serde::de::Deserializer<'de>, | |
{ | |
deserializer.deserialize_str(CharityVisitor) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment