1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
use std::io::Write;

use anyhow::ensure;

use crate::var_int::VarInt;
use crate::{Decode, Encode};

/// A fixed-size array encoded and decoded with a [`VarInt`] length prefix.
///
/// This is used when the length of the array is known statically, but a
/// length prefix is needed anyway.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[repr(transparent)]
pub struct FixedArray<T, const N: usize>(pub [T; N]);

impl<T: Encode, const N: usize> Encode for FixedArray<T, N> {
    fn encode(&self, mut w: impl Write) -> anyhow::Result<()> {
        VarInt(N as i32).encode(&mut w)?;
        self.0.encode(w)
    }
}

impl<'a, T: Decode<'a>, const N: usize> Decode<'a> for FixedArray<T, N> {
    fn decode(r: &mut &'a [u8]) -> anyhow::Result<Self> {
        let len = VarInt::decode(r)?.0;
        ensure!(
            len == N as i32,
            "unexpected length of {len} for fixed-sized array of length {N}"
        );

        <[T; N]>::decode(r).map(FixedArray)
    }
}

impl<T, const N: usize> From<[T; N]> for FixedArray<T, N> {
    fn from(value: [T; N]) -> Self {
        Self(value)
    }
}

impl<T, const N: usize> From<FixedArray<T, N>> for [T; N] {
    fn from(value: FixedArray<T, N>) -> Self {
        value.0
    }
}