Crate serde_bytes_repr

source ·
Expand description

Serde adapter for (de)serializing bytes to and from specific formats

Currently these representations is supported:

  • Base64
  • Hexidecimal

Human readable formats tend not to include a universally agreed way to represent arbitrary binary data, which means those serde libraries can end up using a representation for serde’s “bytes” type which isn’t ideal for all uses. This library gives you the option to choose a different representation than the default for libraries like serde_json, toml and serde_yaml.

How to make sure that your datatype is interpreted as bytes?

Without specialization, Rust forces Serde to treat &u8 just like any other slice and Vec just like any other vector. To enable specialized handling of &[u8] can use the serde_bytes crate.

You’ll se this in use in the examples below:

Serialization

use serde::{Deserialize, Serialize};
use serde_bytes_repr::ByteFmtSerializer;
    #[derive(Serialize, Deserialize)]
    struct Demo {
        #[serde(with = "serde_bytes")]
        bytes: Vec<u8>,
    }
    let bytes = b"testing".to_vec();
    let demo = Demo { bytes };

    let mut out = vec![];
    let mut ser = serde_json::Serializer::new(&mut out);
    let base64_config = base64::engine::GeneralPurposeConfig::new();
    let ser = ByteFmtSerializer::base64(&mut ser,  base64::alphabet::URL_SAFE, base64_config);
    demo.serialize(ser).unwrap();

    let serialized = String::from_utf8(out).unwrap();
    assert_eq!(r#"{"bytes":"dGVzdGluZw=="}"#, serialized.as_str());

Deserialization

use serde::{Deserialize, Serialize};
use serde_bytes_repr::{ByteFmtDeserializer, ByteFmtSerializer};
    #[derive(Serialize, Deserialize)]
    struct Demo {
        #[serde(with = "serde_bytes")]
        bytes: Vec<u8>,
    }

    let json = br#"{"bytes":"dGVzdGluZw=="}"#;
    let mut json_de = serde_json::Deserializer::from_slice(json);
    let base64_config = base64::engine::GeneralPurposeConfig::new();
    let bytefmt_json_de = ByteFmtDeserializer::new_base64(&mut json_de, base64::alphabet::URL_SAFE, base64_config);
    let demo: Demo = Demo::deserialize(bytefmt_json_de).unwrap();

    let deserialized = String::from_utf8(demo.bytes).unwrap();
    assert_eq!("testing", deserialized.as_str());

Structs

  • Deserializer-adapter which decodes bytes from a specified format.
  • Serializer-adapter which encodes bytes to using the specified encoding. The format is serialized to the data formats string representation.