Skip to content

Commit

Permalink
(de)serialize for ItemStack and ItemKind
Browse files Browse the repository at this point in the history
  • Loading branch information
maxomatic458 committed Oct 11, 2024
1 parent 70a266a commit 05615c3
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
1 change: 1 addition & 0 deletions crates/valence_generated/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ workspace = true
valence_math.workspace = true
valence_ident.workspace = true
uuid.workspace = true
serde = { workspace = true, features = ["derive"] }

[build-dependencies]
anyhow.workspace = true
Expand Down
24 changes: 24 additions & 0 deletions crates/valence_generated/build/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,9 @@ pub(crate) fn build() -> anyhow::Result<TokenStream> {
.collect::<TokenStream>();

Ok(quote! {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde::de::{self, Unexpected};

/// Represents an item from the game
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
#[repr(u16)]
Expand All @@ -193,6 +196,27 @@ pub(crate) fn build() -> anyhow::Result<TokenStream> {
pub snack: bool,
}

impl Serialize for ItemKind {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_str())
}
}

impl<'de> Deserialize<'de> for ItemKind {
fn deserialize<D>(deserializer: D) -> Result<ItemKind, D::Error>
where
D: Deserializer<'de>,
{
let s: &str = Deserialize::deserialize(deserializer)?;
ItemKind::from_str(s).ok_or_else(|| {
de::Error::invalid_value(Unexpected::Str(s), &"the snake case item name, like \"white_wool\"")
})
}
}

impl ItemKind {
/// Constructs a item kind from a raw item ID.
///
Expand Down
3 changes: 2 additions & 1 deletion crates/valence_protocol/src/item.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use std::io::Write;

use serde::{Deserialize, Serialize};
pub use valence_generated::item::ItemKind;
use valence_nbt::Compound;

use crate::{Decode, Encode};

/// A stack of items in an inventory.
#[derive(Clone, PartialEq, Debug, Default)]
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug, Default)]
pub struct ItemStack {
pub item: ItemKind,
pub count: i8,
Expand Down

0 comments on commit 05615c3

Please sign in to comment.