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 #[cfg(feature = "v26_1")]
296 pub fn read(r: &mut Reader<'_>, added: i32, removed: i32) -> DecodeResult<Self> {
297 Self::read_with::<C775>(r, added, removed)
298 }
299
300 #[cfg(feature = "v26_2")]
302 pub fn read_776(r: &mut Reader<'_>, added: i32, removed: i32) -> DecodeResult<Self> {
303 Self::read_with::<C776>(r, added, removed)
304 }
305
306 #[must_use]
309 pub fn protocol(&self) -> i32 {
310 match self.codec {
311 Codec::P775 => 775,
312 Codec::P776 => 776,
313 }
314 }
315
316 #[inline]
317 fn read_with<const C: u8>(
318 r: &mut Reader<'_>,
319 added: i32,
320 removed: i32,
321 ) -> DecodeResult<Self> {
322 let added_n = r.check_count(i64::from(added), 1)?;
323 let removed_n = r.check_count(i64::from(removed), 1)?;
324 let (Ok(added), Ok(removed)) = (u16::try_from(added_n), u16::try_from(removed_n))
325 else {
326 return Err(DecodeError::Invalid("component count"));
327 };
328 let start = r.position();
329 let mut added_mask = 0u128;
330 for _ in 0..added_n {
331 added_mask |= bit(r.clone().read_varint()?);
332 skip_one::<C>(r)?;
333 }
334 let split = (r.position() - start) as u32;
335 let mut removed_mask = 0u128;
336 for _ in 0..removed_n {
337 removed_mask |= bit(r.read_varint()?);
338 }
339 Ok(ComponentPatch {
340 bytes: r.bytes_since(start),
341 split,
342 added,
343 removed,
344 added_mask,
345 removed_mask,
346 codec: codec_of::<C>(),
347 })
348 }
349
350 #[must_use]
352 pub fn is_empty(&self) -> bool {
353 self.added == 0 && self.removed == 0
354 }
355
356 #[must_use]
358 pub fn added_len(&self) -> usize {
359 usize::from(self.added)
360 }
361
362 #[must_use]
364 pub fn removed_len(&self) -> usize {
365 usize::from(self.removed)
366 }
367
368 #[must_use]
370 pub fn as_bytes(&self) -> &Bytes {
371 &self.bytes
372 }
373
374 pub fn iter(&self) -> Components<'_> {
376 Components {
377 bytes: self.bytes.slice(..self.split as usize),
378 pos: 0,
379 left: self.added,
380 codec: self.codec,
381 _p: std::marker::PhantomData,
382 }
383 }
384
385 pub fn removed(&self) -> impl Iterator<Item = i32> + '_ {
387 let tail = self.bytes.slice(self.split as usize..);
388 let mut pos = 0usize;
389 (0..self.removed).map_while(move |_| {
390 let mut r = Reader::new(&tail);
391 r.skip(pos).ok()?;
392 let v = r.read_varint().ok()?;
393 pos = r.position();
394 Some(v)
395 })
396 }
397
398 #[must_use]
400 pub fn removes(&self, ty: i32) -> bool {
401 may_have(self.removed_mask, ty) && self.removed().any(|t| t == ty)
402 }
403
404 #[must_use]
406 pub fn adds(&self, ty: i32) -> bool {
407 may_have(self.added_mask, ty) && self.iter().any(|(t, _)| t == ty)
408 }
409
410 #[must_use]
412 pub fn get(&self, ty: i32) -> Option<Bytes> {
413 if !may_have(self.added_mask, ty) {
414 return None;
415 }
416 self.iter().filter(|(t, _)| *t == ty).last().map(|(_, b)| b)
417 }
418
419 fn last_of(&self, ty: i32) -> Option<DecodeResult<usize>> {
421 if !may_have(self.added_mask, ty) {
422 return None;
423 }
424 let mut r = Reader::new(&self.bytes);
425 let mut last = None;
426 for _ in 0..self.added {
427 let start = r.position();
428 let t = match r.clone().read_varint() {
429 Ok(t) => t,
430 Err(e) => return Some(Err(e)),
431 };
432 if let Err(e) = skip_codec(self.codec, &mut r) {
433 return Some(Err(e));
434 }
435 if t == ty {
436 last = Some(start);
437 }
438 }
439 last.map(Ok)
440 }
441
442 fn decode_at<T: crate::codec::Decode>(&self, start: usize) -> DecodeResult<T> {
444 let mut r = Reader::new(&self.bytes);
445 r.skip(start)?;
446 T::decode(&mut r)
447 }
448
449 #[cfg(feature = "v26_1")]
453 #[must_use]
454 pub fn decode(&self, ty: i32) -> Option<DecodeResult<SlotComponent>> {
455 if self.codec != Codec::P775 {
456 return Some(Err(DecodeError::Invalid("patch of protocol 776")));
457 }
458 Some(self.last_of(ty)?.and_then(|start| self.decode_at(start)))
459 }
460
461 #[cfg(feature = "v26_1")]
466 pub fn decode_all(&self) -> DecodeResult<Vec<SlotComponent>> {
467 if self.codec != Codec::P775 {
468 return Err(DecodeError::Invalid("patch of protocol 776"));
469 }
470 let mut r = Reader::new(&self.bytes);
471 (0..self.added)
472 .map(|_| <SlotComponent as crate::codec::Decode>::decode(&mut r))
473 .collect()
474 }
475
476 #[cfg(feature = "v26_2")]
478 #[must_use]
479 pub fn decode_776(
480 &self,
481 ty: i32,
482 ) -> Option<DecodeResult<crate::defs::p776::types::SlotComponent>> {
483 if self.codec != Codec::P776 {
484 return Some(Err(DecodeError::Invalid("patch of protocol 775")));
485 }
486 Some(self.last_of(ty)?.and_then(|start| self.decode_at(start)))
487 }
488
489 #[cfg(feature = "v26_2")]
494 pub fn decode_all_776(&self) -> DecodeResult<Vec<crate::defs::p776::types::SlotComponent>> {
495 if self.codec != Codec::P776 {
496 return Err(DecodeError::Invalid("patch of protocol 775"));
497 }
498 let mut r = Reader::new(&self.bytes);
499 (0..self.added)
500 .map(|_| {
501 <crate::defs::p776::types::SlotComponent as crate::codec::Decode>::decode(
502 &mut r,
503 )
504 })
505 .collect()
506 }
507
508 #[must_use]
513 pub fn same_components(&self, other: &ComponentPatch) -> bool {
514 if self == other {
515 return true;
516 }
517 let mut a: Vec<i32> = self.removed().collect();
518 let mut b: Vec<i32> = other.removed().collect();
519 a.sort_unstable();
520 a.dedup();
521 b.sort_unstable();
522 b.dedup();
523 if a != b {
524 return false;
525 }
526 let last = |p: &ComponentPatch| {
527 let mut v: Vec<(i32, Bytes)> = Vec::new();
528 for (t, b) in p.iter() {
529 match v.iter_mut().find(|(k, _)| *k == t) {
530 Some(e) => e.1 = b,
531 None => v.push((t, b)),
532 }
533 }
534 v.sort_by_key(|(t, _)| *t);
535 v
536 };
537 last(self) == last(other)
538 }
539
540 #[must_use]
543 pub fn from_parts(added: &[(i32, &[u8])], removed: &[i32]) -> ComponentPatch {
544 Self::from_parts_with(Codec::P775, added, removed)
545 }
546
547 #[must_use]
549 pub fn from_parts_776(added: &[(i32, &[u8])], removed: &[i32]) -> ComponentPatch {
550 Self::from_parts_with(Codec::P776, added, removed)
551 }
552
553 fn from_parts_with(
554 codec: Codec,
555 added: &[(i32, &[u8])],
556 removed: &[i32],
557 ) -> ComponentPatch {
558 let mut w = BytesMut::new();
559 for (t, v) in added {
560 w.put_varint(*t);
561 w.put_slice(v);
562 }
563 let split = w.len() as u32;
564 for t in removed {
565 w.put_varint(*t);
566 }
567 ComponentPatch {
568 bytes: w.freeze(),
569 split,
570 added: added.len() as u16,
571 removed: removed.len() as u16,
572 added_mask: added.iter().fold(0, |m, (t, _)| m | bit(*t)),
573 removed_mask: removed.iter().fold(0, |m, t| m | bit(*t)),
574 codec,
575 }
576 }
577 }
578
579 #[derive(Debug, Clone)]
581 pub struct Components<'a> {
582 bytes: Bytes,
583 pos: usize,
584 left: u16,
585 codec: Codec,
586 _p: std::marker::PhantomData<&'a ComponentPatch>,
587 }
588
589 impl Iterator for Components<'_> {
590 type Item = (i32, Bytes);
591
592 #[inline]
593 fn next(&mut self) -> Option<(i32, Bytes)> {
594 if self.left == 0 {
595 return None;
596 }
597 self.left -= 1;
598 let mut r = Reader::new(&self.bytes);
599 r.skip(self.pos).ok()?;
600 let mut value = r.clone();
601 let ty = value.read_varint().ok()?;
602 let value_start = value.position();
603 skip_codec(self.codec, &mut r).ok()?;
604 self.pos = r.position();
605 Some((ty, self.bytes.slice(value_start..self.pos)))
606 }
607 }
608
609 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
611 pub struct ItemStack {
612 pub id: i32,
614 pub count: i32,
616 pub components: ComponentPatch,
618 }
619
620 impl ItemStack {
621 #[cfg(feature = "v26_1")]
623 pub fn read(r: &mut Reader<'_>) -> DecodeResult<Option<ItemStack>> {
624 Self::read_with::<C775>(r)
625 }
626
627 #[cfg(feature = "v26_2")]
629 pub fn read_776(r: &mut Reader<'_>) -> DecodeResult<Option<ItemStack>> {
630 Self::read_with::<C776>(r)
631 }
632
633 #[inline]
634 fn read_with<const C: u8>(r: &mut Reader<'_>) -> DecodeResult<Option<ItemStack>> {
635 let count = r.read_varint()?;
636 if count <= 0 {
637 return Ok(None);
638 }
639 let id = r.read_varint()?;
640 let added = r.read_varint()?;
641 let removed = r.read_varint()?;
642 let components = ComponentPatch::read_with::<C>(r, added, removed)?;
643 Ok(Some(ItemStack {
644 id,
645 count,
646 components,
647 }))
648 }
649
650 pub fn write(s: Option<&ItemStack>, w: &mut BytesMut) {
652 match s {
653 None => w.put_varint(0),
654 Some(s) => {
655 w.put_varint(s.count);
656 w.put_varint(s.id);
657 w.put_varint(i32::from(s.components.added));
658 w.put_varint(i32::from(s.components.removed));
659 w.put_slice(&s.components.bytes);
660 }
661 }
662 }
663 }
664}
665
666#[cfg(test)]
667mod tests {
668 use super::*;
669 use crate::codec::{Encode, decode_exact};
670 use bytes::{Bytes, BytesMut};
671
672 #[test]
673 fn legacy_known_answers() {
674 let b = Bytes::from_static(&[0xff, 0xff]);
676 assert_eq!(decode_exact::<legacy::Slot>(&b), Ok(legacy::Slot::EMPTY));
677 let b = Bytes::from_static(&[0x00, 0x01, 0x40, 0x00, 0x00, 0x00]);
679 let s = decode_exact::<legacy::Slot>(&b).unwrap();
680 let it = s.item().unwrap();
681 assert_eq!(
682 (it.id, it.count, it.damage, it.nbt.is_none()),
683 (1, 64, 0, true)
684 );
685 let mut w = BytesMut::new();
686 s.encode(&mut w).unwrap();
687 assert_eq!(&w[..], &b[..]);
688 let b = Bytes::from_static(&[0x01, 0x14, 0x01, 0x00, 0x05, 0x0a, 0x00, 0x00, 0x00]);
690 let s = decode_exact::<legacy::Slot>(&b).unwrap();
691 assert_eq!(s.item().unwrap().nbt.as_ref().unwrap().as_bytes().len(), 4);
692 }
693
694 #[test]
695 fn modern_known_answers() {
696 let b = Bytes::from_static(&[0x00]);
697 assert_eq!(decode_exact::<modern::Slot>(&b), Ok(modern::Slot::EMPTY));
698 let b = Bytes::from_static(&[0x01, 0xac, 0x02, 0x10, 0x00]);
699 let s = decode_exact::<modern::Slot>(&b).unwrap();
700 let it = s.item().unwrap();
701 assert_eq!((it.id, it.count), (300, 16));
702 }
703}