8 releases

new 0.3.0 Dec 4, 2024
0.2.0 Oct 18, 2023
0.1.5 Feb 3, 2021
0.1.3 Nov 18, 2020
0.1.2 Jul 17, 2020

#353 in Encoding

Download history 3921/week @ 2024-08-16 3921/week @ 2024-08-23 3427/week @ 2024-08-30 2742/week @ 2024-09-06 2940/week @ 2024-09-13 3004/week @ 2024-09-20 3275/week @ 2024-09-27 3225/week @ 2024-10-04 3246/week @ 2024-10-11 3074/week @ 2024-10-18 3573/week @ 2024-10-25 3518/week @ 2024-11-01 3009/week @ 2024-11-08 3288/week @ 2024-11-15 3134/week @ 2024-11-22 3106/week @ 2024-11-29

13,259 downloads per month
Used in 10 crates (6 directly)

MIT license

42KB
1K SLoC

Serde adapter for controlling the representation of bytes

Rust

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::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();
    println!("JSON(base64): {}", serialized);
}

Outputs:

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

Dependencies

~335–590KB
~12K SLoC