diff --git a/crates/valence_anvil/src/lib.rs b/crates/valence_anvil/src/lib.rs index ee3081808..b48238de4 100644 --- a/crates/valence_anvil/src/lib.rs +++ b/crates/valence_anvil/src/lib.rs @@ -44,7 +44,7 @@ pub enum RegionError { #[error("invalid compression scheme number of {0}")] InvalidCompressionScheme(u8), #[error("failed to parse NBT: {0}")] - Nbt(#[from] valence_nbt::binary::Error), + Nbt(#[from] valence_nbt::Error), #[error("not all chunk NBT data was read")] TrailingNbtData, #[error("oversized chunk")] diff --git a/crates/valence_nbt/Cargo.toml b/crates/valence_nbt/Cargo.toml index 5252323fa..067a9841b 100644 --- a/crates/valence_nbt/Cargo.toml +++ b/crates/valence_nbt/Cargo.toml @@ -1,35 +1,39 @@ [package] name = "valence_nbt" -description = "Minecraft's Named Binary Tag (NBT) format." -readme = "README.md" -documentation = "https://docs.rs/valence_nbt/" -license.workspace = true -keywords = ["nbt", "minecraft", "serialization"] version = "0.8.0" +description = "Minecraft's Named Binary Tag (NBT) format." edition.workspace = true +license.workspace = true repository.workspace = true +keywords = ["nbt", "minecraft", "serialization"] +categories = ["data-structures", "game-development"] +rust-version = "1.78.0" -[lints] -workspace = true +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "docsrs"] [features] binary = ["dep:byteorder", "dep:cesu8"] java_string = ["dep:java_string"] snbt = [] -# When enabled, the order of fields in compounds are preserved. preserve_order = ["dep:indexmap"] serde = ["dep:serde", "dep:thiserror", "indexmap?/serde"] +valence_ident = ["dep:valence_ident"] [dependencies] -byteorder = { workspace = true, optional = true } -cesu8 = { workspace = true, optional = true } -indexmap = { workspace = true, optional = true } -java_string = { workspace = true, optional = true } -serde = { workspace = true, features = ["derive"], optional = true } -thiserror = { workspace = true, optional = true } -uuid = { workspace = true, optional = true } -valence_ident = { workspace = true, optional = true } +byteorder = { version = "1.5.0", optional = true } +cesu8 = { version = "1.1.0", optional = true } +indexmap = { version = "2.2.6", optional = true } +java_string = { version = "0.1.2", path = "../java_string", optional = true } +serde = { version = "1.0.200", features = ["derive"], optional = true } +thiserror = { version = "1.0.59", optional = true } +uuid = { version = "1.8.0", optional = true } +valence_ident = { version = "0.2.0-alpha.1", optional = true } [dev-dependencies] -pretty_assertions.workspace = true -serde_json.workspace = true +pretty_assertions = "1.4.0" +serde_json = "1.0.116" + +[lints] +workspace = true diff --git a/crates/valence_nbt/README.md b/crates/valence_nbt/README.md deleted file mode 100644 index 7d3e1f42e..000000000 --- a/crates/valence_nbt/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# valence_nbt - -A library for encoding and decoding Minecraft's [Named Binary Tag] (NBT) -format. - -[Named Binary Tag]: https://minecraft.wiki/w/NBT_format - -# Features -- `binary`: Adds support for serializing and deserializing in Java edition's binary format. -- `snbt`: Adds support for serializing and deserializing in "stringified" format. -- `preserve_order`: Causes the order of fields in [`Compound`]s to be -preserved during insertion and deletion at a slight cost to performance. -The iterators on `Compound` can then implement [`DoubleEndedIterator`]. -- `serde` Adds support for [`serde`](https://docs.rs/serde/latest/serde/) diff --git a/crates/valence_nbt/src/binary.rs b/crates/valence_nbt/src/binary.rs index d17f95a37..a9d62f73f 100644 --- a/crates/valence_nbt/src/binary.rs +++ b/crates/valence_nbt/src/binary.rs @@ -18,13 +18,13 @@ //! //! let mut buf = vec![]; //! -//! to_binary(&c, &mut buf, "").unwrap(); +//! to_binary(&mut buf, "", &c).unwrap(); //! ``` //! //! Decode NBT data from its binary form. //! //! ``` -//! use valence_nbt::{compound, from_binary, Compound}; +//! use valence_nbt::{compound, from_binary, Compound, Value}; //! //! let some_bytes = [10, 0, 0, 3, 0, 3, 105, 110, 116, 0, 0, 222, 173, 0]; //! @@ -32,22 +32,20 @@ //! "int" => 0xdead //! }; //! -//! let (nbt, root_name) = from_binary(&mut some_bytes.as_slice()).unwrap(); +//! let (root_name, nbt) = from_binary(&mut some_bytes.as_slice()).unwrap().unwrap(); //! -//! assert_eq!(nbt, expected_value); +//! assert_eq!(nbt, Value::from(expected_value)); //! assert_eq!(root_name, ""); //! ``` mod decode; mod encode; -mod error; mod modified_utf8; #[cfg(test)] mod tests; -pub use decode::{from_binary, FromModifiedUtf8, FromModifiedUtf8Error}; -pub use encode::{to_binary, written_size, ToModifiedUtf8}; -pub use error::*; +pub use decode::*; +pub use encode::*; use crate::Tag; diff --git a/crates/valence_nbt/src/binary/decode.rs b/crates/valence_nbt/src/binary/decode.rs index 607132084..4568449b1 100644 --- a/crates/valence_nbt/src/binary/decode.rs +++ b/crates/valence_nbt/src/binary/decode.rs @@ -4,9 +4,8 @@ use std::{fmt, mem}; use byteorder::{BigEndian, ReadBytesExt}; -use super::{Error, Result}; use crate::tag::Tag; -use crate::{Compound, List, Value}; +use crate::{Compound, Error, List, Result, Value}; /// Decodes uncompressed NBT binary data from the provided slice. /// diff --git a/crates/valence_nbt/src/binary/encode.rs b/crates/valence_nbt/src/binary/encode.rs index 8cc50b811..5ae84f755 100644 --- a/crates/valence_nbt/src/binary/encode.rs +++ b/crates/valence_nbt/src/binary/encode.rs @@ -4,10 +4,10 @@ use std::io::Write; use byteorder::{BigEndian, WriteBytesExt}; -use super::{modified_utf8, Error, Result}; +use super::modified_utf8; use crate::conv::i8_slice_as_u8_slice; use crate::tag::Tag; -use crate::{Compound, List, Value}; +use crate::{Compound, Error, List, Result, Value}; /// Encodes uncompressed NBT binary data to the provided writer. /// diff --git a/crates/valence_nbt/src/binary/modified_utf8.rs b/crates/valence_nbt/src/binary/modified_utf8.rs index 491745de5..9ee56f77b 100644 --- a/crates/valence_nbt/src/binary/modified_utf8.rs +++ b/crates/valence_nbt/src/binary/modified_utf8.rs @@ -17,7 +17,7 @@ pub(crate) fn write_modified_utf8(mut writer: impl Write, text: &str) -> io::Res while i < bytes.len() { match bytes[i] { 0 => { - writer.write_u16::(0xc080)?; + writer.write_u16::(0xC080)?; i += 1; } b @ 1..=127 => { @@ -35,8 +35,8 @@ pub(crate) fn write_modified_utf8(mut writer: impl Write, text: &str) -> io::Res let s = unsafe { from_utf8_unchecked(&bytes[i..i + w]) }; let c = s.chars().next().unwrap() as u32 - 0x10000; - let s0 = ((c >> 10) as u16) | 0xd800; - let s1 = ((c & 0x3ff) as u16) | 0xdc00; + let s0 = ((c >> 10) as u16) | 0xD800; + let s1 = ((c & 0x3FF) as u16) | 0xDC00; writer.write_all(encode_surrogate(s0).as_slice())?; writer.write_all(encode_surrogate(s1).as_slice())?; @@ -62,13 +62,13 @@ const fn utf8_char_width(first_byte: u8) -> usize { 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; - UTF8_CHAR_WIDTH[first_byte as usize] as _ + UTF8_CHAR_WIDTH[first_byte as usize] as usize } fn encode_surrogate(surrogate: u16) -> [u8; 3] { - debug_assert!((0xd800..=0xdfff).contains(&surrogate)); + debug_assert!((0xD800..=0xDFFF).contains(&surrogate)); - const TAG_CONT_U8: u8 = 0b1000_0000u8; + const TAG_CONT_U8: u8 = 0b1000_0000_u8; [ 0b11100000 | ((surrogate & 0b11110000_00000000) >> 12) as u8, TAG_CONT_U8 | ((surrogate & 0b00001111_11000000) >> 6) as u8, diff --git a/crates/valence_nbt/src/binary/tests.rs b/crates/valence_nbt/src/binary/tests.rs index 837487ef2..f335dbcac 100644 --- a/crates/valence_nbt/src/binary/tests.rs +++ b/crates/valence_nbt/src/binary/tests.rs @@ -1,4 +1,3 @@ -use crate::binary::written_size; use crate::tag::Tag; use crate::{compound, from_binary, to_binary, Compound, List, Value}; @@ -10,26 +9,26 @@ fn round_trip() { let compound = example_compound(); - to_binary(&compound, &mut buf, ROOT_NAME).unwrap(); + to_binary(&mut buf, ROOT_NAME, &compound).unwrap(); println!("{buf:?}"); - let (decoded, root_name) = crate::from_binary(&mut buf.as_slice()).unwrap(); + let (root_name, decoded) = from_binary(&mut buf.as_slice()).unwrap().unwrap(); assert_eq!(root_name, ROOT_NAME); - assert_eq!(compound, decoded); + assert_eq!(Value::from(compound), decoded); } #[test] fn check_min_sizes() { fn check(min_val: Value, expected_size: usize) { - /// TAG_Compound + root name + field tag + field name + TAG_End + /// `TAG_Compound` + root name + field tag + field name + `TAG_End` const COMPOUND_OVERHEAD: usize = 1 + 2 + 1 + 2 + 1; let dbg = format!("{min_val:?}"); let mut buf = vec![]; - to_binary(&compound!("" => min_val), &mut buf, "").unwrap(); + to_binary(&mut buf, "", &compound!("" => min_val)).unwrap(); assert_eq!( expected_size, @@ -45,7 +44,7 @@ fn check_min_sizes() { check(Value::Float(0.0), 4); check(Value::Double(0.0), 8); check(Value::ByteArray([].into()), 4); - check(Value::String("".into()), 2); + check(Value::String(String::new()), 2); check(Value::List(Vec::::new().into()), 5); check(Value::Compound(compound!()), 1); check(Value::IntArray([].into()), 4); @@ -66,7 +65,7 @@ fn deeply_nested_compound_decode() { buf.push(Tag::End as u8); // End root compound // Should not overflow the stack - let _ = from_binary::(&mut buf.as_slice()); + let _ = from_binary::<_, String>(&mut buf.as_slice()); } #[test] @@ -85,17 +84,7 @@ fn deeply_nested_list_decode() { buf.push(Tag::End as u8); // End root compound // Should not overflow the stack - let _ = from_binary::(&mut buf.as_slice()); -} - -#[test] -fn correct_length() { - let c = example_compound(); - - let mut buf = vec![]; - to_binary(&c, &mut buf, "abc").unwrap(); - - assert_eq!(written_size(&c, "abc"), buf.len()); + let _ = from_binary::<_, String>(&mut buf.as_slice()); } fn example_compound() -> Compound { diff --git a/crates/valence_nbt/src/compound.rs b/crates/valence_nbt/src/compound.rs index 636bb2194..913cae533 100644 --- a/crates/valence_nbt/src/compound.rs +++ b/crates/valence_nbt/src/compound.rs @@ -219,8 +219,8 @@ where use indexmap::map::Entry as EntryImpl; match self.map.entry(k.into()) { - EntryImpl::Vacant(ve) => Entry::Vacant(VacantEntry { ve }), - EntryImpl::Occupied(oe) => Entry::Occupied(OccupiedEntry { oe }), + EntryImpl::Vacant(ve) => Entry::Vacant(VacantEntry { entry: ve }), + EntryImpl::Occupied(oe) => Entry::Occupied(OccupiedEntry { entry: oe }), } } @@ -421,7 +421,7 @@ where } } - pub fn or_insert(self, default: impl Into>) -> &'a mut Value { + pub fn or_insert>>(self, default: V) -> &'a mut Value { match self { Entry::Vacant(ve) => ve.insert(default), Entry::Occupied(oe) => oe.into_mut(), @@ -453,11 +453,23 @@ where } } +impl fmt::Debug for Entry<'_, S> +where + S: fmt::Debug + Ord, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Vacant(entry) => f.debug_tuple("Vacant").field(entry).finish(), + Self::Occupied(entry) => f.debug_tuple("Occupied").field(entry).finish(), + } + } +} + pub struct VacantEntry<'a, S = String> { #[cfg(not(feature = "preserve_order"))] - ve: std::collections::btree_map::VacantEntry<'a, S, Value>, + entry: std::collections::btree_map::VacantEntry<'a, S, Value>, #[cfg(feature = "preserve_order")] - ve: indexmap::map::VacantEntry<'a, S, Value>, + entry: indexmap::map::VacantEntry<'a, S, Value>, } impl<'a, S> VacantEntry<'a, S> @@ -465,19 +477,30 @@ where S: Ord + Hash, { pub fn key(&self) -> &S { - self.ve.key() + self.entry.key() + } + + pub fn insert>>(self, v: V) -> &'a mut Value { + self.entry.insert(v.into()) } +} - pub fn insert(self, v: impl Into>) -> &'a mut Value { - self.ve.insert(v.into()) +impl fmt::Debug for VacantEntry<'_, S> +where + S: fmt::Debug + Ord, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("VacantEntry") + .field("entry", &self.entry) + .finish() } } pub struct OccupiedEntry<'a, S = String> { #[cfg(not(feature = "preserve_order"))] - oe: std::collections::btree_map::OccupiedEntry<'a, S, Value>, + entry: std::collections::btree_map::OccupiedEntry<'a, S, Value>, #[cfg(feature = "preserve_order")] - oe: indexmap::map::OccupiedEntry<'a, S, Value>, + entry: indexmap::map::OccupiedEntry<'a, S, Value>, } impl<'a, S> OccupiedEntry<'a, S> @@ -485,40 +508,51 @@ where S: Hash + Ord, { pub fn key(&self) -> &S { - self.oe.key() + self.entry.key() } pub fn get(&self) -> &Value { - self.oe.get() + self.entry.get() } pub fn get_mut(&mut self) -> &mut Value { - self.oe.get_mut() + self.entry.get_mut() } pub fn into_mut(self) -> &'a mut Value { - self.oe.into_mut() + self.entry.into_mut() } - pub fn insert(&mut self, v: impl Into>) -> Value { - self.oe.insert(v.into()) + pub fn insert>>(&mut self, v: V) -> Value { + self.entry.insert(v.into()) } pub fn remove(self) -> Value { #[cfg(feature = "preserve_order")] return self.swap_remove(); #[cfg(not(feature = "preserve_order"))] - return self.oe.remove(); + return self.entry.remove(); } #[cfg(feature = "preserve_order")] pub fn swap_remove(self) -> Value { - self.oe.swap_remove() + self.entry.swap_remove() } #[cfg(feature = "preserve_order")] pub fn shift_remove(self) -> Value { - self.oe.shift_remove() + self.entry.shift_remove() + } +} + +impl fmt::Debug for OccupiedEntry<'_, S> +where + S: fmt::Debug + Ord, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("OccupiedEntry") + .field("entry", &self.entry) + .finish() } } @@ -588,7 +622,7 @@ impl<'a, S> IntoIterator for &'a Compound { } } -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct Iter<'a, S = String> { #[cfg(not(feature = "preserve_order"))] iter: std::collections::btree_map::Iter<'a, S, Value>, @@ -609,6 +643,7 @@ impl<'a, S> IntoIterator for &'a mut Compound { } } +#[derive(Debug)] pub struct IterMut<'a, S = String> { #[cfg(not(feature = "preserve_order"))] iter: std::collections::btree_map::IterMut<'a, S, Value>, @@ -629,6 +664,7 @@ impl IntoIterator for Compound { } } +#[derive(Debug)] pub struct IntoIter { #[cfg(not(feature = "preserve_order"))] iter: std::collections::btree_map::IntoIter>, @@ -638,7 +674,7 @@ pub struct IntoIter { impl_iterator_traits!((IntoIter) => (S, Value)); -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct Keys<'a, S = String> { #[cfg(not(feature = "preserve_order"))] iter: std::collections::btree_map::Keys<'a, S, Value>, @@ -648,7 +684,7 @@ pub struct Keys<'a, S = String> { impl_iterator_traits!((Keys<'a, S>) => &'a S); -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct Values<'a, S = String> { #[cfg(not(feature = "preserve_order"))] iter: std::collections::btree_map::Values<'a, S, Value>, @@ -658,6 +694,7 @@ pub struct Values<'a, S = String> { impl_iterator_traits!((Values<'a, S>) => &'a Value); +#[derive(Debug)] pub struct ValuesMut<'a, S = String> { #[cfg(not(feature = "preserve_order"))] iter: std::collections::btree_map::ValuesMut<'a, S, Value>, diff --git a/crates/valence_nbt/src/binary/error.rs b/crates/valence_nbt/src/error.rs similarity index 92% rename from crates/valence_nbt/src/binary/error.rs rename to crates/valence_nbt/src/error.rs index 8c5c4efaf..8c5fc8cdf 100644 --- a/crates/valence_nbt/src/binary/error.rs +++ b/crates/valence_nbt/src/error.rs @@ -2,7 +2,7 @@ use std::error::Error as StdError; use std::fmt::{Display, Formatter}; use std::io; -pub type Result = std::result::Result; +pub type Result = std::result::Result; /// Errors that can occur when encoding or decoding binary NBT. #[derive(Debug)] @@ -19,12 +19,14 @@ enum Cause { } impl Error { + #[allow(dead_code)] pub(crate) fn new_owned(msg: impl Into>) -> Self { Self { cause: Box::new(Cause::Owned(msg.into())), } } + #[allow(dead_code)] pub(crate) fn new_static(msg: &'static str) -> Self { Self { cause: Box::new(Cause::Static(msg)), diff --git a/crates/valence_nbt/src/lib.rs b/crates/valence_nbt/src/lib.rs index 683cd0ed9..30b1ed41f 100644 --- a/crates/valence_nbt/src/lib.rs +++ b/crates/valence_nbt/src/lib.rs @@ -1,20 +1,28 @@ -#![doc = include_str!("../README.md")] +#![doc = include_str!("../../README.md")] +// Run locally with `RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --all-features --open` +#![cfg_attr(docsrs, feature(doc_cfg))] #[cfg(feature = "binary")] +#[cfg_attr(docsrs, doc(cfg(feature = "binary")))] pub use binary::{from_binary, to_binary}; pub use compound::Compound; +pub use error::*; pub use list::List; -pub use tag::Tag; +pub use tag::*; pub use value::Value; #[cfg(feature = "binary")] +#[cfg_attr(docsrs, doc(cfg(feature = "binary")))] pub mod binary; pub mod compound; pub mod conv; +mod error; pub mod list; #[cfg(feature = "serde")] +#[cfg_attr(docsrs, doc(cfg(feature = "serde")))] pub mod serde; #[cfg(feature = "snbt")] +#[cfg_attr(docsrs, doc(cfg(feature = "snbt")))] pub mod snbt; mod tag; pub mod value; @@ -85,6 +93,7 @@ macro_rules! compound { /// /// [`JavaString`]: java_string::JavaString #[cfg(feature = "java_string")] +#[cfg_attr(docsrs, doc(cfg(feature = "java_string")))] #[macro_export] macro_rules! jcompound { ($($key:expr => $value:expr),* $(,)?) => { diff --git a/crates/valence_nbt/src/list.rs b/crates/valence_nbt/src/list.rs index 8068d9d72..1592501fc 100644 --- a/crates/valence_nbt/src/list.rs +++ b/crates/valence_nbt/src/list.rs @@ -161,7 +161,7 @@ impl List { /// multiple types inside it). Returns `true` if the value was added, /// `false` otherwise. #[must_use] - pub fn try_push(&mut self, value: impl Into>) -> bool { + pub fn try_push>>(&mut self, value: V) -> bool { let value = value.into(); match self { List::End => { @@ -276,7 +276,7 @@ impl List { /// /// Panics if the index is greater than the length of the list. #[must_use] - pub fn try_insert(&mut self, index: usize, value: impl Into>) -> bool { + pub fn try_insert>>(&mut self, index: usize, value: V) -> bool { let value = value.into(); #[cold] @@ -662,10 +662,12 @@ impl<'a, S> IntoIterator for &'a mut List { } /// The owned iterator type for [`List`]. +#[derive(Clone, Debug)] pub struct IntoIter { inner: IntoIterInner, } +#[derive(Clone, Debug)] enum IntoIterInner { End, Byte(std::vec::IntoIter), @@ -686,78 +688,78 @@ impl Iterator for IntoIter { type Item = Value; fn next(&mut self) -> Option { - match self.inner { + match &mut self.inner { IntoIterInner::End => None, - IntoIterInner::Byte(ref mut i) => i.next().map(Value::Byte), - IntoIterInner::Short(ref mut i) => i.next().map(Value::Short), - IntoIterInner::Int(ref mut i) => i.next().map(Value::Int), - IntoIterInner::Long(ref mut i) => i.next().map(Value::Long), - IntoIterInner::Float(ref mut i) => i.next().map(Value::Float), - IntoIterInner::Double(ref mut i) => i.next().map(Value::Double), - IntoIterInner::ByteArray(ref mut i) => i.next().map(Value::ByteArray), - IntoIterInner::String(ref mut i) => i.next().map(Value::String), - IntoIterInner::List(ref mut i) => i.next().map(Value::List), - IntoIterInner::Compound(ref mut i) => i.next().map(Value::Compound), - IntoIterInner::IntArray(ref mut i) => i.next().map(Value::IntArray), - IntoIterInner::LongArray(ref mut i) => i.next().map(Value::LongArray), + IntoIterInner::Byte(i) => i.next().map(Value::Byte), + IntoIterInner::Short(i) => i.next().map(Value::Short), + IntoIterInner::Int(i) => i.next().map(Value::Int), + IntoIterInner::Long(i) => i.next().map(Value::Long), + IntoIterInner::Float(i) => i.next().map(Value::Float), + IntoIterInner::Double(i) => i.next().map(Value::Double), + IntoIterInner::ByteArray(i) => i.next().map(Value::ByteArray), + IntoIterInner::String(i) => i.next().map(Value::String), + IntoIterInner::List(i) => i.next().map(Value::List), + IntoIterInner::Compound(i) => i.next().map(Value::Compound), + IntoIterInner::IntArray(i) => i.next().map(Value::IntArray), + IntoIterInner::LongArray(i) => i.next().map(Value::LongArray), } } fn size_hint(&self) -> (usize, Option) { - match self.inner { + match &self.inner { IntoIterInner::End => (0, Some(0)), - IntoIterInner::Byte(ref i) => i.size_hint(), - IntoIterInner::Short(ref i) => i.size_hint(), - IntoIterInner::Int(ref i) => i.size_hint(), - IntoIterInner::Long(ref i) => i.size_hint(), - IntoIterInner::Float(ref i) => i.size_hint(), - IntoIterInner::Double(ref i) => i.size_hint(), - IntoIterInner::ByteArray(ref i) => i.size_hint(), - IntoIterInner::String(ref i) => i.size_hint(), - IntoIterInner::List(ref i) => i.size_hint(), - IntoIterInner::Compound(ref i) => i.size_hint(), - IntoIterInner::IntArray(ref i) => i.size_hint(), - IntoIterInner::LongArray(ref i) => i.size_hint(), + IntoIterInner::Byte(i) => i.size_hint(), + IntoIterInner::Short(i) => i.size_hint(), + IntoIterInner::Int(i) => i.size_hint(), + IntoIterInner::Long(i) => i.size_hint(), + IntoIterInner::Float(i) => i.size_hint(), + IntoIterInner::Double(i) => i.size_hint(), + IntoIterInner::ByteArray(i) => i.size_hint(), + IntoIterInner::String(i) => i.size_hint(), + IntoIterInner::List(i) => i.size_hint(), + IntoIterInner::Compound(i) => i.size_hint(), + IntoIterInner::IntArray(i) => i.size_hint(), + IntoIterInner::LongArray(i) => i.size_hint(), } } } impl DoubleEndedIterator for IntoIter { fn next_back(&mut self) -> Option { - match self.inner { + match &mut self.inner { IntoIterInner::End => None, - IntoIterInner::Byte(ref mut i) => i.next_back().map(Value::Byte), - IntoIterInner::Short(ref mut i) => i.next_back().map(Value::Short), - IntoIterInner::Int(ref mut i) => i.next_back().map(Value::Int), - IntoIterInner::Long(ref mut i) => i.next_back().map(Value::Long), - IntoIterInner::Float(ref mut i) => i.next_back().map(Value::Float), - IntoIterInner::Double(ref mut i) => i.next_back().map(Value::Double), - IntoIterInner::ByteArray(ref mut i) => i.next_back().map(Value::ByteArray), - IntoIterInner::String(ref mut i) => i.next_back().map(Value::String), - IntoIterInner::List(ref mut i) => i.next_back().map(Value::List), - IntoIterInner::Compound(ref mut i) => i.next_back().map(Value::Compound), - IntoIterInner::IntArray(ref mut i) => i.next_back().map(Value::IntArray), - IntoIterInner::LongArray(ref mut i) => i.next_back().map(Value::LongArray), + IntoIterInner::Byte(i) => i.next_back().map(Value::Byte), + IntoIterInner::Short(i) => i.next_back().map(Value::Short), + IntoIterInner::Int(i) => i.next_back().map(Value::Int), + IntoIterInner::Long(i) => i.next_back().map(Value::Long), + IntoIterInner::Float(i) => i.next_back().map(Value::Float), + IntoIterInner::Double(i) => i.next_back().map(Value::Double), + IntoIterInner::ByteArray(i) => i.next_back().map(Value::ByteArray), + IntoIterInner::String(i) => i.next_back().map(Value::String), + IntoIterInner::List(i) => i.next_back().map(Value::List), + IntoIterInner::Compound(i) => i.next_back().map(Value::Compound), + IntoIterInner::IntArray(i) => i.next_back().map(Value::IntArray), + IntoIterInner::LongArray(i) => i.next_back().map(Value::LongArray), } } } impl ExactSizeIterator for IntoIter { fn len(&self) -> usize { - match self.inner { + match &self.inner { IntoIterInner::End => 0, - IntoIterInner::Byte(ref i) => i.len(), - IntoIterInner::Short(ref i) => i.len(), - IntoIterInner::Int(ref i) => i.len(), - IntoIterInner::Long(ref i) => i.len(), - IntoIterInner::Float(ref i) => i.len(), - IntoIterInner::Double(ref i) => i.len(), - IntoIterInner::ByteArray(ref i) => i.len(), - IntoIterInner::String(ref i) => i.len(), - IntoIterInner::List(ref i) => i.len(), - IntoIterInner::Compound(ref i) => i.len(), - IntoIterInner::IntArray(ref i) => i.len(), - IntoIterInner::LongArray(ref i) => i.len(), + IntoIterInner::Byte(i) => i.len(), + IntoIterInner::Short(i) => i.len(), + IntoIterInner::Int(i) => i.len(), + IntoIterInner::Long(i) => i.len(), + IntoIterInner::Float(i) => i.len(), + IntoIterInner::Double(i) => i.len(), + IntoIterInner::ByteArray(i) => i.len(), + IntoIterInner::String(i) => i.len(), + IntoIterInner::List(i) => i.len(), + IntoIterInner::Compound(i) => i.len(), + IntoIterInner::IntArray(i) => i.len(), + IntoIterInner::LongArray(i) => i.len(), } } } @@ -765,10 +767,12 @@ impl ExactSizeIterator for IntoIter { impl FusedIterator for IntoIter {} /// The borrowing iterator type for [`List`]. +#[derive(Clone, Debug)] pub struct Iter<'a, S = String> { inner: IterInner<'a, S>, } +#[derive(Clone, Debug)] enum IterInner<'a, S> { End, Byte(std::slice::Iter<'a, i8>), @@ -789,82 +793,78 @@ impl<'a, S> Iterator for Iter<'a, S> { type Item = ValueRef<'a, S>; fn next(&mut self) -> Option { - match self.inner { + match &mut self.inner { IterInner::End => None, - IterInner::Byte(ref mut i) => i.next().map(ValueRef::Byte), - IterInner::Short(ref mut i) => i.next().map(ValueRef::Short), - IterInner::Int(ref mut i) => i.next().map(ValueRef::Int), - IterInner::Long(ref mut i) => i.next().map(ValueRef::Long), - IterInner::Float(ref mut i) => i.next().map(ValueRef::Float), - IterInner::Double(ref mut i) => i.next().map(ValueRef::Double), - IterInner::ByteArray(ref mut i) => i.next().map(|arr| ValueRef::ByteArray(&arr[..])), - IterInner::String(ref mut i) => i.next().map(ValueRef::String), - IterInner::List(ref mut i) => i.next().map(ValueRef::List), - IterInner::Compound(ref mut i) => i.next().map(ValueRef::Compound), - IterInner::IntArray(ref mut i) => i.next().map(|arr| ValueRef::IntArray(&arr[..])), - IterInner::LongArray(ref mut i) => i.next().map(|arr| ValueRef::LongArray(&arr[..])), + IterInner::Byte(i) => i.next().map(ValueRef::Byte), + IterInner::Short(i) => i.next().map(ValueRef::Short), + IterInner::Int(i) => i.next().map(ValueRef::Int), + IterInner::Long(i) => i.next().map(ValueRef::Long), + IterInner::Float(i) => i.next().map(ValueRef::Float), + IterInner::Double(i) => i.next().map(ValueRef::Double), + IterInner::ByteArray(i) => i.next().map(|arr| ValueRef::ByteArray(&arr[..])), + IterInner::String(i) => i.next().map(ValueRef::String), + IterInner::List(i) => i.next().map(ValueRef::List), + IterInner::Compound(i) => i.next().map(ValueRef::Compound), + IterInner::IntArray(i) => i.next().map(|arr| ValueRef::IntArray(&arr[..])), + IterInner::LongArray(i) => i.next().map(|arr| ValueRef::LongArray(&arr[..])), } } fn size_hint(&self) -> (usize, Option) { - match self.inner { + match &self.inner { IterInner::End => (0, Some(0)), - IterInner::Byte(ref i) => i.size_hint(), - IterInner::Short(ref i) => i.size_hint(), - IterInner::Int(ref i) => i.size_hint(), - IterInner::Long(ref i) => i.size_hint(), - IterInner::Float(ref i) => i.size_hint(), - IterInner::Double(ref i) => i.size_hint(), - IterInner::ByteArray(ref i) => i.size_hint(), - IterInner::String(ref i) => i.size_hint(), - IterInner::List(ref i) => i.size_hint(), - IterInner::Compound(ref i) => i.size_hint(), - IterInner::IntArray(ref i) => i.size_hint(), - IterInner::LongArray(ref i) => i.size_hint(), + IterInner::Byte(i) => i.size_hint(), + IterInner::Short(i) => i.size_hint(), + IterInner::Int(i) => i.size_hint(), + IterInner::Long(i) => i.size_hint(), + IterInner::Float(i) => i.size_hint(), + IterInner::Double(i) => i.size_hint(), + IterInner::ByteArray(i) => i.size_hint(), + IterInner::String(i) => i.size_hint(), + IterInner::List(i) => i.size_hint(), + IterInner::Compound(i) => i.size_hint(), + IterInner::IntArray(i) => i.size_hint(), + IterInner::LongArray(i) => i.size_hint(), } } } impl DoubleEndedIterator for Iter<'_, S> { fn next_back(&mut self) -> Option { - match self.inner { + match &mut self.inner { IterInner::End => None, - IterInner::Byte(ref mut i) => i.next_back().map(ValueRef::Byte), - IterInner::Short(ref mut i) => i.next_back().map(ValueRef::Short), - IterInner::Int(ref mut i) => i.next_back().map(ValueRef::Int), - IterInner::Long(ref mut i) => i.next_back().map(ValueRef::Long), - IterInner::Float(ref mut i) => i.next_back().map(ValueRef::Float), - IterInner::Double(ref mut i) => i.next_back().map(ValueRef::Double), - IterInner::ByteArray(ref mut i) => { - i.next_back().map(|arr| ValueRef::ByteArray(&arr[..])) - } - IterInner::String(ref mut i) => i.next_back().map(ValueRef::String), - IterInner::List(ref mut i) => i.next_back().map(ValueRef::List), - IterInner::Compound(ref mut i) => i.next_back().map(ValueRef::Compound), - IterInner::IntArray(ref mut i) => i.next_back().map(|arr| ValueRef::IntArray(&arr[..])), - IterInner::LongArray(ref mut i) => { - i.next_back().map(|arr| ValueRef::LongArray(&arr[..])) - } + IterInner::Byte(i) => i.next_back().map(ValueRef::Byte), + IterInner::Short(i) => i.next_back().map(ValueRef::Short), + IterInner::Int(i) => i.next_back().map(ValueRef::Int), + IterInner::Long(i) => i.next_back().map(ValueRef::Long), + IterInner::Float(i) => i.next_back().map(ValueRef::Float), + IterInner::Double(i) => i.next_back().map(ValueRef::Double), + IterInner::ByteArray(i) => i.next_back().map(|arr| ValueRef::ByteArray(&arr[..])), + IterInner::String(i) => i.next_back().map(ValueRef::String), + IterInner::List(i) => i.next_back().map(ValueRef::List), + IterInner::Compound(i) => i.next_back().map(ValueRef::Compound), + IterInner::IntArray(i) => i.next_back().map(|arr| ValueRef::IntArray(&arr[..])), + IterInner::LongArray(i) => i.next_back().map(|arr| ValueRef::LongArray(&arr[..])), } } } impl ExactSizeIterator for Iter<'_, S> { fn len(&self) -> usize { - match self.inner { + match &self.inner { IterInner::End => 0, - IterInner::Byte(ref i) => i.len(), - IterInner::Short(ref i) => i.len(), - IterInner::Int(ref i) => i.len(), - IterInner::Long(ref i) => i.len(), - IterInner::Float(ref i) => i.len(), - IterInner::Double(ref i) => i.len(), - IterInner::ByteArray(ref i) => i.len(), - IterInner::String(ref i) => i.len(), - IterInner::List(ref i) => i.len(), - IterInner::Compound(ref i) => i.len(), - IterInner::IntArray(ref i) => i.len(), - IterInner::LongArray(ref i) => i.len(), + IterInner::Byte(i) => i.len(), + IterInner::Short(i) => i.len(), + IterInner::Int(i) => i.len(), + IterInner::Long(i) => i.len(), + IterInner::Float(i) => i.len(), + IterInner::Double(i) => i.len(), + IterInner::ByteArray(i) => i.len(), + IterInner::String(i) => i.len(), + IterInner::List(i) => i.len(), + IterInner::Compound(i) => i.len(), + IterInner::IntArray(i) => i.len(), + IterInner::LongArray(i) => i.len(), } } } @@ -872,10 +872,12 @@ impl ExactSizeIterator for Iter<'_, S> { impl FusedIterator for Iter<'_, S> {} /// The mutable borrowing iterator type for [`List`]. +#[derive(Debug)] pub struct IterMut<'a, S = String> { inner: IterMutInner<'a, S>, } +#[derive(Debug)] enum IterMutInner<'a, S> { End, Byte(std::slice::IterMut<'a, i8>), @@ -896,78 +898,78 @@ impl<'a, S> Iterator for IterMut<'a, S> { type Item = ValueMut<'a, S>; fn next(&mut self) -> Option { - match self.inner { + match &mut self.inner { IterMutInner::End => None, - IterMutInner::Byte(ref mut i) => i.next().map(ValueMut::Byte), - IterMutInner::Short(ref mut i) => i.next().map(ValueMut::Short), - IterMutInner::Int(ref mut i) => i.next().map(ValueMut::Int), - IterMutInner::Long(ref mut i) => i.next().map(ValueMut::Long), - IterMutInner::Float(ref mut i) => i.next().map(ValueMut::Float), - IterMutInner::Double(ref mut i) => i.next().map(ValueMut::Double), - IterMutInner::ByteArray(ref mut i) => i.next().map(ValueMut::ByteArray), - IterMutInner::String(ref mut i) => i.next().map(ValueMut::String), - IterMutInner::List(ref mut i) => i.next().map(ValueMut::List), - IterMutInner::Compound(ref mut i) => i.next().map(ValueMut::Compound), - IterMutInner::IntArray(ref mut i) => i.next().map(ValueMut::IntArray), - IterMutInner::LongArray(ref mut i) => i.next().map(ValueMut::LongArray), + IterMutInner::Byte(i) => i.next().map(ValueMut::Byte), + IterMutInner::Short(i) => i.next().map(ValueMut::Short), + IterMutInner::Int(i) => i.next().map(ValueMut::Int), + IterMutInner::Long(i) => i.next().map(ValueMut::Long), + IterMutInner::Float(i) => i.next().map(ValueMut::Float), + IterMutInner::Double(i) => i.next().map(ValueMut::Double), + IterMutInner::ByteArray(i) => i.next().map(ValueMut::ByteArray), + IterMutInner::String(i) => i.next().map(ValueMut::String), + IterMutInner::List(i) => i.next().map(ValueMut::List), + IterMutInner::Compound(i) => i.next().map(ValueMut::Compound), + IterMutInner::IntArray(i) => i.next().map(ValueMut::IntArray), + IterMutInner::LongArray(i) => i.next().map(ValueMut::LongArray), } } fn size_hint(&self) -> (usize, Option) { - match self.inner { + match &self.inner { IterMutInner::End => (0, Some(0)), - IterMutInner::Byte(ref i) => i.size_hint(), - IterMutInner::Short(ref i) => i.size_hint(), - IterMutInner::Int(ref i) => i.size_hint(), - IterMutInner::Long(ref i) => i.size_hint(), - IterMutInner::Float(ref i) => i.size_hint(), - IterMutInner::Double(ref i) => i.size_hint(), - IterMutInner::ByteArray(ref i) => i.size_hint(), - IterMutInner::String(ref i) => i.size_hint(), - IterMutInner::List(ref i) => i.size_hint(), - IterMutInner::Compound(ref i) => i.size_hint(), - IterMutInner::IntArray(ref i) => i.size_hint(), - IterMutInner::LongArray(ref i) => i.size_hint(), + IterMutInner::Byte(i) => i.size_hint(), + IterMutInner::Short(i) => i.size_hint(), + IterMutInner::Int(i) => i.size_hint(), + IterMutInner::Long(i) => i.size_hint(), + IterMutInner::Float(i) => i.size_hint(), + IterMutInner::Double(i) => i.size_hint(), + IterMutInner::ByteArray(i) => i.size_hint(), + IterMutInner::String(i) => i.size_hint(), + IterMutInner::List(i) => i.size_hint(), + IterMutInner::Compound(i) => i.size_hint(), + IterMutInner::IntArray(i) => i.size_hint(), + IterMutInner::LongArray(i) => i.size_hint(), } } } impl DoubleEndedIterator for IterMut<'_, S> { fn next_back(&mut self) -> Option { - match self.inner { + match &mut self.inner { IterMutInner::End => None, - IterMutInner::Byte(ref mut i) => i.next_back().map(ValueMut::Byte), - IterMutInner::Short(ref mut i) => i.next_back().map(ValueMut::Short), - IterMutInner::Int(ref mut i) => i.next_back().map(ValueMut::Int), - IterMutInner::Long(ref mut i) => i.next_back().map(ValueMut::Long), - IterMutInner::Float(ref mut i) => i.next_back().map(ValueMut::Float), - IterMutInner::Double(ref mut i) => i.next_back().map(ValueMut::Double), - IterMutInner::ByteArray(ref mut i) => i.next_back().map(ValueMut::ByteArray), - IterMutInner::String(ref mut i) => i.next_back().map(ValueMut::String), - IterMutInner::List(ref mut i) => i.next_back().map(ValueMut::List), - IterMutInner::Compound(ref mut i) => i.next_back().map(ValueMut::Compound), - IterMutInner::IntArray(ref mut i) => i.next_back().map(ValueMut::IntArray), - IterMutInner::LongArray(ref mut i) => i.next_back().map(ValueMut::LongArray), + IterMutInner::Byte(i) => i.next_back().map(ValueMut::Byte), + IterMutInner::Short(i) => i.next_back().map(ValueMut::Short), + IterMutInner::Int(i) => i.next_back().map(ValueMut::Int), + IterMutInner::Long(i) => i.next_back().map(ValueMut::Long), + IterMutInner::Float(i) => i.next_back().map(ValueMut::Float), + IterMutInner::Double(i) => i.next_back().map(ValueMut::Double), + IterMutInner::ByteArray(i) => i.next_back().map(ValueMut::ByteArray), + IterMutInner::String(i) => i.next_back().map(ValueMut::String), + IterMutInner::List(i) => i.next_back().map(ValueMut::List), + IterMutInner::Compound(i) => i.next_back().map(ValueMut::Compound), + IterMutInner::IntArray(i) => i.next_back().map(ValueMut::IntArray), + IterMutInner::LongArray(i) => i.next_back().map(ValueMut::LongArray), } } } impl ExactSizeIterator for IterMut<'_, S> { fn len(&self) -> usize { - match self.inner { + match &self.inner { IterMutInner::End => 0, - IterMutInner::Byte(ref i) => i.len(), - IterMutInner::Short(ref i) => i.len(), - IterMutInner::Int(ref i) => i.len(), - IterMutInner::Long(ref i) => i.len(), - IterMutInner::Float(ref i) => i.len(), - IterMutInner::Double(ref i) => i.len(), - IterMutInner::ByteArray(ref i) => i.len(), - IterMutInner::String(ref i) => i.len(), - IterMutInner::List(ref i) => i.len(), - IterMutInner::Compound(ref i) => i.len(), - IterMutInner::IntArray(ref i) => i.len(), - IterMutInner::LongArray(ref i) => i.len(), + IterMutInner::Byte(i) => i.len(), + IterMutInner::Short(i) => i.len(), + IterMutInner::Int(i) => i.len(), + IterMutInner::Long(i) => i.len(), + IterMutInner::Float(i) => i.len(), + IterMutInner::Double(i) => i.len(), + IterMutInner::ByteArray(i) => i.len(), + IterMutInner::String(i) => i.len(), + IterMutInner::List(i) => i.len(), + IterMutInner::Compound(i) => i.len(), + IterMutInner::IntArray(i) => i.len(), + IterMutInner::LongArray(i) => i.len(), } } } diff --git a/crates/valence_nbt/src/serde.rs b/crates/valence_nbt/src/serde.rs index 8159f5d7d..793cb26c6 100644 --- a/crates/valence_nbt/src/serde.rs +++ b/crates/valence_nbt/src/serde.rs @@ -1,31 +1,20 @@ use std::fmt; pub use ser::*; -use thiserror::Error; + +use crate::Error; mod de; mod ser; #[cfg(test)] mod tests; -/// Errors that can occur while serializing or deserializing. -#[derive(Clone, Error, Debug)] -#[error("{0}")] - -pub struct Error(Box); - -impl Error { - fn new(s: impl Into>) -> Self { - Self(s.into()) - } -} - impl serde::de::Error for Error { fn custom(msg: T) -> Self where T: fmt::Display, { - Self::new(format!("{msg}")) + Self::new_owned(format!("{msg}")) } } @@ -34,6 +23,6 @@ impl serde::ser::Error for Error { where T: fmt::Display, { - Self::new(format!("{msg}")) + Self::new_owned(format!("{msg}")) } } diff --git a/crates/valence_nbt/src/serde/de.rs b/crates/valence_nbt/src/serde/de.rs index 0c5b280f1..e3826d782 100644 --- a/crates/valence_nbt/src/serde/de.rs +++ b/crates/valence_nbt/src/serde/de.rs @@ -37,7 +37,7 @@ where where E: de::Error, { - Ok(Value::Byte(v as _)) + Ok(Value::Byte(v.into())) } fn visit_i8(self, v: i8) -> Result @@ -72,28 +72,28 @@ where where E: de::Error, { - Ok(Value::Byte(v as _)) + Ok(Value::Byte(v as i8)) } fn visit_u16(self, v: u16) -> Result where E: de::Error, { - Ok(Value::Short(v as _)) + Ok(Value::Short(v as i16)) } fn visit_u32(self, v: u32) -> Result where E: de::Error, { - Ok(Value::Int(v as _)) + Ok(Value::Int(v as i32)) } fn visit_u64(self, v: u64) -> Result where E: de::Error, { - Ok(Value::Long(v as _)) + Ok(Value::Long(v as i64)) } fn visit_f32(self, v: f32) -> Result diff --git a/crates/valence_nbt/src/serde/ser.rs b/crates/valence_nbt/src/serde/ser.rs index 25bfca896..610a18d16 100644 --- a/crates/valence_nbt/src/serde/ser.rs +++ b/crates/valence_nbt/src/serde/ser.rs @@ -61,11 +61,12 @@ where macro_rules! unsupported { ($lit:literal) => { - Err(Error::new(concat!("unsupported type: ", $lit))) + Err(Error::new_static(concat!("unsupported type: ", $lit))) }; } /// [`Serializer`] whose output is [`Compound`]. +#[derive(Debug)] pub struct CompoundSerializer; impl Serializer for CompoundSerializer { @@ -147,9 +148,9 @@ impl Serializer for CompoundSerializer { unsupported!("none") } - fn serialize_some(self, _value: &T) -> Result + fn serialize_some(self, _value: &T) -> Result where - T: Serialize, + T: Serialize + ?Sized, { unsupported!("some") } @@ -171,18 +172,18 @@ impl Serializer for CompoundSerializer { unsupported!("unit variant") } - fn serialize_newtype_struct( + fn serialize_newtype_struct( self, _name: &'static str, _value: &T, ) -> Result where - T: Serialize, + T: Serialize + ?Sized, { unsupported!("newtype struct") } - fn serialize_newtype_variant( + fn serialize_newtype_variant( self, _name: &'static str, _variant_index: u32, @@ -190,7 +191,7 @@ impl Serializer for CompoundSerializer { _value: &T, ) -> Result where - T: Serialize, + T: Serialize + ?Sized, { unsupported!("newtype variant") } @@ -267,7 +268,7 @@ impl Serializer for ValueSerializer { type SerializeStructVariant = Impossible; fn serialize_bool(self, v: bool) -> Result { - Ok(Value::Byte(v as _)) + Ok(Value::Byte(v.into())) } fn serialize_i8(self, v: i8) -> Result { @@ -287,19 +288,19 @@ impl Serializer for ValueSerializer { } fn serialize_u8(self, v: u8) -> Result { - Ok(Value::Byte(v as _)) + Ok(Value::Byte(v as i8)) } fn serialize_u16(self, v: u16) -> Result { - Ok(Value::Short(v as _)) + Ok(Value::Short(v as i16)) } fn serialize_u32(self, v: u32) -> Result { - Ok(Value::Int(v as _)) + Ok(Value::Int(v as i32)) } fn serialize_u64(self, v: u64) -> Result { - Ok(Value::Long(v as _)) + Ok(Value::Long(v as i64)) } fn serialize_f32(self, v: f32) -> Result { @@ -326,9 +327,9 @@ impl Serializer for ValueSerializer { unsupported!("none") } - fn serialize_some(self, value: &T) -> Result + fn serialize_some(self, value: &T) -> Result where - T: Serialize, + T: Serialize + ?Sized, { value.serialize(self) } @@ -350,18 +351,18 @@ impl Serializer for ValueSerializer { Ok(Value::String(variant.into())) } - fn serialize_newtype_struct( + fn serialize_newtype_struct( self, _name: &'static str, value: &T, ) -> Result where - T: Serialize, + T: Serialize + ?Sized, { value.serialize(self) } - fn serialize_newtype_variant( + fn serialize_newtype_variant( self, _name: &'static str, _variant_index: u32, @@ -369,7 +370,7 @@ impl Serializer for ValueSerializer { _value: &T, ) -> Result where - T: Serialize, + T: Serialize + ?Sized, { unsupported!("newtype variant") } @@ -446,9 +447,9 @@ impl SerializeSeq for ValueSerializeSeq { type Error = Error; - fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> + fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> where - T: Serialize, + T: Serialize + ?Sized, { macro_rules! serialize_variant { ($variant:ident, $vec:ident, $elem:ident) => {{ @@ -457,7 +458,7 @@ impl SerializeSeq for ValueSerializeSeq { $vec.push(val); Ok(()) } - _ => Err(Error::new(concat!( + _ => Err(Error::new_static(concat!( "heterogeneous NBT list (expected `", stringify!($variant), "` element)" @@ -526,6 +527,7 @@ impl SerializeSeq for ValueSerializeSeq { } #[doc(hidden)] +#[derive(Debug)] pub struct GenericSerializeMap { /// Temp storage for `serialize_key`. key: Option, @@ -551,9 +553,9 @@ where type Error = Error; - fn serialize_key(&mut self, key: &T) -> Result<(), Self::Error> + fn serialize_key(&mut self, key: &T) -> Result<(), Self::Error> where - T: Serialize, + T: Serialize + ?Sized, { debug_assert!( self.key.is_none(), @@ -565,13 +567,13 @@ where self.key = Some(s); Ok(()) } - _ => Err(Error::new("invalid map key type (expected string)")), + _ => Err(Error::new_static("invalid map key type (expected string)")), } } - fn serialize_value(&mut self, value: &T) -> Result<(), Self::Error> + fn serialize_value(&mut self, value: &T) -> Result<(), Self::Error> where - T: Serialize, + T: Serialize + ?Sized, { let key = self .key @@ -587,6 +589,7 @@ where } #[doc(hidden)] +#[derive(Debug)] pub struct GenericSerializeStruct { c: Compound, _marker: PhantomData, @@ -609,13 +612,9 @@ where type Error = Error; - fn serialize_field( - &mut self, - key: &'static str, - value: &T, - ) -> Result<(), Self::Error> + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> where - T: Serialize, + T: Serialize + ?Sized, { self.c.insert(key, value.serialize(ValueSerializer)?); Ok(()) diff --git a/crates/valence_nbt/src/snbt.rs b/crates/valence_nbt/src/snbt.rs index e207da762..fa4947bbe 100644 --- a/crates/valence_nbt/src/snbt.rs +++ b/crates/valence_nbt/src/snbt.rs @@ -45,24 +45,20 @@ impl Display for SnbtErrorKind { #[derive(Debug, Clone, PartialEq, Eq, Copy)] pub struct SnbtError { - pub error_type: SnbtErrorKind, + pub kind: SnbtErrorKind, pub line: usize, pub column: usize, } impl SnbtError { - pub fn new(error_type: SnbtErrorKind, line: usize, column: usize) -> Self { - Self { - error_type, - line, - column, - } + pub fn new(kind: SnbtErrorKind, line: usize, column: usize) -> Self { + Self { kind, line, column } } } impl Display for SnbtError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "@ {},{}: {}", self.line, self.column, self.error_type) + write!(f, "@ {},{}: {}", self.line, self.column, self.kind) } } @@ -70,6 +66,7 @@ impl Error for SnbtError {} type Result = std::result::Result; +#[derive(Debug)] pub struct SnbtReader<'a> { line: usize, column: usize, @@ -102,8 +99,8 @@ impl<'a> SnbtReader<'a> { } } - fn make_error(&self, error_type: SnbtErrorKind) -> SnbtError { - SnbtError::new(error_type, self.line, self.column) + fn make_error(&self, kind: SnbtErrorKind) -> SnbtError { + SnbtError::new(kind, self.line, self.column) } fn peek(&mut self) -> Result { @@ -444,6 +441,7 @@ pub fn from_snbt_str(snbt: &str) -> Result { SnbtReader::new(snbt).read() } +#[derive(Debug)] pub struct SnbtWriter<'a> { output: &'a mut String, } @@ -549,7 +547,7 @@ impl<'a> SnbtWriter<'a> { self.output.push('{'); let mut first = true; - for (k, v) in compound.iter() { + for (k, v) in compound { if !first { self.output.push(','); } @@ -654,56 +652,54 @@ mod tests { assert_eq!(list[0], "Bibabo"); assert_eq!( - from_snbt_str("\"\\n\"").unwrap_err().error_type, + from_snbt_str("\"\\n\"").unwrap_err().kind, SnbtErrorKind::InvalidEscapeSequence ); assert_eq!( - from_snbt_str("[L; 1]").unwrap_err().error_type, + from_snbt_str("[L; 1]").unwrap_err().kind, SnbtErrorKind::WrongTypeInArray ); assert_eq!( - from_snbt_str("[L; 1L, 2L, 3L").unwrap_err().error_type, + from_snbt_str("[L; 1L, 2L, 3L").unwrap_err().kind, SnbtErrorKind::ReachEndOfStream ); assert_eq!( - from_snbt_str("[L; 1L, 2L, 3L,]dewdwe") - .unwrap_err() - .error_type, + from_snbt_str("[L; 1L, 2L, 3L,]dewdwe").unwrap_err().kind, SnbtErrorKind::TrailingData ); assert_eq!( - from_snbt_str("{ foo: }").unwrap_err().error_type, + from_snbt_str("{ foo: }").unwrap_err().kind, SnbtErrorKind::ExpectValue ); assert_eq!( - from_snbt_str("{ {}, }").unwrap_err().error_type, + from_snbt_str("{ {}, }").unwrap_err().kind, SnbtErrorKind::EmptyKeyInCompound ); assert_eq!( - from_snbt_str("{ foo 1 }").unwrap_err().error_type, + from_snbt_str("{ foo 1 }").unwrap_err().kind, SnbtErrorKind::ExpectColon ); assert_eq!( - from_snbt_str("{ foo: 1 bar: 2 }").unwrap_err().error_type, + from_snbt_str("{ foo: 1 bar: 2 }").unwrap_err().kind, SnbtErrorKind::ExpectComma ); assert_eq!( - from_snbt_str("[{}, []]").unwrap_err().error_type, + from_snbt_str("[{}, []]").unwrap_err().kind, SnbtErrorKind::DifferentTypesInList ); assert_eq!( from_snbt_str(&String::from_utf8(vec![b'e'; 32768]).unwrap()) .unwrap_err() - .error_type, + .kind, SnbtErrorKind::LongString ); @@ -713,7 +709,7 @@ mod tests { .unwrap() ) .unwrap_err() - .error_type, + .kind, SnbtErrorKind::DepthLimitExceeded ); diff --git a/crates/valence_nbt/src/tag.rs b/crates/valence_nbt/src/tag.rs index 4bc9e2639..ecb30f322 100644 --- a/crates/valence_nbt/src/tag.rs +++ b/crates/valence_nbt/src/tag.rs @@ -1,5 +1,6 @@ /// One of the possible NBT data types. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] +#[repr(u8)] pub enum Tag { // Variant order is significant! End, diff --git a/crates/valence_nbt/src/value.rs b/crates/valence_nbt/src/value.rs index 4cb30661e..4d2d7956e 100644 --- a/crates/valence_nbt/src/value.rs +++ b/crates/valence_nbt/src/value.rs @@ -315,7 +315,7 @@ impl<'a, S> ValueMut<'a, S> { /// Bools are usually represented as `0` or `1` bytes in NBT. impl From for Value { fn from(b: bool) -> Self { - Value::Byte(b as _) + Value::Byte(b.into()) } } diff --git a/tools/packet_inspector/build.rs b/tools/packet_inspector/build.rs index 8e089b7f3..9a64b69f8 100644 --- a/tools/packet_inspector/build.rs +++ b/tools/packet_inspector/build.rs @@ -197,7 +197,7 @@ fn write_transformer(packets: &[Packet]) -> anyhow::Result<()> { let generated = quote! { const NOT_AVAILABLE: &str = "Not yet implemented"; - pub fn packet_to_string(packet: &ProxyPacket) -> Result> { + pub(crate) fn packet_to_string(packet: &ProxyPacket) -> Result> { let bytes = packet.data.as_ref().unwrap(); let mut data = &bytes.clone()[..];