bin_layout/record/
string.rs

1use crate::*;
2macro_rules! impl_encoder_fn {
3    [$($data:tt)*] => (
4        #[inline] fn encoder(&self, c: &mut impl Write) -> io::Result<()> {
5            encode_len!(self $($data)*, c);
6            c.write_all(self $($data)* .as_ref())
7        }
8    );
9}
10macro_rules! impl_encoder_for {
11    [$($ty:ty; $rec_ty:ty),*] => {$(
12        impl Encoder for $ty { impl_encoder_fn!(); }
13        impl<Len: LenType> Encoder for $rec_ty { impl_encoder_fn!(.data); }
14    )*};
15    [$($data:tt)*] => (
16        #[inline] fn encoder(&self, c: &mut impl Write) -> io::Result<()> {
17            encode_len!(self $($data)*, c);
18            c.write_all(self $($data)* .as_ref())
19        }
20    );
21}
22impl_encoder_for!(str; Record<Len, &str>, String; Record<Len, String>);
23
24macro_rules! read_slice {
25    [$c: expr] => ({
26        let len = decode_len!($c);
27        get_slice($c, len)
28    });
29}
30
31impl<'de> Decoder<'de> for String {
32    fn decoder(c: &mut &'de [u8]) -> Result<Self> {
33        let data = read_slice!(c)?;
34        String::from_utf8(data.to_vec()).map_err(DynErr::from)
35    }
36}
37
38impl<'de, Len: LenType> Decoder<'de> for Record<Len, String> {
39    fn decoder(c: &mut &'de [u8]) -> Result<Self> {
40        let data = read_slice!(c)?;
41        String::from_utf8(data.to_vec())
42            .map_err(DynErr::from)
43            .map(Record::new)
44    }
45}
46
47impl<'de: 'a, 'a> Decoder<'de> for &'a str {
48    fn decoder(c: &mut &'de [u8]) -> Result<Self> {
49        let data = read_slice!(c)?;
50        std::str::from_utf8(data).map_err(DynErr::from)
51    }
52}
53
54impl<'de: 'a, 'a, Len: LenType> Decoder<'de> for Record<Len, &'a str> {
55    fn decoder(c: &mut &'de [u8]) -> Result<Self> {
56        let data = read_slice!(c)?;
57        core::str::from_utf8(data)
58            .map_err(DynErr::from)
59            .map(Record::new)
60    }
61}
62
63//------------------------------------------------------------------------------------------
64
65impl<'de: 'a, 'a> Decoder<'de> for &'a [u8] {
66    fn decoder(c: &mut &'de [u8]) -> Result<Self> {
67        read_slice!(c)
68    }
69}
70
71impl<'de: 'a, 'a, Len: LenType> Decoder<'de> for Record<Len, &'a [u8]> {
72    fn decoder(c: &mut &'de [u8]) -> Result<Self> {
73        read_slice!(c).map(Record::new)
74    }
75}