chore: move to crates folder

This commit is contained in:
Alexander Medvedev committed 2026-08-06 12:56:40 +02:00
1 parent 5d10c0d8a8
commit cb3660bcd2
3393 files changed
+1270 -741

No files matched your search

+436
View File
@@ -0,0 +1,436 @@
//! Storage and convenience methods for NBT compound tags.
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use uuid::Uuid;
use crate::deserializer::NbtReadHelper;
use crate::serializer::NbtWriteHelper;
use crate::tag::NbtTag;
use crate::{END_ID, Error, Nbt};
use std::collections::hash_map::IntoIter;
use std::io::ErrorKind;
#[macro_export]
/// Creates an [`NbtTag::Compound`](crate::tag::NbtTag::Compound) from key-value pairs.
///
/// The macro also accepts an empty invocation to create an empty compound tag.
macro_rules! nbt_compound_tag {
{ $($key:literal : $tag:expr),+ $(,)* } => {
{
let mut compound = NbtCompound::new();
$( compound.put($key, $tag); )+
NbtTag::Compound(compound)
}
};
// For empty compounds
{} => {
NbtTag::Compound(NbtCompound::new())
};
}
/// Represents a Compound NBT tag, effectively a hash map.
///
/// Internally, this uses a `HashMap<String, NbtTag>`, which does not preserve insertion order,
/// just like Minecraft: Java Edition, but it does mean lookups are O(1).
///
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NbtCompound {
/// Tags in the compound, indexed by their names.
pub child_tags: HashMap<Box<str>, NbtTag>,
}
impl NbtCompound {
/// Creates an empty compound.
#[must_use]
pub fn new() -> Self {
Self {
child_tags: HashMap::new(),
}
}
/// Advances a reader past a compound's payload without allocating its tags.
pub fn skip_content<'a, R: NbtReadHelper<'a>>(reader: &mut R) -> Result<(), Error> {
loop {
let tag_id = match reader.get_u8() {
Ok(id) => id,
Err(Error::Incomplete(e)) if e.kind() == ErrorKind::UnexpectedEof => break,
Err(e) => return Err(e),
};
if tag_id == END_ID {
break;
}
reader.skip_string()?;
// Skip Value
NbtTag::skip_data(reader, tag_id)?;
}
Ok(())
}
/// Deserializes a compound payload, starting after the compound's name.
pub fn deserialize_content<'a, R: NbtReadHelper<'a>>(reader: &mut R) -> Result<Self, Error> {
let mut compound = Self::new();
loop {
let tag_id = match reader.get_u8() {
Ok(id) => id,
Err(Error::Incomplete(e)) if e.kind() == ErrorKind::UnexpectedEof => break,
Err(e) => return Err(e),
};
if tag_id == END_ID {
break;
}
let name = reader.get_string()?;
let tag = NbtTag::deserialize_data(reader, tag_id)?;
compound.child_tags.insert(name.into(), tag);
}
Ok(compound)
}
/// Serializes the compound's entries followed by an end tag.
pub fn serialize_content<W: NbtWriteHelper>(self, w: &mut W) -> Result<(), Error> {
for (name, tag) in self.child_tags {
w.write_u8(tag.get_type_id())?;
w.write_string(&name)?;
tag.serialize_data(w)?;
}
w.write_u8(END_ID)?;
Ok(())
}
/// Returns `true` when the compound contains no child tags.
#[must_use]
pub fn is_empty(&self) -> bool {
self.child_tags.is_empty()
}
/// Inserts or replaces a tag for `name`.
pub fn put(&mut self, name: &str, value: impl Into<NbtTag>) {
self.child_tags.insert(name.into(), value.into());
}
/// Inserts a string tag when `name` is not already present.
pub fn put_string(&mut self, name: &str, value: String) {
self.put(name, NbtTag::String(value.into()));
}
/// Inserts a list tag when `name` is not already present.
pub fn put_list(&mut self, name: &str, value: Vec<NbtTag>) {
self.put(name, NbtTag::List(value));
}
/// Inserts a byte tag when `name` is not already present.
pub fn put_byte(&mut self, name: &str, value: i8) {
self.put(name, NbtTag::Byte(value));
}
/// Inserts a boolean encoded as a byte tag when `name` is not already present.
pub fn put_bool(&mut self, name: &str, value: bool) {
self.put(name, NbtTag::Byte(i8::from(value)));
}
/// Inserts a short tag when `name` is not already present.
pub fn put_short(&mut self, name: &str, value: i16) {
self.put(name, NbtTag::Short(value));
}
/// Inserts an integer tag when `name` is not already present.
pub fn put_int(&mut self, name: &str, value: i32) {
self.put(name, NbtTag::Int(value));
}
/// Inserts a long tag when `name` is not already present.
pub fn put_long(&mut self, name: &str, value: i64) {
self.put(name, NbtTag::Long(value));
}
/// Inserts a float tag when `name` is not already present.
pub fn put_float(&mut self, name: &str, value: f32) {
self.put(name, NbtTag::Float(value));
}
/// Inserts a double tag when `name` is not already present.
pub fn put_double(&mut self, name: &str, value: f64) {
self.put(name, NbtTag::Double(value));
}
/// Inserts a compound tag when `name` is not already present.
pub fn put_compound(&mut self, name: &str, value: Self) {
self.put(name, NbtTag::Compound(value));
}
/// Stores a UUID as a 4-element int array, most significant bits first
/// (the vanilla `UUID` layout).
pub fn put_uuid(&mut self, name: &str, value: Uuid) {
let value = value.as_u128();
self.put(
name,
NbtTag::IntArray(vec![
(value >> 96) as i32,
((value >> 64) & 0xFFFF_FFFF) as i32,
((value >> 32) & 0xFFFF_FFFF) as i32,
(value & 0xFFFF_FFFF) as i32,
]),
);
}
/// Returns the named byte value, or `None` if the tag is absent or has another type.
#[must_use]
pub fn get_byte(&self, name: &str) -> Option<i8> {
self.get(name).and_then(super::tag::NbtTag::extract_byte)
}
/// Returns the named tag.
#[inline]
#[must_use]
pub fn get(&self, name: &str) -> Option<&NbtTag> {
self.child_tags.get(name)
}
/// Returns whether the compound contains `name`.
#[inline]
#[must_use]
pub fn has(&self, name: &str) -> bool {
self.child_tags.contains_key(name)
}
/// Returns the named short value, or `None` if the tag is absent or has another type.
#[must_use]
pub fn get_short(&self, name: &str) -> Option<i16> {
self.get(name).and_then(super::tag::NbtTag::extract_short)
}
/// Returns the named integer value, or `None` if the tag is absent or has another type.
#[must_use]
pub fn get_int(&self, name: &str) -> Option<i32> {
self.get(name).and_then(super::tag::NbtTag::extract_int)
}
/// Returns the named long value, or `None` if the tag is absent or has another type.
#[must_use]
pub fn get_long(&self, name: &str) -> Option<i64> {
self.get(name).and_then(super::tag::NbtTag::extract_long)
}
/// Returns the named float value, or `None` if the tag is absent or has another type.
#[must_use]
pub fn get_float(&self, name: &str) -> Option<f32> {
self.get(name).and_then(super::tag::NbtTag::extract_float)
}
/// Returns the named double value, or `None` if the tag is absent or has another type.
#[must_use]
pub fn get_double(&self, name: &str) -> Option<f64> {
self.get(name).and_then(super::tag::NbtTag::extract_double)
}
/// Returns the named byte as a boolean, where zero is `false`.
#[must_use]
pub fn get_bool(&self, name: &str) -> Option<bool> {
self.get(name).and_then(super::tag::NbtTag::extract_bool)
}
/// Returns the named string, or `None` if the tag is absent or has another type.
#[must_use]
pub fn get_string(&self, name: &str) -> Option<&str> {
self.get(name).and_then(|tag| tag.extract_string())
}
/// Returns the named list, or `None` if the tag is absent or has another type.
#[must_use]
pub fn get_list(&self, name: &str) -> Option<&[NbtTag]> {
self.get(name).and_then(|tag| tag.extract_list())
}
/// Returns the named compound, or `None` if the tag is absent or has another type.
#[must_use]
pub fn get_compound(&self, name: &str) -> Option<&Self> {
self.get(name).and_then(|tag| tag.extract_compound())
}
/// Returns the named integer array, or `None` if the tag is absent or has another type.
#[must_use]
pub fn get_int_array(&self, name: &str) -> Option<&[i32]> {
self.get(name).and_then(|tag| tag.extract_int_array())
}
/// Returns the named long array, or `None` if the tag is absent or has another type.
#[must_use]
pub fn get_long_array(&self, name: &str) -> Option<&[i64]> {
self.get(name).and_then(|tag| tag.extract_long_array())
}
/// Reads a UUID stored as a 4-element int array, most significant bits
/// first (the vanilla `UUID` layout written by [`Self::put_uuid`]).
#[must_use]
pub fn get_uuid(&self, name: &str) -> Option<Uuid> {
let &[a, b, c, d] = self.get_int_array(name)? else {
return None;
};
Some(Uuid::from_u128(
((a as u32 as u128) << 96)
| ((b as u32 as u128) << 64)
| ((c as u32 as u128) << 32)
| (d as u32 as u128),
))
}
}
impl From<Nbt> for NbtCompound {
fn from(value: Nbt) -> Self {
value.root_tag
}
}
impl FromIterator<(String, NbtTag)> for NbtCompound {
fn from_iter<T: IntoIterator<Item = (String, NbtTag)>>(iter: T) -> Self {
let mut compound = Self::new();
for (key, value) in iter {
compound.put(&key, value);
}
compound
}
}
impl FromIterator<(Box<str>, NbtTag)> for NbtCompound {
fn from_iter<T: IntoIterator<Item = (Box<str>, NbtTag)>>(iter: T) -> Self {
let mut compound = Self::new();
for (key, value) in iter {
compound.child_tags.insert(key, value);
}
compound
}
}
impl IntoIterator for NbtCompound {
type Item = (Box<str>, NbtTag);
type IntoIter = IntoIter<Box<str>, NbtTag>;
fn into_iter(self) -> Self::IntoIter {
self.child_tags.into_iter()
}
}
impl Extend<(String, NbtTag)> for NbtCompound {
fn extend<T: IntoIterator<Item = (String, NbtTag)>>(&mut self, iter: T) {
for (key, value) in iter {
self.put(&key, value);
}
}
}
impl Extend<(Box<str>, NbtTag)> for NbtCompound {
fn extend<T: IntoIterator<Item = (Box<str>, NbtTag)>>(&mut self, iter: T) {
self.child_tags.extend(iter);
}
}
// Rust's AsRef is currently not reflexive so we need to implement it manually
impl AsRef<Self> for NbtCompound {
fn as_ref(&self) -> &Self {
self
}
}
impl From<NbtCompound> for NbtTag {
fn from(value: NbtCompound) -> Self {
Self::Compound(value)
}
}
/// SNBT display implementation for `NbtCompound`
impl Display for NbtCompound {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str("{")?;
for (i, (key, value)) in self.child_tags.iter().enumerate() {
if i > 0 {
f.write_str(", ")?;
}
write!(f, "{key}: {value}")?;
}
f.write_str("}")
}
}
impl Display for NbtTag {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::End => Ok(()),
Self::Byte(v) => write!(f, "{v}b"),
Self::Short(v) => write!(f, "{v}s"),
Self::Int(v) => write!(f, "{v}"),
Self::Long(v) => write!(f, "{v}L"),
Self::Float(v) => write!(f, "{v}f"),
Self::Double(v) => write!(f, "{v}d"),
Self::String(v) => write!(f, "\"{v}\""), // TODO: Proper escaping needed for robust SNBT
Self::Compound(v) => write!(f, "{v}"),
Self::ByteArray(v) => {
f.write_str("[B;")?;
for (i, byte) in v.iter().enumerate() {
if i > 0 {
f.write_str(",")?;
}
write!(f, " {byte}b")?;
}
f.write_str("]")
}
Self::List(v) => {
f.write_str("[")?;
for (i, tag) in v.iter().enumerate() {
if i > 0 {
f.write_str(", ")?;
}
write!(f, "{tag}")?;
}
f.write_str("]")
}
Self::IntArray(v) => {
f.write_str("[I;")?;
for (i, int) in v.iter().enumerate() {
if i > 0 {
f.write_str(",")?;
}
write!(f, " {int}")?;
}
f.write_str("]")
}
Self::LongArray(v) => {
f.write_str("[L;")?;
for (i, long) in v.iter().enumerate() {
if i > 0 {
f.write_str(",")?;
}
write!(f, " {long}L")?;
}
f.write_str("]")
}
}
}
}
#[cfg(test)]
mod tests {
use super::NbtCompound;
use uuid::Uuid;
#[test]
fn uuid_int_array_round_trip() {
let original = Uuid::from_u128(0x0123_4567_89ab_cdef_fedc_ba98_7654_3210);
let mut nbt = NbtCompound::new();
nbt.put_uuid("UUID", original);
assert_eq!(nbt.get_uuid("UUID"), Some(original));
// Missing or malformed entries fall back to None.
assert_eq!(nbt.get_uuid("missing"), None);
let mut short = NbtCompound::new();
short.put("UUID", crate::tag::NbtTag::IntArray(vec![1, 2, 3]));
assert_eq!(short.get_uuid("UUID"), None);
}
}
+433
View File
@@ -0,0 +1,433 @@
//! Deserialization from Java Edition, unnamed network, and Bedrock NBT.
use std::borrow::Cow;
use std::io::{Cursor, Seek, SeekFrom};
use crate::{Error, io};
use io::Read;
/// Result type returned by NBT deserialization operations.
pub type Result<T> = std::result::Result<T, Error>;
/// Byte source used by NBT read helpers.
///
/// Implementations may return borrowed strings and byte arrays when the
/// underlying storage permits it.
pub trait NbtDataSource<'a> {
/// Reads one unsigned byte.
fn read_u8(&mut self) -> Result<u8>;
/// Fills `buf` with bytes from the source.
fn read_bytes(&mut self, buf: &mut [u8]) -> Result<()>;
/// Moves the current position by `offset` bytes.
fn seek_relative(&mut self, offset: i64) -> Result<()>;
/// Reads and decodes a string payload of `len` bytes.
fn read_string(&mut self, len: usize) -> Result<Cow<'a, str>>;
/// Reads a byte-array payload of `len` elements.
fn read_byte_array(&mut self, len: usize) -> Result<Cow<'a, [i8]>>;
}
/// Adapts a [`Read`] and [`Seek`] stream into an [`NbtDataSource`].
pub struct NbtStreamReader<R>(
/// Wrapped input stream.
pub R,
);
impl<'a, R: Read + Seek> NbtDataSource<'a> for NbtStreamReader<R> {
fn read_u8(&mut self) -> Result<u8> {
let mut buf = [0u8; 1];
self.0.read_exact(&mut buf).map_err(Error::Incomplete)?;
Ok(buf[0])
}
fn read_bytes(&mut self, buf: &mut [u8]) -> Result<()> {
self.0.read_exact(buf).map_err(Error::Incomplete)
}
fn seek_relative(&mut self, offset: i64) -> Result<()> {
self.0
.seek(SeekFrom::Current(offset))
.map_err(Error::Incomplete)?;
Ok(())
}
fn read_string(&mut self, len: usize) -> Result<Cow<'a, str>> {
let mut buf = vec![0u8; len];
self.0.read_exact(&mut buf).map_err(Error::Incomplete)?;
let string = cesu8::from_java_cesu8(&buf).map_err(|_| Error::Cesu8DecodingError)?;
Ok(Cow::Owned(string.into_owned()))
}
fn read_byte_array(&mut self, len: usize) -> Result<Cow<'a, [i8]>> {
let mut buf = vec![0u8; len];
self.0.read_exact(&mut buf).map_err(Error::Incomplete)?;
let i8_buf: Vec<i8> = buf.into_iter().map(|b| b as i8).collect();
Ok(Cow::Owned(i8_buf))
}
}
impl<'a> NbtDataSource<'a> for Cursor<&'a [u8]> {
fn read_u8(&mut self) -> Result<u8> {
let mut buf = [0u8; 1];
self.read_exact(&mut buf).map_err(Error::Incomplete)?;
Ok(buf[0])
}
fn read_bytes(&mut self, buf: &mut [u8]) -> Result<()> {
self.read_exact(buf).map_err(Error::Incomplete)
}
fn seek_relative(&mut self, offset: i64) -> Result<()> {
self.seek(SeekFrom::Current(offset))
.map_err(Error::Incomplete)?;
Ok(())
}
fn read_string(&mut self, len: usize) -> Result<Cow<'a, str>> {
let pos = self.position() as usize;
let data_len = self.get_ref().len();
if pos + len > data_len {
return Err(Error::Incomplete(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"unexpected EOF",
)));
}
self.set_position((pos + len) as u64);
let data = self.get_ref();
let slice = &data[pos..pos + len];
if let Ok(s) = std::str::from_utf8(slice) {
Ok(Cow::Borrowed(s))
} else {
let string = cesu8::from_java_cesu8(slice).map_err(|_| Error::Cesu8DecodingError)?;
Ok(string)
}
}
fn read_byte_array(&mut self, len: usize) -> Result<Cow<'a, [i8]>> {
let pos = self.position() as usize;
let data_len = self.get_ref().len();
if pos + len > data_len {
return Err(Error::Incomplete(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"unexpected EOF",
)));
}
self.set_position((pos + len) as u64);
let data = self.get_ref();
let slice = &data[pos..pos + len];
// SAFETY: `slice` is a valid byte slice of length `len`. `u8` and `i8` have identical size, alignment (1 byte), and valid value representations.
let i8_slice = unsafe { std::slice::from_raw_parts(slice.as_ptr().cast::<i8>(), len) };
Ok(Cow::Borrowed(i8_slice))
}
}
impl<'a, S: NbtDataSource<'a> + ?Sized> NbtDataSource<'a> for &mut S {
fn read_u8(&mut self) -> Result<u8> {
(**self).read_u8()
}
fn read_bytes(&mut self, buf: &mut [u8]) -> Result<()> {
(**self).read_bytes(buf)
}
fn seek_relative(&mut self, offset: i64) -> Result<()> {
(**self).seek_relative(offset)
}
fn read_string(&mut self, len: usize) -> Result<Cow<'a, str>> {
(**self).read_string(len)
}
fn read_byte_array(&mut self, len: usize) -> Result<Cow<'a, [i8]>> {
(**self).read_byte_array(len)
}
}
impl<'a> NbtDataSource<'a> for Cursor<Vec<u8>> {
fn read_u8(&mut self) -> Result<u8> {
let mut buf = [0u8; 1];
self.read_exact(&mut buf).map_err(Error::Incomplete)?;
Ok(buf[0])
}
fn read_bytes(&mut self, buf: &mut [u8]) -> Result<()> {
self.read_exact(buf).map_err(Error::Incomplete)
}
fn seek_relative(&mut self, offset: i64) -> Result<()> {
self.seek(SeekFrom::Current(offset))
.map_err(Error::Incomplete)?;
Ok(())
}
fn read_string(&mut self, len: usize) -> Result<Cow<'a, str>> {
let pos = self.position() as usize;
let data_len = self.get_ref().len();
if pos + len > data_len {
return Err(Error::Incomplete(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"unexpected EOF",
)));
}
self.set_position((pos + len) as u64);
let data = self.get_ref();
let slice = &data[pos..pos + len];
let string = cesu8::from_java_cesu8(slice).map_err(|_| Error::Cesu8DecodingError)?;
Ok(Cow::Owned(string.into_owned()))
}
fn read_byte_array(&mut self, len: usize) -> Result<Cow<'a, [i8]>> {
let pos = self.position() as usize;
let data_len = self.get_ref().len();
if pos + len > data_len {
return Err(Error::Incomplete(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"unexpected EOF",
)));
}
self.set_position((pos + len) as u64);
let data = self.get_ref();
let slice = &data[pos..pos + len];
// SAFETY: `slice` is a valid byte slice of length `len`. `u8` and `i8` have identical size, alignment (1 byte), and valid value representations.
let i8_slice = unsafe { std::slice::from_raw_parts(slice.as_ptr().cast::<i8>(), len) };
Ok(Cow::Owned(i8_slice.to_vec()))
}
}
/// Format-specific primitive reader used by the NBT parser.
pub trait NbtReadHelper<'a> {
/// Underlying byte source.
type Reader: NbtDataSource<'a>;
/// Returns the underlying byte source.
fn reader(&mut self) -> &mut Self::Reader;
/// Advances by `count` bytes.
fn skip_bytes(&mut self, count: i64) -> Result<()> {
self.reader().seek_relative(count)
}
/// Advances past an unsigned byte.
fn skip_u8(&mut self) -> Result<()> {
self.skip_bytes(1)
}
/// Advances past a signed byte.
fn skip_i8(&mut self) -> Result<()> {
self.skip_bytes(1)
}
/// Advances past a 16-bit signed integer.
fn skip_i16(&mut self) -> Result<()> {
self.skip_bytes(2)
}
/// Advances past a 32-bit signed integer.
fn skip_i32(&mut self) -> Result<()> {
self.skip_bytes(4)
}
/// Advances past a 64-bit signed integer.
fn skip_i64(&mut self) -> Result<()> {
self.skip_bytes(8)
}
/// Advances past a 32-bit floating-point number.
fn skip_f32(&mut self) -> Result<()> {
self.skip_bytes(4)
}
/// Advances past a 64-bit floating-point number.
fn skip_f64(&mut self) -> Result<()> {
self.skip_bytes(8)
}
/// Advances past a length-prefixed string.
fn skip_string(&mut self) -> Result<()>;
/// Reads an unsigned byte.
fn get_u8(&mut self) -> Result<u8>;
/// Reads a signed byte.
fn get_i8(&mut self) -> Result<i8>;
/// Reads a 16-bit signed integer.
fn get_i16(&mut self) -> Result<i16>;
/// Reads a 32-bit signed integer.
fn get_i32(&mut self) -> Result<i32>;
/// Reads a 64-bit signed integer.
fn get_i64(&mut self) -> Result<i64>;
/// Reads a 32-bit floating-point number.
fn get_f32(&mut self) -> Result<f32>;
/// Reads a 64-bit floating-point number.
fn get_f64(&mut self) -> Result<f64>;
/// Reads a length-prefixed string.
fn get_string(&mut self) -> Result<Cow<'a, str>>;
/// Reads a byte array with the supplied element count.
fn get_byte_array(&mut self, len: usize) -> Result<Cow<'a, [i8]>>;
}
/// Reads Java Edition NBT primitives using big-endian numeric encoding.
pub struct NbtReadHelperJava<D> {
reader: D,
}
impl<D> NbtReadHelperJava<D> {
/// Creates a Java Edition reader over `r`.
pub const fn new(r: D) -> Self {
Self { reader: r }
}
}
/// Reads Bedrock network NBT primitives using little-endian and variable-length encoding.
pub struct NbtReadHelperBedrock<D> {
reader: D,
}
impl<D> NbtReadHelperBedrock<D> {
/// Creates a Bedrock network reader over `r`.
pub const fn new(r: D) -> Self {
Self { reader: r }
}
}
impl<'a, D: NbtDataSource<'a>> NbtReadHelperJava<D> {
fn get_string_len(&mut self) -> Result<u16> {
let mut buf = [0u8; 2];
self.reader.read_bytes(&mut buf)?;
Ok(u16::from_be_bytes(buf))
}
}
impl<'a, D: NbtDataSource<'a>> NbtReadHelper<'a> for NbtReadHelperJava<D> {
type Reader = D;
fn reader(&mut self) -> &mut D {
&mut self.reader
}
fn skip_string(&mut self) -> Result<()> {
let len = self.get_string_len()? as i64;
self.skip_bytes(len)
}
fn get_u8(&mut self) -> Result<u8> {
self.reader.read_u8()
}
fn get_i8(&mut self) -> Result<i8> {
Ok(self.reader.read_u8()? as i8)
}
fn get_i16(&mut self) -> Result<i16> {
let mut buf = [0u8; 2];
self.reader.read_bytes(&mut buf)?;
Ok(i16::from_be_bytes(buf))
}
fn get_i32(&mut self) -> Result<i32> {
let mut buf = [0u8; 4];
self.reader.read_bytes(&mut buf)?;
Ok(i32::from_be_bytes(buf))
}
fn get_i64(&mut self) -> Result<i64> {
let mut buf = [0u8; 8];
self.reader.read_bytes(&mut buf)?;
Ok(i64::from_be_bytes(buf))
}
fn get_f32(&mut self) -> Result<f32> {
let mut buf = [0u8; 4];
self.reader.read_bytes(&mut buf)?;
Ok(f32::from_be_bytes(buf))
}
fn get_f64(&mut self) -> Result<f64> {
let mut buf = [0u8; 8];
self.reader.read_bytes(&mut buf)?;
Ok(f64::from_be_bytes(buf))
}
fn get_string(&mut self) -> Result<Cow<'a, str>> {
let len = self.get_string_len()? as usize;
self.reader.read_string(len)
}
fn get_byte_array(&mut self, len: usize) -> Result<Cow<'a, [i8]>> {
self.reader.read_byte_array(len)
}
}
impl<'a, D: NbtDataSource<'a>> NbtReadHelperBedrock<D> {
fn get_u8(&mut self) -> Result<u8> {
self.reader.read_u8()
}
fn get_var_u32(&mut self) -> Result<u32> {
let mut val = 0;
for i in 0..5 {
let byte = self.get_u8()?;
val |= (u32::from(byte) & 0x7F) << (i * 7);
if byte & 0x80 == 0 {
return Ok(val);
}
}
Err(Error::VarIntTooLarge)
}
fn get_var_i32(&mut self) -> Result<i32> {
let val = self.get_var_u32()?;
Ok(((val >> 1) as i32) ^ -((val as i32) & 1))
}
fn get_var_u64(&mut self) -> Result<u64> {
let mut val = 0;
for i in 0..10 {
let byte = self.get_u8()?;
val |= (u64::from(byte) & 0x7F) << (i * 7);
if byte & 0x80 == 0 {
return Ok(val);
}
}
Err(Error::VarLongTooLarge)
}
fn get_var_i64(&mut self) -> Result<i64> {
let val = self.get_var_u64()?;
Ok(((val >> 1) as i64) ^ -((val as i64) & 1))
}
fn get_string_len(&mut self) -> Result<u32> {
self.get_var_u32()
}
}
impl<'a, D: NbtDataSource<'a>> NbtReadHelper<'a> for NbtReadHelperBedrock<D> {
type Reader = D;
fn reader(&mut self) -> &mut D {
&mut self.reader
}
fn skip_string(&mut self) -> Result<()> {
let len = self.get_string_len()? as i64;
self.skip_bytes(len)
}
fn get_u8(&mut self) -> Result<u8> {
self.reader.read_u8()
}
fn get_i8(&mut self) -> Result<i8> {
Ok(self.reader.read_u8()? as i8)
}
fn get_i16(&mut self) -> Result<i16> {
let mut buf = [0u8; 2];
self.reader.read_bytes(&mut buf)?;
Ok(i16::from_le_bytes(buf))
}
fn get_i32(&mut self) -> Result<i32> {
self.get_var_i32()
}
fn get_i64(&mut self) -> Result<i64> {
self.get_var_i64()
}
fn get_f32(&mut self) -> Result<f32> {
let mut buf = [0u8; 4];
self.reader.read_bytes(&mut buf)?;
Ok(f32::from_le_bytes(buf))
}
fn get_f64(&mut self) -> Result<f64> {
let mut buf = [0u8; 8];
self.reader.read_bytes(&mut buf)?;
Ok(f64::from_le_bytes(buf))
}
fn get_string(&mut self) -> Result<Cow<'a, str>> {
let len = self.get_string_len()? as usize;
self.reader.read_string(len)
}
fn get_byte_array(&mut self, len: usize) -> Result<Cow<'a, [i8]>> {
self.reader.read_byte_array(len)
}
}
+241
View File
@@ -0,0 +1,241 @@
//! Reading, writing, and manipulating Minecraft's Named Binary Tag (NBT) data.
//!
//! The crate supports the standard Java Edition representation, unnamed network
//! NBT, Bedrock network NBT, and gzip-compressed NBT. Data is handled directly
//! via [`Nbt`], [`NbtCompound`], and [`NbtTag`].
use std::{
io::{self, Write},
ops::Deref,
};
use bytes::Bytes;
use deserializer::NbtReadHelper;
use serializer::{NbtWriteHelper, NbtWriteHelperBedrock, NbtWriteHelperJava};
use tag::NbtTag;
use thiserror::Error;
/// Compound-tag storage and construction helpers.
pub mod compound;
/// Low-level NBT deserialization support.
pub mod deserializer;
/// Reading and writing gzip-compressed NBT.
pub mod nbt_compress;
/// Integration with Pumpkin's dynamic codec operations.
pub mod nbt_ops;
/// Low-level NBT serialization support.
pub mod serializer;
/// The individual NBT tag types.
pub mod tag;
pub use compound::NbtCompound;
// This NBT crate is inspired from CrabNBT
/// Numeric identifier for an end tag.
pub const END_ID: u8 = 0x00;
/// Numeric identifier for a byte tag.
pub const BYTE_ID: u8 = 0x01;
/// Numeric identifier for a short tag.
pub const SHORT_ID: u8 = 0x02;
/// Numeric identifier for an integer tag.
pub const INT_ID: u8 = 0x03;
/// Numeric identifier for a long tag.
pub const LONG_ID: u8 = 0x04;
/// Numeric identifier for a float tag.
pub const FLOAT_ID: u8 = 0x05;
/// Numeric identifier for a double tag.
pub const DOUBLE_ID: u8 = 0x06;
/// Numeric identifier for a byte-array tag.
pub const BYTE_ARRAY_ID: u8 = 0x07;
/// Numeric identifier for a string tag.
pub const STRING_ID: u8 = 0x08;
/// Numeric identifier for a list tag.
pub const LIST_ID: u8 = 0x09;
/// Numeric identifier for a compound tag.
pub const COMPOUND_ID: u8 = 0x0A;
/// Numeric identifier for an integer-array tag.
pub const INT_ARRAY_ID: u8 = 0x0B;
/// Numeric identifier for a long-array tag.
pub const LONG_ARRAY_ID: u8 = 0x0C;
/// Maximum number of elements accepted when decoding a list or array.
pub const MAX_ARRAY_LENGTH: usize = 2_000_000;
/// Errors produced while reading, writing, or converting NBT data.
#[derive(Error, Debug)]
pub enum Error {
/// The root tag was not a compound tag and contains the reported tag ID.
#[error("The root tag of the NBT file is not a compound tag. Received tag id: {0}")]
NoRootCompound(u8),
/// A tag ID not defined by the NBT format was encountered.
#[error("Encountered an unknown NBT tag id: {0}.")]
UnknownTagId(u8),
/// A Java CESU-8 string could not be decoded.
#[error("Failed to Cesu 8 Decode")]
Cesu8DecodingError,
/// A string could not be decoded as UTF-8.
#[error("Failed to UTF-8 Decode")]
Utf8DecodingError,
/// Serde reported an invalid value or serializer state.
#[error("Serde error: {0}")]
SerdeError(String),
/// The requested Rust type has no NBT representation.
#[error("NBT doesn't support this type: {0}")]
UnsupportedType(String),
/// The underlying reader or writer returned an I/O error.
#[error("NBT reading was cut short: {0}")]
Incomplete(io::Error),
/// A list or array declared a negative element count.
#[error("Negative list length: {0}")]
NegativeLength(i32),
/// A string, list, or array exceeded the supported length.
#[error("Length too large: {0}")]
LargeLength(usize),
/// A Bedrock variable-length integer exceeded its maximum encoded size.
#[error("Failed to decode varint - value too large")]
VarIntTooLarge,
/// A Bedrock variable-length long exceeded its maximum encoded size.
#[error("Failed to decode varlong - value too large")]
VarLongTooLarge,
}
/// A complete NBT document containing a named root compound.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Nbt {
/// Name stored alongside the root compound.
pub name: String,
/// Root compound containing the document's tags.
pub root_tag: NbtCompound,
}
impl Nbt {
/// Creates a document from a root name and compound.
#[must_use]
pub const fn new(name: String, tag: NbtCompound) -> Self {
Self {
name,
root_tag: tag,
}
}
/// Reads a named NBT document from a format-specific reader.
///
/// Returns [`Error::NoRootCompound`] when the first tag is not a compound.
pub fn read<'a, R: NbtReadHelper<'a>>(reader: &mut R) -> Result<Self, Error> {
let tag_type_id = reader.get_u8()?;
if tag_type_id != COMPOUND_ID {
return Err(Error::NoRootCompound(tag_type_id));
}
Ok(Self {
name: reader.get_string()?.into_owned(),
root_tag: NbtCompound::deserialize_content(reader)?,
})
}
/// Reads an NBT document that omits the root compound's name.
///
/// The returned document has an empty [`Self::name`].
pub fn read_unnamed<'a, R: NbtReadHelper<'a>>(reader: &mut R) -> Result<Self, Error> {
let tag_type_id = reader.get_u8()?;
if tag_type_id != COMPOUND_ID {
return Err(Error::NoRootCompound(tag_type_id));
}
Ok(Self {
name: String::new(),
root_tag: NbtCompound::deserialize_content(reader)?,
})
}
/// Serializes this document using the Java Edition NBT representation.
#[must_use]
pub fn write(self) -> Bytes {
let mut bytes = Vec::new();
let mut writer = NbtWriteHelperJava::new(&mut bytes);
writer.write_u8(COMPOUND_ID).unwrap();
NbtTag::String(self.name.into())
.serialize_data(&mut writer)
.unwrap();
self.root_tag.serialize_content(&mut writer).unwrap();
bytes.into()
}
/// Serializes this document using the Bedrock network NBT representation.
#[must_use]
pub fn write_bedrock(self) -> Bytes {
let mut bytes = Vec::new();
let mut writer = NbtWriteHelperBedrock::new(&mut bytes);
writer.write_u8(COMPOUND_ID).unwrap();
NbtTag::String(self.name.into())
.serialize_data(&mut writer)
.unwrap();
self.root_tag.serialize_content(&mut writer).unwrap();
bytes.into()
}
/// Writes this document in the Java Edition representation.
pub fn write_to_writer<W: Write>(self, mut writer: W) -> Result<(), io::Error> {
writer.write_all(&self.write())?;
Ok(())
}
/// Writes this document in the Bedrock network representation.
pub fn write_to_writer_bedrock<W: Write>(self, mut writer: W) -> Result<(), io::Error> {
writer.write_all(&self.write_bedrock())?;
Ok(())
}
/// Serializes this document without the root compound's name.
#[must_use]
pub fn write_unnamed(self) -> Bytes {
let mut bytes = Vec::new();
let mut writer = NbtWriteHelperJava::new(&mut bytes);
writer.write_u8(COMPOUND_ID).unwrap();
self.root_tag.serialize_content(&mut writer).unwrap();
bytes.into()
}
/// Writes this document without the root compound's name.
pub fn write_unnamed_to_writer<W: Write>(self, mut writer: W) -> Result<(), io::Error> {
writer.write_all(&self.write_unnamed())?;
Ok(())
}
}
impl Deref for Nbt {
type Target = NbtCompound;
fn deref(&self) -> &Self::Target {
&self.root_tag
}
}
impl From<NbtCompound> for Nbt {
fn from(value: NbtCompound) -> Self {
Self::new(String::new(), value)
}
}
impl<T> AsRef<T> for Nbt
where
T: ?Sized,
<Self as Deref>::Target: AsRef<T>,
{
fn as_ref(&self) -> &T {
self.deref().as_ref()
}
}
impl AsMut<NbtCompound> for Nbt {
fn as_mut(&mut self) -> &mut NbtCompound {
&mut self.root_tag
}
}
+178
View File
@@ -0,0 +1,178 @@
//! Helpers for reading and writing gzip-compressed NBT data.
use crate::deserializer::NbtReadHelperJava;
use crate::{Error, Nbt, NbtCompound};
use flate2::{Compression, read::GzDecoder, write::GzEncoder};
use std::io::{Cursor, Read, Seek, Write};
/// Reads a gzip-compressed, named NBT compound from a seekable reader.
///
/// Decompressed data is limited to 64 MiB.
pub fn read_gzip_compound_tag(input: impl Read + Seek) -> Result<NbtCompound, Error> {
// Create a GZip decoder and directly chain it to the NBT reader
let mut decoder = GzDecoder::new(input).take(64 * 1024 * 1024); // 64 MB limit
let mut buf = Vec::new();
decoder.read_to_end(&mut buf).map_err(Error::Incomplete)?;
let mut reader = NbtReadHelperJava::new(Cursor::new(buf));
// Read the NBT data directly from the decoder stream
let nbt = Nbt::read(&mut reader)?;
Ok(nbt.root_tag)
}
/// Writes a named NBT compound with gzip compression.
///
/// The root name is written as an empty string.
pub fn write_gzip_compound_tag(compound: NbtCompound, output: impl Write) -> Result<(), Error> {
// Create a GZip encoder that writes to the output
let mut encoder = GzEncoder::new(output, Compression::default());
// Create an NBT wrapper and write directly to the encoder
let nbt = Nbt::new(String::new(), compound);
nbt.write_to_writer(&mut encoder)
.map_err(Error::Incomplete)?;
// Finish the encoder to ensure all data is written
encoder.finish().map_err(Error::Incomplete)?;
Ok(())
}
/// Serializes a named NBT compound into a gzip-compressed byte vector.
///
/// The root name is written as an empty string.
pub fn write_gzip_compound_tag_to_bytes(compound: NbtCompound) -> Result<Vec<u8>, Error> {
let mut buffer = Vec::new();
write_gzip_compound_tag(compound, &mut buffer)?;
Ok(buffer)
}
#[cfg(test)]
mod tests {
use crate::{
NbtCompound,
nbt_compress::{
read_gzip_compound_tag, write_gzip_compound_tag, write_gzip_compound_tag_to_bytes,
},
tag::NbtTag,
};
use std::fs::File;
use std::io::Cursor;
#[test]
fn gzip_read_write_compound() {
// Create a test compound
let mut compound = NbtCompound::new();
compound.put_byte("byte_value", 123);
compound.put_short("short_value", 12345);
compound.put_int("int_value", 1234567);
compound.put_long("long_value", 123456789);
compound.put_float("float_value", 123.456);
compound.put_double("double_value", 123456.789);
compound.put("bool_value", true);
compound.put("string_value", NbtTag::String("test string".into()));
// Create a nested compound
let mut nested = NbtCompound::new();
nested.put_int("nested_int", 42);
compound.put_compound("nested_compound", nested);
// Write to GZip using streaming
let mut buffer = Vec::new();
write_gzip_compound_tag(compound, &mut buffer).expect("Failed to compress compound");
// Read from GZip using streaming
let read_compound =
read_gzip_compound_tag(Cursor::new(&buffer)).expect("Failed to decompress compound");
// Verify values
assert_eq!(read_compound.get_byte("byte_value"), Some(123));
assert_eq!(read_compound.get_short("short_value"), Some(12345));
assert_eq!(read_compound.get_int("int_value"), Some(1234567));
assert_eq!(read_compound.get_long("long_value"), Some(123456789));
assert_eq!(read_compound.get_float("float_value"), Some(123.456));
assert_eq!(read_compound.get_double("double_value"), Some(123456.789));
assert_eq!(read_compound.get_bool("bool_value"), Some(true));
assert_eq!(
read_compound.get_string("string_value"),
Some("test string")
);
// Verify nested compound
if let Some(nested) = read_compound.get_compound("nested_compound") {
assert_eq!(nested.get_int("nested_int"), Some(42));
} else {
panic!("Failed to retrieve nested compound");
}
}
#[test]
fn gzip_convenience_methods() {
// Create a test compound
let mut compound = NbtCompound::new();
compound.put_int("test_value", 12345);
// Test convenience method for writing
let buffer =
write_gzip_compound_tag_to_bytes(compound).expect("Failed to compress compound");
// Test streaming read from the buffer
let read_compound =
read_gzip_compound_tag(Cursor::new(buffer)).expect("Failed to decompress compound");
assert_eq!(read_compound.get_int("test_value"), Some(12345));
}
#[test]
fn gzip_empty_compound() {
let compound = NbtCompound::new();
let mut buffer = Vec::new();
write_gzip_compound_tag(compound, &mut buffer).expect("Failed to compress empty compound");
let read_compound = read_gzip_compound_tag(Cursor::new(buffer))
.expect("Failed to decompress empty compound");
assert_eq!(read_compound.child_tags.len(), 0);
}
#[test]
fn gzip_large_compound() {
let mut compound = NbtCompound::new();
// Add 1000 integer entries
for i in 0..1000 {
compound.put_int(&format!("value_{i}"), i);
}
let mut buffer = Vec::new();
write_gzip_compound_tag(compound, &mut buffer).expect("Failed to compress large compound");
let read_compound = read_gzip_compound_tag(Cursor::new(buffer))
.expect("Failed to decompress large compound");
assert_eq!(read_compound.child_tags.len(), 1000);
// Verify a few entries
assert_eq!(read_compound.get_int("value_0"), Some(0));
assert_eq!(read_compound.get_int("value_500"), Some(500));
assert_eq!(read_compound.get_int("value_999"), Some(999));
}
#[test]
fn direct_file_io() {
use tempfile::tempdir;
let temp_dir = tempdir().expect("Failed to create temporary directory");
let file_path = temp_dir.path().join("test_compound.dat");
let mut compound = NbtCompound::new();
compound.put_int("test_value", 42);
let file = File::create(&file_path).expect("Failed to create temp file");
write_gzip_compound_tag(compound, file).expect("Failed to write compound to file");
let file = File::open(&file_path).expect("Failed to open temp file");
let read_compound =
read_gzip_compound_tag(file).expect("Failed to read compound from file");
assert_eq!(read_compound.get_int("test_value"), Some(42));
}
}
+727
View File
@@ -0,0 +1,727 @@
//! NBT support for Pumpkin's dynamic serialization operations.
use crate::compound::NbtCompound;
use crate::tag::NbtTag;
use pumpkin_codecs::DataResult;
use pumpkin_codecs::DynamicOps;
use pumpkin_codecs::Lifecycle;
use pumpkin_codecs::MapLike;
use pumpkin_codecs::Number;
use pumpkin_codecs::struct_builder::{ResultStructBuilder, StringStructBuilder, StructBuilder};
use pumpkin_codecs::{impl_get_list, impl_string_struct_builder, impl_struct_builder};
use std::iter::Map;
use std::vec::IntoIter;
use tracing::warn;
/// A [`DynamicOps`] implementation that represents values as [`NbtTag`]s.
pub struct NbtOps;
impl DynamicOps for NbtOps {
type Value = NbtTag;
type StructBuilder = NbtStructBuilder;
fn empty(&self) -> Self::Value {
NbtTag::End
}
fn create_number(&self, n: Number) -> Self::Value {
NbtTag::Double(n.into())
}
fn create_byte(&self, data: i8) -> Self::Value {
NbtTag::Byte(data)
}
fn create_short(&self, data: i16) -> Self::Value {
NbtTag::Short(data)
}
fn create_int(&self, data: i32) -> Self::Value {
NbtTag::Int(data)
}
fn create_long(&self, data: i64) -> Self::Value {
NbtTag::Long(data)
}
fn create_float(&self, data: f32) -> Self::Value {
NbtTag::Float(data)
}
fn create_double(&self, data: f64) -> Self::Value {
NbtTag::Double(data)
}
fn create_bool(&self, data: bool) -> Self::Value {
NbtTag::Byte(data.into())
}
fn create_string(&self, data: &str) -> Self::Value {
NbtTag::String(data.into())
}
fn create_list<I>(&self, values: I) -> Self::Value
where
I: IntoIterator<Item = Self::Value>,
{
ListCollector::new_collector().accept_all(values).result()
}
fn create_map<I>(&self, entries: I) -> Self::Value
where
I: IntoIterator<Item = (Self::Value, Self::Value)>,
{
let mut compound = NbtCompound::new();
for (k, v) in entries {
if let Some(key) = k.extract_string() {
compound.put(key, v);
} else {
// The Minecraft implementation just uses the string representation of the key tag,
// but that probably isn't meant to be intentionally used, so we will just
// log a warning.
warn!("Invalid key tag for creating NBT compound: {k}");
}
}
compound.into()
}
fn get_bool(&self, input: &Self::Value) -> DataResult<bool> {
self.get_number(input).map(|n| f64::from(n) != 0.0)
}
fn get_number(&self, input: &Self::Value) -> DataResult<Number> {
match input {
NbtTag::Byte(b) => DataResult::new_success(Number::Byte(*b)),
NbtTag::Short(s) => DataResult::new_success(Number::Short(*s)),
NbtTag::Int(i) => DataResult::new_success(Number::Int(*i)),
NbtTag::Long(l) => DataResult::new_success(Number::Long(*l)),
NbtTag::Float(f) => DataResult::new_success(Number::Float(*f)),
NbtTag::Double(d) => DataResult::new_success(Number::Double(*d)),
_ => DataResult::new_error("Not a number".to_string()),
}
}
fn get_string(&self, input: &Self::Value) -> DataResult<String> {
input.extract_string().map_or_else(
|| DataResult::new_error("Not a string".to_string()),
|s| DataResult::new_success(s.to_string()),
)
}
fn get_map_iter<'a>(
&'a self,
input: &'a Self::Value,
) -> DataResult<impl Iterator<Item = (Self::Value, &'a Self::Value)> + 'a> {
if let NbtTag::Compound(compound) = input {
DataResult::new_success(
compound
.child_tags
.iter()
.map(|(k, v)| (self.create_string(k), v)),
)
} else {
DataResult::new_error(format!("Not a map: {input}"))
}
}
fn get_map<'a>(
&self,
input: &'a Self::Value,
) -> DataResult<impl MapLike<Value = Self::Value> + 'a> {
if let NbtTag::Compound(compound) = input {
DataResult::new_success(NbtMapLike { compound })
} else {
DataResult::new_error(format!("Not a map: {input}"))
}
}
fn get_iter(&self, input: Self::Value) -> DataResult<impl Iterator<Item = Self::Value>> {
match input {
NbtTag::List(l) => {
// Check the type of this list.
// If the list contains compounds, we try unwrapping them.
if !l.is_empty()
&& let NbtTag::Compound(_) = l.first().unwrap()
{
DataResult::new_success(NbtIter::CompoundList(l.into_iter().map(|c| {
if let NbtTag::Compound(compound) = c {
Self::try_unwrap(compound)
} else {
c.clone()
}
})))
} else {
DataResult::new_success(NbtIter::List(l.into_iter()))
}
}
NbtTag::ByteArray(b) => DataResult::new_success(NbtIter::ByteArray(
b.into_iter().map(|b| Self.create_byte(b)),
)),
NbtTag::IntArray(i) => DataResult::new_success(NbtIter::IntArray(
i.into_iter().map(|i| Self.create_int(i)),
)),
NbtTag::LongArray(l) => DataResult::new_success(NbtIter::LongArray(
l.into_iter().map(|l| Self.create_long(l)),
)),
_ => DataResult::new_error(format!("Not a list: {input}")),
}
}
fn get_byte_list(&self, input: Self::Value) -> DataResult<Vec<i8>> {
if let NbtTag::ByteArray(b) = input {
DataResult::new_success(b.into())
} else {
impl_get_list!(self, input, "bytes")
}
}
fn create_byte_list(&self, buffer: Vec<i8>) -> Self::Value {
NbtTag::ByteArray(buffer.into())
}
fn get_int_list(&self, input: Self::Value) -> DataResult<Vec<i32>> {
if let NbtTag::IntArray(i) = input {
DataResult::new_success(i)
} else {
impl_get_list!(self, input, "ints")
}
}
fn create_int_list(&self, list: Vec<i32>) -> Self::Value {
NbtTag::IntArray(list)
}
fn get_long_list(&self, input: Self::Value) -> DataResult<Vec<i64>> {
if let NbtTag::LongArray(i) = input {
DataResult::new_success(i)
} else {
impl_get_list!(self, input, "longs")
}
}
fn create_long_list(&self, list: Vec<i64>) -> Self::Value {
NbtTag::LongArray(list)
}
fn merge_into_list(&self, list: Self::Value, value: Self::Value) -> DataResult<Self::Value> {
ListCollector::new(list.clone()).map_or_else(
|| DataResult::new_partial_error("Not a list".to_string(), list),
|c| DataResult::new_success(c.accept(value).result()),
)
}
fn merge_values_into_list<I>(&self, list: Self::Value, values: I) -> DataResult<Self::Value>
where
I: IntoIterator<Item = Self::Value>,
{
ListCollector::new(list.clone()).map_or_else(
|| DataResult::new_partial_error("Not a list".to_string(), list),
|c| DataResult::new_success(c.accept_all(values).result()),
)
}
fn merge_into_map(
&self,
map: Self::Value,
key: Self::Value,
value: Self::Value,
) -> DataResult<Self::Value>
where
Self::Value: Clone,
{
if !matches!(map, NbtTag::Compound(_) | NbtTag::End) {
DataResult::new_partial_error(format!("Not a map: {map}"), map)
} else if !matches!(key, NbtTag::String(_)) {
DataResult::new_partial_error(format!("Key is not a string: {key}"), map)
} else {
let mut compound = if let NbtTag::Compound(c) = map {
c
} else {
NbtCompound::new()
};
compound.put(key.extract_string().unwrap(), value);
DataResult::new_success(compound.into())
}
}
fn merge_map_like_into_map<M>(
&self,
map: Self::Value,
other_map_like: M,
) -> DataResult<Self::Value>
where
M: MapLike<Value = Self::Value>,
Self::Value: Clone,
{
if matches!(map, NbtTag::Compound(_) | NbtTag::End) {
let mut compound = if let NbtTag::Compound(c) = map {
c
} else {
NbtCompound::default()
};
let mut failed = vec![];
other_map_like.iter().for_each(|(k, v)| {
if let NbtTag::String(key) = k {
compound.put(&key, v.clone());
} else {
failed.push((k, v));
}
});
if failed.is_empty() {
DataResult::new_success(compound.into())
} else {
DataResult::new_partial_error(
format!("Some keys are not strings: {failed:?}"),
NbtTag::Compound(compound),
)
}
} else {
DataResult::new_partial_error(format!("Not a map: {map}"), map)
}
}
fn remove(&self, input: Self::Value, key: &str) -> Self::Value {
if let NbtTag::Compound(compound) = input {
// Try to remove any entries whose key matches with `key`.
NbtTag::Compound(
compound
.child_tags
.into_iter()
.filter(|s| s.0.as_ref() != key)
.collect(),
)
} else {
input
}
}
fn convert_to<U>(&self, out_ops: &impl DynamicOps<Value = U>, input: Self::Value) -> U {
match input {
NbtTag::End => out_ops.empty(),
NbtTag::Byte(b) => out_ops.create_byte(b),
NbtTag::Short(s) => out_ops.create_short(s),
NbtTag::Int(i) => out_ops.create_int(i),
NbtTag::Long(l) => out_ops.create_long(l),
NbtTag::Float(f) => out_ops.create_float(f),
NbtTag::Double(d) => out_ops.create_double(d),
NbtTag::ByteArray(b) => out_ops.create_byte_list(b.to_vec()),
NbtTag::String(s) => out_ops.create_string(&s),
NbtTag::List(_) => self.convert_list(out_ops, input),
NbtTag::Compound(_) => self.convert_map(out_ops, input),
NbtTag::IntArray(i) => out_ops.create_int_list(i),
NbtTag::LongArray(l) => out_ops.create_long_list(l),
}
}
fn map_builder(&'static self) -> Self::StructBuilder {
NbtStructBuilder {
builder: DataResult::new_success_with_lifecycle(
NbtTag::Compound(NbtCompound::new()),
Lifecycle::Stable,
),
}
}
}
impl NbtOps {
/// Tries to unwrap an [`NbtCompound`].
///
/// If `compound` only has one element with an empty key (`""`), it returns that element.
/// Otherwise, this simply returns a new [`NbtTag::Compound`] with `compound`.
fn try_unwrap(mut compound: NbtCompound) -> NbtTag {
if compound.child_tags.len() == 1 && compound.has("") {
// Remove the element to own the contained tag.
compound.child_tags.remove("").unwrap()
} else {
NbtTag::from(compound)
}
}
}
/// A single concrete type for an iterator of an NBT element.
enum NbtIter {
List(IntoIter<NbtTag>),
CompoundList(Map<IntoIter<NbtTag>, fn(NbtTag) -> NbtTag>),
ByteArray(Map<IntoIter<i8>, fn(i8) -> NbtTag>),
IntArray(Map<IntoIter<i32>, fn(i32) -> NbtTag>),
LongArray(Map<IntoIter<i64>, fn(i64) -> NbtTag>),
}
impl Iterator for NbtIter {
type Item = NbtTag;
fn next(&mut self) -> Option<Self::Item> {
match self {
Self::List(iter) => iter.next(),
Self::CompoundList(iter) => iter.next(),
Self::ByteArray(iter) => iter.next(),
Self::IntArray(iter) => iter.next(),
Self::LongArray(iter) => iter.next(),
}
}
}
/// An implementation of [`MapLike`] for NBT objects.
/// The lifetime is that of the referenced map.
struct NbtMapLike<'a> {
compound: &'a NbtCompound,
}
impl MapLike for NbtMapLike<'_> {
type Value = NbtTag;
fn get(&self, key: &Self::Value) -> Option<&Self::Value> {
key.extract_string().and_then(|s| self.get_str(s))
}
fn get_str(&self, key: &str) -> Option<&Self::Value> {
self.compound.get(key)
}
fn iter(&self) -> impl Iterator<Item = (Self::Value, &Self::Value)> + '_ {
self.compound
.child_tags
.iter()
.map(|(k, v)| (NbtTag::String(k.clone()), v))
}
}
/// Builds NBT compounds for the [`NbtOps`] dynamic codec implementation.
pub struct NbtStructBuilder {
builder: DataResult<NbtTag>,
}
impl ResultStructBuilder for NbtStructBuilder {
type Result = NbtTag;
fn build_with_builder(
self,
builder: Self::Result,
prefix: Self::Value,
) -> DataResult<Self::Value> {
match prefix {
NbtTag::End => DataResult::new_success(builder),
NbtTag::Compound(mut compound) => {
match builder {
NbtTag::Compound(builder_compound) => {
for (k, v) in builder_compound {
compound.put(&k, v);
}
}
// This shouldn't happen, but just in case.
_ => {
return DataResult::new_error(format!(
"Expected compound in builder, found {builder}"
));
}
}
DataResult::new_success(compound.into())
}
_ => DataResult::new_partial_error(format!("Prefix is not a map: {prefix}"), prefix),
}
}
}
impl StructBuilder for NbtStructBuilder {
type Value = NbtTag;
impl_struct_builder!(builder);
impl_string_struct_builder!(builder, NbtOps);
}
impl StringStructBuilder for NbtStructBuilder {
fn append(&self, key: &str, value: Self::Value, builder: Self::Result) -> Self::Result {
if let NbtTag::Compound(mut compound) = builder {
compound.put(key, value);
compound.into()
} else {
builder
}
}
}
// List collectors
/// A collector object for NBT lists.
///
/// The variants of this object should not be used as that is an implementation detail.
enum ListCollector {
Generic(InnerGenericListCollector),
Byte(InnerByteListCollector),
Int(InnerIntListCollector),
Long(InnerLongListCollector),
}
impl ListCollector {
/// Creates a new [`ListCollector`].
///
/// This only returns an actual collector for [`NbtTag::End`] and all list [`NbtTag`]s.
fn new(tag: NbtTag) -> Option<Self> {
match tag {
NbtTag::End => Some(Self::new_collector()),
NbtTag::List(_) | NbtTag::ByteArray(_) | NbtTag::IntArray(_) | NbtTag::LongArray(_) => {
// Try to get the length of the tag.
let len = match &tag {
NbtTag::List(list) => list.len(),
NbtTag::ByteArray(list) => list.len(),
NbtTag::IntArray(list) => list.len(),
NbtTag::LongArray(list) => list.len(),
_ => return None,
};
if len == 0 {
return Some(Self::new_collector());
}
// From this point onwards, we know that the list is not empty.
match tag {
NbtTag::List(list) => Some(Self::Generic(InnerGenericListCollector::new(list))),
NbtTag::ByteArray(list) => {
Some(Self::Byte(InnerByteListCollector::new(list.into())))
}
NbtTag::IntArray(list) => Some(Self::Int(InnerIntListCollector::new(list))),
NbtTag::LongArray(list) => Some(Self::Long(InnerLongListCollector::new(list))),
_ => None,
}
}
_ => None,
}
}
/// Creates a new initial collector.
/// [`NbtTag`]s can directly be added to this collector without any type worries.
const fn new_collector() -> Self {
Self::Generic(InnerGenericListCollector {
result: NbtTag::List(vec![]),
})
}
/// Accepts an [`NbtTag`].
fn accept(self, tag: NbtTag) -> Self {
match self {
Self::Generic(c) => c.accept(tag),
Self::Byte(c) => c.accept(tag),
Self::Int(c) => c.accept(tag),
Self::Long(c) => c.accept(tag),
}
}
/// Accepts all [`NbtTag`]s of the provided list.
fn accept_all(self, tags: impl IntoIterator<Item = NbtTag>) -> Self {
let mut collector = self;
for tag in tags {
collector = collector.accept(tag);
}
collector
}
/// Provides the final result.
fn result(self) -> NbtTag {
match self {
Self::Generic(c) => c.result(),
Self::Byte(c) => c.result(),
Self::Int(c) => c.result(),
Self::Long(c) => c.result(),
}
}
}
/// An 'inner' list collector stored in one of the corresponding [`ListCollector`] enums.
trait InnerListCollector {
fn accept(self, tag: NbtTag) -> ListCollector
where
Self: Sized;
fn result(self) -> NbtTag;
}
/// An implementation of [`InnerListCollector`] for a generic list (of any type).
struct InnerGenericListCollector {
result: NbtTag,
}
impl InnerListCollector for InnerGenericListCollector {
fn accept(mut self, tag: NbtTag) -> ListCollector
where
Self: Sized,
{
if let NbtTag::List(list) = &mut self.result {
list.push(tag);
}
ListCollector::Generic(self)
}
fn result(self) -> NbtTag {
self.result
}
}
impl From<InnerByteListCollector> for InnerGenericListCollector {
fn from(value: InnerByteListCollector) -> Self {
Self {
result: NbtTag::List(value.list.into_iter().map(NbtTag::Byte).collect()),
}
}
}
impl InnerGenericListCollector {
const fn new(list: Vec<NbtTag>) -> Self {
Self {
result: NbtTag::List(list),
}
}
}
/// An implementation of [`InnerListCollector`] specifically for [`NbtTag::ByteArray`]s.
struct InnerByteListCollector {
list: Vec<i8>,
}
impl InnerListCollector for InnerByteListCollector {
fn accept(mut self, tag: NbtTag) -> ListCollector
where
Self: Sized,
{
if let NbtTag::Byte(byte) = tag {
self.list.push(byte);
ListCollector::Byte(self)
} else {
<Self as Into<InnerGenericListCollector>>::into(self).accept(tag)
}
}
fn result(self) -> NbtTag {
NbtTag::ByteArray(self.list.into())
}
}
impl InnerByteListCollector {
const fn new(list: Vec<i8>) -> Self {
Self { list }
}
}
macro_rules! add_inner_specific_array_collector_impl {
($name:ident, $single_type:ident, $array_type:ident, $ty:ty) => {
#[doc = concat!("An implementation of [`InnerListCollector`] specifically for [`NbtTag::", stringify!($array_type), "`]s.")]
struct $name {
list: Vec<$ty>
}
impl InnerListCollector for $name {
fn accept(mut self, tag: NbtTag) -> ListCollector
where
Self: Sized
{
if let NbtTag::$single_type(v) = tag {
self.list.push(v);
ListCollector::$single_type(self)
} else {
<Self as Into<InnerGenericListCollector>>::into(self)
.accept(tag)
}
}
fn result(self) -> NbtTag {
NbtTag::$array_type(self.list)
}
}
impl $name {
const fn new(list: Vec<$ty>) -> Self {
Self {
list
}
}
}
impl From<$name> for InnerGenericListCollector {
fn from(value: $name) -> Self {
InnerGenericListCollector {
result: NbtTag::List(
value.list.into_iter().map(|b| NbtTag::$single_type(b)).collect()
)
}
}
}
};
}
add_inner_specific_array_collector_impl!(InnerIntListCollector, Int, IntArray, i32);
add_inner_specific_array_collector_impl!(InnerLongListCollector, Long, LongArray, i64);
#[cfg(test)]
mod test {
use crate::nbt_ops::ListCollector;
use crate::tag::NbtTag;
#[test]
fn list_collecting() {
// Int list collector
let tag = NbtTag::IntArray(vec![10, 15, 20]);
assert_eq!(
ListCollector::new(tag)
.expect("List collector should exist")
.result(),
NbtTag::IntArray(vec![10, 15, 20])
);
// Byte list collector
let tag = NbtTag::ByteArray(vec![-1, 45, 100].into());
assert_eq!(
ListCollector::new(tag)
.expect("List collector should exist")
.result(),
NbtTag::ByteArray(vec![-1, 45, 100].into())
);
// Long list
let tag = NbtTag::LongArray(vec![11_234_567_890, -986, 1, -937_238_122]);
assert_eq!(
ListCollector::new(tag)
.expect("List collector should exist")
.result(),
NbtTag::LongArray(vec![11_234_567_890, -986, 1, -937_238_122])
);
// Generic list collector
// Homogeneous elements
let mut collector = ListCollector::new_collector();
collector = collector.accept(NbtTag::Float(-123.4));
collector = collector.accept(NbtTag::Float(12.5));
assert_eq!(
collector.result(),
NbtTag::List(vec![NbtTag::Float(-123.4), NbtTag::Float(12.5)])
);
// Heterogeneous elements
let mut collector = ListCollector::new_collector();
collector = collector.accept(NbtTag::Byte(99));
collector = collector.accept(NbtTag::String("99".into()));
collector = collector.accept(NbtTag::LongArray(vec![1, 2, 3]));
assert_eq!(
collector.result(),
NbtTag::List(vec![
NbtTag::Byte(99),
NbtTag::String("99".into()),
NbtTag::LongArray(vec![1, 2, 3])
])
);
}
}
+197
View File
@@ -0,0 +1,197 @@
use std::io::Write;
use crate::Error;
/// Result type returned by NBT serialization operations.
pub type Result<T> = std::result::Result<T, Error>;
macro_rules! define_write_number_be {
($name:ident, $type:ty) => {
fn $name(&mut self, value: $type) -> Result<()> {
let buf = value.to_be_bytes();
self.writer.write_all(&buf).map_err(Error::Incomplete)?;
Ok(())
}
};
}
macro_rules! define_write_number_le {
($name:ident, $type:ty) => {
fn $name(&mut self, value: $type) -> Result<()> {
let buf = value.to_le_bytes();
self.writer.write_all(&buf).map_err(Error::Incomplete)?;
Ok(())
}
};
}
/// Format-specific primitive writer used by the NBT serializer.
pub trait NbtWriteHelper {
/// Underlying output writer.
type Writer: Write;
/// Returns the underlying output writer.
fn writer(&mut self) -> &mut Self::Writer;
/// Writes an unsigned byte.
fn write_u8(&mut self, value: u8) -> Result<()>;
/// Writes a signed byte.
fn write_i8(&mut self, value: i8) -> Result<()>;
/// Writes a 16-bit signed integer.
fn write_i16(&mut self, value: i16) -> Result<()>;
/// Writes a 32-bit signed integer.
fn write_i32(&mut self, value: i32) -> Result<()>;
/// Writes a 64-bit signed integer.
fn write_i64(&mut self, value: i64) -> Result<()>;
/// Writes a 32-bit floating-point number.
fn write_f32(&mut self, value: f32) -> Result<()>;
/// Writes a 64-bit floating-point number.
fn write_f64(&mut self, value: f64) -> Result<()>;
/// Writes a length-prefixed string.
fn write_string(&mut self, value: &str) -> Result<()>;
/// Writes an unmodified byte slice.
fn write_slice(&mut self, value: &[u8]) -> Result<()> {
self.writer().write_all(value).map_err(Error::Incomplete)?;
Ok(())
}
}
/// Writes Java Edition NBT primitives using big-endian numeric encoding.
pub struct NbtWriteHelperJava<W: Write> {
writer: W,
}
impl<W: Write> NbtWriteHelperJava<W> {
/// Creates a Java Edition writer over `w`.
pub const fn new(w: W) -> Self {
Self { writer: w }
}
}
impl<W: Write> NbtWriteHelperJava<W> {
define_write_number_be!(write_string_len, u16);
}
impl<W: Write> NbtWriteHelper for NbtWriteHelperJava<W> {
type Writer = W;
fn writer(&mut self) -> &mut Self::Writer {
&mut self.writer
}
define_write_number_be!(write_u8, u8);
define_write_number_be!(write_i8, i8);
define_write_number_be!(write_i16, i16);
define_write_number_be!(write_i32, i32);
define_write_number_be!(write_i64, i64);
define_write_number_be!(write_f32, f32);
define_write_number_be!(write_f64, f64);
fn write_string(&mut self, value: &str) -> Result<()> {
let java_string = cesu8::to_java_cesu8(value);
let len = java_string.len();
if len > u16::MAX as usize {
return Err(Error::LargeLength(len));
}
self.write_string_len(len as u16)?;
self.writer
.write_all(&java_string)
.map_err(Error::Incomplete)?;
Ok(())
}
}
/// Writes Bedrock network NBT primitives using little-endian and variable-length encoding.
pub struct NbtWriteHelperBedrock<W: Write> {
writer: W,
}
impl<W: Write> NbtWriteHelperBedrock<W> {
/// Creates a Bedrock network writer over `w`.
pub const fn new(w: W) -> Self {
Self { writer: w }
}
}
impl<W: Write> NbtWriteHelperBedrock<W> {
fn write_var_u32(&mut self, mut value: u32) -> Result<()> {
// LEB128
loop {
let mut byte = (value & 0x7F) as u8;
value >>= 7;
if value != 0 {
byte |= 0x80;
}
self.write_u8(byte)?;
if value == 0 {
break;
}
}
Ok(())
}
fn write_var_i32(&mut self, value: i32) -> Result<()> {
// ZigZag
self.write_var_u32(((value << 1) ^ (value >> 31)) as u32)
}
fn write_var_u64(&mut self, mut value: u64) -> Result<()> {
// LEB128
loop {
let mut byte = (value & 0x7F) as u8;
value >>= 7;
if value != 0 {
byte |= 0x80;
}
self.write_u8(byte)?;
if value == 0 {
break;
}
}
Ok(())
}
fn write_var_i64(&mut self, value: i64) -> Result<()> {
// ZigZag
self.write_var_u64(((value << 1) ^ (value >> 63)) as u64)
}
fn write_string_len(&mut self, value: u32) -> Result<()> {
self.write_var_u32(value)
}
}
impl<W: Write> NbtWriteHelper for NbtWriteHelperBedrock<W> {
type Writer = W;
fn writer(&mut self) -> &mut Self::Writer {
&mut self.writer
}
define_write_number_le!(write_u8, u8);
define_write_number_le!(write_i8, i8);
define_write_number_le!(write_i16, i16);
fn write_i32(&mut self, value: i32) -> Result<()> {
self.write_var_i32(value)
}
fn write_i64(&mut self, value: i64) -> Result<()> {
self.write_var_i64(value)
}
define_write_number_le!(write_f32, f32);
define_write_number_le!(write_f64, f64);
fn write_string(&mut self, value: &str) -> Result<()> {
let bedrock_string = value.as_bytes();
let len = bedrock_string.len();
if len > u32::MAX as usize {
return Err(Error::LargeLength(len));
}
self.write_string_len(len as u32)?;
self.writer
.write_all(bedrock_string)
.map_err(Error::Incomplete)?;
Ok(())
}
}
+516
View File
@@ -0,0 +1,516 @@
//! The in-memory representation of individual NBT tags.
use compound::NbtCompound;
use deserializer::NbtReadHelper;
use serializer::NbtWriteHelper;
use crate::{
BYTE_ARRAY_ID, BYTE_ID, COMPOUND_ID, DOUBLE_ID, END_ID, Error, FLOAT_ID, INT_ARRAY_ID, INT_ID,
LIST_ID, LONG_ARRAY_ID, LONG_ID, MAX_ARRAY_LENGTH, SHORT_ID, STRING_ID, compound, deserializer,
serializer,
};
/// A value represented by one of the tag types defined by the NBT format.
#[derive(Clone, Debug, PartialEq)]
#[repr(u8)]
pub enum NbtTag {
/// Marks the end of a compound.
End = END_ID,
/// An 8-bit signed integer.
Byte(i8) = BYTE_ID,
/// A 16-bit signed integer.
Short(i16) = SHORT_ID,
/// A 32-bit signed integer.
Int(i32) = INT_ID,
/// A 64-bit signed integer.
Long(i64) = LONG_ID,
/// A 32-bit floating-point number.
Float(f32) = FLOAT_ID,
/// A 64-bit floating-point number.
Double(f64) = DOUBLE_ID,
/// An array of 8-bit signed integers.
ByteArray(Box<[i8]>) = BYTE_ARRAY_ID,
/// A string.
String(Box<str>) = STRING_ID,
/// A sequence of tags.
List(Vec<Self>) = LIST_ID,
/// A map of named tags.
Compound(NbtCompound) = COMPOUND_ID,
/// An array of 32-bit signed integers.
IntArray(Vec<i32>) = INT_ARRAY_ID,
/// An array of 64-bit signed integers.
LongArray(Vec<i64>) = LONG_ARRAY_ID,
}
impl NbtTag {
/// Returns the numeric id associated with the data type.
#[must_use]
pub const fn get_type_id(&self) -> u8 {
// SAFETY: Since Self is repr(u8), it is guaranteed to hold the discriminant in the first byte
// See https://doc.rust-lang.org/reference/items/enumerations.html#pointer-casting
unsafe { *std::ptr::from_ref::<Self>(self).cast::<u8>() }
}
/// Serializes the tag's type ID followed by its payload.
pub fn serialize<W: NbtWriteHelper>(self, w: &mut W) -> serializer::Result<()> {
w.write_u8(self.get_type_id())?;
self.serialize_data(w)?;
Ok(())
}
/// Gets the element type of [`NbtTag::List`] the provided `Vec`
/// represents. If any elements in the `Vec` are found to be of
/// different types, this returns [`COMPOUND_ID`].
#[must_use]
fn get_list_element_type_id(list: &[Self]) -> u8 {
let mut element_id = END_ID;
for tag in list {
let id = tag.get_type_id();
if element_id == END_ID {
element_id = id;
} else if element_id != id {
return COMPOUND_ID;
}
}
element_id
}
/// Tries to unwrap (flatten) a wrapped `NbtTag`. If there is a wrapped tag, it is returned.
/// If no unwrap is possible, this returns the given tag.
fn flatten(tag: Self) -> Self {
if let Self::Compound(mut compound) = tag {
// Try to get the wrapped tag, stored by "".
if Self::is_wrapper_compound(&compound) {
compound.child_tags.remove("").unwrap()
} else {
Self::Compound(compound)
}
} else {
tag
}
}
/// Returns whether an [`NbtCompound`] is a wrapper compound.
///
/// A *wrapper compound* is a compound that stores exactly one
/// key-value pair, an empty string key (`""`) and an `NbtTag`.
fn is_wrapper_compound(compound: &NbtCompound) -> bool {
compound.child_tags.len() == 1 && compound.child_tags.contains_key("")
}
/// Wraps the provided tag if needed with the provided element type of list
/// the wrapped tag, if any, would be added to.
fn wrap_tag_if_needed(element_type: u8, tag: Self) -> Self {
if element_type == COMPOUND_ID {
if let Self::Compound(compound) = &tag
&& !Self::is_wrapper_compound(compound)
{
tag
} else {
Self::wrap_tag(tag)
}
} else {
tag
}
}
fn wrap_tag(tag: Self) -> Self {
let mut compound = NbtCompound::new();
compound.put("", tag);
Self::Compound(compound)
}
/// Serializes the tag payload without writing its type ID.
pub fn serialize_data<W: NbtWriteHelper>(self, w: &mut W) -> serializer::Result<()> {
match self {
Self::End => {}
Self::Byte(byte) => w.write_i8(byte)?,
Self::Short(short) => w.write_i16(short)?,
Self::Int(int) => w.write_i32(int)?,
Self::Long(long) => w.write_i64(long)?,
Self::Float(float) => w.write_f32(float)?,
Self::Double(double) => w.write_f64(double)?,
Self::ByteArray(byte_array) => {
let len = byte_array.len();
if len > i32::MAX as usize {
return Err(Error::LargeLength(len));
}
w.write_i32(len as i32)?;
for int in byte_array {
w.write_i8(int)?;
}
}
Self::String(string) => {
w.write_string(&string)?;
}
Self::List(list) => {
let len = list.len();
if len > i32::MAX as usize {
return Err(Error::LargeLength(len));
}
let list_element_id = Self::get_list_element_type_id(&list);
w.write_u8(list_element_id)?;
w.write_i32(len as i32)?;
for nbt_tag in list {
// Since tags in the same list tag must have the same type,
// we need to handle those of different tag types by
// wrapping them in `NbtCompound`s if needed.
Self::wrap_tag_if_needed(list_element_id, nbt_tag).serialize_data(w)?;
}
}
Self::Compound(compound) => {
compound.serialize_content(w)?;
}
Self::IntArray(int_array) => {
let len = int_array.len();
if len > i32::MAX as usize {
return Err(Error::LargeLength(len));
}
w.write_i32(len as i32)?;
for int in int_array {
w.write_i32(int)?;
}
}
Self::LongArray(long_array) => {
let len = long_array.len();
if len > i32::MAX as usize {
return Err(Error::LargeLength(len));
}
w.write_i32(len as i32)?;
for long in long_array {
w.write_i64(long)?;
}
}
}
Ok(())
}
/// Deserializes a type ID and its following payload.
pub fn deserialize<'a, R: NbtReadHelper<'a>>(reader: &mut R) -> Result<Self, Error> {
let tag_id = reader.get_u8()?;
Self::deserialize_data(reader, tag_id)
}
/// Advances a reader past the payload belonging to `tag_id`.
pub fn skip_data<'a, R: NbtReadHelper<'a>>(reader: &mut R, tag_id: u8) -> Result<(), Error> {
match tag_id {
END_ID => Ok(()),
BYTE_ID => reader.skip_i8(),
SHORT_ID => reader.skip_i16(),
INT_ID => reader.skip_i32(),
LONG_ID => reader.skip_i64(),
FLOAT_ID => reader.skip_f32(),
DOUBLE_ID => reader.skip_f64(),
BYTE_ARRAY_ID => {
let len = reader.get_i32()?;
if len < 0 {
return Err(Error::NegativeLength(len));
}
reader.skip_bytes(i64::from(len))
}
STRING_ID => reader.skip_string(),
LIST_ID => {
let tag_type_id = reader.get_u8()?;
let len = reader.get_i32()?;
if len < 0 {
return Err(Error::NegativeLength(len));
}
for _ in 0..len {
Self::skip_data(reader, tag_type_id)?;
}
Ok(())
}
COMPOUND_ID => NbtCompound::skip_content(reader),
INT_ARRAY_ID => {
let len = reader.get_i32()?;
if len < 0 {
return Err(Error::NegativeLength(len));
}
for _ in 0..len {
reader.skip_i32()?;
}
Ok(())
}
LONG_ARRAY_ID => {
let len = reader.get_i32()?;
if len < 0 {
return Err(Error::NegativeLength(len));
}
for _ in 0..len {
reader.skip_i64()?;
}
Ok(())
}
_ => Err(Error::UnknownTagId(tag_id)),
}
}
/// Deserializes a payload whose type is identified by `tag_id`.
pub fn deserialize_data<'a, R: NbtReadHelper<'a>>(
reader: &mut R,
tag_id: u8,
) -> Result<Self, Error> {
match tag_id {
END_ID => Ok(Self::End),
BYTE_ID => {
let byte = reader.get_i8()?;
Ok(Self::Byte(byte))
}
SHORT_ID => {
let short = reader.get_i16()?;
Ok(Self::Short(short))
}
INT_ID => {
let int = reader.get_i32()?;
Ok(Self::Int(int))
}
LONG_ID => {
let long = reader.get_i64()?;
Ok(Self::Long(long))
}
FLOAT_ID => {
let float = reader.get_f32()?;
Ok(Self::Float(float))
}
DOUBLE_ID => {
let double = reader.get_f64()?;
Ok(Self::Double(double))
}
BYTE_ARRAY_ID => {
let len = reader.get_i32()?;
if len < 0 {
return Err(Error::NegativeLength(len));
}
let len = len as usize;
if len > MAX_ARRAY_LENGTH {
return Err(Error::LargeLength(len));
}
let mut byte_array = Vec::with_capacity(len);
for _ in 0..len {
let byte = reader.get_i8()?;
byte_array.push(byte);
}
Ok(Self::ByteArray(byte_array.into()))
}
STRING_ID => Ok(Self::String(reader.get_string()?.into_owned().into())),
LIST_ID => {
let tag_type_id = reader.get_u8()?;
let len = reader.get_i32()?;
if len < 0 {
return Err(Error::NegativeLength(len));
}
let len = len as usize;
if len > MAX_ARRAY_LENGTH {
return Err(Error::LargeLength(len));
}
let mut list = Vec::with_capacity(len);
for _ in 0..len {
let tag = Self::deserialize_data(reader, tag_type_id)?;
assert_eq!(tag.get_type_id(), tag_type_id);
// Try unwrapping the tag.
list.push(Self::flatten(tag));
}
Ok(Self::List(list))
}
COMPOUND_ID => Ok(Self::Compound(NbtCompound::deserialize_content(reader)?)),
INT_ARRAY_ID => {
let len = reader.get_i32()?;
if len < 0 {
return Err(Error::NegativeLength(len));
}
let len = len as usize;
if len > MAX_ARRAY_LENGTH {
return Err(Error::LargeLength(len));
}
let mut int_array = Vec::with_capacity(len);
for _ in 0..len {
let int = reader.get_i32()?;
int_array.push(int);
}
Ok(Self::IntArray(int_array))
}
LONG_ARRAY_ID => {
let len = reader.get_i32()?;
if len < 0 {
return Err(Error::NegativeLength(len));
}
let len = len as usize;
if len > MAX_ARRAY_LENGTH {
return Err(Error::LargeLength(len));
}
let mut long_array = Vec::with_capacity(len);
for _ in 0..len {
let long = reader.get_i64()?;
long_array.push(long);
}
Ok(Self::LongArray(long_array))
}
_ => Err(Error::UnknownTagId(tag_id)),
}
}
/// Returns the contained byte, if this is a byte tag.
#[must_use]
pub const fn extract_byte(&self) -> Option<i8> {
match self {
Self::Byte(byte) => Some(*byte),
_ => None,
}
}
/// Returns the contained short, if this is a short tag.
#[must_use]
pub const fn extract_short(&self) -> Option<i16> {
match self {
Self::Short(short) => Some(*short),
_ => None,
}
}
/// Returns the contained integer, if this is an integer tag.
#[must_use]
pub const fn extract_int(&self) -> Option<i32> {
match self {
Self::Int(int) => Some(*int),
_ => None,
}
}
/// Returns the contained long, if this is a long tag.
#[must_use]
pub const fn extract_long(&self) -> Option<i64> {
match self {
Self::Long(long) => Some(*long),
_ => None,
}
}
/// Returns the contained float, if this is a float tag.
#[must_use]
pub const fn extract_float(&self) -> Option<f32> {
match self {
Self::Float(float) => Some(*float),
_ => None,
}
}
/// Returns the contained double, if this is a double tag.
#[must_use]
pub const fn extract_double(&self) -> Option<f64> {
match self {
Self::Double(double) => Some(*double),
_ => None,
}
}
/// Returns the contained byte as a boolean, where zero is `false`.
#[must_use]
pub fn extract_bool(&self) -> Option<bool> {
match self {
Self::Byte(byte) => Some(byte != &0),
_ => None,
}
}
/// Returns the contained byte array, if this is a byte-array tag.
#[must_use]
pub fn extract_byte_array(&self) -> Option<&[i8]> {
match self {
Self::ByteArray(byte_array) => Some(byte_array),
_ => None,
}
}
/// Returns the contained string, if this is a string tag.
#[must_use]
pub fn extract_string(&self) -> Option<&str> {
match self {
Self::String(string) => Some(string),
_ => None,
}
}
/// Returns the contained list, if this is a list tag.
#[must_use]
pub fn extract_list(&self) -> Option<&[Self]> {
match self {
Self::List(list) => Some(list),
_ => None,
}
}
/// Returns the contained compound, if this is a compound tag.
#[must_use]
pub const fn extract_compound(&self) -> Option<&NbtCompound> {
match self {
Self::Compound(compound) => Some(compound),
_ => None,
}
}
/// Returns the contained integer array, if this is an integer-array tag.
#[must_use]
pub fn extract_int_array(&self) -> Option<&[i32]> {
match self {
Self::IntArray(int_array) => Some(int_array),
_ => None,
}
}
/// Returns the contained long array, if this is a long-array tag.
#[must_use]
pub fn extract_long_array(&self) -> Option<&[i64]> {
match self {
Self::LongArray(long_array) => Some(long_array),
_ => None,
}
}
}
impl From<&str> for NbtTag {
fn from(value: &str) -> Self {
Self::String(value.into())
}
}
impl From<&[i8]> for NbtTag {
fn from(value: &[i8]) -> Self {
Self::ByteArray(value.into())
}
}
impl From<f32> for NbtTag {
fn from(value: f32) -> Self {
Self::Float(value)
}
}
impl From<f64> for NbtTag {
fn from(value: f64) -> Self {
Self::Double(value)
}
}
impl From<bool> for NbtTag {
fn from(value: bool) -> Self {
Self::Byte(i8::from(value))
}
}