Skip to content

Commit 602e55d

Browse files
committed
FEAT: Use drop_in_place for truncate and clear (and drop)
This should perform better in both release and debug mode. NOTE: This is significant because it changes the drop order of the elements, and how we handle panicking destructors. If just one of the destructors panic during ArrayVec drop, clear or truncate, the rest of the elements should still drop. If we encounter another panic during that process, however, Rust will abort as usual for panic during unwinding.
1 parent 3f9cdc5 commit 602e55d

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

src/lib.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -459,12 +459,18 @@ impl<A: Array> ArrayVec<A> {
459459
/// assert_eq!(&array[..], &[1, 2, 3]);
460460
/// ```
461461
pub fn truncate(&mut self, len: usize) {
462-
while self.len() > len { self.pop(); }
462+
unsafe {
463+
if len < self.len() {
464+
let tail: *mut [_] = &mut self[len..];
465+
self.set_len(len);
466+
ptr::drop_in_place(tail);
467+
}
468+
}
463469
}
464470

465471
/// Remove all elements in the vector.
466472
pub fn clear(&mut self) {
467-
while let Some(_) = self.pop() { }
473+
self.truncate(0)
468474
}
469475

470476
/// Retains only the elements specified by the predicate.

0 commit comments

Comments
 (0)