Use reserve_exact for pushing to Subtree

This commit is contained in:
GnomedDev 2024-02-04 22:17:20 +00:00
parent 8011b56827
commit a607e1b04b
No known key found for this signature in database
GPG key ID: 9BF10F8372B254D1
2 changed files with 13 additions and 6 deletions

View file

@ -361,9 +361,7 @@ fn panic_expand(
};
// FIXME(slow): quote! have a way to expand to builder to make this a vec!
let mut mutable_trees = std::mem::take(&mut call.token_trees).into_vec();
mutable_trees.push(tt::TokenTree::Subtree(subtree));
call.token_trees = mutable_trees.into_boxed_slice();
call.push(tt::TokenTree::Subtree(subtree));
ExpandResult::ok(call)
}
@ -395,9 +393,7 @@ fn unreachable_expand(
};
// FIXME(slow): quote! have a way to expand to builder to make this a vec!
let mut mutable_trees = std::mem::take(&mut call.token_trees).into_vec();
mutable_trees.push(tt::TokenTree::Subtree(subtree));
call.token_trees = mutable_trees.into_boxed_slice();
call.push(tt::TokenTree::Subtree(subtree));
ExpandResult::ok(call)
}

View file

@ -77,6 +77,17 @@ impl<S: Span> Subtree<S> {
Subtree { delimiter: Delimiter::invisible_delim_spanned(span), token_trees: Box::new([]) }
}
/// This is slow, and should be avoided, as it will always reallocate!
pub fn push(&mut self, subtree: TokenTree<S>) {
let mut mutable_trees = std::mem::take(&mut self.token_trees).into_vec();
// Reserve exactly space for one element, to avoid `into_boxed_slice` having to reallocate again.
mutable_trees.reserve_exact(1);
mutable_trees.push(subtree);
self.token_trees = mutable_trees.into_boxed_slice();
}
pub fn visit_ids(&mut self, f: &mut impl FnMut(S) -> S) {
self.delimiter.open = f(self.delimiter.open);
self.delimiter.close = f(self.delimiter.close);