Skip to main content

deser_core/foreign_impls/
bytes.rs

1//! `Bytes` and `BytesMut` of `bytes`.
2//!
3//! They are serialized like `Vec<u8>`: as bytes, which formats without
4//! native bytes represent as strings (base64 by default).  When
5//! deserialized, they accept what `Vec<u8>` accepts.
6use ::bytes::{Bytes, BytesMut};
7use alloc::borrow::Cow;
8use alloc::vec::Vec;
9
10use crate::State;
11use crate::adapters::bytes::{BytesBufImpl, encoding_adapter};
12use crate::de::impls::{Via, deserialize_via};
13use crate::de::{Deserialize, SinkHandle};
14use crate::error::Error;
15use crate::event::Atom;
16use crate::ser::{Emit, Serialize, plain_atom};
17
18macro_rules! byte_buffer {
19    ($($ty:ty => $convert:expr;)*) => {
20        $(
21            impl Serialize for $ty {
22                begin_without_finish!();
23                plain_atom!(|v| Atom::Bytes(crate::Bytes::new(&v[..])));
24
25                fn serialize<'a>(value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
26                    Ok(Emit::Atom(Atom::Bytes(crate::Bytes::new(&value[..]))))
27                }
28            }
29
30            impl Via<Vec<u8>> for $ty {
31                #[inline]
32                fn convert(value: Vec<u8>) -> Result<Self, Error> {
33                    Ok($convert(value))
34                }
35            }
36
37            deserialize_via! {
38                [] $ty => Vec<u8>;
39            }
40
41            impl BytesBufImpl for $ty {
42                #[inline]
43                fn bytes(&self) -> &[u8] {
44                    self
45                }
46
47                #[inline]
48                fn from_vec(bytes: Vec<u8>) -> Result<Self, Error> {
49                    Ok($convert(bytes))
50                }
51
52                #[inline]
53                fn deserialize_into<'a, 'de>(out: &'a mut Option<Self>, state: &mut State) -> SinkHandle<'a, 'de> {
54                    <Self as Deserialize<'de>>::deserialize_into(out, state)
55                }
56
57                fn expecting() -> Cow<'static, str> {
58                    <Self as Deserialize<'static>>::expecting()
59                }
60            }
61
62            encoding_adapter!([] $ty);
63        )*
64    };
65}
66
67byte_buffer! {
68    Bytes => Bytes::from;
69    // converting from `Bytes` does not copy as the buffer is unique
70    BytesMut => |value| BytesMut::from(Bytes::from(value));
71}