Struct serde_with::Bytes[][src]

pub struct Bytes;

Optimized handling of owned and borrowed byte representations.

Serialization of byte sequences like &[u8] or Vec<u8> is quite inefficient since each value will be serialized individually. This converter type optimizes the serialization and deserialization.

This is a port of the serde_bytes crate making it compatible with the serde_as-annotation, which allows it to be used in more cases than provided by serde_bytes.

The type provides de-/serialization for these types:

  • [u8; N], Rust 1.51+, not possible using serde_bytes
  • &[u8]
  • Box<[u8; N]>, Rust 1.51+, not possible using serde_bytes
  • Box<[u8]>
  • Vec<u8>
  • Cow<'_, [u8]>

Examples

#[serde_as]
#[derive(Deserialize, Serialize)]
struct Test<'a> {
    #[serde_as(as = "Bytes")]
    array: [u8; 15],
    #[serde_as(as = "Bytes")]
    boxed: Box<[u8]>,
    #[serde_as(as = "Bytes")]
    #[serde(borrow)]
    cow: Cow<'a, [u8]>,
    #[serde_as(as = "Bytes")]
    vec: Vec<u8>,
}

let value = Test {
    array: b"0123456789ABCDE".clone(),
    boxed: b"...".to_vec().into_boxed_slice(),
    cow: Cow::Borrowed(b"FooBar"),
    vec: vec![0x41, 0x61, 0x21],
};
let expected = r#"(
    array: "MDEyMzQ1Njc4OUFCQ0RF",
    boxed: "Li4u",
    cow: "Rm9vQmFy",
    vec: "QWEh",
)"#;

assert_eq!(expected, ron::ser::to_string_pretty(&value, pretty_config).unwrap());
assert_eq!(value, ron::from_str(&expected).unwrap());

Alternative to BytesOrString

The Bytes can replace BytesOrString. Bytes is implemented for more types, which makes it better. The serialization behavior of Bytes differs from BytesOrString, therefore only deserialize_as should be used.

#[serde_as]
#[derive(Deserialize, serde::Serialize)]
struct Test {
    #[serde_as(deserialize_as = "Bytes")]
    from_bytes: Vec<u8>,
    #[serde_as(deserialize_as = "Bytes")]
    from_str: Vec<u8>,
}

// Different serialized values ...
let j = json!({
    "from_bytes": [70,111,111,45,66,97,114],
    "from_str": "Foo-Bar",
});

// can be deserialized ...
let test = Test {
    from_bytes: b"Foo-Bar".to_vec(),
    from_str: b"Foo-Bar".to_vec(),
};
assert_eq!(test, serde_json::from_value(j).unwrap());

// and serialization will always be a byte sequence
{
    "from_bytes": [70,111,111,45,66,97,114],
    "from_str": [70,111,111,45,66,97,114],
}

Trait Implementations

impl Clone for Bytes[src]

fn clone(&self) -> Bytes[src]

Returns a copy of the value. Read more

fn clone_from(&mut self, source: &Self)1.0.0[src]

Performs copy-assignment from source. Read more

impl Debug for Bytes[src]

fn fmt(&self, f: &mut Formatter<'_>) -> Result[src]

Formats the value using the given formatter. Read more

impl Default for Bytes[src]

fn default() -> Bytes[src]

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

impl<'de> DeserializeAs<'de, &'de [u8]> for Bytes[src]

fn deserialize_as<D>(deserializer: D) -> Result<&'de [u8], D::Error> where
    D: Deserializer<'de>, 
[src]

Deserialize this value from the given Serde deserializer.

impl<'de, const N: usize> DeserializeAs<'de, [u8; N]> for Bytes[src]

fn deserialize_as<D>(deserializer: D) -> Result<[u8; N], D::Error> where
    D: Deserializer<'de>, 
[src]

Deserialize this value from the given Serde deserializer.

impl<'de, const N: usize> DeserializeAs<'de, Box<[u8; N], Global>> for Bytes[src]

fn deserialize_as<D>(deserializer: D) -> Result<Box<[u8; N]>, D::Error> where
    D: Deserializer<'de>, 
[src]

Deserialize this value from the given Serde deserializer.

impl<'de> DeserializeAs<'de, Box<[u8], Global>> for Bytes[src]

fn deserialize_as<D>(deserializer: D) -> Result<Box<[u8]>, D::Error> where
    D: Deserializer<'de>, 
[src]

Deserialize this value from the given Serde deserializer.

impl<'de> DeserializeAs<'de, Cow<'de, [u8]>> for Bytes[src]

fn deserialize_as<D>(deserializer: D) -> Result<Cow<'de, [u8]>, D::Error> where
    D: Deserializer<'de>, 
[src]

Deserialize this value from the given Serde deserializer.

impl<'de> DeserializeAs<'de, Vec<u8, Global>> for Bytes[src]

fn deserialize_as<D>(deserializer: D) -> Result<Vec<u8>, D::Error> where
    D: Deserializer<'de>, 
[src]

Deserialize this value from the given Serde deserializer.

impl SerializeAs<&'_ [u8]> for Bytes[src]

fn serialize_as<S>(bytes: &&[u8], serializer: S) -> Result<S::Ok, S::Error> where
    S: Serializer
[src]

Serialize this value into the given Serde serializer.

impl<'a, const N: usize> SerializeAs<[u8; N]> for Bytes[src]

fn serialize_as<S>(bytes: &[u8; N], serializer: S) -> Result<S::Ok, S::Error> where
    S: Serializer
[src]

Serialize this value into the given Serde serializer.

impl<'a, const N: usize> SerializeAs<Box<[u8; N], Global>> for Bytes[src]

fn serialize_as<S>(
    bytes: &Box<[u8; N]>,
    serializer: S
) -> Result<S::Ok, S::Error> where
    S: Serializer
[src]

Serialize this value into the given Serde serializer.

impl SerializeAs<Box<[u8], Global>> for Bytes[src]

fn serialize_as<S>(bytes: &Box<[u8]>, serializer: S) -> Result<S::Ok, S::Error> where
    S: Serializer
[src]

Serialize this value into the given Serde serializer.

impl<'a> SerializeAs<Cow<'a, [u8]>> for Bytes[src]

fn serialize_as<S>(
    bytes: &Cow<'a, [u8]>,
    serializer: S
) -> Result<S::Ok, S::Error> where
    S: Serializer
[src]

Serialize this value into the given Serde serializer.

impl SerializeAs<Vec<u8, Global>> for Bytes[src]

fn serialize_as<S>(bytes: &Vec<u8>, serializer: S) -> Result<S::Ok, S::Error> where
    S: Serializer
[src]

Serialize this value into the given Serde serializer.

impl Copy for Bytes[src]

Auto Trait Implementations

impl RefUnwindSafe for Bytes

impl Send for Bytes

impl Sync for Bytes

impl Unpin for Bytes

impl UnwindSafe for Bytes

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

pub fn type_id(&self) -> TypeId[src]

Gets the TypeId of self. Read more

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

pub fn borrow(&self) -> &T[src]

Immutably borrows from an owned value. Read more

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

pub fn borrow_mut(&mut self) -> &mut T[src]

Mutably borrows from an owned value. Read more

impl<T> From<T> for T[src]

pub fn from(t: T) -> T[src]

Performs the conversion.

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

pub fn into(self) -> U[src]

Performs the conversion.

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

pub fn to_owned(&self) -> T[src]

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

pub fn clone_into(&self, target: &mut T)[src]

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

recently added

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

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>[src]

Performs the conversion.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

pub fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>[src]

Performs the conversion.