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///
47/// What the stack means is read per version (`v` = [`Inventory::version`](crate::Inventory::version)):
48/// [`Stack::item_name`], [`Stack::kind`] / [`Stack::is_sword`], [`Stack::max_stack_size`],
49/// [`Stack::max_damage`] / [`Stack::damage_value`] (durability left = max − damage),
50/// [`Stack::custom_name`], [`Stack::lore`], [`Stack::enchantments`] (levels by name:
51/// [`Inventory::enchantment_level`](crate::Inventory::enchantment_level)) and
52/// [`Stack::potion`]. The version's static item facts are in `ghast-data`
53/// (`ghast_data::v1_8::Item::from_id(id).info()`, and so on).
54#[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    /// Numeric item id (1.8 / 1.12: legacy id; 1.16.5 / 26.1: item registry id).
64    #[inline]
65    #[must_use]
66    pub fn id(&self) -> i32 {
67        self.id
68    }
69
70    /// Stack size.
71    #[inline]
72    #[must_use]
73    pub fn count(&self) -> i32 {
74        self.count
75    }
76
77    /// 1.8 / 1.12 damage / metadata. Always 0 on 1.16.5 (the `Damage` NBT tag) and 26.1 (the
78    /// `damage` component); see [`Stack::damage_value`].
79    #[inline]
80    #[must_use]
81    pub fn damage(&self) -> i16 {
82        self.damage
83    }
84
85    /// NBT or data components exactly as received.
86    #[inline]
87    #[must_use]
88    pub fn data(&self) -> &ItemData {
89        &self.data
90    }
91
92    /// This stack with another item data.
93    #[must_use]
94    pub fn with_data(mut self, data: ItemData) -> Stack {
95        self.data = data;
96        self
97    }
98
99    /// This stack with another damage / metadata value.
100    #[must_use]
101    pub fn with_damage(mut self, damage: i16) -> Stack {
102        self.damage = damage;
103        self
104    }
105
106    /// A stack without NBT or component changes.
107    #[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    /// The NBT (1.8 – 1.16.5), if any.
118    #[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    /// This stack with its NBT replaced.
127    #[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    /// The 26.1 component patch, if the stack changes any component.
134    #[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    /// The same item (id, damage, NBT) with another count.
144    #[must_use]
145    pub fn with_count(&self, count: i32) -> Stack {
146        Stack {
147            count,
148            ..self.clone()
149        }
150    }
151
152    /// Converts a 1.8 wire stack.
153    #[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    /// Converts a 1.16.5 wire stack.
164    #[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    /// The stack with its NBT / components in an allocation of their own instead of a view
175    /// into the packet (for single-slot packets, whose frame shares the receive buffer with
176    /// other packets: a stack kept in the inventory would keep that buffer alive).
177    #[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    /// Converts a 26.1 wire stack (an empty patch becomes [`ItemData::None`]).
200    #[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    /// The 26.1 wire form (any NBT is dropped: 26.1 has none).
216    #[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    /// The 1.8 wire form (count truncated to a byte like Java's `writeByte`).
227    #[must_use]
228    pub fn to_legacy(&self) -> legacy::ItemStack {
229        legacy::ItemStack {
230            // An id outside i16 cannot come from a 1.8 server; -1 would encode "empty".
231            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    /// The 1.16.5 wire form.
242    #[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    /// Same item, damage and data (vanilla's item + damage check and its NBT check; 26.1
252    /// `isSameItemSameComponents`); counts are not compared.
253    #[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    /// Vanilla's data comparison: NBT both absent, or both present and equal as trees; 26.1
259    /// component patches equal as maps.
260    #[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    /// Same as [`Stack::data_eq`] (kept from 0.3, where item data was always NBT).
275    #[must_use]
276    pub fn nbt_eq(&self, other: &Stack) -> bool {
277        self.data_eq(other)
278    }
279
280    /// Exact equality as the server checks the clicked item (count, id, damage, NBT).
281    #[must_use]
282    pub fn equals_exact(&self, other: &Stack) -> bool {
283        self.count == other.count && self.same_item(other)
284    }
285
286    /// `getBoolean(key)` of the root compound: a numeric tag whose byte value is not zero.
287    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    /// `getInt(key)` of the root compound (0 when absent or not numeric).
292    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    /// 1.16.5 `EnchantmentHelper.hasBindingCurse`: an `Enchantments` entry with id
303    /// `minecraft:binding_curse` and `lvl` > 0.
304    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                // getLevel returns the first matching entry, clamped to 0..=255.
320                return last(e, "lvl").and_then(number).unwrap_or(0) as i32 > 0;
321            }
322        }
323        false
324    }
325}
326
327impl Stack {
328    /// 1.12 `EnchantmentHelper.hasBindingCurse`: the first `ench` entry whose short `id` is 10
329    /// (binding curse) decides, by its short `lvl` > 0.
330    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            // `getList("ench", 10)`: a list of anything but compounds reads as empty
339            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
349/// The value of the last entry named `key` (a Java `HashMap` keeps the last duplicate).
350pub(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        // NbtFloat/NbtDouble int and byte values are `MathHelper.floor(value)` (then `& 0xFF`).
361        Tag::Float(v) => {
362            let i = v as i32; // Java (int): saturating, NaN -> 0
363            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/// Vanilla tag equality on raw NBT: equal bytes are equal; otherwise both trees are parsed and
374/// compared (compounds as maps, root names ignored). Unparsable NBT only equals itself.
375#[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            // Map semantics: the last value of each key, same key set.
397            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; // a later duplicate decides
409                }
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        // Java `==` on float/double values: NaN != NaN, 0.0 == -0.0.
419        (Tag::Float(x), Tag::Float(y)) => x == y,
420        (Tag::Double(x), Tag::Double(y)) => x == y,
421        _ => a == b,
422    }
423}
424
425/// `Option<&Stack>` exact equality (the server's `ItemStack.equalsAll`).
426#[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/// Converts a 1.8 wire slot.
436#[must_use]
437pub fn from_legacy_slot(s: legacy::Slot) -> Option<Stack> {
438    s.0.map(Stack::from_legacy)
439}
440
441/// Converts a 1.16.5 wire slot; stacks that vanilla treats as empty (air, count <= 0) are `None`.
442#[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/// The 1.8 wire slot of an optional stack.
449#[must_use]
450pub fn to_legacy_slot(s: Option<&Stack>) -> legacy::Slot {
451    legacy::Slot(s.map(Stack::to_legacy))
452}
453
454/// The 1.16.5 wire slot of an optional stack.
455#[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        // Java float `==`: NaN is never equal (only reached when the bytes differ).
498        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        // Garbage NBT never panics.
540        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}