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///
168/// 26.2 (protocol 776) has the same slot format with its own component registry (one more
169/// component type, so most type ids differ). Its stacks use the same
170/// [`ComponentPatch`](v775::ComponentPatch) and [`ItemStack`](v775::ItemStack) types, read
171/// with [`ComponentPatch::read_776`](v775::ComponentPatch::read_776) /
172/// [`ItemStack::read_776`](v775::ItemStack::read_776); the patch remembers which protocol's
173/// component codec it was read with ([`ComponentPatch::protocol`](v775::ComponentPatch::protocol)),
174/// so iteration skips with the right one. Type ids in a
175/// patch are always the ids of that protocol.
176///
177/// 26.3 (protocol 777) keeps the slot format too (122 component types; `*_777` readers).
178#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
179pub mod v775 {
180    use bytes::{BufMut, Bytes, BytesMut};
181
182    use crate::codec::{DecodeResult, McWrite, Reader};
183    #[cfg(feature = "v26_1")]
184    use crate::defs::p775::types::SlotComponent;
185    use crate::error::DecodeError;
186
187    /// The component codec a patch was read with.
188    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
189    enum Codec {
190        /// Protocol 775 (26.1 - 26.1.2).
191        #[default]
192        P775,
193        /// Protocol 776 (26.2).
194        P776,
195        /// Protocol 777 (26.3).
196        P777,
197    }
198
199    /// `Codec::P775` / `Codec::P776` as const parameters: each reader is its own instance with
200    /// the codec as a constant (one shared body would test the codec per component).
201    const C775: u8 = 0;
202    const C776: u8 = 1;
203    const C777: u8 = 2;
204
205    /// The codec of a const parameter.
206    #[inline(always)]
207    const fn codec_of<const C: u8>() -> Codec {
208        match C {
209            C776 => Codec::P776,
210            C777 => Codec::P777,
211            _ => Codec::P775,
212        }
213    }
214
215    /// Skips one component (type id + value) with `codec`'s generated structural skip.
216    #[inline]
217    fn skip_one<const C: u8>(r: &mut Reader<'_>) -> DecodeResult<()> {
218        match codec_of::<C>() {
219            #[cfg(feature = "v26_1")]
220            Codec::P775 => SlotComponent::skip(r),
221            #[cfg(feature = "v26_2")]
222            Codec::P776 => crate::defs::p776::types::SlotComponent::skip(r),
223            #[cfg(feature = "v26_3")]
224            Codec::P777 => crate::defs::p777::types::SlotComponent::skip(r),
225            #[allow(unreachable_patterns)]
226            _ => Err(DecodeError::Invalid(
227                "component codec of a disabled protocol",
228            )),
229        }
230    }
231
232    /// [`skip_one`] with the codec known at run time (iteration over a stored patch).
233    #[inline]
234    fn skip_codec(codec: Codec, r: &mut Reader<'_>) -> DecodeResult<()> {
235        match codec {
236            Codec::P775 => skip_one::<C775>(r),
237            Codec::P776 => skip_one::<C776>(r),
238            Codec::P777 => skip_one::<C777>(r),
239        }
240    }
241
242    /// The data component patch of a stack (added components, then removed types), exactly as
243    /// received.
244    #[derive(Debug, Clone, Default)]
245    pub struct ComponentPatch {
246        /// Added components followed by the removed types.
247        bytes: Bytes,
248        /// Byte offset of the removed list in `bytes`.
249        split: u32,
250        added: u16,
251        removed: u16,
252        /// Added / removed types below 127 as bits; bit 127 = a type outside `0..127` occurs
253        /// (lookups of such types scan). Lets lookups of absent types skip the scan.
254        added_mask: u128,
255        removed_mask: u128,
256        /// Fits in the padding after `removed`: the struct does not grow.
257        codec: Codec,
258    }
259
260    /// The mask bit of a component type.
261    #[inline]
262    fn bit(ty: i32) -> u128 {
263        match u32::try_from(ty) {
264            Ok(t) if t < 127 => 1u128 << t,
265            _ => 1u128 << 127,
266        }
267    }
268
269    /// Whether a mask may contain `ty`.
270    #[inline]
271    fn may_have(mask: u128, ty: i32) -> bool {
272        mask & (bit(ty) | 1u128 << 127) != 0
273    }
274
275    /// Patches are equal when their bytes are (component order included; see
276    /// [`ComponentPatch::same_components`] for vanilla's map equality).
277    impl PartialEq for ComponentPatch {
278        fn eq(&self, other: &Self) -> bool {
279            self.added == other.added
280                && self.removed == other.removed
281                && self.bytes == other.bytes
282                && (self.codec == other.codec || self.bytes.is_empty())
283        }
284    }
285
286    impl Eq for ComponentPatch {}
287
288    impl std::hash::Hash for ComponentPatch {
289        fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
290            self.bytes.hash(h);
291        }
292    }
293
294    impl ComponentPatch {
295        /// The empty patch (the item's default components).
296        pub const EMPTY: ComponentPatch = ComponentPatch {
297            bytes: Bytes::new(),
298            split: 0,
299            added: 0,
300            removed: 0,
301            added_mask: 0,
302            removed_mask: 0,
303            codec: Codec::P775,
304        };
305
306        /// Moves the patch's bytes to an allocation of their own. A read patch is a view into
307        /// the received packet, which may share its buffer with other packets: a stack kept
308        /// for long (one `set_slot`) would keep all of that alive.
309        pub fn detach(&mut self) {
310            if !self.bytes.is_empty() {
311                self.bytes = Bytes::copy_from_slice(&self.bytes);
312            }
313        }
314
315        /// Reads `added` components and `removed` types (protocol 775) by skipping over them.
316        #[cfg(feature = "v26_1")]
317        pub fn read(r: &mut Reader<'_>, added: i32, removed: i32) -> DecodeResult<Self> {
318            Self::read_with::<C775>(r, added, removed)
319        }
320
321        /// [`read`](Self::read) for protocol 776 (26.2).
322        #[cfg(feature = "v26_2")]
323        pub fn read_776(r: &mut Reader<'_>, added: i32, removed: i32) -> DecodeResult<Self> {
324            Self::read_with::<C776>(r, added, removed)
325        }
326
327        /// [`read`](Self::read) for protocol 777 (26.3).
328        #[cfg(feature = "v26_3")]
329        pub fn read_777(r: &mut Reader<'_>, added: i32, removed: i32) -> DecodeResult<Self> {
330            Self::read_with::<C777>(r, added, removed)
331        }
332
333        /// The protocol number whose component registry the type ids belong to (775, 776 or
334        /// 777).
335        #[must_use]
336        pub fn protocol(&self) -> i32 {
337            match self.codec {
338                Codec::P775 => 775,
339                Codec::P776 => 776,
340                Codec::P777 => 777,
341            }
342        }
343
344        #[inline]
345        fn read_with<const C: u8>(
346            r: &mut Reader<'_>,
347            added: i32,
348            removed: i32,
349        ) -> DecodeResult<Self> {
350            let added_n = r.check_count(i64::from(added), 1)?;
351            let removed_n = r.check_count(i64::from(removed), 1)?;
352            let (Ok(added), Ok(removed)) = (u16::try_from(added_n), u16::try_from(removed_n))
353            else {
354                return Err(DecodeError::Invalid("component count"));
355            };
356            let start = r.position();
357            let mut added_mask = 0u128;
358            for _ in 0..added_n {
359                added_mask |= bit(r.clone().read_varint()?);
360                skip_one::<C>(r)?;
361            }
362            let split = (r.position() - start) as u32;
363            let mut removed_mask = 0u128;
364            for _ in 0..removed_n {
365                removed_mask |= bit(r.read_varint()?);
366            }
367            Ok(ComponentPatch {
368                bytes: r.bytes_since(start),
369                split,
370                added,
371                removed,
372                added_mask,
373                removed_mask,
374                codec: codec_of::<C>(),
375            })
376        }
377
378        /// `true` when nothing is added or removed.
379        #[must_use]
380        pub fn is_empty(&self) -> bool {
381            self.added == 0 && self.removed == 0
382        }
383
384        /// Number of added components.
385        #[must_use]
386        pub fn added_len(&self) -> usize {
387            usize::from(self.added)
388        }
389
390        /// Number of removed component types.
391        #[must_use]
392        pub fn removed_len(&self) -> usize {
393            usize::from(self.removed)
394        }
395
396        /// The patch bytes as received (added components, then removed types).
397        #[must_use]
398        pub fn as_bytes(&self) -> &Bytes {
399            &self.bytes
400        }
401
402        /// The added components as `(type id, value bytes)`, in wire order.
403        pub fn iter(&self) -> Components<'_> {
404            Components {
405                bytes: self.bytes.slice(..self.split as usize),
406                pos: 0,
407                left: self.added,
408                codec: self.codec,
409                _p: std::marker::PhantomData,
410            }
411        }
412
413        /// The removed component type ids, in wire order.
414        pub fn removed(&self) -> impl Iterator<Item = i32> + '_ {
415            let tail = self.bytes.slice(self.split as usize..);
416            let mut pos = 0usize;
417            (0..self.removed).map_while(move |_| {
418                let mut r = Reader::new(&tail);
419                r.skip(pos).ok()?;
420                let v = r.read_varint().ok()?;
421                pos = r.position();
422                Some(v)
423            })
424        }
425
426        /// `true` when the patch removes component `ty`.
427        #[must_use]
428        pub fn removes(&self, ty: i32) -> bool {
429            may_have(self.removed_mask, ty) && self.removed().any(|t| t == ty)
430        }
431
432        /// Whether the patch adds component `ty` (no scan when it certainly does not).
433        #[must_use]
434        pub fn adds(&self, ty: i32) -> bool {
435            may_have(self.added_mask, ty) && self.iter().any(|(t, _)| t == ty)
436        }
437
438        /// The value bytes of added component `ty` (vanilla keeps the last one of a type).
439        #[must_use]
440        pub fn get(&self, ty: i32) -> Option<Bytes> {
441            if !may_have(self.added_mask, ty) {
442                return None;
443            }
444            self.iter().filter(|(t, _)| *t == ty).last().map(|(_, b)| b)
445        }
446
447        /// Byte offset of the last added component of type `ty`.
448        fn last_of(&self, ty: i32) -> Option<DecodeResult<usize>> {
449            if !may_have(self.added_mask, ty) {
450                return None;
451            }
452            let mut r = Reader::new(&self.bytes);
453            let mut last = None;
454            for _ in 0..self.added {
455                let start = r.position();
456                let t = match r.clone().read_varint() {
457                    Ok(t) => t,
458                    Err(e) => return Some(Err(e)),
459                };
460                if let Err(e) = skip_codec(self.codec, &mut r) {
461                    return Some(Err(e));
462                }
463                if t == ty {
464                    last = Some(start);
465                }
466            }
467            last.map(Ok)
468        }
469
470        /// Decodes the component at byte offset `start` with `T`.
471        fn decode_at<T: crate::codec::Decode>(&self, start: usize) -> DecodeResult<T> {
472            let mut r = Reader::new(&self.bytes);
473            r.skip(start)?;
474            T::decode(&mut r)
475        }
476
477        /// Decodes added component `ty` with the generated type (the last one of that type).
478        /// A patch of another protocol gives `Some(Err(..))`; use
479        /// `decode_776` / `decode_777` (features `v26_2` / `v26_3`).
480        #[cfg(feature = "v26_1")]
481        #[must_use]
482        pub fn decode(&self, ty: i32) -> Option<DecodeResult<SlotComponent>> {
483            if self.codec != Codec::P775 {
484                return Some(Err(DecodeError::Invalid("patch of another protocol")));
485            }
486            Some(self.last_of(ty)?.and_then(|start| self.decode_at(start)))
487        }
488
489        /// Decodes every added component with the generated type.
490        ///
491        /// # Errors
492        /// A malformed component, or a patch of another protocol.
493        #[cfg(feature = "v26_1")]
494        pub fn decode_all(&self) -> DecodeResult<Vec<SlotComponent>> {
495            if self.codec != Codec::P775 {
496                return Err(DecodeError::Invalid("patch of another protocol"));
497            }
498            let mut r = Reader::new(&self.bytes);
499            (0..self.added)
500                .map(|_| <SlotComponent as crate::codec::Decode>::decode(&mut r))
501                .collect()
502        }
503
504        /// [`decode`](Self::decode) for a patch of protocol 776 (26.2).
505        #[cfg(feature = "v26_2")]
506        #[must_use]
507        pub fn decode_776(
508            &self,
509            ty: i32,
510        ) -> Option<DecodeResult<crate::defs::p776::types::SlotComponent>> {
511            if self.codec != Codec::P776 {
512                return Some(Err(DecodeError::Invalid("patch of another protocol")));
513            }
514            Some(self.last_of(ty)?.and_then(|start| self.decode_at(start)))
515        }
516
517        /// [`decode_all`](Self::decode_all) for a patch of protocol 776 (26.2).
518        ///
519        /// # Errors
520        /// A malformed component, or a patch of another protocol.
521        #[cfg(feature = "v26_2")]
522        pub fn decode_all_776(&self) -> DecodeResult<Vec<crate::defs::p776::types::SlotComponent>> {
523            if self.codec != Codec::P776 {
524                return Err(DecodeError::Invalid("patch of another protocol"));
525            }
526            let mut r = Reader::new(&self.bytes);
527            (0..self.added)
528                .map(|_| {
529                    <crate::defs::p776::types::SlotComponent as crate::codec::Decode>::decode(
530                        &mut r,
531                    )
532                })
533                .collect()
534        }
535
536        /// [`decode`](Self::decode) for a patch of protocol 777 (26.3).
537        #[cfg(feature = "v26_3")]
538        #[must_use]
539        pub fn decode_777(
540            &self,
541            ty: i32,
542        ) -> Option<DecodeResult<crate::defs::p777::types::SlotComponent>> {
543            if self.codec != Codec::P777 {
544                return Some(Err(DecodeError::Invalid("patch of another protocol")));
545            }
546            Some(self.last_of(ty)?.and_then(|start| self.decode_at(start)))
547        }
548
549        /// [`decode_all`](Self::decode_all) for a patch of protocol 777 (26.3).
550        ///
551        /// # Errors
552        /// A malformed component, or a patch of another protocol.
553        #[cfg(feature = "v26_3")]
554        pub fn decode_all_777(&self) -> DecodeResult<Vec<crate::defs::p777::types::SlotComponent>> {
555            if self.codec != Codec::P777 {
556                return Err(DecodeError::Invalid("patch of another protocol"));
557            }
558            let mut r = Reader::new(&self.bytes);
559            (0..self.added)
560                .map(|_| {
561                    <crate::defs::p777::types::SlotComponent as crate::codec::Decode>::decode(
562                        &mut r,
563                    )
564                })
565                .collect()
566        }
567
568        /// Vanilla's patch equality (`DataComponentPatch.equals`: a map from type to value):
569        /// the same removed types and the same added `(type, value bytes)` set, in any order.
570        /// Values compare by bytes (values that differ only in NBT compound key order compare
571        /// unequal here; vanilla would compare their trees).
572        #[must_use]
573        pub fn same_components(&self, other: &ComponentPatch) -> bool {
574            if self == other {
575                return true;
576            }
577            let mut a: Vec<i32> = self.removed().collect();
578            let mut b: Vec<i32> = other.removed().collect();
579            a.sort_unstable();
580            a.dedup();
581            b.sort_unstable();
582            b.dedup();
583            if a != b {
584                return false;
585            }
586            let last = |p: &ComponentPatch| {
587                let mut v: Vec<(i32, Bytes)> = Vec::new();
588                for (t, b) in p.iter() {
589                    match v.iter_mut().find(|(k, _)| *k == t) {
590                        Some(e) => e.1 = b,
591                        None => v.push((t, b)),
592                    }
593                }
594                v.sort_by_key(|(t, _)| *t);
595                v
596            };
597            last(self) == last(other)
598        }
599
600        /// Builds a patch from `(type, value bytes)` components and removed types (tests,
601        /// creative clients). Type ids of protocol 775.
602        #[must_use]
603        pub fn from_parts(added: &[(i32, &[u8])], removed: &[i32]) -> ComponentPatch {
604            Self::from_parts_with(Codec::P775, added, removed)
605        }
606
607        /// [`from_parts`](Self::from_parts) with type ids of protocol 776 (26.2).
608        #[must_use]
609        pub fn from_parts_776(added: &[(i32, &[u8])], removed: &[i32]) -> ComponentPatch {
610            Self::from_parts_with(Codec::P776, added, removed)
611        }
612
613        /// [`from_parts`](Self::from_parts) with type ids of protocol 777 (26.3).
614        #[must_use]
615        pub fn from_parts_777(added: &[(i32, &[u8])], removed: &[i32]) -> ComponentPatch {
616            Self::from_parts_with(Codec::P777, added, removed)
617        }
618
619        fn from_parts_with(
620            codec: Codec,
621            added: &[(i32, &[u8])],
622            removed: &[i32],
623        ) -> ComponentPatch {
624            let mut w = BytesMut::new();
625            for (t, v) in added {
626                w.put_varint(*t);
627                w.put_slice(v);
628            }
629            let split = w.len() as u32;
630            for t in removed {
631                w.put_varint(*t);
632            }
633            ComponentPatch {
634                bytes: w.freeze(),
635                split,
636                added: added.len() as u16,
637                removed: removed.len() as u16,
638                added_mask: added.iter().fold(0, |m, (t, _)| m | bit(*t)),
639                removed_mask: removed.iter().fold(0, |m, t| m | bit(*t)),
640                codec,
641            }
642        }
643    }
644
645    /// Iterator over the added components of a [`ComponentPatch`].
646    #[derive(Debug, Clone)]
647    pub struct Components<'a> {
648        bytes: Bytes,
649        pos: usize,
650        left: u16,
651        codec: Codec,
652        _p: std::marker::PhantomData<&'a ComponentPatch>,
653    }
654
655    impl Iterator for Components<'_> {
656        type Item = (i32, Bytes);
657
658        #[inline]
659        fn next(&mut self) -> Option<(i32, Bytes)> {
660            if self.left == 0 {
661                return None;
662            }
663            self.left -= 1;
664            let mut r = Reader::new(&self.bytes);
665            r.skip(self.pos).ok()?;
666            let mut value = r.clone();
667            let ty = value.read_varint().ok()?;
668            let value_start = value.position();
669            skip_codec(self.codec, &mut r).ok()?;
670            self.pos = r.position();
671            Some((ty, self.bytes.slice(value_start..self.pos)))
672        }
673    }
674
675    /// A non-empty 26.1 item stack.
676    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
677    pub struct ItemStack {
678        /// Item registry id.
679        pub id: i32,
680        /// Stack size (`> 0`).
681        pub count: i32,
682        /// Data component patch against the item's defaults.
683        pub components: ComponentPatch,
684    }
685
686    impl ItemStack {
687        /// Reads one slot; `None` for an empty one (count `<= 0`, as vanilla reads it).
688        #[cfg(feature = "v26_1")]
689        pub fn read(r: &mut Reader<'_>) -> DecodeResult<Option<ItemStack>> {
690            Self::read_with::<C775>(r)
691        }
692
693        /// [`read`](Self::read) for protocol 776 (26.2).
694        #[cfg(feature = "v26_2")]
695        pub fn read_776(r: &mut Reader<'_>) -> DecodeResult<Option<ItemStack>> {
696            Self::read_with::<C776>(r)
697        }
698
699        /// [`read`](Self::read) for protocol 777 (26.3).
700        #[cfg(feature = "v26_3")]
701        pub fn read_777(r: &mut Reader<'_>) -> DecodeResult<Option<ItemStack>> {
702            Self::read_with::<C777>(r)
703        }
704
705        #[inline]
706        fn read_with<const C: u8>(r: &mut Reader<'_>) -> DecodeResult<Option<ItemStack>> {
707            let count = r.read_varint()?;
708            if count <= 0 {
709                return Ok(None);
710            }
711            let id = r.read_varint()?;
712            let added = r.read_varint()?;
713            let removed = r.read_varint()?;
714            let components = ComponentPatch::read_with::<C>(r, added, removed)?;
715            Ok(Some(ItemStack {
716                id,
717                count,
718                components,
719            }))
720        }
721
722        /// Writes one slot (`None` = empty).
723        pub fn write(s: Option<&ItemStack>, w: &mut BytesMut) {
724            match s {
725                None => w.put_varint(0),
726                Some(s) => {
727                    w.put_varint(s.count);
728                    w.put_varint(s.id);
729                    w.put_varint(i32::from(s.components.added));
730                    w.put_varint(i32::from(s.components.removed));
731                    w.put_slice(&s.components.bytes);
732                }
733            }
734        }
735    }
736}
737
738#[cfg(test)]
739mod tests {
740    use super::*;
741    use crate::codec::{Encode, decode_exact};
742    use bytes::{Bytes, BytesMut};
743
744    #[test]
745    fn legacy_known_answers() {
746        // Empty slot.
747        let b = Bytes::from_static(&[0xff, 0xff]);
748        assert_eq!(decode_exact::<legacy::Slot>(&b), Ok(legacy::Slot::EMPTY));
749        // 64 x stone (id 1), damage 0, no NBT.
750        let b = Bytes::from_static(&[0x00, 0x01, 0x40, 0x00, 0x00, 0x00]);
751        let s = decode_exact::<legacy::Slot>(&b).unwrap();
752        let it = s.item().unwrap();
753        assert_eq!(
754            (it.id, it.count, it.damage, it.nbt.is_none()),
755            (1, 64, 0, true)
756        );
757        let mut w = BytesMut::new();
758        s.encode(&mut w).unwrap();
759        assert_eq!(&w[..], &b[..]);
760        // With an empty-named empty compound as NBT.
761        let b = Bytes::from_static(&[0x01, 0x14, 0x01, 0x00, 0x05, 0x0a, 0x00, 0x00, 0x00]);
762        let s = decode_exact::<legacy::Slot>(&b).unwrap();
763        assert_eq!(s.item().unwrap().nbt.as_ref().unwrap().as_bytes().len(), 4);
764    }
765
766    #[test]
767    fn modern_known_answers() {
768        let b = Bytes::from_static(&[0x00]);
769        assert_eq!(decode_exact::<modern::Slot>(&b), Ok(modern::Slot::EMPTY));
770        let b = Bytes::from_static(&[0x01, 0xac, 0x02, 0x10, 0x00]);
771        let s = decode_exact::<modern::Slot>(&b).unwrap();
772        let it = s.item().unwrap();
773        assert_eq!((it.id, it.count), (300, 16));
774    }
775}