bin_proto/impls/
slice.rs

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