From 9a10ea4ed99428c228cbe980783dfa31c511d20f Mon Sep 17 00:00:00 2001 From: lukas0008 Date: Sat, 17 Aug 2024 21:11:31 +0200 Subject: [PATCH] Slot type --- pumpkin-protocol/src/lib.rs | 1 + pumpkin-protocol/src/slot.rs | 76 ++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 pumpkin-protocol/src/slot.rs diff --git a/pumpkin-protocol/src/lib.rs b/pumpkin-protocol/src/lib.rs index 3e2b8cdff..380a487e0 100644 --- a/pumpkin-protocol/src/lib.rs +++ b/pumpkin-protocol/src/lib.rs @@ -11,6 +11,7 @@ pub mod packet_encoder; pub mod position; pub mod server; pub mod uuid; +pub mod slot; pub const CURRENT_MC_PROTOCOL: u32 = 767; diff --git a/pumpkin-protocol/src/slot.rs b/pumpkin-protocol/src/slot.rs new file mode 100644 index 000000000..f6b3d8370 --- /dev/null +++ b/pumpkin-protocol/src/slot.rs @@ -0,0 +1,76 @@ +use serde::{ + de::{self, SeqAccess, Visitor}, + Deserialize, +}; + +use crate::VarInt; + +#[derive(Debug, Clone)] +pub struct Slot { + item_count: VarInt, + item_id: Option, + num_components_to_add: Option, + num_components_to_remove: Option, + components_to_add: Option>, // The second type depends on the varint + components_to_remove: Option>, +} + +impl<'de> Deserialize<'de> for Slot { + fn deserialize(deserializer: D) -> Result + where + D: de::Deserializer<'de>, + { + struct VarIntVisitor; + impl<'de> Visitor<'de> for VarIntVisitor { + type Value = Slot; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("a valid VarInt encoded in a byte sequence") + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let item_count = seq + .next_element::()? + .ok_or(de::Error::custom("Failed to decode VarInt"))?; + if item_count.0 == 0 { + return Ok(Slot { + item_count: 0.into(), + item_id: None, + num_components_to_add: None, + num_components_to_remove: None, + components_to_add: None, + components_to_remove: None, + }); + } + let item_id = seq + .next_element::()? + .ok_or(de::Error::custom("Failed to decode VarInt"))?; + let num_components_to_add = seq + .next_element::()? + .ok_or(de::Error::custom("Failed to decode VarInt"))?; + let num_components_to_remove = seq + .next_element::()? + .ok_or(de::Error::custom("Failed to decode VarInt"))?; + if num_components_to_add.0 != 0 || num_components_to_remove.0 != 0 { + return Err(de::Error::custom( + "Slot components are currently unsupported", + )); + } + + Ok(Slot { + item_count, + item_id: Some(item_id), + num_components_to_add: Some(num_components_to_add), + num_components_to_remove: Some(num_components_to_remove), + components_to_add: None, + components_to_remove: None, + }) + } + } + + deserializer.deserialize_seq(VarIntVisitor) + } +}