Closed Phidelux closed 10 months ago
Bincode does not support other formats. However you can do something like:
enum Data {
Type1([u8; 64]),
Type2([u8; 20]),
Type3([u8; 64]),
}
impl<'de> serde::de::Deserialize<'de> for Data {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de> {
let b = u8::deserialize(deserializer)?;
match b {
0 => Ok(Data::Type1(<[u8; 64>::deserialize(deserializer)?)),
1 => Ok(Data::Type2(<[u8; 20>::deserialize(deserializer)?)),
2 => Ok(Data::Type3(<[u8; 64>::deserialize(deserializer)?)),
3 => Err(...)
]
}
}
impl Serialize for Data {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer {
match self {
Self::Type1(b) => {
0u8.serialize(serializer)?;
b.serialize(serializer)?;
Ok(())
},
// ...
}
}
}
I have the following data, which should be (de)serialized using bincode:
Now I have to ensure that the
DataType
matches theData
, if possible without doubling the enum discriminant, which should match. How would I implement this?