Created
May 15, 2018 08:03
-
-
Save Nyrox/76cba597bc599a6aff599dfc8d1d58c6 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
struct ParseVisitor<T> { | |
_marker: PhantomData<T> | |
} | |
impl<'de, T> Visitor<'de> for ParseVisitor<T> | |
where T: std::str::FromStr | |
{ | |
type Value = T; | |
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { | |
formatter.write_str("a string object that parses to T") | |
} | |
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E> | |
where E: de::Error, | |
{ | |
if let Ok(t) = s.parse::<T>() { | |
Ok(t) | |
} | |
else { | |
Err(de::Error::invalid_value(Unexpected::Str(s), &self)) | |
} | |
} | |
} | |
fn deserialize_parse<'de, T, D>(deserializer: D) -> Result<T, D::Error> | |
where D: Deserializer<'de>, T: str::FromStr | |
{ | |
deserializer.deserialize_string(ParseVisitor::<T> { _marker: PhantomData }) | |
} | |
#[derive(Debug, Deserialize)] | |
struct Stream { | |
#[serde(deserialize_with="deserialize_parse")] | |
id: u64, | |
#[serde(deserialize_with="deserialize_parse")] | |
user_id: u64, | |
#[serde(deserialize_with="deserialize_parse")] | |
game_id: u64, | |
title: String, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment