1
0
Fork 0
mirror of https://github.com/azalea-rs/simdnbt.git synced 2025-08-02 15:36:03 +00:00

optimize reading arrays of compounds in owned read

This commit is contained in:
mat 2024-05-14 00:07:53 +00:00
parent 608cf43886
commit 740e7afbe9
2 changed files with 14 additions and 3 deletions

View file

@ -32,7 +32,11 @@ impl NbtCompound {
Self::read_with_depth(data, 0) Self::read_with_depth(data, 0)
} }
pub fn read_with_depth(data: &mut Cursor<&[u8]>, depth: usize) -> Result<Self, Error> { pub fn read_with_depth_and_capacity(
data: &mut Cursor<&[u8]>,
depth: usize,
capacity: usize,
) -> Result<Self, Error> {
if depth > MAX_DEPTH { if depth > MAX_DEPTH {
return Err(Error::MaxDepthExceeded); return Err(Error::MaxDepthExceeded);
} }
@ -42,7 +46,7 @@ impl NbtCompound {
}; };
let mut tags_buffer_len: usize = 0; let mut tags_buffer_len: usize = 0;
let mut values = Vec::with_capacity(8); let mut values = Vec::with_capacity(capacity);
loop { loop {
let tag_type = data.read_u8().map_err(|_| Error::UnexpectedEof)?; let tag_type = data.read_u8().map_err(|_| Error::UnexpectedEof)?;
if tag_type == END_ID { if tag_type == END_ID {
@ -69,6 +73,10 @@ impl NbtCompound {
Ok(Self { values }) Ok(Self { values })
} }
pub fn read_with_depth(data: &mut Cursor<&[u8]>, depth: usize) -> Result<Self, Error> {
Self::read_with_depth_and_capacity(data, depth, 8)
}
pub fn write(&self, data: &mut Vec<u8>) { pub fn write(&self, data: &mut Vec<u8>) {
for (name, tag) in &self.values { for (name, tag) in &self.values {
// reserve 4 bytes extra so we can avoid reallocating for small tags // reserve 4 bytes extra so we can avoid reallocating for small tags

View file

@ -84,8 +84,11 @@ impl NbtList {
let length = read_u32(data)?; let length = read_u32(data)?;
// arbitrary number to prevent big allocations // arbitrary number to prevent big allocations
let mut compounds = Vec::with_capacity(length.min(128) as usize); let mut compounds = Vec::with_capacity(length.min(128) as usize);
let mut capacity: usize = 8;
for _ in 0..length { for _ in 0..length {
compounds.push(NbtCompound::read_with_depth(data, depth + 1)?) let tag = NbtCompound::read_with_depth_and_capacity(data, depth + 1, capacity)?;
capacity = tag.len();
compounds.push(tag);
} }
compounds compounds
}), }),