Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bytes are serialized to Vec<u8> #10

Open
rnbguy opened this issue Feb 8, 2022 · 2 comments
Open

bytes are serialized to Vec<u8> #10

rnbguy opened this issue Feb 8, 2022 · 2 comments

Comments

@rnbguy
Copy link
Contributor

rnbguy commented Feb 8, 2022

Protobuf bytes should be deserialized to base64 strings.

Right now all Vec<_> are deserialized as they are. The Vec<u8> case should be handled differently.

@rnbguy
Copy link
Contributor Author

rnbguy commented Feb 9, 2022

My quick-fix is to use Serde field attributes.

pub fn base64_to_bytes<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
    D: Deserializer<'de>,
{
    let value: Option<&str> = Deserialize::deserialize(deserializer)?;
    Ok(match value {
        Some(value) => base64::decode(value).map_err(D::Error::custom)?,
        None => vec![],
    })
}

/// Serialize bytes to base64 string.
pub fn bytes_to_base64<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    serializer.serialize_str(&base64::encode(bytes))
}

And then,

    #[serde(
        serialize_with = "bytes_to_base64",
        deserialize_with = "base64_to_bytes"
    )]
    pub bytes: ::prost::alloc::vec::Vec<u8>,

@rnbguy
Copy link
Contributor Author

rnbguy commented Jul 8, 2022

I found serde_with which can be used with field_attributes for data: ::prost::alloc::vec::Vec<u8>.

config.field_attribute("data", "#[serde(with = \"serde_with::As::<serde_with::base64::Base64>\")]");

or for repeated_data: ::prost::alloc::vec::Vec<::prost::alloc::vec::Vec<u8>>

config.field_attribute("repeated_data", "#[serde(with = \"serde_with::As::<Vec<serde_with::base64::Base64>>\")]");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant