Serde: Serialize newtype_struct to diffrent types

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?

You cannot do this. bincode is a “non-self-describing” data format, which means that the deserialization is guided by the Deserialize implementation telling the Deserializer what to expect — the information of “whether the serialized data is Unit or newtype struct” does not exist in the serialized data. Therefore, your serializer must be consistent in what it produces.

2 Likes