Skip to content

Instantly share code, notes, and snippets.

@durka
Created August 15, 2017 00:10
Show Gist options
  • Save durka/d6a247f8c8f66ed71639a1c36c56c656 to your computer and use it in GitHub Desktop.
Save durka/d6a247f8c8f66ed71639a1c36c56c656 to your computer and use it in GitHub Desktop.
macro_rules! deser {
($name:ident, $expect:expr, |$s:ident| $pred:expr) => {
fn $name<'de, D: ::serde::Deserializer<'de>>(de: D) -> StdResult<bool, D::Error> {
struct Visitor;
impl<'de> ::serde::de::Visitor<'de> for Visitor {
type Value = bool;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str($expect)
}
fn visit_str<E: ::serde::de::Error>(self, $s: &str) -> StdResult<bool, E> {
Ok($pred)
}
}
de.deserialize_str(Visitor)
}
}
}
deser!(check_to_bool, "an empty string or a check mark ✓", |s| !s.is_empty());
deser!(yesno_to_bool, "Yes or No", |s| s == "Yes");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment