valence_protocol/
array.rs

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