Skip to main content

azalea_protocol/common/
optional_compound_tag.rs

1use std::io::{self, Cursor, Write};
2
3use azalea_buf::{AzBuf, BufReadError, BufReadErrorRepr};
4use simdnbt::owned::NbtCompound;
5
6// TODO: this should be moved into simdnbt
7#[derive(Clone, Debug, PartialEq)]
8pub struct OptionalNbtCompound(pub Option<NbtCompound>);
9
10impl AzBuf for OptionalNbtCompound {
11    fn azalea_read(ctx: azalea_buf::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
12        let tag_type = u8::azalea_read(ctx, buf)?;
13        match tag_type {
14            10 => Ok(Self(Some(
15                simdnbt::owned::read_compound(buf).map_err(simdnbt::Error::from)?,
16            ))),
17            0 => Ok(Self(None)),
18            _ => Err(BufReadErrorRepr::UnexpectedEnumVariant {
19                id: tag_type.into(),
20            }
21            .into()),
22        }
23    }
24
25    fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
26        if let Some(compound) = &self.0 {
27            10u8.azalea_write(ctx, buf)?;
28            compound.azalea_write(ctx, buf)?;
29        } else {
30            0u8.azalea_write(ctx, buf)?;
31        }
32        Ok(())
33    }
34}