Skip to main content

ghast_protocol/types/
slot.rs

1//! Inventory slots (item stacks) in their per-version wire formats.
2//!
3//! NBT is kept raw ([`RawNbt`](crate::nbt::RawNbt)): decoding a `window_items` packet only walks the NBT to
4//! find its end; building a tree is up to the caller ([`RawNbt::parse`](crate::nbt::RawNbt::parse)).
5
6/// Slot format of 1.8 – 1.12.2: `i16` item id (`-1` = empty), `i8` count, `i16` damage,
7/// optional NBT (`0` byte = none).
8pub mod legacy {
9    use bytes::{BufMut, BytesMut};
10
11    use crate::codec::{Decode, DecodeResult, Encode, EncodeResult, Reader};
12    use crate::error::EncodeError;
13    use crate::nbt::RawNbt;
14
15    /// A non-empty item stack.
16    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
17    pub struct ItemStack {
18        /// Numeric item id. Never `-1` (that encodes an empty slot).
19        pub id: i16,
20        /// Stack size.
21        pub count: i8,
22        /// Damage / metadata value.
23        pub damage: i16,
24        /// Item NBT, if any.
25        pub nbt: Option<RawNbt>,
26    }
27
28    /// One slot: empty or an item stack.
29    #[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
30    pub struct Slot(pub Option<ItemStack>);
31
32    impl Slot {
33        /// The empty slot.
34        pub const EMPTY: Slot = Slot(None);
35
36        /// Whether the slot is empty.
37        #[inline]
38        pub fn is_empty(&self) -> bool {
39            self.0.is_none()
40        }
41
42        /// The item stack, if any.
43        #[inline]
44        pub fn item(&self) -> Option<&ItemStack> {
45            self.0.as_ref()
46        }
47    }
48
49    impl Decode for Slot {
50        #[inline]
51        fn decode(r: &mut Reader<'_>) -> DecodeResult<Self> {
52            let id = r.read_i16()?;
53            if id == -1 {
54                return Ok(Slot(None));
55            }
56            Ok(Slot(Some(ItemStack {
57                id,
58                count: r.read_i8()?,
59                damage: r.read_i16()?,
60                nbt: RawNbt::read_optional(r)?,
61            })))
62        }
63    }
64
65    impl Encode for Slot {
66        #[inline]
67        fn encode(&self, w: &mut BytesMut) -> EncodeResult {
68            match &self.0 {
69                None => w.put_i16(-1),
70                Some(it) => {
71                    if it.id == -1 {
72                        return Err(EncodeError::Invalid(
73                            "item id -1 is reserved for empty slots",
74                        ));
75                    }
76                    w.put_i16(it.id);
77                    w.put_i8(it.count);
78                    w.put_i16(it.damage);
79                    RawNbt::write_optional(&it.nbt, w);
80                }
81            }
82            Ok(())
83        }
84    }
85}
86
87/// Slot format of 1.13.2 – 1.20.4: `bool` present, then VarInt item id, `i8` count,
88/// optional NBT.
89pub mod modern {
90    use bytes::{BufMut, BytesMut};
91
92    use crate::codec::{Decode, DecodeResult, Encode, EncodeResult, McWrite, Reader};
93    use crate::nbt::RawNbt;
94
95    /// A non-empty item stack.
96    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
97    pub struct ItemStack {
98        /// Registry item id.
99        pub id: i32,
100        /// Stack size.
101        pub count: i8,
102        /// Item NBT, if any.
103        pub nbt: Option<RawNbt>,
104    }
105
106    /// One slot: empty or an item stack.
107    #[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
108    pub struct Slot(pub Option<ItemStack>);
109
110    impl Slot {
111        /// The empty slot.
112        pub const EMPTY: Slot = Slot(None);
113
114        /// Whether the slot is empty.
115        #[inline]
116        pub fn is_empty(&self) -> bool {
117            self.0.is_none()
118        }
119
120        /// The item stack, if any.
121        #[inline]
122        pub fn item(&self) -> Option<&ItemStack> {
123            self.0.as_ref()
124        }
125    }
126
127    impl Decode for Slot {
128        #[inline]
129        fn decode(r: &mut Reader<'_>) -> DecodeResult<Self> {
130            if !r.read_bool()? {
131                return Ok(Slot(None));
132            }
133            Ok(Slot(Some(ItemStack {
134                id: r.read_varint()?,
135                count: r.read_i8()?,
136                nbt: RawNbt::read_optional(r)?,
137            })))
138        }
139    }
140
141    impl Encode for Slot {
142        #[inline]
143        fn encode(&self, w: &mut BytesMut) -> EncodeResult {
144            match &self.0 {
145                None => w.put_bool(false),
146                Some(it) => {
147                    w.put_bool(true);
148                    w.put_varint(it.id);
149                    w.put_i8(it.count);
150                    RawNbt::write_optional(&it.nbt, w);
151                }
152            }
153            Ok(())
154        }
155    }
156}
157
158/// Slot format of 26.1 (protocol 775) with lazily decoded data components.
159///
160/// On the wire (vanilla `ItemStack.OPTIONAL_STREAM_CODEC`): VarInt count (`<= 0` = empty),
161/// VarInt item id, VarInt added-component count, VarInt removed-component count, the added
162/// components (VarInt type + value, **not** length-prefixed), the removed component types.
163/// [`ItemStack::read`](v775::ItemStack::read) walks the components with the generated
164/// structural skip ([`SlotComponent::skip`](crate::defs::p775::types::SlotComponent::skip))
165/// and keeps the patch as one zero-copy [`Bytes`](bytes::Bytes) slice; a
166/// component is decoded only when asked for.
167#[cfg(feature = "v26_1")]
168pub mod v775 {
169    use bytes::{BufMut, Bytes, BytesMut};
170
171    use crate::codec::{DecodeResult, McWrite, Reader};
172    use crate::defs::p775::types::SlotComponent;
173    use crate::error::DecodeError;
174
175    /// The data component patch of a stack (added components, then removed types), exactly as
176    /// received.
177    #[derive(Debug, Clone, Default)]
178    pub struct ComponentPatch {
179        /// Added components followed by the removed types.
180        bytes: Bytes,
181        /// Byte offset of the removed list in `bytes`.
182        split: u32,
183        added: u16,
184        removed: u16,
185        /// Added / removed types below 127 as bits; bit 127 = a type outside `0..127` occurs
186        /// (lookups of such types scan). Lets lookups of absent types skip the scan.
187        added_mask: u128,
188        removed_mask: u128,
189    }
190
191    /// The mask bit of a component type.
192    #[inline]
193    fn bit(ty: i32) -> u128 {
194        match u32::try_from(ty) {
195            Ok(t) if t < 127 => 1u128 << t,
196            _ => 1u128 << 127,
197        }
198    }
199
200    /// Whether a mask may contain `ty`.
201    #[inline]
202    fn may_have(mask: u128, ty: i32) -> bool {
203        mask & (bit(ty) | 1u128 << 127) != 0
204    }
205
206    /// Patches are equal when their bytes are (component order included; see
207    /// [`ComponentPatch::same_components`] for vanilla's map equality).
208    impl PartialEq for ComponentPatch {
209        fn eq(&self, other: &Self) -> bool {
210            self.added == other.added && self.removed == other.removed && self.bytes == other.bytes
211        }
212    }
213
214    impl Eq for ComponentPatch {}
215
216    impl std::hash::Hash for ComponentPatch {
217        fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
218            self.bytes.hash(h);
219        }
220    }
221
222    impl ComponentPatch {
223        /// The empty patch (the item's default components).
224        pub const EMPTY: ComponentPatch = ComponentPatch {
225            bytes: Bytes::new(),
226            split: 0,
227            added: 0,
228            removed: 0,
229            added_mask: 0,
230            removed_mask: 0,
231        };
232
233        /// Reads `added` components and `removed` types by skipping over them.
234        pub fn read(r: &mut Reader<'_>, added: i32, removed: i32) -> DecodeResult<Self> {
235            let added_n = r.check_count(i64::from(added), 1)?;
236            let removed_n = r.check_count(i64::from(removed), 1)?;
237            let (Ok(added), Ok(removed)) = (u16::try_from(added_n), u16::try_from(removed_n))
238            else {
239                return Err(DecodeError::Invalid("component count"));
240            };
241            let start = r.position();
242            let mut added_mask = 0u128;
243            for _ in 0..added_n {
244                added_mask |= bit(r.clone().read_varint()?);
245                SlotComponent::skip(r)?;
246            }
247            let split = (r.position() - start) as u32;
248            let mut removed_mask = 0u128;
249            for _ in 0..removed_n {
250                removed_mask |= bit(r.read_varint()?);
251            }
252            Ok(ComponentPatch {
253                bytes: r.bytes_since(start),
254                split,
255                added,
256                removed,
257                added_mask,
258                removed_mask,
259            })
260        }
261
262        /// `true` when nothing is added or removed.
263        #[must_use]
264        pub fn is_empty(&self) -> bool {
265            self.added == 0 && self.removed == 0
266        }
267
268        /// Number of added components.
269        #[must_use]
270        pub fn added_len(&self) -> usize {
271            usize::from(self.added)
272        }
273
274        /// Number of removed component types.
275        #[must_use]
276        pub fn removed_len(&self) -> usize {
277            usize::from(self.removed)
278        }
279
280        /// The patch bytes as received (added components, then removed types).
281        #[must_use]
282        pub fn as_bytes(&self) -> &Bytes {
283            &self.bytes
284        }
285
286        /// The added components as `(type id, value bytes)`, in wire order.
287        pub fn iter(&self) -> Components<'_> {
288            Components {
289                bytes: self.bytes.slice(..self.split as usize),
290                pos: 0,
291                left: self.added,
292                _p: std::marker::PhantomData,
293            }
294        }
295
296        /// The removed component type ids, in wire order.
297        pub fn removed(&self) -> impl Iterator<Item = i32> + '_ {
298            let tail = self.bytes.slice(self.split as usize..);
299            let mut pos = 0usize;
300            (0..self.removed).map_while(move |_| {
301                let mut r = Reader::new(&tail);
302                r.skip(pos).ok()?;
303                let v = r.read_varint().ok()?;
304                pos = r.position();
305                Some(v)
306            })
307        }
308
309        /// `true` when the patch removes component `ty`.
310        #[must_use]
311        pub fn removes(&self, ty: i32) -> bool {
312            may_have(self.removed_mask, ty) && self.removed().any(|t| t == ty)
313        }
314
315        /// Whether the patch adds component `ty` (no scan when it certainly does not).
316        #[must_use]
317        pub fn adds(&self, ty: i32) -> bool {
318            may_have(self.added_mask, ty) && self.iter().any(|(t, _)| t == ty)
319        }
320
321        /// The value bytes of added component `ty` (vanilla keeps the last one of a type).
322        #[must_use]
323        pub fn get(&self, ty: i32) -> Option<Bytes> {
324            if !may_have(self.added_mask, ty) {
325                return None;
326            }
327            self.iter().filter(|(t, _)| *t == ty).last().map(|(_, b)| b)
328        }
329
330        /// Decodes added component `ty` with the generated type (the last one of that type).
331        #[must_use]
332        pub fn decode(&self, ty: i32) -> Option<DecodeResult<SlotComponent>> {
333            if !may_have(self.added_mask, ty) {
334                return None;
335            }
336            let mut r = Reader::new(&self.bytes);
337            let mut last = None;
338            for _ in 0..self.added {
339                let start = r.position();
340                let t = match r.clone().read_varint() {
341                    Ok(t) => t,
342                    Err(e) => return Some(Err(e)),
343                };
344                if let Err(e) = SlotComponent::skip(&mut r) {
345                    return Some(Err(e));
346                }
347                if t == ty {
348                    last = Some(start);
349                }
350            }
351            let start = last?;
352            let mut r = Reader::new(&self.bytes);
353            if let Err(e) = r.skip(start) {
354                return Some(Err(e));
355            }
356            Some(<SlotComponent as crate::codec::Decode>::decode(&mut r))
357        }
358
359        /// Decodes every added component with the generated type.
360        ///
361        /// # Errors
362        /// A malformed component.
363        pub fn decode_all(&self) -> DecodeResult<Vec<SlotComponent>> {
364            let mut r = Reader::new(&self.bytes);
365            (0..self.added)
366                .map(|_| <SlotComponent as crate::codec::Decode>::decode(&mut r))
367                .collect()
368        }
369
370        /// Vanilla's patch equality (`DataComponentPatch.equals`: a map from type to value):
371        /// the same removed types and the same added `(type, value bytes)` set, in any order.
372        /// Values compare by bytes (values that differ only in NBT compound key order compare
373        /// unequal here; vanilla would compare their trees).
374        #[must_use]
375        pub fn same_components(&self, other: &ComponentPatch) -> bool {
376            if self == other {
377                return true;
378            }
379            let mut a: Vec<i32> = self.removed().collect();
380            let mut b: Vec<i32> = other.removed().collect();
381            a.sort_unstable();
382            a.dedup();
383            b.sort_unstable();
384            b.dedup();
385            if a != b {
386                return false;
387            }
388            let last = |p: &ComponentPatch| {
389                let mut v: Vec<(i32, Bytes)> = Vec::new();
390                for (t, b) in p.iter() {
391                    match v.iter_mut().find(|(k, _)| *k == t) {
392                        Some(e) => e.1 = b,
393                        None => v.push((t, b)),
394                    }
395                }
396                v.sort_by_key(|(t, _)| *t);
397                v
398            };
399            last(self) == last(other)
400        }
401
402        /// Builds a patch from `(type, value bytes)` components and removed types (tests,
403        /// creative clients).
404        #[must_use]
405        pub fn from_parts(added: &[(i32, &[u8])], removed: &[i32]) -> ComponentPatch {
406            let mut w = BytesMut::new();
407            for (t, v) in added {
408                w.put_varint(*t);
409                w.put_slice(v);
410            }
411            let split = w.len() as u32;
412            for t in removed {
413                w.put_varint(*t);
414            }
415            ComponentPatch {
416                bytes: w.freeze(),
417                split,
418                added: added.len() as u16,
419                removed: removed.len() as u16,
420                added_mask: added.iter().fold(0, |m, (t, _)| m | bit(*t)),
421                removed_mask: removed.iter().fold(0, |m, t| m | bit(*t)),
422            }
423        }
424    }
425
426    /// Iterator over the added components of a [`ComponentPatch`].
427    #[derive(Debug, Clone)]
428    pub struct Components<'a> {
429        bytes: Bytes,
430        pos: usize,
431        left: u16,
432        _p: std::marker::PhantomData<&'a ComponentPatch>,
433    }
434
435    impl Iterator for Components<'_> {
436        type Item = (i32, Bytes);
437
438        fn next(&mut self) -> Option<(i32, Bytes)> {
439            if self.left == 0 {
440                return None;
441            }
442            self.left -= 1;
443            let mut r = Reader::new(&self.bytes);
444            r.skip(self.pos).ok()?;
445            let mut value = r.clone();
446            let ty = value.read_varint().ok()?;
447            let value_start = value.position();
448            SlotComponent::skip(&mut r).ok()?;
449            self.pos = r.position();
450            Some((ty, self.bytes.slice(value_start..self.pos)))
451        }
452    }
453
454    /// A non-empty 26.1 item stack.
455    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
456    pub struct ItemStack {
457        /// Item registry id.
458        pub id: i32,
459        /// Stack size (`> 0`).
460        pub count: i32,
461        /// Data component patch against the item's defaults.
462        pub components: ComponentPatch,
463    }
464
465    impl ItemStack {
466        /// Reads one slot; `None` for an empty one (count `<= 0`, as vanilla reads it).
467        pub fn read(r: &mut Reader<'_>) -> DecodeResult<Option<ItemStack>> {
468            let count = r.read_varint()?;
469            if count <= 0 {
470                return Ok(None);
471            }
472            let id = r.read_varint()?;
473            let added = r.read_varint()?;
474            let removed = r.read_varint()?;
475            let components = ComponentPatch::read(r, added, removed)?;
476            Ok(Some(ItemStack {
477                id,
478                count,
479                components,
480            }))
481        }
482
483        /// Writes one slot (`None` = empty).
484        pub fn write(s: Option<&ItemStack>, w: &mut BytesMut) {
485            match s {
486                None => w.put_varint(0),
487                Some(s) => {
488                    w.put_varint(s.count);
489                    w.put_varint(s.id);
490                    w.put_varint(i32::from(s.components.added));
491                    w.put_varint(i32::from(s.components.removed));
492                    w.put_slice(&s.components.bytes);
493                }
494            }
495        }
496    }
497}
498
499#[cfg(test)]
500mod tests {
501    use super::*;
502    use crate::codec::{Encode, decode_exact};
503    use bytes::{Bytes, BytesMut};
504
505    #[test]
506    fn legacy_known_answers() {
507        // Empty slot.
508        let b = Bytes::from_static(&[0xff, 0xff]);
509        assert_eq!(decode_exact::<legacy::Slot>(&b), Ok(legacy::Slot::EMPTY));
510        // 64 x stone (id 1), damage 0, no NBT.
511        let b = Bytes::from_static(&[0x00, 0x01, 0x40, 0x00, 0x00, 0x00]);
512        let s = decode_exact::<legacy::Slot>(&b).unwrap();
513        let it = s.item().unwrap();
514        assert_eq!(
515            (it.id, it.count, it.damage, it.nbt.is_none()),
516            (1, 64, 0, true)
517        );
518        let mut w = BytesMut::new();
519        s.encode(&mut w).unwrap();
520        assert_eq!(&w[..], &b[..]);
521        // With an empty-named empty compound as NBT.
522        let b = Bytes::from_static(&[0x01, 0x14, 0x01, 0x00, 0x05, 0x0a, 0x00, 0x00, 0x00]);
523        let s = decode_exact::<legacy::Slot>(&b).unwrap();
524        assert_eq!(s.item().unwrap().nbt.as_ref().unwrap().as_bytes().len(), 4);
525    }
526
527    #[test]
528    fn modern_known_answers() {
529        let b = Bytes::from_static(&[0x00]);
530        assert_eq!(decode_exact::<modern::Slot>(&b), Ok(modern::Slot::EMPTY));
531        let b = Bytes::from_static(&[0x01, 0xac, 0x02, 0x10, 0x00]);
532        let s = decode_exact::<modern::Slot>(&b).unwrap();
533        let it = s.item().unwrap();
534        assert_eq!((it.id, it.count), (300, 16));
535    }
536}