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.
This commit is contained in:
bluss
2018-03-25 23:21:18 +02:00
parent 3f9cdc52cd
commit 602e55dc67
+8 -2
View File
@@ -459,12 +459,18 @@ impl<A: Array> ArrayVec<A> {
/// assert_eq!(&array[..], &[1, 2, 3]);
/// ```
pub fn truncate(&mut self, len: usize) {
while self.len() > len { self.pop(); }
unsafe {
if len < self.len() {
let tail: *mut [_] = &mut self[len..];
self.set_len(len);
ptr::drop_in_place(tail);
}
}
}
/// Remove all elements in the vector.
pub fn clear(&mut self) {
while let Some(_) = self.pop() { }
self.truncate(0)
}
/// Retains only the elements specified by the predicate.