memberlist_proto/data/
string.rs

1use super::{Data, DataRef};
2
3macro_rules! impl_str {
4  ($($ty:ty => $from:ident),+$(,)?) => {
5    $(
6      impl<'a> DataRef<'a, $ty> for &'a str {
7        fn decode(src: &'a [u8]) -> Result<(usize, Self), super::DecodeError> {
8          match core::str::from_utf8(src) {
9            Ok(value) => Ok((src.len(), value)),
10            Err(e) => Err(super::DecodeError::custom(e.to_string())),
11          }
12        }
13      }
14
15      impl Data for $ty {
16        type Ref<'a> = &'a str;
17
18        fn from_ref(val: Self::Ref<'_>) -> Result<Self, super::DecodeError> {
19          Ok(Self::$from(val))
20        }
21
22        #[inline]
23        fn encoded_len(&self) -> usize {
24          let bytes = self.as_bytes();
25
26          if bytes.is_empty() {
27            return 0;
28          }
29
30          bytes.len()
31        }
32
33        #[inline]
34        fn encode(&self, buf: &mut [u8]) -> Result<usize, super::EncodeError> {
35          let bytes = self.as_bytes();
36          if bytes.is_empty() {
37            return Ok(0);
38          }
39
40          let len = bytes.len();
41          let buf_len = buf.len();
42          if len > buf_len {
43            return Err(super::EncodeError::insufficient_buffer(len, buf_len));
44          }
45
46          super::super::check_encoded_message_size(len)?;
47
48          buf[..len].copy_from_slice(bytes);
49          Ok(len)
50        }
51      }
52    )*
53  };
54}
55
56impl_str!(
57  std::string::String => from,
58  smol_str::SmolStr => new,
59  std::sync::Arc<str> => from,
60  std::boxed::Box<str> => from,
61  triomphe::Arc<str> => from,
62);