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    /// and charged against the total budget.
54    #[inline]
55    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
56        decoder.read_length_prefixed().map(Bytes::from)
57    }
58}
59
60impl Serialize for BytesMut {
61    #[inline]
62    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
63        Serialize::serialize(self.as_ref(), encoder)
64    }
65
66    #[inline]
67    fn encoded_len(&self) -> Result<usize> {
68        Ok(varint_len(self.len() as u64).saturating_add(self.len()))
69    }
70}
71
72impl Deserialize for BytesMut {
73    #[inline]
74    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
75        let declared = decoder.read_varint_u64()?;
76        let len = crate::codec::guard_owned_bytes(declared, decoder)?;
77        let bytes: Cow<'_, [u8]> = decoder.read_byte_cow(len)?;
78        Ok(BytesMut::from(&*bytes))
79    }
80}
81
82/// Appends to the buffer, growing it as needed. Never fails.
83impl Encode for BytesMut {
84    #[inline]
85    fn write_byte(&mut self, byte: u8) -> Result<()> {
86        self.put_u8(byte);
87        Ok(())
88    }
89
90    #[inline]
91    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
92        self.extend_from_slice(bytes);
93        Ok(())
94    }
95
96    #[inline]
97    fn reserve(&mut self, additional: usize) {
98        BytesMut::reserve(self, additional);
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105    use crate::{decode, encode};
106
107    #[test]
108    fn test_bytes_round_trip_matches_vec_wire() {
109        let b = Bytes::from_static(b"abc");
110        let bytes = encode(&b).unwrap();
111        assert_eq!(bytes, encode(&b"abc".to_vec()).unwrap());
112        assert_eq!(decode::<Bytes>(&bytes).unwrap(), b);
113        assert_eq!(&decode::<BytesMut>(&bytes).unwrap()[..], b"abc");
114        assert_eq!(b.encoded_len().unwrap(), bytes.len());
115    }
116
117    #[test]
118    fn test_bytes_mut_encode_appends() {
119        let mut buf = BytesMut::from(&b"x"[..]);
120        300_u32.serialize(&mut buf).unwrap();
121        assert_eq!(&buf[..], &[b'x', 0xac, 0x02]);
122    }
123}