Skip to main content

ghast_inventory/
stack.rs

1//! Item stacks: one version-independent type over the 1.8 / 1.12 (`slot::legacy`), 1.16.5
2//! (`slot::modern`) and 26.1 (`slot::v775`) wire formats.
3//!
4//! Item data stays raw: NBT as [`RawNbt`], 26.1 data components as a
5//! [`ComponentPatch`](ghast_protocol::types::slot::v775::ComponentPatch) slice. Converting a
6//! `window_items` packet into stacks only moves reference-counted bytes. Comparisons compare
7//! the raw bytes first and only look inside when the bytes differ (vanilla compares NBT trees,
8//! which ignore compound key order and the root name, and component maps, which ignore order).
9
10use ghast_protocol::nbt::{RawNbt, Tag};
11use ghast_protocol::types::slot::{legacy, modern};
12
13/// The item data a stack carries, in its version's form.
14#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
15#[non_exhaustive]
16pub enum ItemData {
17    /// Nothing beyond the item id (no NBT; 26.1: the item's default components).
18    #[default]
19    None,
20    /// 1.8 – 1.16.5 item NBT exactly as received.
21    Nbt(RawNbt),
22    /// 26.1 data component patch (added / removed against the item's defaults) exactly as
23    /// received; components are decoded only when asked for. Boxed so that a [`Stack`] stays
24    /// small for the versions without components.
25    #[cfg(modern)]
26    Components(Box<ghast_protocol::types::slot::v775::ComponentPatch>),
27}
28
29impl ItemData {
30    /// From optional NBT.
31    #[must_use]
32    pub fn from_nbt(nbt: Option<RawNbt>) -> ItemData {
33        nbt.map_or(ItemData::None, ItemData::Nbt)
34    }
35}
36
37/// A non-empty item stack as the client holds it.
38///
39/// `count` is a Java `int` in vanilla (sent as a byte before 26.1). 1.8 keeps stacks with a
40/// count of zero or less as real stacks (they render as a red "0"); later versions treat them as
41/// empty, so their [`Inventory`](crate::Inventory) never stores one.
42///
43/// The fields are private so the representation can change without breaking users: read them
44/// with [`Stack::id`], [`Stack::count`], [`Stack::damage`], [`Stack::data`], build stacks with
45/// [`Stack::new`] and the `with_*` methods.
46#[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    /// Numeric item id (1.8 / 1.12: legacy id; 1.16.5 / 26.1: item registry id).
56    #[inline]
57    #[must_use]
58    pub fn id(&self) -> i32 {
59        self.id
60    }
61
62    /// Stack size.
63    #[inline]
64    #[must_use]
65    pub fn count(&self) -> i32 {
66        self.count
67    }
68
69    /// 1.8 / 1.12 damage / metadata. Always 0 on 1.16.5 (the `Damage` NBT tag) and 26.1 (the
70    /// `damage` component); see [`Stack::damage_value`].
71    #[inline]
72    #[must_use]
73    pub fn damage(&self) -> i16 {
74        self.damage
75    }
76
77    /// NBT or data components exactly as received.
78    #[inline]
79    #[must_use]
80    pub fn data(&self) -> &ItemData {
81        &self.data
82    }
83
84    /// This stack with another item data.
85    #[must_use]
86    pub fn with_data(mut self, data: ItemData) -> Stack {
87        self.data = data;
88        self
89    }
90
91    /// This stack with another damage / metadata value.
92    #[must_use]
93    pub fn with_damage(mut self, damage: i16) -> Stack {
94        self.damage = damage;
95        self
96    }
97
98    /// A stack without NBT or component changes.
99    #[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    /// The NBT (1.8 – 1.16.5), if any.
110    #[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    /// This stack with its NBT replaced.
119    #[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    /// The 26.1 component patch, if the stack changes any component.
126    #[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    /// The same item (id, damage, NBT) with another count.
136    #[must_use]
137    pub fn with_count(&self, count: i32) -> Stack {
138        Stack {
139            count,
140            ..self.clone()
141        }
142    }
143
144    /// Converts a 1.8 wire stack.
145    #[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    /// Converts a 1.16.5 wire stack.
156    #[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    /// The stack with its NBT / components in an allocation of their own instead of a view
167    /// into the packet (for single-slot packets, whose frame shares the receive buffer with
168    /// other packets: a stack kept in the inventory would keep that buffer alive).
169    #[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    /// Converts a 26.1 wire stack (an empty patch becomes [`ItemData::None`]).
191    #[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    /// The 26.1 wire form (any NBT is dropped: 26.1 has none).
207    #[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    /// The 1.8 wire form (count truncated to a byte like Java's `writeByte`).
218    #[must_use]
219    pub fn to_legacy(&self) -> legacy::ItemStack {
220        legacy::ItemStack {
221            // An id outside i16 cannot come from a 1.8 server; -1 would encode "empty".
222            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    /// The 1.16.5 wire form.
233    #[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    /// Same item, damage and data (vanilla's item + damage check and its NBT check; 26.1
243    /// `isSameItemSameComponents`); counts are not compared.
244    #[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    /// Vanilla's data comparison: NBT both absent, or both present and equal as trees; 26.1
250    /// component patches equal as maps.
251    #[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    /// Same as [`Stack::data_eq`] (kept from 0.3, where item data was always NBT).
266    #[must_use]
267    pub fn nbt_eq(&self, other: &Stack) -> bool {
268        self.data_eq(other)
269    }
270
271    /// Exact equality as the server checks the clicked item (count, id, damage, NBT).
272    #[must_use]
273    pub fn equals_exact(&self, other: &Stack) -> bool {
274        self.count == other.count && self.same_item(other)
275    }
276
277    /// `getBoolean(key)` of the root compound: a numeric tag whose byte value is not zero.
278    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    /// `getInt(key)` of the root compound (0 when absent or not numeric).
283    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    /// 1.16.5 `EnchantmentHelper.hasBindingCurse`: an `Enchantments` entry with id
294    /// `minecraft:binding_curse` and `lvl` > 0.
295    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                // getLevel returns the first matching entry, clamped to 0..=255.
311                return last(e, "lvl").and_then(number).unwrap_or(0) as i32 > 0;
312            }
313        }
314        false
315    }
316}
317
318impl Stack {
319    /// 1.12 `EnchantmentHelper.hasBindingCurse`: the first `ench` entry whose short `id` is 10
320    /// (binding curse) decides, by its short `lvl` > 0.
321    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            // `getList("ench", 10)`: a list of anything but compounds reads as empty
330            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
340/// The value of the last entry named `key` (a Java `HashMap` keeps the last duplicate).
341pub(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        // NbtFloat/NbtDouble int and byte values are `MathHelper.floor(value)` (then `& 0xFF`).
352        Tag::Float(v) => {
353            let i = v as i32; // Java (int): saturating, NaN -> 0
354            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/// Vanilla tag equality on raw NBT: equal bytes are equal; otherwise both trees are parsed and
365/// compared (compounds as maps, root names ignored). Unparsable NBT only equals itself.
366#[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            // Map semantics: the last value of each key, same key set.
388            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; // a later duplicate decides
400                }
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        // Java `==` on float/double values: NaN != NaN, 0.0 == -0.0.
410        (Tag::Float(x), Tag::Float(y)) => x == y,
411        (Tag::Double(x), Tag::Double(y)) => x == y,
412        _ => a == b,
413    }
414}
415
416/// `Option<&Stack>` exact equality (the server's `ItemStack.equalsAll`).
417#[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/// Converts a 1.8 wire slot.
427#[must_use]
428pub fn from_legacy_slot(s: legacy::Slot) -> Option<Stack> {
429    s.0.map(Stack::from_legacy)
430}
431
432/// Converts a 1.16.5 wire slot; stacks that vanilla treats as empty (air, count <= 0) are `None`.
433#[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/// The 1.8 wire slot of an optional stack.
440#[must_use]
441pub fn to_legacy_slot(s: Option<&Stack>) -> legacy::Slot {
442    legacy::Slot(s.map(Stack::to_legacy))
443}
444
445/// The 1.16.5 wire slot of an optional stack.
446#[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        // Java float `==`: NaN is never equal (only reached when the bytes differ).
489        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        // Garbage NBT never panics.
531        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}