chunkedge_binary/
array.rs

1use std::io::Write;
2
3use anyhow::ensure;
4
5use crate::{Decode, Encode, VarInt};
6
7/// A fixed-size array encoded and decoded with a [`VarInt`] length prefix.
8///
9/// This is used when the length of the array is known statically, but a
10/// length prefix is needed anyway.
11#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
12#[repr(transparent)]
13pub struct FixedArray<T, const N: usize>(pub [T; N]);
14
15impl<T: Encode, const N: usize> Encode for FixedArray<T, N> {
16    fn encode(&self, mut w: impl Write) -> anyhow::Result<()> {
17        VarInt(N as i32).encode(&mut w)?;
18        self.0.encode(w)
19    }
20}
21
22impl<'a, T: Decode<'a>, const N: usize> Decode<'a> for FixedArray<T, N> {
23    fn decode(r: &mut &'a [u8]) -> anyhow::Result<Self> {
24        let len = VarInt::decode(r)?.0;
25        ensure!(
26            len == N as i32,
27            "unexpected length of {len} for fixed-sized array of length {N}"
28        );
29
30        <[T; N]>::decode(r).map(FixedArray)
31    }
32}
33
34impl<T, const N: usize> From<[T; N]> for FixedArray<T, N> {
35    fn from(value: [T; N]) -> Self {
36        Self(value)
37    }
38}
39
40impl<T, const N: usize> From<FixedArray<T, N>> for [T; N] {
41    fn from(value: FixedArray<T, N>) -> Self {
42        value.0
43    }
44}