diff --git a/simdnbt/src/owned/compound.rs b/simdnbt/src/owned/compound.rs index ec6c547..e5166d1 100644 --- a/simdnbt/src/owned/compound.rs +++ b/simdnbt/src/owned/compound.rs @@ -32,7 +32,11 @@ impl NbtCompound { Self::read_with_depth(data, 0) } - pub fn read_with_depth(data: &mut Cursor<&[u8]>, depth: usize) -> Result { + pub fn read_with_depth_and_capacity( + data: &mut Cursor<&[u8]>, + depth: usize, + capacity: usize, + ) -> Result { if depth > MAX_DEPTH { return Err(Error::MaxDepthExceeded); } @@ -42,7 +46,7 @@ impl NbtCompound { }; let mut tags_buffer_len: usize = 0; - let mut values = Vec::with_capacity(8); + let mut values = Vec::with_capacity(capacity); loop { let tag_type = data.read_u8().map_err(|_| Error::UnexpectedEof)?; if tag_type == END_ID { @@ -69,6 +73,10 @@ impl NbtCompound { Ok(Self { values }) } + pub fn read_with_depth(data: &mut Cursor<&[u8]>, depth: usize) -> Result { + Self::read_with_depth_and_capacity(data, depth, 8) + } + pub fn write(&self, data: &mut Vec) { for (name, tag) in &self.values { // reserve 4 bytes extra so we can avoid reallocating for small tags diff --git a/simdnbt/src/owned/list.rs b/simdnbt/src/owned/list.rs index d9f9fb0..02b9a27 100644 --- a/simdnbt/src/owned/list.rs +++ b/simdnbt/src/owned/list.rs @@ -84,8 +84,11 @@ impl NbtList { let length = read_u32(data)?; // arbitrary number to prevent big allocations let mut compounds = Vec::with_capacity(length.min(128) as usize); + let mut capacity: usize = 8; 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 }),