|
1 | 1 | //! [`Encode`] and [`Decode`] impls on foreign types. |
2 | 2 |
|
| 3 | +use core::slice; |
3 | 4 | use std::borrow::Cow; |
4 | 5 | use std::collections::{BTreeSet, HashSet}; |
5 | 6 | use std::hash::{BuildHasher, Hash}; |
@@ -27,8 +28,8 @@ impl Encode for bool { |
27 | 28 |
|
28 | 29 | fn encode_slice(slice: &[bool], mut w: impl Write) -> Result<()> { |
29 | 30 | // SAFETY: Bools have the same layout as u8. |
| 31 | + let bytes = unsafe { slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len()) }; |
30 | 32 | // Bools are guaranteed to have the correct bit pattern. |
31 | | - let bytes: &[u8] = unsafe { mem::transmute(slice) }; |
32 | 33 | Ok(w.write_all(bytes)?) |
33 | 34 | } |
34 | 35 | } |
@@ -64,7 +65,7 @@ impl Encode for i8 { |
64 | 65 |
|
65 | 66 | fn encode_slice(slice: &[i8], mut w: impl Write) -> Result<()> { |
66 | 67 | // SAFETY: i8 has the same layout as u8. |
67 | | - let bytes: &[u8] = unsafe { mem::transmute(slice) }; |
| 68 | + let bytes = unsafe { slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len()) }; |
68 | 69 | Ok(w.write_all(bytes)?) |
69 | 70 | } |
70 | 71 | } |
@@ -471,7 +472,6 @@ impl<const N: usize, T: Encode> Encode for [T; N] { |
471 | 472 | impl<'a, const N: usize, T: Decode<'a>> Decode<'a> for [T; N] { |
472 | 473 | fn decode(r: &mut &'a [u8]) -> Result<Self> { |
473 | 474 | // TODO: rewrite using std::array::try_from_fn when stabilized? |
474 | | - // TODO: specialization for [f64; 3] improved performance. |
475 | 475 |
|
476 | 476 | let mut data: [MaybeUninit<T>; N] = unsafe { MaybeUninit::uninit().assume_init() }; |
477 | 477 |
|
@@ -539,9 +539,12 @@ impl<'a> Decode<'a> for &'a [u8] { |
539 | 539 |
|
540 | 540 | impl<'a> Decode<'a> for &'a [i8] { |
541 | 541 | fn decode(r: &mut &'a [u8]) -> Result<Self> { |
542 | | - let unsigned_bytes = <&[u8]>::decode(r)?; |
543 | | - let signed_bytes: &[i8] = unsafe { mem::transmute(unsigned_bytes) }; |
544 | | - Ok(signed_bytes) |
| 542 | + let bytes = <&[u8]>::decode(r)?; |
| 543 | + |
| 544 | + // SAFETY: i8 and u8 have the same layout. |
| 545 | + let bytes = unsafe { slice::from_raw_parts(bytes.as_ptr() as *const i8, bytes.len()) }; |
| 546 | + |
| 547 | + Ok(bytes) |
545 | 548 | } |
546 | 549 | } |
547 | 550 |
|
@@ -765,12 +768,12 @@ impl<'a> Decode<'a> for Uuid { |
765 | 768 |
|
766 | 769 | impl Encode for Compound { |
767 | 770 | fn encode(&self, w: impl Write) -> Result<()> { |
768 | | - Ok(valence_nbt::to_binary_writer(w, self, "")?) |
| 771 | + Ok(self.to_binary(w, "")?) |
769 | 772 | } |
770 | 773 | } |
771 | 774 |
|
772 | 775 | impl Decode<'_> for Compound { |
773 | 776 | fn decode(r: &mut &[u8]) -> Result<Self> { |
774 | | - Ok(valence_nbt::from_binary_slice(r)?.0) |
| 777 | + Ok(Self::from_binary(r)?.0) |
775 | 778 | } |
776 | 779 | } |
0 commit comments