diff --git a/shen-nbt5/src/lib.rs b/shen-nbt5/src/lib.rs index 77d62ca..f30f0d2 100644 --- a/shen-nbt5/src/lib.rs +++ b/shen-nbt5/src/lib.rs @@ -21,7 +21,7 @@ macro_rules! read { #[doc = concat!("读取 ", stringify!($ty), " 类型 ", $size, " 长度的数据")] pub fn $name(&mut self) -> $ty { unsafe { - let value = *(self.data[self.cursor..].as_ptr() as *const $ty); + let value = std::ptr::read_unaligned(self.data[self.cursor..].as_ptr() as *const $ty); self.cursor += std::mem::size_of::<$ty>(); value.to_be() } @@ -31,7 +31,7 @@ macro_rules! read { #[doc = concat!("读取 ", stringify!($ty), " 类型 ", $size, " 长度的数据")] pub fn $name(&mut self) -> $ty { unsafe { - let value = *(self.data[self.cursor..].as_ptr() as *const $ty); + let value = std::ptr::read_unaligned(self.data[self.cursor..].as_ptr() as *const $ty); self.cursor += std::mem::size_of::<$ty>(); value } @@ -56,14 +56,14 @@ impl NbtReader<'_> { self.cursor += 1; value } - read!(read_i16, i16, 2); - read!(read_u16, u16, 2); - read!(read_i32, i32, 4); - read!(read_u32, u32, 4); - read!(read_i64, i64, 8); - read!(read_u64, u64, 8); - read!(read_f32, f32, 4, false); - read!(read_f64, f64, 8, false); + read!(read_i16_unchecked, i16, 2); + read!(read_u16_unchecked, u16, 2); + read!(read_i32_unchecked, i32, 4); + read!(read_u32_unchecked, u32, 4); + read!(read_i64_unchecked, i64, 8); + read!(read_u64_unchecked, u64, 8); + read!(read_f32_unchecked, f32, 4, false); + read!(read_f64_unchecked, f64, 8, false); pub fn read_u8_array(&mut self, len: usize) -> &[u8] { let value = &self.data[self.cursor..self.cursor + len]; diff --git a/shen-nbt5/src/tests.rs b/shen-nbt5/src/tests.rs index 3969d6b..0b56792 100644 --- a/shen-nbt5/src/tests.rs +++ b/shen-nbt5/src/tests.rs @@ -20,6 +20,21 @@ fn read_i8() { assert_eq!(reader.cursor, 2); } +#[test] +fn read_one_datas() { + let mut datas = vec![0x01, 0x02, 0x03, 0x04, 0x05, + 0x06, 0x07, 0x08, 0x09, 0x0A, + 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x01, 0x02, 0x03, 0x04, 0x05,]; + let mut reader = NbtReader::new(&mut datas); + assert_eq!(reader.read_i8(), 0x01); + assert_eq!(reader.read_u8(), 0x02); + assert_eq!(reader.read_i16_unchecked(), 0x0304); + assert_eq!(reader.read_u16_unchecked(), 0x0506); + assert_eq!(reader.read_i32_unchecked(), 0x0708090A); + assert_eq!(reader.read_i64_unchecked(), 0x0B0C0D0E0F010203); +} + #[test] fn read_array() { let mut data = vec![0x01, 0x02, 0x03, 0x04];