Hi, I'm trying to implement Serialize trait for a newtype struct wrapping a hash map using bincode as Serializer and Deserializer. I want to serialize it to Unit () when the inner map is empty, otherwise use serialize_newtype_struct as usual.
#[derive(Default)]
pub struct HashMapWrapper(pub HashMap<Key, Value>);
impl Serialize for HashMapWrapper {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
if self.0.is_empty() {
serializer.serialize_unit()
} else {
serializer.serialize_newtype_struct("HashMapWrapper", &self.0)
}
}
}
However, I found it difficult to implement the corresponding Deserialize trait because I can't determined whether the serialized data is Unit or newtype struct. Does anyone know if this is feasible?