Skip to content

Instantly share code, notes, and snippets.

@fulmicoton fulmicoton/toto.rs
Created Nov 28, 2018

Embed
What would you like to do?
impl Serialize for MyEnum {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: ::serde::Serializer,
{
serializer.serialize_u16(self as u16)
}
}
impl<'de> ::serde::Deserialize<'de> for MyEnum {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: ::serde::Deserializer<'de>,
{
struct Visitor;
impl<'de> ::serde::de::Visitor<'de> for Visitor {
type Value = MyEnum;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("2 byte representing MyEnum. Accepted values are {0, 11}")
}
fn visit_u16<E>(self, value: u64) -> Result<MyEnum, E>
where
E: ::serde::de::Error,
{
// again, you can also cast.
match value {
0 => MyEnum::Unknown,
11 => MyEnum::First,
}
}
}
// Deserialize the enum from a u64.
deserializer.deserialize_u16(Visitor)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.