Skip to main content

pack_io/
bytes_impls.rs

1//! `bytes` crate integration (feature `bytes`).
2//!
3//! - [`bytes::Bytes`] and [`bytes::BytesMut`] implement [`Serialize`] /
4//!   [`Deserialize`] with the same wire shape as `Vec<u8>` (a varint length
5//!   prefix and the raw bytes), so they are interchangeable with `Vec<u8>`
6//!   and `&[u8]` fields on either side of the wire.
7//! - [`bytes::BytesMut`] implements [`Encode`], so a value can be encoded
8//!   straight into a tokio codec's output buffer without an intermediate
9//!   `Vec`.
10//!
11//! Zero-copy decoding from a `Bytes` frame needs no extra API: decode a
12//! view with [`crate::decode_view`] and turn each borrowed `&[u8]` back into
13//! a cheap, reference-counted slice of the frame with
14//! [`Bytes::slice_ref`](bytes::Bytes::slice_ref):
15//!
16//! ```
17//! use bytes::{Bytes, BytesMut};
18//! use pack_io::{Serialize, decode_view};
19//!
20//! // Encode straight into a BytesMut, then freeze it into a frame.
21//! let mut buf = BytesMut::new();
22//! (7_u32, b"payload".as_slice()).serialize(&mut buf).unwrap();
23//! let frame: Bytes = buf.freeze();
24//!
25//! let (id, body): (u32, &[u8]) = decode_view(&frame).unwrap();
26//! let body: Bytes = frame.slice_ref(body); // shares the frame's allocation
27//! assert_eq!((id, &body[..]), (7, &b"payload"[..]));
28//! ```
29
30use alloc::borrow::Cow;
31
32use bytes::{BufMut, Bytes, BytesMut};
33
34use crate::codec::{Decode, Encode, varint_len};
35use crate::error::Result;
36use crate::traits::{Deserialize, Serialize};
37
38impl Serialize for Bytes {
39    #[inline]
40    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
41        Serialize::serialize(self.as_ref(), encoder)
42    }
43
44    #[inline]
45    fn encoded_len(&self) -> Result<usize> {
46        Ok(varint_len(self.len() as u64).saturating_add(self.len()))
47    }
48}
49
50impl Deserialize for Bytes {
51    /// Bounded exactly like `Vec<u8>`: the length is checked against
52    /// `max_alloc` and the remaining input before anything is allocated.
53    #[inline]
54    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
55        decoder.read_length_prefixed().map(Bytes::from)
56    }
57}
58
59impl Serialize for BytesMut {
60    #[inline]
61    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
62        Serialize::serialize(self.as_ref(), encoder)
63    }
64
65    #[inline]
66    fn encoded_len(&self) -> Result<usize> {
67        Ok(varint_len(self.len() as u64).saturating_add(self.len()))
68    }
69}
70
71impl Deserialize for BytesMut {
72    #[inline]
73    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
74        let declared = decoder.read_varint_u64()?;
75        let len = crate::codec::guard_element_count(declared, decoder)?;
76        let bytes: Cow<'_, [u8]> = decoder.read_byte_cow(len)?;
77        Ok(BytesMut::from(&*bytes))
78    }
79}
80
81/// Appends to the buffer, growing it as needed. Never fails.
82impl Encode for BytesMut {
83    #[inline]
84    fn write_byte(&mut self, byte: u8) -> Result<()> {
85        self.put_u8(byte);
86        Ok(())
87    }
88
89    #[inline]
90    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
91        self.extend_from_slice(bytes);
92        Ok(())
93    }
94
95    #[inline]
96    fn reserve(&mut self, additional: usize) {
97        BytesMut::reserve(self, additional);
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use crate::{decode, encode};
105
106    #[test]
107    fn test_bytes_round_trip_matches_vec_wire() {
108        let b = Bytes::from_static(b"abc");
109        let bytes = encode(&b).unwrap();
110        assert_eq!(bytes, encode(&b"abc".to_vec()).unwrap());
111        assert_eq!(decode::<Bytes>(&bytes).unwrap(), b);
112        assert_eq!(&decode::<BytesMut>(&bytes).unwrap()[..], b"abc");
113        assert_eq!(b.encoded_len().unwrap(), bytes.len());
114    }
115
116    #[test]
117    fn test_bytes_mut_encode_appends() {
118        let mut buf = BytesMut::from(&b"x"[..]);
119        300_u32.serialize(&mut buf).unwrap();
120        assert_eq!(&buf[..], &[b'x', 0xac, 0x02]);
121    }
122}