1pub 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 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
17 pub struct ItemStack {
18 pub id: i16,
20 pub count: i8,
22 pub damage: i16,
24 pub nbt: Option<RawNbt>,
26 }
27
28 #[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
30 pub struct Slot(pub Option<ItemStack>);
31
32 impl Slot {
33 pub const EMPTY: Slot = Slot(None);
35
36 #[inline]
38 pub fn is_empty(&self) -> bool {
39 self.0.is_none()
40 }
41
42 #[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
87pub 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 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
97 pub struct ItemStack {
98 pub id: i32,
100 pub count: i8,
102 pub nbt: Option<RawNbt>,
104 }
105
106 #[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
108 pub struct Slot(pub Option<ItemStack>);
109
110 impl Slot {
111 pub const EMPTY: Slot = Slot(None);
113
114 #[inline]
116 pub fn is_empty(&self) -> bool {
117 self.0.is_none()
118 }
119
120 #[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#[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 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
189 enum Codec {
190 #[default]
192 P775,
193 P776,
195 P777,
197 }
198
199 const C775: u8 = 0;
202 const C776: u8 = 1;
203 const C777: u8 = 2;
204
205 #[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 #[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 #[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 #[derive(Debug, Clone, Default)]
245 pub struct ComponentPatch {
246 bytes: Bytes,
248 split: u32,
250 added: u16,
251 removed: u16,
252 added_mask: u128,
255 removed_mask: u128,
256 codec: Codec,
258 }
259
260 #[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 #[inline]
271 fn may_have(mask: u128, ty: i32) -> bool {
272 mask & (bit(ty) | 1u128 << 127) != 0
273 }
274
275 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 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 pub fn detach(&mut self) {
310 if !self.bytes.is_empty() {
311 self.bytes = Bytes::copy_from_slice(&self.bytes);
312 }
313 }
314
315 #[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 #[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 #[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 #[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 #[must_use]
380 pub fn is_empty(&self) -> bool {
381 self.added == 0 && self.removed == 0
382 }
383
384 #[must_use]
386 pub fn added_len(&self) -> usize {
387 usize::from(self.added)
388 }
389
390 #[must_use]
392 pub fn removed_len(&self) -> usize {
393 usize::from(self.removed)
394 }
395
396 #[must_use]
398 pub fn as_bytes(&self) -> &Bytes {
399 &self.bytes
400 }
401
402 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 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 #[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 #[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 #[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 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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
677 pub struct ItemStack {
678 pub id: i32,
680 pub count: i32,
682 pub components: ComponentPatch,
684 }
685
686 impl ItemStack {
687 #[cfg(feature = "v26_1")]
689 pub fn read(r: &mut Reader<'_>) -> DecodeResult<Option<ItemStack>> {
690 Self::read_with::<C775>(r)
691 }
692
693 #[cfg(feature = "v26_2")]
695 pub fn read_776(r: &mut Reader<'_>) -> DecodeResult<Option<ItemStack>> {
696 Self::read_with::<C776>(r)
697 }
698
699 #[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 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 let b = Bytes::from_static(&[0xff, 0xff]);
748 assert_eq!(decode_exact::<legacy::Slot>(&b), Ok(legacy::Slot::EMPTY));
749 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 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}