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