Crate base64_bytes

source ·
Expand description

Intelligent serialization for binary blobs.

Where Vec<u8> always serializes as an array of bytes, this crate provides serialization functions which try to make an intelligent decision about how to serialize a byte vector based on the serialization format.

For binary formats like bincode, the array-of-bytes serialization works great: it is compact and introduces very little overhead. But for human-readable types such as serde_json, it’s far from ideal. The text encoding of an array introduces substantial overhead, and the resulting array of opaque bytes isn’t particularly readable anyways.

base64-bytes uses the is_human_readable property of a serializer to distinguish these cases. For binary formats, it uses the default Vec<u8> serialization. For human-readable formats, it uses a much more compact and conventional base 64 encoding.

§Usage

The interface consists of serialize and deserialize functions. While these can be called directly, they are intended to be used with serde’s field attributes controlling serialization, like:

use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize)]
struct SomeType {
    #[serde(
        serialize_with = "base64_bytes::serialize",
        deserialize_with = "base64_bytes::deserialize",
    )]
    bytes: Vec<u8>,
}

Or, as a shorthand:

use serde::{Deserialize, Serialize};

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

Functions§