pub struct Base64<CHARSET: CharacterSet = Standard, PADDING: Format = Padded>(_);
Available on crate feature base64 only.
Expand description

Serialize bytes with base64

The type serializes a sequence of bytes as a base64 string. It works on any type implementing AsRef<[u8]> for serialization and TryFrom<Vec<u8>> for deserialization.

The type allows customizing the character set and the padding behavior. The CHARSET is a type implementing CharacterSet. PADDING specifies if serializing should emit padding. Deserialization always supports padded and unpadded formats. formats::Padded emits padding and formats::Unpadded leaves it off.

use serde_with::base64::{Base64, Bcrypt, BinHex, Standard};
use serde_with::formats::{Padded, Unpadded};

#[serde_as]
#[derive(Serialize, Deserialize)]
struct B64 {
    // The default is the same as Standard character set with padding
    #[serde_as(as = "Base64")]
    default: Vec<u8>,
    // Only change the character set, implies padding
    #[serde_as(as = "Base64<BinHex>")]
    charset_binhex: Vec<u8>,

    #[serde_as(as = "Base64<Standard, Padded>")]
    explicit_padding: Vec<u8>,
    #[serde_as(as = "Base64<Bcrypt, Unpadded>")]
    no_padding: Vec<u8>,
}

let b64 = B64 {
    default: b"Hello World".to_vec(),
    charset_binhex: b"Hello World".to_vec(),
    explicit_padding: b"Hello World".to_vec(),
    no_padding: b"Hello World".to_vec(),
};
let json = serde_json::json!({
    "default": "SGVsbG8gV29ybGQ=",
    "charset_binhex": "5'8VD'mI8epaD'3=",
    "explicit_padding": "SGVsbG8gV29ybGQ=",
    "no_padding": "QETqZE6eT07wZEO",
});

// Test serialization and deserialization
assert_eq!(json, serde_json::to_value(&b64).unwrap());
assert_eq!(b64, serde_json::from_value(json).unwrap());

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

Deserialize this value from the given Serde deserializer.

Serialize this value into the given Serde serializer.

Serialize this value into the given Serde serializer.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.