Simplify resize with element or function

Avoids a call to Clone of the element by using the provided instance as
the one inserted last. A similar optimization is used in the standard
library. Also changes the iteration to an independent iterator as the
number of insert elements must be known in advance.
This commit is contained in:
Andreas Molzer
2020-01-18 16:23:35 +01:00
parent 381eacaa46
commit c21132b495
+10 -12
View File
@@ -414,14 +414,14 @@ impl<A: Array> ArrayVec<A> {
where
A::Item: Clone,
{
use core::cmp::Ordering;
match new_len.cmp(&self.len) {
Ordering::Less => self.truncate(new_len),
Ordering::Equal => (),
Ordering::Greater => {
while self.len < new_len {
match new_len.checked_sub(self.len) {
None => self.truncate(new_len),
Some(0) => (),
Some(new_elements) => {
for _ in 1..new_elements {
self.push(new_val.clone());
}
self.push(new_val);
}
}
}
@@ -454,12 +454,10 @@ impl<A: Array> ArrayVec<A> {
new_len: usize,
mut f: F,
) {
use core::cmp::Ordering;
match new_len.cmp(&self.len) {
Ordering::Less => self.truncate(new_len),
Ordering::Equal => (),
Ordering::Greater => {
while self.len < new_len {
match new_len.checked_sub(self.len) {
None => self.truncate(new_len),
Some(new_elements) => {
for _ in 0..new_elements {
self.push(f());
}
}