#serde #adapter #bytes #bytearray

dev serde-bytes-repr

Serde adapter for controlling the representation of bytes

6 releases

0.1.5 Feb 3, 2021
0.1.4 Feb 2, 2021
0.1.3 Nov 18, 2020
0.1.2 Jul 17, 2020

#125 in Encoding

Download history 1066/week @ 2022-03-12 1316/week @ 2022-03-19 1190/week @ 2022-03-26 1265/week @ 2022-04-02 1070/week @ 2022-04-09 1433/week @ 2022-04-16 1686/week @ 2022-04-23 1996/week @ 2022-04-30 3240/week @ 2022-05-07 4007/week @ 2022-05-14 7551/week @ 2022-05-21 4236/week @ 2022-05-28 3880/week @ 2022-06-04 4765/week @ 2022-06-11 5082/week @ 2022-06-18 4200/week @ 2022-06-25

18,974 downloads per month
Used in 4 crates

MIT license

42KB
1K SLoC

Serde adapter for controlling the representation of bytes

Build Status

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.

// [dependencies]
// serde = { version = "1.0", features = ["derive"] }
// serde_bytes = "0.11"
// serde_json = "1.0"
// serde_yaml = "0.8"
// toml = "0.5"

use serde::Serialize;

#[derive(Serialize)]
struct Demo {
    #[serde(with = "serde_bytes")]
    bytes: Vec<u8>,
}

fn main() {
    let bytes = b"testing".to_vec();
    let s = Demo { bytes };

    println!("JSON: {}", serde_json::to_string(&s).unwrap());
    println!("YAML: {}", serde_yaml::to_string(&s).unwrap());
    println!("TOML: {}", toml::to_string(&s).unwrap());
}
JSON: {"bytes":[116,101,115,116,105,110,103]}
YAML: ---
bytes:
  - 116
  - 101
  - 115
  - 116
  - 105
  - 110
  - 103
TOML: bytes = [116, 101, 115, 116, 105, 110, 103]

This adapter lets you control how the bytes are represented by wrapping a serializer like this:

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

fn main() {
    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::Config::new(base64::CharacterSet::UrlSafe, true);
    let ser = BytesRepr::base64(&mut ser, base64_config);
    demo.serialize(ser).unwrap();

    let serialized = String::from_utf8(out).unwrap();
    println!("JSON(base64): {}", serialized);
}

Outputs:

JSON(base64): {"bytes":"dGVzdGluZw=="}

Dependencies

~300–450KB