read datas

This commit is contained in:
shenjack 2024-03-06 23:06:42 +08:00
parent 20889e1fd3
commit 25605c7479
Signed by: shenjack
GPG Key ID: 7B1134A979775551

View File

@ -1,44 +1,70 @@
// pub enum Endian {
// Big,
// Little,
// }
/// 用于读取 NBT 数据 /// 用于读取 NBT 数据
pub struct NbtReader<'data> { pub struct NbtReader<'data> {
data: &'data [u8], /// NBT 数据
cursor: usize, 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<'_> { impl NbtReader<'_> {
pub fn new(data: &[u8]) -> NbtReader { pub fn new(data: &[u8]) -> NbtReader {
NbtReader { NbtReader {
data, data,
cursor: 0, cursor: 0,
// endian: Endian::Big,
} }
} }
pub fn read_i8(&mut self) -> i8 { pub fn read_i8(&mut self) -> i8 {
let value = self.data[self.cursor] as i8; let value = self.data[self.cursor] as i8;
self.cursor += 1; self.cursor += 1;
value value
} }
pub fn read_i16(&mut self) -> i16 { pub fn read_u8(&mut self) -> u8 {
unsafe { let value = self.data[self.cursor];
let value = *(self.data[self.cursor..].as_ptr() as *const i16); self.cursor += 1;
self.cursor += 2; value
value.to_be()
}
}
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 /// 12
LongArray(Vec<i64>), LongArray(Vec<i64>),
} }