diff --git a/shen-nbt5/src/lib.rs b/shen-nbt5/src/lib.rs index fedf84b..0d0db11 100644 --- a/shen-nbt5/src/lib.rs +++ b/shen-nbt5/src/lib.rs @@ -3,6 +3,9 @@ // Little, // } +#[cfg(test)] +mod tests; + /// 用于读取 NBT 数据 pub struct NbtReader<'data> { /// NBT 数据 @@ -81,14 +84,16 @@ impl NbtReader<'_> { } pub fn read_int_array(&mut self, len: usize) -> &[i32] { unsafe { + let value = std::slice::from_raw_parts(self.data[self.cursor..].as_ptr() as *const i32, len); self.cursor += len * 4; - std::slice::from_raw_parts(self.data[self.cursor..].as_ptr() as *const i32, len) + value } } pub fn read_long_array(&mut self, len: usize) -> &[i64] { unsafe { + let value = std::slice::from_raw_parts(self.data[self.cursor..].as_ptr() as *const i64, len); self.cursor += len * 8; - std::slice::from_raw_parts(self.data[self.cursor..].as_ptr() as *const i64, len) + value } } diff --git a/shen-nbt5/src/tests.rs b/shen-nbt5/src/tests.rs new file mode 100644 index 0000000..0b60653 --- /dev/null +++ b/shen-nbt5/src/tests.rs @@ -0,0 +1,38 @@ +use crate::{NbtReader, NbtValue}; + +#[test] +fn basic_init() { + let data = vec![0x01, 0x02, 0x03, 0x04]; + let reader = NbtReader::new(&data); + assert_eq!(reader.cursor, 0); + assert_eq!(reader.data, &data); +} + + +#[test] +fn read_i8() { + let data = vec![0x01, 0x02, 0x03, 0x04]; + let mut reader = NbtReader::new(&data); + assert_eq!(reader.read_i8(), 0x01); + assert_eq!(reader.cursor, 1); + assert_eq!(reader.read_i8(), 0x02); + assert_eq!(reader.cursor, 2); +} + +#[test] +fn read_array() { + let data = vec![0x01, 0x02, 0x03, 0x04]; + let mut reader = NbtReader::new(&data); + assert_eq!(reader.read_u8_array(2), &[0x01, 0x02]); + assert_eq!(reader.cursor, 2); + assert_eq!(reader.read_i8_array(2), &[0x03, 0x04]); + assert_eq!(reader.cursor, 4); +} + +#[test] +fn read_long_array() { + let data = vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]; + let mut reader = NbtReader::new(&data); + assert_eq!(reader.read_long_array(1), &[i64::from_be_bytes([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08])]); + assert_eq!(reader.cursor, 8); +}