bin_proto/impls/
array.rs

1use bitstream_io::{BitRead, BitWrite, Endianness};
2
3use crate::{util, BitDecode, BitEncode, Result};
4use core::mem::MaybeUninit;
5
6impl<Ctx, T, const N: usize> BitDecode<Ctx> for [T; N]
7where
8    T: BitDecode<Ctx>,
9{
10    fn decode<R, E>(read: &mut R, ctx: &mut Ctx, (): ()) -> Result<Self>
11    where
12        R: BitRead,
13        E: Endianness,
14    {
15        let elements = util::decode_items::<_, E, _, _>(N, read, ctx);
16        let mut array: MaybeUninit<[T; N]> = MaybeUninit::uninit();
17        let array_ptr = array.as_mut_ptr().cast::<T>();
18        unsafe {
19            for (i, item) in elements.enumerate() {
20                array_ptr.add(i).write(item?);
21            }
22            Ok(array.assume_init())
23        }
24    }
25}
26
27impl<Ctx, T, const N: usize> BitEncode<Ctx> for [T; N]
28where
29    T: BitEncode<Ctx> + Sized,
30{
31    fn encode<W, E>(&self, write: &mut W, ctx: &mut Ctx, (): ()) -> Result<()>
32    where
33        W: BitWrite,
34        E: Endianness,
35    {
36        util::encode_items::<_, E, _, _>(self.iter(), write, ctx)
37    }
38}
39
40test_codec!([u8; 4]; [0, 1, 2, 3] => [0x00, 0x01, 0x02, 0x03]);
41test_roundtrip!([u8; 4]);