1use alloc::{string::String, vec::Vec, fmt};
4use crate::utils::*;
5use crate::uuid::UUID4;
6use crate::*;
7
8pub use super::chat::*;
9
10#[cfg(all(test, feature = "std"))]
11use crate::protocol::TestRandom;
12use crate::byte_order::{ProtoByteOrder, ByteOrder};
13
14impl Serialize for bool {
16 fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult {
17 to.serialize_byte(if *self { 1 } else { 0 })
18 }
19}
20
21impl Deserialize for bool {
22 fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> {
23 ProtoByteOrder::read_ubyte(data)?.try_map(move |b| match b {
24 0x00 => Ok(false),
25 0x01 => Ok(true),
26 other => Err(DeserializeErr::InvalidBool(other)),
27 })
28 }
29}
30
31#[cfg(all(test, feature = "std"))]
32impl TestRandom for bool {
33 fn test_gen_random() -> Self {
34 rand::random()
35 }
36}
37
38macro_rules! def_primitive {
39 ($nam: ty, $read: ident, $write: ident) => {
40 impl Serialize for $nam {
41 fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult {
42 let data = ProtoByteOrder::$write(*self);
43 to.serialize_bytes(&data)
44 }
45 }
46
47 impl Deserialize for $nam {
48 fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> {
49 ProtoByteOrder::$read(data)
50 }
51 }
52
53 #[cfg(all(test, feature = "std"))]
54 impl TestRandom for $nam {
55 fn test_gen_random() -> Self {
56 rand::random()
57 }
58 }
59 };
60}
61
62def_primitive!(u8, read_ubyte, write_ubyte);
63def_primitive!(i8, read_byte, write_byte);
64def_primitive!(u16, read_ushort, write_ushort);
65def_primitive!(i16, read_short, write_short);
66def_primitive!(u32, read_uint, write_uint);
67def_primitive!(i32, read_int, write_int);
68def_primitive!(u64, read_ulong, write_ulong);
69def_primitive!(i64, read_long, write_long);
70def_primitive!(u128, read_u2long, write_u2long);
71def_primitive!(i128, read_2long, write_2long);
72def_primitive!(f32, read_float, write_float);
73def_primitive!(f64, read_double, write_double);
74
75macro_rules! def_varnum {
77 ($nam: ident, $data_type: ty, $working_type: ty, $max_bytes: literal) => {
78 #[derive(Copy, Clone, PartialOrd, PartialEq, Default, Hash, Ord, Eq)]
79 pub struct $nam(pub $data_type);
80
81 impl Serialize for $nam {
82 fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult {
83 let mut out = [0u8; $max_bytes];
84 let mut v: $working_type = self.0 as $working_type;
85 let mut byte_idx = 0;
86 let mut has_more = true;
87 while has_more {
88 if byte_idx == out.len() {
89 panic!("tried to write too much data for {}", stringify!($nam));
90 }
91
92 let mut v_byte = (v & 0x7F) as u8;
93 v >>= 7;
94 has_more = v != 0;
95 if has_more {
96 v_byte |= 0x80;
97 }
98
99 out[byte_idx] = v_byte;
100 byte_idx += 1;
101 }
102
103 to.serialize_bytes(&out[..byte_idx])
104 }
105 }
106
107 impl Deserialize for $nam {
108 fn mc_deserialize(orig_data: &[u8]) -> DeserializeResult<Self> {
109 let mut data = orig_data;
110 let mut v: $working_type = 0;
111 let mut bit_place: usize = 0;
112 let mut i: usize = 0;
113 let mut has_more = true;
114
115 while has_more {
116 if i == $max_bytes {
117 return DeserializeErr::VarNumTooLong(Vec::from(&orig_data[..i])).into();
118 }
119 let Deserialized { value: byte, data: rest } = ProtoByteOrder::read_ubyte(data)?;
120 data = rest;
121 has_more = byte & 0x80 != 0;
122 v |= ((byte as $working_type) & 0x7F) << bit_place;
123 bit_place += 7;
124 i += 1;
125 }
126
127 Deserialized::ok(Self(v as $data_type), data)
128 }
129 }
130
131 impl From<$data_type> for $nam {
132 fn from(other: $data_type) -> Self {
133 Self(other)
134 }
135 }
136
137 impl From<$nam> for $data_type {
138 fn from(other: $nam) -> Self {
139 other.0
140 }
141 }
142
143 impl core::ops::Deref for $nam {
144 type Target = $data_type;
145
146 fn deref(&self) -> &Self::Target {
147 &self.0
148 }
149 }
150
151 impl fmt::Display for $nam {
152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153 write!(f, "{}", self.0)
154 }
155 }
156
157 impl fmt::Debug for $nam {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 f.write_str(stringify!($nam))?;
160 f.write_str("(")?;
161 write!(f, "{}", self.0)?;
162 f.write_str(")")?;
163 Ok(())
164 }
165 }
166
167 #[cfg(all(test, feature = "std"))]
168 impl TestRandom for $nam {
169 fn test_gen_random() -> Self {
170 let out: $data_type = rand::random();
171 Self(out)
172 }
173 }
174 }
175}
176
177def_varnum!(VarInt, i32, u32, 5);
178def_varnum!(VarLong, i64, u64, 10);
179
180impl Serialize for String {
182 fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult {
183 to.serialize_other(&VarInt(self.len() as i32))?;
184 to.serialize_bytes(self.as_bytes())
185 }
186}
187
188impl Deserialize for String {
189 fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> {
190 VarInt::mc_deserialize(data)?.and_then(move |length, rest| {
191 if length.0 < 0 {
192 Err(DeserializeErr::NegativeLength(length))
193 } else {
194 take(length.0 as usize, rest)?.try_map(move |taken| {
195 String::from_utf8(taken.to_vec()).map_err(DeserializeErr::BadStringEncoding)
196 })
197 }
198 })
199 }
200}
201
202#[cfg(all(test, feature = "std"))]
203impl TestRandom for String {
204 fn test_gen_random() -> Self {
205 let raw_len: u8 = rand::random();
206 let len = raw_len as usize;
207 let mut out = String::with_capacity(len);
208 for _ in 0..len {
209 let c_idx: u8 = rand::random::<u8>() % 36;
210
211 let c = if c_idx <= 10 {
212 (48 + c_idx) as char
213 } else {
214 ((c_idx - 10) + 65) as char
215 };
216
217 out.push(c)
218 }
219
220 out
221 }
222}
223
224#[derive(Clone, Copy, PartialEq, Hash, Debug)]
226pub struct IntPosition {
227 pub x: i32,
228 pub y: i16,
229 pub z: i32,
230}
231
232impl Serialize for IntPosition {
233 fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult {
234 let x_raw = if self.x < 0 {
235 (self.x + 0x2000000) as u64 | 0x2000000
236 } else {
237 self.x as u64
238 } & 0x3FFFFFF;
239
240 let z_raw = if self.z < 0 {
241 (self.z + 0x2000000) as u64 | 0x2000000
242 } else {
243 self.z as u64
244 } & 0x3FFFFFF;
245
246 let y_raw = if self.y < 0 {
247 (self.y + 0x800) as u64 | 0x800
248 } else {
249 self.y as u64
250 } & 0xFFF;
251
252 let data = ProtoByteOrder::write_ulong(((x_raw << 38) | (z_raw << 12) | y_raw) as u64);
253 to.serialize_bytes(&data)
254 }
255}
256
257impl Deserialize for IntPosition {
258 fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> {
259 let Deserialized { value: raw, data } = ProtoByteOrder::read_ulong(data)?;
260 let mut x = ((raw >> 38) as u32) & 0x3FFFFFF;
261 let mut z = ((raw >> 12) & 0x3FFFFFF) as u32;
262 let mut y = ((raw & 0xFFF) as u16) & 0xFFF;
263
264 if (x & 0x2000000) != 0 {
265 x = (((x & 0x1FFFFFF) as i32) - 0x2000000) as u32;
270 }
271 if (y & 0x800) != 0 {
272 y = (((y & 0x7FF) as i16) - 0x800) as u16;
273 }
274 if (z & 0x2000000) != 0 {
275 z = (((z & 0x1FFFFFF) as i32) - 0x2000000) as u32;
276 }
277
278 Deserialized::ok(
279 IntPosition {
280 x: x as i32,
281 y: y as i16,
282 z: z as i32,
283 },
284 data,
285 )
286 }
287}
288
289#[cfg(all(test, feature = "std"))]
290impl TestRandom for IntPosition {
291 fn test_gen_random() -> Self {
292 let x: i32 = ((rand::random::<u32>() % (1 << 26)) as i32) - (1 << 25);
293 let z: i32 = ((rand::random::<u32>() % (1 << 26)) as i32) - (1 << 25);
294 let y: i16 = ((rand::random::<u16>() % (1 << 12)) as i16) - (1 << 11);
295 Self { x, y, z }
296 }
297}
298
299#[derive(Copy, Clone, PartialEq, Hash, Debug)]
301pub struct Angle {
302 pub value: u8,
303}
304
305impl Serialize for Angle {
306 fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult {
307 to.serialize_byte(self.value)
308 }
309}
310
311impl Deserialize for Angle {
312 fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> {
313 Ok(ProtoByteOrder::read_ubyte(data)?.map(move |b| Angle { value: b }))
314 }
315}
316
317#[cfg(all(test, feature = "std"))]
318impl TestRandom for Angle {
319 fn test_gen_random() -> Self {
320 Self {
321 value: rand::random(),
322 }
323 }
324}
325
326impl Serialize for UUID4 {
329 fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult {
330 let bytes = ProtoByteOrder::write_u2long(self.to_u128());
331 to.serialize_bytes(&bytes[..])
332 }
333}
334
335impl Deserialize for UUID4 {
336 fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> {
337 Ok(ProtoByteOrder::read_u2long(data)?.map(move |raw| UUID4::from(raw)))
338 }
339}
340
341#[cfg(all(test, feature = "std"))]
342impl TestRandom for UUID4 {
343 fn test_gen_random() -> Self {
344 UUID4::random()
345 }
346}
347
348#[derive(Clone, PartialEq, Debug)]
351pub struct NamedNbtTag {
352 pub root: nbt::NamedTag,
353}
354
355impl Serialize for NamedNbtTag {
356 fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult {
357 let bytes = self.root.bytes();
358 to.serialize_bytes(bytes.as_slice())
359 }
360}
361
362impl Deserialize for NamedNbtTag {
363 fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> {
364 Ok(
365 nbt::NamedTag::root_compound_tag_from_bytes(data)?
366 .map(move |root| NamedNbtTag { root }),
367 )
368 }
369}
370
371impl From<nbt::NamedTag> for NamedNbtTag {
372 fn from(root: nbt::NamedTag) -> Self {
373 Self { root }
374 }
375}
376
377impl Into<nbt::NamedTag> for NamedNbtTag {
378 fn into(self) -> nbt::NamedTag {
379 self.root
380 }
381}
382
383#[cfg(all(test, feature = "std"))]
384impl TestRandom for NamedNbtTag {
385 fn test_gen_random() -> Self {
386 Self {
387 root: nbt::NamedTag::test_gen_random(),
388 }
389 }
390}
391
392#[derive(Clone, Copy, Debug, PartialEq, Eq)]
393pub struct FixedInt {
394 raw: i32,
395}
396
397impl Serialize for FixedInt {
398 fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult {
399 to.serialize_other(&self.raw)
400 }
401}
402
403impl Deserialize for FixedInt {
404 fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> {
405 Ok(i32::mc_deserialize(data)?.map(move |raw| FixedInt { raw }))
406 }
407}
408
409impl FixedInt {
410 pub fn new(data: f64, fractional_bytes: usize) -> Self {
411 Self {
412 raw: (data * ((1 << fractional_bytes) as f64)) as i32,
413 }
414 }
415
416 pub fn into_float(self, fractional_bytes: usize) -> f64 {
417 (self.raw as f64) / ((1 << fractional_bytes) as f64)
418 }
419}
420
421#[cfg(all(test, feature = "std"))]
422impl TestRandom for FixedInt {
423 fn test_gen_random() -> Self {
424 FixedInt::new(f64::test_gen_random(), 16)
425 }
426}
427
428#[derive(Default)]
429pub struct BytesSerializer {
430 data: Vec<u8>,
431}
432
433impl Serializer for BytesSerializer {
434 fn serialize_bytes(&mut self, data: &[u8]) -> SerializeResult {
435 self.data.extend_from_slice(data);
436 Ok(())
437 }
438}
439
440impl BytesSerializer {
441 pub fn with_capacity(cap: usize) -> Self {
442 BytesSerializer {
443 data: Vec::with_capacity(cap),
444 }
445 }
446
447 pub fn into_bytes(self) -> Vec<u8> {
448 self.data
449 }
450}
451
452impl<T> Serialize for Option<T>
453 where
454 T: Serialize,
455{
456 fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult {
457 match self {
458 Some(value) => {
459 to.serialize_other(&true)?;
460 to.serialize_other(value)
461 }
462 None => to.serialize_other(&false),
463 }
464 }
465}
466
467impl<T> Deserialize for Option<T>
468 where
469 T: Deserialize,
470{
471 fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> {
472 bool::mc_deserialize(data)?.and_then(move |is_present, data| {
473 if is_present {
474 Ok(T::mc_deserialize(data)?.map(move |component| Some(component)))
475 } else {
476 Deserialized::ok(None, data)
477 }
478 })
479 }
480}
481
482#[cfg(all(test, feature = "std"))]
483impl<T> TestRandom for Option<T>
484 where
485 T: TestRandom,
486{
487 fn test_gen_random() -> Self {
488 let is_present: bool = rand::random();
489 if is_present {
490 Some(T::test_gen_random())
491 } else {
492 None
493 }
494 }
495}
496
497#[derive(Debug, PartialEq, Clone)]
499pub struct ItemStack {
500 pub item_id: VarInt,
501 pub item_count: i8,
502 pub nbt: Option<nbt::NamedTag>,
503}
504
505impl Serialize for ItemStack {
506 fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult {
507 to.serialize_other(&self.item_id)?;
508 to.serialize_other(&self.item_count)?;
509 match self.nbt.as_ref() {
510 Some(nbt) => to.serialize_bytes(nbt.bytes().as_slice()),
511 None => to.serialize_byte(nbt::Tag::End.id()),
512 }
513 }
514}
515
516impl Deserialize for ItemStack {
517 fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> {
518 let Deserialized { value: item_id, data } = VarInt::mc_deserialize(data)?;
519 let Deserialized { value: item_count, data } = i8::mc_deserialize(data)?;
520 if data.is_empty() {
521 return Err(DeserializeErr::Eof);
522 }
523
524 let id = data[0];
525 let rest = &data[1..];
526 Ok(match id {
527 0x00 => Deserialized {
528 value: None,
529 data: rest,
530 },
531 _ => nbt::read_named_tag(data)?.map(move |tag| Some(tag)),
532 }.map(move |nbt| Self {
533 item_id,
534 item_count,
535 nbt,
536 }))
537 }
538}
539
540#[cfg(all(test, feature = "std"))]
541impl TestRandom for ItemStack {
542 fn test_gen_random() -> Self {
543 let item_id = VarInt::test_gen_random();
544 let item_count = i8::test_gen_random() % 65;
545 let nbt = <Option<nbt::NamedTag>>::test_gen_random();
546
547 Self {
548 item_id,
549 item_count,
550 nbt,
551 }
552 }
553}
554
555pub type Slot = Option<ItemStack>;
556
557macro_rules! def_vector_type {
558 ($name: ident, $($fnam: ident),+) => {
559 crate::as_item! {
560 pub struct $name<T> {
561 $(pub $fnam: T),+
562 }
563 }
564
565 impl<T> Serialize for $name<T> where T: Serialize {
566 fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult {
567 $(
568 to.serialize_other(&self.$fnam)?;
569 )+
570 Ok(())
571 }
572 }
573
574 impl<T> Deserialize for $name<T> where T: Deserialize {
575 fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> {
576 $(let Deserialized { value: $fnam, data } = T::mc_deserialize(data)?;)+
577 Deserialized::ok(Self { $($fnam),+ }, data)
578 }
579 }
580
581 #[cfg(all(test, feature = "std"))]
582 impl<T> TestRandom for $name<T> where T: TestRandom {
583 fn test_gen_random() -> Self {
584 Self {
585 $($fnam: T::test_gen_random(),)+
586 }
587 }
588 }
589
590 impl<T> Clone for $name<T> where T: Clone {
591 fn clone(&self) -> Self {
592 Self {
593 $($fnam: self.$fnam.clone(),)+
594 }
595 }
596 }
597
598 impl<T> Copy for $name<T> where T: Copy {}
599
600 impl<T, Rhs> PartialEq<$name<Rhs>> for $name<T> where T: PartialEq<Rhs> {
601 fn eq(&self, other: &$name<Rhs>) -> bool {
602 $(self.$fnam.eq(&other.$fnam)) && +
603 }
604
605 fn ne(&self, other: &$name<Rhs>) -> bool {
606 $(self.$fnam.ne(&other.$fnam)) || +
607 }
608 }
609
610 impl<T> core::hash::Hash for $name<T> where T: core::hash::Hash {
611 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
612 $(self.$fnam.hash(state);)+
613 }
614 }
615
616 impl<T> fmt::Debug for $name<T> where T: fmt::Debug {
617 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
618 f.write_str(stringify!($name))?;
619 f.write_str("( ")?;
620 $(
621 f.write_str(stringify!($fnam))?;
622 f.write_str("=")?;
623 self.$fnam.fmt(f)?;
624 f.write_str(" ")?;
625 )+
626 f.write_str(")")?;
627 Ok(())
628 }
629 }
630
631 impl<T> fmt::Display for $name<T> where T: fmt::Display {
632 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
633 f.write_str(stringify!($name))?;
634 f.write_str("( ")?;
635 $(
636 f.write_str(stringify!($fnam))?;
637 f.write_str("=")?;
638 self.$fnam.fmt(f)?;
639 f.write_str(" ")?;
640 )+
641 f.write_str(")")?;
642 Ok(())
643 }
644 }
645
646 impl<T> From<$name<T>> for ($(crate::instead_of_ident!($fnam, T)),+) {
647 fn from(other: $name<T>) -> Self {
648 ($(other.$fnam),+)
649 }
650 }
651
652 impl<'a, T> From<&'a $name<T>> for ($(&'a crate::instead_of_ident!($fnam, T)),+) {
653 fn from(other: &'a $name<T>) -> Self {
654 ($(&other.$fnam),+)
655 }
656 }
657
658 impl<'a, T> From<&'a $name<T>> for ($(crate::instead_of_ident!($fnam, T)),+) where T: Clone {
659 fn from(other: &'a $name<T>) -> Self {
660 ($(other.$fnam.clone()),+)
661 }
662 }
663
664 impl<T> From<($(crate::instead_of_ident!($fnam, T)),+)> for $name<T> {
665 fn from(other: ($(crate::instead_of_ident!($fnam, T)),+)) -> Self {
666 let ($($fnam),+) = other;
667 Self { $($fnam),+ }
668 }
669 }
670
671 impl<'a, T> From<&'a ($(crate::instead_of_ident!($fnam, T)),+)> for $name<T> where T: Clone {
672 fn from(other: &'a ($(crate::instead_of_ident!($fnam, T)),+)) -> Self {
673 let ($($fnam),+) = other;
674 $(let $fnam = $fnam.clone();)+
675 Self { $($fnam),+ }
676 }
677 }
678
679 impl<'a, T> From<($(&'a crate::instead_of_ident!($fnam, T)),+)> for $name<T> where T: Clone {
680 fn from(other: ($(&'a crate::instead_of_ident!($fnam, T)),+)) -> Self {
681 let ($($fnam),+) = other;
682 $(let $fnam = $fnam.clone();)+
683 Self { $($fnam),+ }
684 }
685 }
686
687 impl<T> $name<T> {
688 pub fn from_other<O>(other: O) -> Self where O: Into<($(crate::instead_of_ident!($fnam, T)),+)> {
689 let ($($fnam),+) = other.into();
690 Self { $($fnam,)+ }
691 }
692
693 pub fn as_other<O>(&self) -> O where O: From<($(crate::instead_of_ident!($fnam, T)),+)>, T: Clone {
694 O::from(self.into())
695 }
696
697 pub fn into_other<O>(self) -> O where O: From<($(crate::instead_of_ident!($fnam, T)),+)> {
698 O::from(self.into())
699 }
700 }
701 };
702}
703
704def_vector_type!(Vec3, x, y, z);
705def_vector_type!(Vec2, x, y);
706def_vector_type!(ChunkPosition, x, z);
707pub type TopDownPosition<T> = ChunkPosition<T>;
708def_vector_type!(EntityRotation, yaw, pitch);
709
710proto_struct!(EntityLocation<P, R> {
711 position: Vec3<P>,
712 rotation: EntityRotation<R>
713});
714
715#[derive(Clone, Debug, PartialEq)]
716pub struct CountedArray<E, C> {
717 data: Vec<E>,
718 _counter_type: core::marker::PhantomData<C>,
719}
720
721pub trait ArrayCounter: Serialize + Deserialize {
722
723 fn as_count(&self) -> usize;
724
725 fn from_count(count: usize) -> Self;
726}
727
728impl<E, C> Serialize for CountedArray<E, C> where E: Serialize, C: ArrayCounter {
729 fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult {
730 let count = C::from_count(self.data.len());
731 to.serialize_other(&count)?;
732 for elem in &self.data {
733 to.serialize_other(elem)?;
734 }
735 Ok(())
736 }
737}
738
739impl<E, C> Deserialize for CountedArray<E, C> where E: Deserialize, C: ArrayCounter {
740 fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> {
741 let Deserialized { value: count, mut data } = C::mc_deserialize(data)?;
742 let count = count.as_count();
743 let mut elems = Vec::with_capacity(count);
744 for _ in 0..count {
745 let Deserialized { value: elem, data: rest } = E::mc_deserialize(data)?;
746 data = rest;
747 elems.push(elem);
748 }
749
750 Deserialized::ok(Self {
751 data: elems,
752 _counter_type: core::marker::PhantomData,
753 }, data)
754 }
755}
756
757impl<E, C> core::ops::Deref for CountedArray<E, C> where C: ArrayCounter {
758 type Target = Vec<E>;
759
760 fn deref(&self) -> &Self::Target {
761 &self.data
762 }
763}
764
765impl<E, C> core::ops::DerefMut for CountedArray<E, C> where C: ArrayCounter {
766 fn deref_mut(&mut self) -> &mut Self::Target {
767 &mut self.data
768 }
769}
770
771impl<E, C> From<CountedArray<E, C>> for Vec<E> where C: ArrayCounter {
772 fn from(other: CountedArray<E, C>) -> Self {
773 other.data
774 }
775}
776
777impl<E, C> From<Vec<E>> for CountedArray<E, C> where C: ArrayCounter {
778 fn from(data: Vec<E>) -> Self {
779 Self {
780 data,
781 _counter_type: core::marker::PhantomData,
782 }
783 }
784}
785
786#[cfg(all(test, feature = "std"))]
787impl<E, C> TestRandom for CountedArray<E, C>
788 where E: TestRandom, C: ArrayCounter
789{
790 fn test_gen_random() -> Self {
791 let elem_count: usize = rand::random::<usize>() % 32;
792 let mut out = Vec::with_capacity(elem_count);
793 for _ in 0..elem_count {
794 out.push(E::test_gen_random());
795 }
796
797 out.into()
798 }
799}
800
801impl ArrayCounter for VarInt {
802 fn as_count(&self) -> usize {
803 self.0 as usize
804 }
805
806 fn from_count(count: usize) -> Self {
807 Self(count as i32)
808 }
809}
810
811impl ArrayCounter for i16 {
812 fn as_count(&self) -> usize {
813 (*self) as usize
814 }
815
816 fn from_count(count: usize) -> Self {
817 count as i16
818 }
819}
820
821impl ArrayCounter for i32 {
822 fn as_count(&self) -> usize {
823 (*self) as usize
824 }
825
826 fn from_count(count: usize) -> Self {
827 count as i32
828 }
829}
830
831impl ArrayCounter for i8 {
832 fn as_count(&self) -> usize {
833 (*self) as usize
834 }
835
836 fn from_count(count: usize) -> Self {
837 count as i8
838 }
839}
840
841#[derive(Debug, Clone, PartialEq)]
842pub struct RemainingBytes {
843 pub data: Vec<u8>,
844}
845
846impl Serialize for RemainingBytes {
847 fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult {
848 to.serialize_bytes(self.data.as_slice())
849 }
850}
851
852impl Deserialize for RemainingBytes {
853 fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> {
854 Deserialized::ok(
855 RemainingBytes {
856 data: Vec::from(data),
857 },
858 &[],
859 )
860 }
861}
862
863impl Into<Vec<u8>> for RemainingBytes {
864 fn into(self) -> Vec<u8> {
865 self.data
866 }
867}
868
869impl From<Vec<u8>> for RemainingBytes {
870 fn from(data: Vec<u8>) -> Self {
871 Self { data }
872 }
873}
874
875impl core::ops::Deref for RemainingBytes {
876 type Target = Vec<u8>;
877
878 fn deref(&self) -> &Self::Target {
879 &self.data
880 }
881}
882
883impl core::ops::DerefMut for RemainingBytes {
884 fn deref_mut(&mut self) -> &mut Self::Target {
885 &mut self.data
886 }
887}
888
889#[cfg(all(test, feature = "std"))]
890impl TestRandom for RemainingBytes {
891 fn test_gen_random() -> Self {
892 let size: usize = rand::random::<usize>() % 256;
893 let mut out = Vec::with_capacity(size);
894 for _ in 0..size {
895 out.push(rand::random());
896 }
897
898 Self { data: out }
899 }
900}
901
902#[cfg(test)]
903mod tests {
904 use super::*;
905 use alloc::fmt::Debug;
906 use alloc::borrow::ToOwned;
907
908 #[test]
909 fn test_bool() {
910 test_type(true);
911 test_type(false);
912 }
913
914 #[test]
915 fn test_signed_byte() {
916 test_type(0i8);
917 test_type(127i8);
918 test_type(-15i8);
919 }
920
921 #[test]
922 fn test_unsigned_byte() {
923 test_type(0u8);
924 test_type(128u8);
925 test_type(255u8);
926 }
927
928 #[test]
929 fn test_signed_short() {
930 test_type(0i16);
931 test_type(-88i16);
932 test_type(25521i16);
933 }
934
935 #[test]
936 fn test_unsigned_short() {
937 test_type(0u16);
938 test_type(1723u16);
939 test_type(65534u16);
940 }
941
942 #[test]
943 fn test_signed_int() {
944 test_type(0i32);
945 test_type(123127i32);
946 test_type(-171238i32);
947 test_type(2147483647i32);
948 }
949
950 #[test]
951 fn test_signed_long() {
952 test_type(0i64);
953 test_type(123127i64);
954 test_type(-12123127i64);
955 test_type(2147483647i64);
956 test_type(-10170482028482i64);
957 }
958
959 #[test]
960 fn test_float() {
961 test_type(0.2313f32);
962 test_type(0f32);
963 test_type(123123213f32);
964 test_type(-123123f32);
965 }
966
967 #[test]
968 fn test_double() {
969 test_type(0.2313f64);
970 test_type(0f64);
971 test_type(123123213f64);
972 test_type(-123123f64);
973 }
974
975 #[test]
976 fn test_var_int() {
977 test_type(VarInt(0));
978 test_type(VarInt(1231231));
979 test_type(VarInt(2147483647));
980 test_type(VarInt(-2147483648));
981 test_type(VarInt(-1));
982 test_type(VarInt(-1001237));
983 }
984
985 #[test]
986 fn test_var_long() {
987 test_type(VarLong(0));
988 test_type(VarLong(1231231));
989 test_type(VarLong(12312319123));
990 test_type(VarLong(9223372036854775807));
991 test_type(VarLong(-1));
992 test_type(VarLong(-12312319123));
993 test_type(VarLong(-9223372036854775808));
994 test_type(VarLong(-1001237));
995 }
996
997 #[test]
998 fn test_string() {
999 test_type(String::from("hello my name is joey 123"));
1000 test_type(String::from(""));
1001 test_type(String::from("AAAA"));
1002 test_type(String::from("hello my name is joey 123").repeat(1000));
1003 }
1004
1005 #[test]
1006 fn test_nbt() {
1007 test_type(NamedNbtTag {
1008 root: nbt::Tag::Compound(alloc::vec![
1009 nbt::Tag::String("test 123".to_owned()).with_name("abc 123")
1010 ])
1011 .with_name("root"),
1012 })
1013 }
1014
1015 #[test]
1016 fn test_int_position() {
1017 test_type(IntPosition {
1018 x: 12312,
1019 y: -32,
1020 z: 321312,
1021 });
1022
1023 test_type(IntPosition {
1024 x: 12312,
1025 y: -32,
1026 z: -321312,
1027 });
1028
1029 test_type(IntPosition {
1030 x: -12312,
1031 y: -32,
1032 z: -321312,
1033 });
1034
1035 test_type(IntPosition {
1036 x: -12312,
1037 y: 32,
1038 z: 321312,
1039 });
1040
1041 test_type(IntPosition { x: 0, y: 0, z: 0 });
1042
1043 test_type(IntPosition {
1044 x: 48,
1045 y: 232,
1046 z: 12,
1047 });
1048
1049 test_type(IntPosition {
1050 x: 33554431,
1051 y: 2047,
1052 z: 33554431,
1053 });
1054
1055 test_type(IntPosition {
1056 x: -33554432,
1057 y: -2048,
1058 z: -33554432,
1059 });
1060
1061 test_type(IntPosition {
1062 x: 3,
1063 y: 0,
1064 z: 110655,
1065 });
1066 }
1067
1068 #[cfg(feature = "std")]
1069 #[test]
1070 fn test_uuid() {
1071 for _ in 0..5 {
1072 test_type(UUID4::random());
1073 }
1074 }
1075
1076 #[test]
1077 fn test_angle() {
1078 test_type(Angle { value: 0 });
1079 test_type(Angle { value: 24 });
1080 test_type(Angle { value: 255 });
1081 test_type(Angle { value: 8 });
1082 }
1083
1084 fn test_type<S: Serialize + Deserialize + PartialEq + Debug>(value: S) {
1085 let bytes = {
1086 let mut test = BytesSerializer::default();
1087 value
1088 .mc_serialize(&mut test)
1089 .expect("serialization should succeed");
1090 test.into_bytes()
1091 };
1092 let deserialized =
1093 S::mc_deserialize(bytes.as_slice()).expect("deserialization should succeed");
1094 assert!(deserialized.data.is_empty());
1095 assert_eq!(
1096 deserialized.value, value,
1097 "deserialized value == serialized value"
1098 );
1099 let re_serialized = {
1100 let mut test = BytesSerializer::default();
1101 deserialized
1102 .value
1103 .mc_serialize(&mut test)
1104 .expect("serialization should succeed");
1105 test.into_bytes()
1106 };
1107 assert_eq!(
1108 re_serialized, bytes,
1109 "serialized value == original serialized bytes"
1110 );
1111 }
1112}