1use 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 #[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
82impl 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}