Created
February 4, 2018 17:51
-
-
Save dherman/3f85ff18fa0571133a3e4d7059a4295e to your computer and use it in GitHub Desktop.
example code of custom serialization/deserialization
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
#[derive(Eq, PartialEq, Clone)] | |
pub struct ToolVersion(Version); | |
impl Serialize for ToolVersion { | |
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { | |
let &ToolVersion(ref version) = self; | |
let unparsed = format!("{}", version); | |
serializer.serialize_str(&unparsed[..]) | |
} | |
} | |
struct ToolVersionVisitor; | |
impl<'de> Visitor<'de> for ToolVersionVisitor { | |
type Value = ToolVersion; | |
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { | |
formatter.write_str("a semver version string") | |
} | |
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> { | |
Version::parse(v) | |
.map(ToolVersion) | |
.map_err(|e| E::custom(format!("{}", e))) | |
} | |
} | |
impl<'de> Deserialize<'de> for ToolVersion { | |
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<ToolVersion, D::Error> { | |
deserializer.deserialize_str(ToolVersionVisitor) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment