Skip to content

Optional fields #16

@rendaw

Description

@rendaw

Sorry for another "this probably isn't the right place for it but this is the only place for it right now" type of ticket.

So if you have a field:

#[serde(with = "serdeb64")]
x: Option<Vec<u8>>,

This doesn't work. The workaround is to implement a wrapper type like:

pub struct ConfigurationBytes(Vec<u8>);

impl Serialize for ConfigurationBytes {
    fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where
        S: Serializer {
        SerdeB64::serialize(&self.0, serializer)
    }
}

impl<'de> Deserialize<'de> for ConfigurationBytes {
    fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error> where
        D: Deserializer<'de> {
        SerdeB64::deserialize(deserializer).map(|v| ConfigurationBytes(v))
    }
}

impl Debug for ConfigurationBytes {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        self.0.fmt(f)
    }
}

impl From<&[u8]> for ConfigurationBytes {
    fn from(v: &[u8]) -> Self {
        ConfigurationBytes(v.to_vec())
    }
}

impl From<Vec<u8>> for ConfigurationBytes {
    fn from(v: Vec<u8>) -> Self {
        ConfigurationBytes(v)
    }
}

But it's a lot of boilerplate of course (plus .into(), .0, etc).

Handling every combination of Option Box Rc here would probably be crazy but if might be nice to have Option support as well.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions