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(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 #[derive(Debug, Clone, Default)]
178 pub struct ComponentPatch {
179 bytes: Bytes,
181 split: u32,
183 added: u16,
184 removed: u16,
185 added_mask: u128,
188 removed_mask: u128,
189 }
190
191 #[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 #[inline]
202 fn may_have(mask: u128, ty: i32) -> bool {
203 mask & (bit(ty) | 1u128 << 127) != 0
204 }
205
206 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 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 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 #[must_use]
264 pub fn is_empty(&self) -> bool {
265 self.added == 0 && self.removed == 0
266 }
267
268 #[must_use]
270 pub fn added_len(&self) -> usize {
271 usize::from(self.added)
272 }
273
274 #[must_use]
276 pub fn removed_len(&self) -> usize {
277 usize::from(self.removed)
278 }
279
280 #[must_use]
282 pub fn as_bytes(&self) -> &Bytes {
283 &self.bytes
284 }
285
286 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 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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
456 pub struct ItemStack {
457 pub id: i32,
459 pub count: i32,
461 pub components: ComponentPatch,
463 }
464
465 impl ItemStack {
466 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 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 let b = Bytes::from_static(&[0xff, 0xff]);
509 assert_eq!(decode_exact::<legacy::Slot>(&b), Ok(legacy::Slot::EMPTY));
510 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 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}