bin_proto/impls/
str_.rs

1use crate::{util, BitEncode, Result, Untagged};
2
3use bitstream_io::{BitWrite, Endianness};
4
5impl<Ctx> BitEncode<Ctx, Untagged> for str {
6    fn encode<W, E>(&self, write: &mut W, ctx: &mut Ctx, _: Untagged) -> Result<()>
7    where
8        W: BitWrite,
9        E: Endianness,
10    {
11        util::encode_items::<_, E, _, _>(self.as_bytes(), write, ctx)
12    }
13}
14
15#[cfg(feature = "prepend-tags")]
16impl<Ctx> BitEncode<Ctx> for str {
17    fn encode<W, E>(&self, write: &mut W, ctx: &mut Ctx, (): ()) -> Result<()>
18    where
19        W: BitWrite,
20        E: Endianness,
21    {
22        self.len().encode::<_, E>(write, ctx, ())?;
23        self.encode::<_, E>(write, ctx, Untagged)
24    }
25}
26
27#[cfg(feature = "alloc")]
28#[allow(clippy::wildcard_imports)]
29mod decode {
30    use alloc::{boxed::Box, string::String};
31    use bitstream_io::BitRead;
32
33    use crate::BitDecode;
34
35    use super::*;
36
37    impl<Ctx> BitDecode<Ctx, Untagged> for Box<str> {
38        fn decode<R, E>(read: &mut R, ctx: &mut Ctx, tag: Untagged) -> Result<Self>
39        where
40            R: BitRead,
41            E: Endianness,
42        {
43            String::decode::<_, E>(read, ctx, tag).map(Into::into)
44        }
45    }
46
47    impl<Tag, Ctx> BitDecode<Ctx, crate::Tag<Tag>> for Box<str>
48    where
49        Tag: TryInto<usize>,
50    {
51        fn decode<R, E>(read: &mut R, ctx: &mut Ctx, tag: crate::Tag<Tag>) -> Result<Self>
52        where
53            R: BitRead,
54            E: Endianness,
55        {
56            String::decode::<_, E>(read, ctx, tag).map(Into::into)
57        }
58    }
59
60    #[cfg(feature = "prepend-tags")]
61    impl<Ctx> BitDecode<Ctx> for Box<str> {
62        fn decode<R, E>(read: &mut R, ctx: &mut Ctx, (): ()) -> Result<Self>
63        where
64            R: BitRead,
65            E: Endianness,
66        {
67            String::decode::<_, E>(read, ctx, ()).map(Into::into)
68        }
69    }
70
71    test_decode!(Box<str>| crate::Tag(3); [b'a', b'b', b'c'] => "abc".into());
72
73    #[cfg(test)]
74    mod untagged {
75        use super::*;
76
77        test_decode!(Box<str>| Untagged; [b'a', b'b', b'c'] => "abc".into());
78    }
79
80    #[cfg(feature = "prepend-tags")]
81    test_roundtrip!(Box<str>);
82}
83
84test_encode!(&str| Untagged; "abc" => [b'a', b'b', b'c']);