1use ghast_protocol::nbt::{RawNbt, Tag};
11use ghast_protocol::types::slot::{legacy, modern};
12
13#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
15#[non_exhaustive]
16pub enum ItemData {
17 #[default]
19 None,
20 Nbt(RawNbt),
22 #[cfg(modern)]
26 Components(Box<ghast_protocol::types::slot::v775::ComponentPatch>),
27}
28
29impl ItemData {
30 #[must_use]
32 pub fn from_nbt(nbt: Option<RawNbt>) -> ItemData {
33 nbt.map_or(ItemData::None, ItemData::Nbt)
34 }
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, Hash)]
47pub struct Stack {
48 pub(crate) id: i32,
49 pub(crate) count: i32,
50 pub(crate) damage: i16,
51 pub(crate) data: ItemData,
52}
53
54impl Stack {
55 #[inline]
57 #[must_use]
58 pub fn id(&self) -> i32 {
59 self.id
60 }
61
62 #[inline]
64 #[must_use]
65 pub fn count(&self) -> i32 {
66 self.count
67 }
68
69 #[inline]
72 #[must_use]
73 pub fn damage(&self) -> i16 {
74 self.damage
75 }
76
77 #[inline]
79 #[must_use]
80 pub fn data(&self) -> &ItemData {
81 &self.data
82 }
83
84 #[must_use]
86 pub fn with_data(mut self, data: ItemData) -> Stack {
87 self.data = data;
88 self
89 }
90
91 #[must_use]
93 pub fn with_damage(mut self, damage: i16) -> Stack {
94 self.damage = damage;
95 self
96 }
97
98 #[must_use]
100 pub fn new(id: i32, count: i32, damage: i16) -> Stack {
101 Stack {
102 id,
103 count,
104 damage,
105 data: ItemData::None,
106 }
107 }
108
109 #[must_use]
111 pub fn nbt(&self) -> Option<&RawNbt> {
112 match &self.data {
113 ItemData::Nbt(n) => Some(n),
114 _ => None,
115 }
116 }
117
118 #[must_use]
120 pub fn with_nbt(mut self, nbt: Option<RawNbt>) -> Stack {
121 self.data = ItemData::from_nbt(nbt);
122 self
123 }
124
125 #[cfg(modern)]
127 #[must_use]
128 pub fn components(&self) -> Option<&ghast_protocol::types::slot::v775::ComponentPatch> {
129 match &self.data {
130 ItemData::Components(c) => Some(c),
131 _ => None,
132 }
133 }
134
135 #[must_use]
137 pub fn with_count(&self, count: i32) -> Stack {
138 Stack {
139 count,
140 ..self.clone()
141 }
142 }
143
144 #[must_use]
146 pub fn from_legacy(s: legacy::ItemStack) -> Stack {
147 Stack {
148 id: i32::from(s.id),
149 count: i32::from(s.count),
150 damage: s.damage,
151 data: ItemData::from_nbt(s.nbt),
152 }
153 }
154
155 #[must_use]
157 pub fn from_modern(s: modern::ItemStack) -> Stack {
158 Stack {
159 id: s.id,
160 count: i32::from(s.count),
161 damage: 0,
162 data: ItemData::from_nbt(s.nbt),
163 }
164 }
165
166 #[must_use]
170 #[cfg_attr(
171 not(any(
172 feature = "v1_8",
173 feature = "v1_12",
174 feature = "v1_16_5",
175 feature = "v26_1",
176 feature = "v26_2"
177 )),
178 allow(dead_code)
179 )]
180 pub(crate) fn detached(mut self) -> Stack {
181 match &mut self.data {
182 ItemData::None => {}
183 ItemData::Nbt(n) => n.detach(),
184 #[cfg(modern)]
185 ItemData::Components(c) => c.detach(),
186 }
187 self
188 }
189
190 #[cfg(modern)]
192 #[must_use]
193 pub fn from_v775(s: ghast_protocol::types::slot::v775::ItemStack) -> Stack {
194 Stack {
195 id: s.id,
196 count: s.count,
197 damage: 0,
198 data: if s.components.is_empty() {
199 ItemData::None
200 } else {
201 ItemData::Components(Box::new(s.components))
202 },
203 }
204 }
205
206 #[cfg(modern)]
208 #[must_use]
209 pub fn to_v775(&self) -> ghast_protocol::types::slot::v775::ItemStack {
210 ghast_protocol::types::slot::v775::ItemStack {
211 id: self.id,
212 count: self.count,
213 components: self.components().cloned().unwrap_or_default(),
214 }
215 }
216
217 #[must_use]
219 pub fn to_legacy(&self) -> legacy::ItemStack {
220 legacy::ItemStack {
221 id: i16::try_from(self.id)
223 .ok()
224 .filter(|&i| i != -1)
225 .unwrap_or(0),
226 count: self.count as i8,
227 damage: self.damage,
228 nbt: self.nbt().cloned(),
229 }
230 }
231
232 #[must_use]
234 pub fn to_modern(&self) -> modern::ItemStack {
235 modern::ItemStack {
236 id: self.id,
237 count: self.count as i8,
238 nbt: self.nbt().cloned(),
239 }
240 }
241
242 #[must_use]
245 pub fn same_item(&self, other: &Stack) -> bool {
246 self.id == other.id && self.damage == other.damage && self.data_eq(other)
247 }
248
249 #[must_use]
252 pub fn data_eq(&self, other: &Stack) -> bool {
253 match (&self.data, &other.data) {
254 (ItemData::None, ItemData::None) => true,
255 (ItemData::Nbt(a), ItemData::Nbt(b)) => nbt_eq(Some(a), Some(b)),
256 #[cfg(modern)]
257 (ItemData::Components(a), ItemData::Components(b)) => a.same_components(b),
258 #[cfg(modern)]
259 (ItemData::Components(c), ItemData::None)
260 | (ItemData::None, ItemData::Components(c)) => c.is_empty(),
261 _ => false,
262 }
263 }
264
265 #[must_use]
267 pub fn nbt_eq(&self, other: &Stack) -> bool {
268 self.data_eq(other)
269 }
270
271 #[must_use]
273 pub fn equals_exact(&self, other: &Stack) -> bool {
274 self.count == other.count && self.same_item(other)
275 }
276
277 pub(crate) fn nbt_bool(&self, key: &str) -> bool {
279 self.nbt_number(key).is_some_and(|v| v as i8 != 0)
280 }
281
282 pub(crate) fn nbt_int(&self, key: &str) -> i32 {
284 self.nbt_number(key).unwrap_or(0) as i32
285 }
286
287 fn nbt_number(&self, key: &str) -> Option<i64> {
288 let tree = self.nbt()?.parse().ok()??;
289 let c = tree.tag.as_compound()?;
290 number(last(c, key)?)
291 }
292
293 pub(crate) fn has_binding_curse(&self) -> bool {
296 let Some(Ok(Some(tree))) = self.nbt().map(RawNbt::parse) else {
297 return false;
298 };
299 let Some(Tag::List(list)) = tree.tag.as_compound().and_then(|c| last(c, "Enchantments"))
300 else {
301 return false;
302 };
303 for e in &list.items {
304 let Tag::Compound(e) = e else { return false };
305 let id = match last(e, "id") {
306 Some(Tag::String(s)) => s.as_str(),
307 _ => "",
308 };
309 if id == "minecraft:binding_curse" || id == "binding_curse" {
310 return last(e, "lvl").and_then(number).unwrap_or(0) as i32 > 0;
312 }
313 }
314 false
315 }
316}
317
318impl Stack {
319 pub(crate) fn has_binding_curse_1_12(&self) -> bool {
322 let Some(Ok(Some(tree))) = self.nbt().map(RawNbt::parse) else {
323 return false;
324 };
325 let Some(Tag::List(list)) = tree.tag.as_compound().and_then(|c| last(c, "ench")) else {
326 return false;
327 };
328 for e in &list.items {
329 let Tag::Compound(e) = e else { return false };
331 let short = |k: &str| last(e, k).and_then(number).unwrap_or(0) as i16;
332 if short("id") == 10 {
333 return short("lvl") > 0;
334 }
335 }
336 false
337 }
338}
339
340pub(crate) fn last<'a>(c: &'a ghast_protocol::nbt::Compound, key: &str) -> Option<&'a Tag> {
342 c.0.iter().rev().find(|(k, _)| k == key).map(|(_, v)| v)
343}
344
345pub(crate) fn number(t: &Tag) -> Option<i64> {
346 Some(match *t {
347 Tag::Byte(v) => i64::from(v),
348 Tag::Short(v) => i64::from(v),
349 Tag::Int(v) => i64::from(v),
350 Tag::Long(v) => v,
351 Tag::Float(v) => {
353 let i = v as i32; i64::from(if v < i as f32 { i - 1 } else { i })
355 }
356 Tag::Double(v) => {
357 let i = v as i32;
358 i64::from(if v < f64::from(i) { i - 1 } else { i })
359 }
360 _ => return None,
361 })
362}
363
364#[must_use]
367pub fn nbt_eq(a: Option<&RawNbt>, b: Option<&RawNbt>) -> bool {
368 match (a, b) {
369 (None, None) => true,
370 (Some(a), Some(b)) => {
371 if a.as_bytes() == b.as_bytes() {
372 return true;
373 }
374 match (a.parse(), b.parse()) {
375 (Ok(Some(x)), Ok(Some(y))) => tag_eq(&x.tag, &y.tag),
376 (Ok(None), Ok(None)) => true,
377 _ => false,
378 }
379 }
380 _ => false,
381 }
382}
383
384fn tag_eq(a: &Tag, b: &Tag) -> bool {
385 match (a, b) {
386 (Tag::Compound(x), Tag::Compound(y)) => {
387 let distinct = |c: &ghast_protocol::nbt::Compound| {
389 c.0.iter()
390 .enumerate()
391 .filter(|(i, (k, _))| !c.0[i + 1..].iter().any(|(k2, _)| k2 == k))
392 .count()
393 };
394 if distinct(x) != distinct(y) {
395 return false;
396 }
397 x.0.iter().enumerate().all(|(i, (k, v))| {
398 if x.0[i + 1..].iter().any(|(k2, _)| k2 == k) {
399 return true; }
401 last(y, k).is_some_and(|w| tag_eq(v, w))
402 })
403 }
404 (Tag::List(x), Tag::List(y)) => {
405 x.elem_type == y.elem_type
406 && x.items.len() == y.items.len()
407 && x.items.iter().zip(&y.items).all(|(v, w)| tag_eq(v, w))
408 }
409 (Tag::Float(x), Tag::Float(y)) => x == y,
411 (Tag::Double(x), Tag::Double(y)) => x == y,
412 _ => a == b,
413 }
414}
415
416#[must_use]
418pub fn stacks_equal(a: Option<&Stack>, b: Option<&Stack>) -> bool {
419 match (a, b) {
420 (None, None) => true,
421 (Some(a), Some(b)) => a.equals_exact(b),
422 _ => false,
423 }
424}
425
426#[must_use]
428pub fn from_legacy_slot(s: legacy::Slot) -> Option<Stack> {
429 s.0.map(Stack::from_legacy)
430}
431
432#[must_use]
434pub fn from_modern_slot(s: modern::Slot) -> Option<Stack> {
435 s.0.map(Stack::from_modern)
436 .filter(|s| s.id != 0 && s.count > 0)
437}
438
439#[must_use]
441pub fn to_legacy_slot(s: Option<&Stack>) -> legacy::Slot {
442 legacy::Slot(s.map(Stack::to_legacy))
443}
444
445#[must_use]
447pub fn to_modern_slot(s: Option<&Stack>) -> modern::Slot {
448 modern::Slot(s.map(Stack::to_modern))
449}
450
451#[cfg(test)]
452mod tests {
453 use super::*;
454 use bytes::Bytes;
455 use ghast_protocol::nbt::{Compound, NamedTag};
456
457 fn raw(entries: Vec<(&str, Tag)>, root: &str) -> RawNbt {
458 RawNbt::from_named(&NamedTag {
459 name: root.into(),
460 tag: Tag::Compound(Compound(
461 entries
462 .into_iter()
463 .map(|(k, v)| (k.to_string(), v))
464 .collect(),
465 )),
466 })
467 .unwrap()
468 }
469
470 #[test]
471 fn nbt_equality_is_tree_equality() {
472 let a = raw(vec![("a", Tag::Int(1)), ("b", Tag::Byte(2))], "");
473 let b = raw(vec![("b", Tag::Byte(2)), ("a", Tag::Int(1))], "");
474 let c = raw(vec![("a", Tag::Int(1)), ("b", Tag::Byte(3))], "");
475 let d = raw(vec![("a", Tag::Int(1)), ("b", Tag::Byte(2))], "root");
476 assert!(nbt_eq(Some(&a), Some(&a)));
477 assert!(nbt_eq(Some(&a), Some(&b)));
478 assert!(!nbt_eq(Some(&a), Some(&c)));
479 assert!(nbt_eq(Some(&a), Some(&d)));
480 assert!(!nbt_eq(Some(&a), None));
481 let empty = raw(vec![], "");
482 assert!(!nbt_eq(Some(&empty), None));
483 let dup = raw(
484 vec![("a", Tag::Int(5)), ("a", Tag::Int(1)), ("b", Tag::Byte(2))],
485 "",
486 );
487 assert!(nbt_eq(Some(&a), Some(&dup)));
488 let nan = raw(vec![("f", Tag::Float(f32::NAN)), ("g", Tag::Byte(0))], "");
490 let nan_reordered = raw(vec![("g", Tag::Byte(0)), ("f", Tag::Float(f32::NAN))], "");
491 assert!(!nbt_eq(Some(&nan), Some(&nan_reordered)));
492 }
493
494 #[test]
495 fn nbt_helpers() {
496 let mut s = Stack::new(1, 1, 0);
497 assert!(!s.nbt_bool("Unbreakable"));
498 s.data = ItemData::Nbt(raw(
499 vec![("Unbreakable", Tag::Byte(1)), ("Damage", Tag::Int(7))],
500 "",
501 ));
502 assert!(s.nbt_bool("Unbreakable"));
503 assert_eq!(s.nbt_int("Damage"), 7);
504 s.data = ItemData::Nbt(raw(vec![("Unbreakable", Tag::Int(256))], ""));
505 assert!(!s.nbt_bool("Unbreakable"), "(byte) 256 == 0");
506 let ench = |id: &str, lvl: i16| {
507 Tag::List(ghast_protocol::nbt::List {
508 elem_type: 10,
509 items: vec![Tag::Compound(Compound(vec![
510 ("id".into(), Tag::String(id.into())),
511 ("lvl".into(), Tag::Short(lvl)),
512 ]))],
513 })
514 };
515 s.data = ItemData::Nbt(raw(
516 vec![("Enchantments", ench("minecraft:binding_curse", 1))],
517 "",
518 ));
519 assert!(s.has_binding_curse());
520 s.data = ItemData::Nbt(raw(
521 vec![("Enchantments", ench("minecraft:binding_curse", 0))],
522 "",
523 ));
524 assert!(!s.has_binding_curse());
525 s.data = ItemData::Nbt(raw(
526 vec![("StoredEnchantments", ench("minecraft:binding_curse", 1))],
527 "",
528 ));
529 assert!(!s.has_binding_curse());
530 s.data = ItemData::from_nbt(RawNbt::from_bytes(Bytes::from_static(&[0x0a, 0, 0, 0])).ok());
532 assert!(!s.has_binding_curse());
533 }
534
535 #[test]
536 fn wire_round_trip() {
537 let s = Stack::new(276, 1, 5);
538 assert_eq!(Stack::from_legacy(s.to_legacy()), s);
539 let m = Stack::new(600, 64, 0);
540 assert_eq!(Stack::from_modern(m.to_modern()), m);
541 assert_eq!(
542 from_modern_slot(modern::Slot(Some(modern::ItemStack {
543 id: 1,
544 count: 0,
545 nbt: None
546 }))),
547 None
548 );
549 assert_eq!(
550 from_modern_slot(modern::Slot(Some(modern::ItemStack {
551 id: 0,
552 count: 5,
553 nbt: None
554 }))),
555 None
556 );
557 assert!(
558 from_legacy_slot(legacy::Slot(Some(legacy::ItemStack {
559 id: 1,
560 count: 0,
561 damage: 0,
562 nbt: None
563 })))
564 .is_some()
565 );
566 assert_eq!(Stack::new(1, 300, 0).to_legacy().count, 44);
567 }
568}