Skip to content
This repository has been archived by the owner on Mar 25, 2024. It is now read-only.

Binary types #91

Open
nagy opened this issue Feb 22, 2018 · 5 comments
Open

Binary types #91

nagy opened this issue Feb 22, 2018 · 5 comments

Comments

@nagy
Copy link

nagy commented Feb 22, 2018

Please support the deserialization of binary types into Vec<u8> .

@dtolnay
Copy link
Owner

dtolnay commented Oct 15, 2018

Seems reasonable, I would accept a PR to implement this.

@pickfire

This comment was marked as off-topic.

@rogpeppe

This comment was marked as off-topic.

@Beiri22
Copy link

Beiri22 commented Aug 22, 2023

is someone working on that?

@bobdebuildr
Copy link

This is a feature I would really like. I'm new to implementing serde internals, but could take a look at implementing this. A few questions:

  • If the two functions deserialize_bytes and deserialize_byte_buf were implemented, which types could we deserialize to? I guess Vec<u8> would not work, just something like serde_bytes::ByteBuf and serde_bytes::Byte, respectively. Is this correct?
  • What would be needed to deserialize to Vec<u8> directly?
  • The document mentioned in the original post defines that base64 is used to encode the data. Which base64 dependency would you prefer to add for this feature?

In case anyone else has this problem, I'm currently using the following workaround:

cargo add base64 serde serde_yaml

use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};

fn from_base64<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
    let mut s: String = Deserialize::deserialize(deserializer)?;
    s.retain(|c| !c.is_whitespace());
    base64::decode(s).map_err(D::Error::custom)
}

fn to_base64<S: Serializer>(x: &[u8], s: S) -> Result<S::Ok, S::Error> {
    s.serialize_str(&base64::encode(x))
}

#[derive(Debug, Deserialize, Serialize)]
struct MyThing {
    #[serde(deserialize_with = "from_base64", serialize_with = "to_base64")]
    data: Vec<u8>,
}

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

No branches or pull requests

6 participants