Created
November 28, 2018 08:50
-
-
Save fulmicoton/4e18ce741f90101e2276c906118d65c2 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
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