From 25605c7479bd17f8a8bdf3868d37bfce8ebb48aa Mon Sep 17 00:00:00 2001 From: shenjack <3695888@qq.com> Date: Wed, 6 Mar 2024 23:06:42 +0800 Subject: [PATCH] read datas --- shen-nbt5/src/lib.rs | 73 +++++++++++++++++++++++++++++--------------- 1 file changed, 49 insertions(+), 24 deletions(-) diff --git a/shen-nbt5/src/lib.rs b/shen-nbt5/src/lib.rs index 58d2b35..24ad0df 100644 --- a/shen-nbt5/src/lib.rs +++ b/shen-nbt5/src/lib.rs @@ -1,44 +1,70 @@ - +// pub enum Endian { +// Big, +// Little, +// } /// 用于读取 NBT 数据 pub struct NbtReader<'data> { - data: &'data [u8], - cursor: usize, + /// NBT 数据 + pub data: &'data [u8], + /// 当前读取的位置 + pub cursor: usize, + // be/le + // pub endian: Endian, } +macro_rules! read { + ($name:ident, $ty:ty, $size:literal) => { + #[doc = concat!("读取 ", stringify!($ty), " 类型 ", $size, " 长度的数据")] + pub fn $name(&mut self) -> $ty { + unsafe { + let value = *(self.data[self.cursor..].as_ptr() as *const $ty); + self.cursor += std::mem::size_of::<$ty>(); + value.to_be() + } + } + }; + ($name:ident, $ty:ty, $size:literal, false) => { + #[doc = concat!("读取 ", stringify!($ty), " 类型 ", $size, " 长度的数据")] + pub fn $name(&mut self) -> $ty { + unsafe { + let value = *(self.data[self.cursor..].as_ptr() as *const $ty); + self.cursor += std::mem::size_of::<$ty>(); + value + } + } + }; +} impl NbtReader<'_> { pub fn new(data: &[u8]) -> NbtReader { NbtReader { data, cursor: 0, + // endian: Endian::Big, } } - pub fn read_i8(&mut self) -> i8 { let value = self.data[self.cursor] as i8; self.cursor += 1; value } - pub fn read_i16(&mut self) -> i16 { - unsafe { - let value = *(self.data[self.cursor..].as_ptr() as *const i16); - self.cursor += 2; - value.to_be() - } + pub fn read_u8(&mut self) -> u8 { + let value = self.data[self.cursor]; + self.cursor += 1; + value } - pub fn read_i32(&mut self) -> i32 { - unsafe { - let value = *(self.data[self.cursor..].as_ptr() as *const i32); - self.cursor += 4; - value.to_be() - } - } - pub fn read_i64(&mut self) -> i64 { - unsafe { - let value = *(self.data[self.cursor..].as_ptr() as *const i64); - self.cursor += 8; - value.to_be() - } + 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); + pub fn read_bytes(&mut self, len: usize) -> &[u8] { + let value = &self.data[self.cursor..self.cursor + len]; + self.cursor += len; + value } } @@ -71,4 +97,3 @@ pub enum NbtValue<'value> { /// 12 LongArray(Vec), } -