1
0
Fork 0
mirror of https://github.com/azalea-rs/simdnbt.git synced 2025-08-02 07:26:04 +00:00

remove compound approx_len

This commit is contained in:
mat 2024-10-18 06:12:20 +00:00
parent d7eb3e4ed1
commit 77a541efd4
3 changed files with 34 additions and 17 deletions

View file

@ -147,27 +147,28 @@ impl<'a: 'tape, 'tape> NbtCompound<'a, 'tape> {
/// Returns the number of tags directly in this compound.
///
/// Note that due to an internal optimization, this function runs at `O(n)`
/// if the compound has at least 2^24 items. Use [`Self::approx_len`] if you
/// want to avoid that.
/// Note that this function runs at `O(n)` due to not storing the length
/// directly.
pub fn len(&self) -> usize {
let len = self.approx_len();
if len < 2u32.pow(24) {
len as usize
} else {
self.iter().count()
}
self.iter().count()
// let len = self.approx_len();
// if len < 2u32.pow(24) {
// len as usize
// } else {
// self.iter().count()
// }
}
/// A version of [`Self::len`] that saturates at 2^24.
pub fn approx_len(self) -> u32 {
let el = self.element();
debug_assert_eq!(el.kind(), TapeTagKind::Compound);
el.approx_len_and_offset().0
}
// /// A version of [`Self::len`] that saturates at 2^24.
// pub fn approx_len(self) -> u32 {
// let el = self.element();
// debug_assert_eq!(el.kind(), TapeTagKind::Compound);
// el.approx_len_and_offset().0
// }
pub fn is_empty(&self) -> bool {
self.approx_len() == 0
self.iter().next().is_none()
}
#[allow(clippy::type_complexity)]
pub fn keys(
@ -444,6 +445,8 @@ fn handle_compound_end(tapes: &mut Tapes, stack: &mut ParsingStack) {
tapes
.main
.get_unchecked_mut(index_of_compound_element as usize)
// we don't set the approx_len because determining it for compounds
// is too expensive
.set_offset(index_after_end_element as u32 - index_of_compound_element);
};
}

View file

@ -722,4 +722,18 @@ mod tests {
let nbt = super::read(&mut Cursor::new(&data)).unwrap().unwrap();
nbt.as_compound().to_owned();
}
#[test]
fn compound_len() {
let src = include_bytes!("../../tests/complex_player.dat").to_vec();
let mut src_slice = src.as_slice();
let mut decoded_src_decoder = GzDecoder::new(&mut src_slice);
let mut decoded_src = Vec::new();
decoded_src_decoder.read_to_end(&mut decoded_src).unwrap();
let nbt = super::read(&mut Cursor::new(&decoded_src))
.unwrap()
.unwrap();
assert_eq!(nbt.as_compound().len(), nbt.as_compound().iter().count());
}
}

View file

@ -39,7 +39,7 @@ pub trait ToNbtTag: Sized {
impl<K: Display + FromStr + Eq + Hash, V: FromNbtTag> Deserialize for HashMap<K, V> {
fn from_compound(compound: crate::borrow::NbtCompound) -> Result<Self, DeserializeError> {
let mut hashmap = HashMap::with_capacity(compound.approx_len() as usize);
let mut hashmap = HashMap::new();
for (k, v) in compound.iter() {
let k_str = k.to_str();