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"))]
177pub mod v775 {
178 use bytes::{BufMut, Bytes, BytesMut};
179
180 use crate::codec::{DecodeResult, McWrite, Reader};
181 #[cfg(feature = "v26_1")]
182 use crate::defs::p775::types::SlotComponent;
183 use crate::error::DecodeError;
184
185 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
187 enum Codec {
188 #[default]
190 P775,
191 P776,
193 }
194
195 const C775: u8 = 0;
198 const C776: u8 = 1;
199
200 #[inline(always)]
202 const fn codec_of<const C: u8>() -> Codec {
203 if C == C776 { Codec::P776 } else { Codec::P775 }
204 }
205
206 #[inline]
208 fn skip_one<const C: u8>(r: &mut Reader<'_>) -> DecodeResult<()> {
209 match codec_of::<C>() {
210 #[cfg(feature = "v26_1")]
211 Codec::P775 => SlotComponent::skip(r),
212 #[cfg(feature = "v26_2")]
213 Codec::P776 => crate::defs::p776::types::SlotComponent::skip(r),
214 #[allow(unreachable_patterns)]
215 _ => Err(DecodeError::Invalid(
216 "component codec of a disabled protocol",
217 )),
218 }
219 }
220
221 #[inline]
223 fn skip_codec(codec: Codec, r: &mut Reader<'_>) -> DecodeResult<()> {
224 match codec {
225 Codec::P775 => skip_one::<C775>(r),
226 Codec::P776 => skip_one::<C776>(r),
227 }
228 }
229
230 #[derive(Debug, Clone, Default)]
233 pub struct ComponentPatch {
234 bytes: Bytes,
236 split: u32,
238 added: u16,
239 removed: u16,
240 added_mask: u128,
243 removed_mask: u128,
244 codec: Codec,
246 }
247
248 #[inline]
250 fn bit(ty: i32) -> u128 {
251 match u32::try_from(ty) {
252 Ok(t) if t < 127 => 1u128 << t,
253 _ => 1u128 << 127,
254 }
255 }
256
257 #[inline]
259 fn may_have(mask: u128, ty: i32) -> bool {
260 mask & (bit(ty) | 1u128 << 127) != 0
261 }
262
263 impl PartialEq for ComponentPatch {
266 fn eq(&self, other: &Self) -> bool {
267 self.added == other.added
268 && self.removed == other.removed
269 && self.bytes == other.bytes
270 && (self.codec == other.codec || self.bytes.is_empty())
271 }
272 }
273
274 impl Eq for ComponentPatch {}
275
276 impl std::hash::Hash for ComponentPatch {
277 fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
278 self.bytes.hash(h);
279 }
280 }
281
282 impl ComponentPatch {
283 pub const EMPTY: ComponentPatch = ComponentPatch {
285 bytes: Bytes::new(),
286 split: 0,
287 added: 0,
288 removed: 0,
289 added_mask: 0,
290 removed_mask: 0,
291 codec: Codec::P775,
292 };
293
294 pub fn detach(&mut self) {
298 if !self.bytes.is_empty() {
299 self.bytes = Bytes::copy_from_slice(&self.bytes);
300 }
301 }
302
303 #[cfg(feature = "v26_1")]
305 pub fn read(r: &mut Reader<'_>, added: i32, removed: i32) -> DecodeResult<Self> {
306 Self::read_with::<C775>(r, added, removed)
307 }
308
309 #[cfg(feature = "v26_2")]
311 pub fn read_776(r: &mut Reader<'_>, added: i32, removed: i32) -> DecodeResult<Self> {
312 Self::read_with::<C776>(r, added, removed)
313 }
314
315 #[must_use]
318 pub fn protocol(&self) -> i32 {
319 match self.codec {
320 Codec::P775 => 775,
321 Codec::P776 => 776,
322 }
323 }
324
325 #[inline]
326 fn read_with<const C: u8>(
327 r: &mut Reader<'_>,
328 added: i32,
329 removed: i32,
330 ) -> DecodeResult<Self> {
331 let added_n = r.check_count(i64::from(added), 1)?;
332 let removed_n = r.check_count(i64::from(removed), 1)?;
333 let (Ok(added), Ok(removed)) = (u16::try_from(added_n), u16::try_from(removed_n))
334 else {
335 return Err(DecodeError::Invalid("component count"));
336 };
337 let start = r.position();
338 let mut added_mask = 0u128;
339 for _ in 0..added_n {
340 added_mask |= bit(r.clone().read_varint()?);
341 skip_one::<C>(r)?;
342 }
343 let split = (r.position() - start) as u32;
344 let mut removed_mask = 0u128;
345 for _ in 0..removed_n {
346 removed_mask |= bit(r.read_varint()?);
347 }
348 Ok(ComponentPatch {
349 bytes: r.bytes_since(start),
350 split,
351 added,
352 removed,
353 added_mask,
354 removed_mask,
355 codec: codec_of::<C>(),
356 })
357 }
358
359 #[must_use]
361 pub fn is_empty(&self) -> bool {
362 self.added == 0 && self.removed == 0
363 }
364
365 #[must_use]
367 pub fn added_len(&self) -> usize {
368 usize::from(self.added)
369 }
370
371 #[must_use]
373 pub fn removed_len(&self) -> usize {
374 usize::from(self.removed)
375 }
376
377 #[must_use]
379 pub fn as_bytes(&self) -> &Bytes {
380 &self.bytes
381 }
382
383 pub fn iter(&self) -> Components<'_> {
385 Components {
386 bytes: self.bytes.slice(..self.split as usize),
387 pos: 0,
388 left: self.added,
389 codec: self.codec,
390 _p: std::marker::PhantomData,
391 }
392 }
393
394 pub fn removed(&self) -> impl Iterator<Item = i32> + '_ {
396 let tail = self.bytes.slice(self.split as usize..);
397 let mut pos = 0usize;
398 (0..self.removed).map_while(move |_| {
399 let mut r = Reader::new(&tail);
400 r.skip(pos).ok()?;
401 let v = r.read_varint().ok()?;
402 pos = r.position();
403 Some(v)
404 })
405 }
406
407 #[must_use]
409 pub fn removes(&self, ty: i32) -> bool {
410 may_have(self.removed_mask, ty) && self.removed().any(|t| t == ty)
411 }
412
413 #[must_use]
415 pub fn adds(&self, ty: i32) -> bool {
416 may_have(self.added_mask, ty) && self.iter().any(|(t, _)| t == ty)
417 }
418
419 #[must_use]
421 pub fn get(&self, ty: i32) -> Option<Bytes> {
422 if !may_have(self.added_mask, ty) {
423 return None;
424 }
425 self.iter().filter(|(t, _)| *t == ty).last().map(|(_, b)| b)
426 }
427
428 fn last_of(&self, ty: i32) -> Option<DecodeResult<usize>> {
430 if !may_have(self.added_mask, ty) {
431 return None;
432 }
433 let mut r = Reader::new(&self.bytes);
434 let mut last = None;
435 for _ in 0..self.added {
436 let start = r.position();
437 let t = match r.clone().read_varint() {
438 Ok(t) => t,
439 Err(e) => return Some(Err(e)),
440 };
441 if let Err(e) = skip_codec(self.codec, &mut r) {
442 return Some(Err(e));
443 }
444 if t == ty {
445 last = Some(start);
446 }
447 }
448 last.map(Ok)
449 }
450
451 fn decode_at<T: crate::codec::Decode>(&self, start: usize) -> DecodeResult<T> {
453 let mut r = Reader::new(&self.bytes);
454 r.skip(start)?;
455 T::decode(&mut r)
456 }
457
458 #[cfg(feature = "v26_1")]
462 #[must_use]
463 pub fn decode(&self, ty: i32) -> Option<DecodeResult<SlotComponent>> {
464 if self.codec != Codec::P775 {
465 return Some(Err(DecodeError::Invalid("patch of protocol 776")));
466 }
467 Some(self.last_of(ty)?.and_then(|start| self.decode_at(start)))
468 }
469
470 #[cfg(feature = "v26_1")]
475 pub fn decode_all(&self) -> DecodeResult<Vec<SlotComponent>> {
476 if self.codec != Codec::P775 {
477 return Err(DecodeError::Invalid("patch of protocol 776"));
478 }
479 let mut r = Reader::new(&self.bytes);
480 (0..self.added)
481 .map(|_| <SlotComponent as crate::codec::Decode>::decode(&mut r))
482 .collect()
483 }
484
485 #[cfg(feature = "v26_2")]
487 #[must_use]
488 pub fn decode_776(
489 &self,
490 ty: i32,
491 ) -> Option<DecodeResult<crate::defs::p776::types::SlotComponent>> {
492 if self.codec != Codec::P776 {
493 return Some(Err(DecodeError::Invalid("patch of protocol 775")));
494 }
495 Some(self.last_of(ty)?.and_then(|start| self.decode_at(start)))
496 }
497
498 #[cfg(feature = "v26_2")]
503 pub fn decode_all_776(&self) -> DecodeResult<Vec<crate::defs::p776::types::SlotComponent>> {
504 if self.codec != Codec::P776 {
505 return Err(DecodeError::Invalid("patch of protocol 775"));
506 }
507 let mut r = Reader::new(&self.bytes);
508 (0..self.added)
509 .map(|_| {
510 <crate::defs::p776::types::SlotComponent as crate::codec::Decode>::decode(
511 &mut r,
512 )
513 })
514 .collect()
515 }
516
517 #[must_use]
522 pub fn same_components(&self, other: &ComponentPatch) -> bool {
523 if self == other {
524 return true;
525 }
526 let mut a: Vec<i32> = self.removed().collect();
527 let mut b: Vec<i32> = other.removed().collect();
528 a.sort_unstable();
529 a.dedup();
530 b.sort_unstable();
531 b.dedup();
532 if a != b {
533 return false;
534 }
535 let last = |p: &ComponentPatch| {
536 let mut v: Vec<(i32, Bytes)> = Vec::new();
537 for (t, b) in p.iter() {
538 match v.iter_mut().find(|(k, _)| *k == t) {
539 Some(e) => e.1 = b,
540 None => v.push((t, b)),
541 }
542 }
543 v.sort_by_key(|(t, _)| *t);
544 v
545 };
546 last(self) == last(other)
547 }
548
549 #[must_use]
552 pub fn from_parts(added: &[(i32, &[u8])], removed: &[i32]) -> ComponentPatch {
553 Self::from_parts_with(Codec::P775, added, removed)
554 }
555
556 #[must_use]
558 pub fn from_parts_776(added: &[(i32, &[u8])], removed: &[i32]) -> ComponentPatch {
559 Self::from_parts_with(Codec::P776, added, removed)
560 }
561
562 fn from_parts_with(
563 codec: Codec,
564 added: &[(i32, &[u8])],
565 removed: &[i32],
566 ) -> ComponentPatch {
567 let mut w = BytesMut::new();
568 for (t, v) in added {
569 w.put_varint(*t);
570 w.put_slice(v);
571 }
572 let split = w.len() as u32;
573 for t in removed {
574 w.put_varint(*t);
575 }
576 ComponentPatch {
577 bytes: w.freeze(),
578 split,
579 added: added.len() as u16,
580 removed: removed.len() as u16,
581 added_mask: added.iter().fold(0, |m, (t, _)| m | bit(*t)),
582 removed_mask: removed.iter().fold(0, |m, t| m | bit(*t)),
583 codec,
584 }
585 }
586 }
587
588 #[derive(Debug, Clone)]
590 pub struct Components<'a> {
591 bytes: Bytes,
592 pos: usize,
593 left: u16,
594 codec: Codec,
595 _p: std::marker::PhantomData<&'a ComponentPatch>,
596 }
597
598 impl Iterator for Components<'_> {
599 type Item = (i32, Bytes);
600
601 #[inline]
602 fn next(&mut self) -> Option<(i32, Bytes)> {
603 if self.left == 0 {
604 return None;
605 }
606 self.left -= 1;
607 let mut r = Reader::new(&self.bytes);
608 r.skip(self.pos).ok()?;
609 let mut value = r.clone();
610 let ty = value.read_varint().ok()?;
611 let value_start = value.position();
612 skip_codec(self.codec, &mut r).ok()?;
613 self.pos = r.position();
614 Some((ty, self.bytes.slice(value_start..self.pos)))
615 }
616 }
617
618 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
620 pub struct ItemStack {
621 pub id: i32,
623 pub count: i32,
625 pub components: ComponentPatch,
627 }
628
629 impl ItemStack {
630 #[cfg(feature = "v26_1")]
632 pub fn read(r: &mut Reader<'_>) -> DecodeResult<Option<ItemStack>> {
633 Self::read_with::<C775>(r)
634 }
635
636 #[cfg(feature = "v26_2")]
638 pub fn read_776(r: &mut Reader<'_>) -> DecodeResult<Option<ItemStack>> {
639 Self::read_with::<C776>(r)
640 }
641
642 #[inline]
643 fn read_with<const C: u8>(r: &mut Reader<'_>) -> DecodeResult<Option<ItemStack>> {
644 let count = r.read_varint()?;
645 if count <= 0 {
646 return Ok(None);
647 }
648 let id = r.read_varint()?;
649 let added = r.read_varint()?;
650 let removed = r.read_varint()?;
651 let components = ComponentPatch::read_with::<C>(r, added, removed)?;
652 Ok(Some(ItemStack {
653 id,
654 count,
655 components,
656 }))
657 }
658
659 pub fn write(s: Option<&ItemStack>, w: &mut BytesMut) {
661 match s {
662 None => w.put_varint(0),
663 Some(s) => {
664 w.put_varint(s.count);
665 w.put_varint(s.id);
666 w.put_varint(i32::from(s.components.added));
667 w.put_varint(i32::from(s.components.removed));
668 w.put_slice(&s.components.bytes);
669 }
670 }
671 }
672 }
673}
674
675#[cfg(test)]
676mod tests {
677 use super::*;
678 use crate::codec::{Encode, decode_exact};
679 use bytes::{Bytes, BytesMut};
680
681 #[test]
682 fn legacy_known_answers() {
683 let b = Bytes::from_static(&[0xff, 0xff]);
685 assert_eq!(decode_exact::<legacy::Slot>(&b), Ok(legacy::Slot::EMPTY));
686 let b = Bytes::from_static(&[0x00, 0x01, 0x40, 0x00, 0x00, 0x00]);
688 let s = decode_exact::<legacy::Slot>(&b).unwrap();
689 let it = s.item().unwrap();
690 assert_eq!(
691 (it.id, it.count, it.damage, it.nbt.is_none()),
692 (1, 64, 0, true)
693 );
694 let mut w = BytesMut::new();
695 s.encode(&mut w).unwrap();
696 assert_eq!(&w[..], &b[..]);
697 let b = Bytes::from_static(&[0x01, 0x14, 0x01, 0x00, 0x05, 0x0a, 0x00, 0x00, 0x00]);
699 let s = decode_exact::<legacy::Slot>(&b).unwrap();
700 assert_eq!(s.item().unwrap().nbt.as_ref().unwrap().as_bytes().len(), 4);
701 }
702
703 #[test]
704 fn modern_known_answers() {
705 let b = Bytes::from_static(&[0x00]);
706 assert_eq!(decode_exact::<modern::Slot>(&b), Ok(modern::Slot::EMPTY));
707 let b = Bytes::from_static(&[0x01, 0xac, 0x02, 0x10, 0x00]);
708 let s = decode_exact::<modern::Slot>(&b).unwrap();
709 let it = s.item().unwrap();
710 assert_eq!((it.id, it.count), (300, 16));
711 }
712}