memberlist_proto/data/
bytes.rs1use super::{super::check_encoded_message_size, Data, DataRef};
2
3macro_rules! impl_bytes {
4 ($($ty:ty => $from:ident),+$(,)?) => {
5 $(
6 impl<'a> DataRef<'a, $ty> for &'a [u8] {
7 fn decode(buf: &'a [u8]) -> Result<(usize, Self), super::DecodeError> {
8 Ok((buf.len(), buf))
9 }
10 }
11
12 impl Data for $ty {
13 type Ref<'a> = &'a [u8];
14
15 fn from_ref(val: Self::Ref<'_>) -> Result<Self, super::DecodeError> {
16 Ok(Self::$from(val))
17 }
18
19 fn encoded_len(&self) -> usize {
20 if self.is_empty() {
21 return 0;
22 }
23
24 self.len()
25 }
26
27 fn encode(&self, buf: &mut [u8]) -> Result<usize, super::EncodeError> {
28 if self.is_empty() {
29 return Ok(0);
30 }
31
32 let len = self.len();
33 let buf_len = buf.len();
34 if len > buf_len {
35 return Err(super::EncodeError::insufficient_buffer(len, buf_len));
36 }
37
38 check_encoded_message_size(len)?;
39
40 buf[..len].copy_from_slice(self);
41 Ok(len)
42 }
43 }
44 )*
45 };
46}
47
48impl_bytes!(
49 bytes::Bytes => copy_from_slice,
50 Vec<u8> => from,
51 Box<[u8]> => from,
52 std::sync::Arc<[u8]> => from,
53);
54
55impl<'a, const N: usize> DataRef<'a, [u8; N]> for [u8; N] {
56 fn decode(src: &'a [u8]) -> Result<(usize, [u8; N]), super::DecodeError> {
57 if src.len() < N {
58 return Err(super::DecodeError::buffer_underflow());
59 }
60
61 let mut bytes = [0; N];
62 bytes.copy_from_slice(&src[..N]);
63 Ok((N, bytes))
64 }
65}
66
67impl<const N: usize> Data for [u8; N] {
68 type Ref<'a> = Self;
69
70 fn from_ref(val: Self::Ref<'_>) -> Result<Self, super::DecodeError> {
71 Ok(val)
72 }
73
74 fn encoded_len(&self) -> usize {
75 N
76 }
77
78 fn encode(&self, buf: &mut [u8]) -> Result<usize, super::EncodeError> {
79 check_encoded_message_size(N)?;
80
81 if N > buf.len() {
82 return Err(super::EncodeError::insufficient_buffer(N, buf.len()));
83 }
84
85 buf[..N].copy_from_slice(self);
86 Ok(N)
87 }
88}