From cd4cd34c474e2f45d38ba7df1690642fa20a3b3f Mon Sep 17 00:00:00 2001 From: Andreas Molzer Date: Sat, 18 Jan 2020 19:01:40 +0100 Subject: [PATCH] Fix element drop order on failed insert --- src/arrayvec.rs | 30 +++++++++++------------------- 1 file changed, 11 insertions(+), 19 deletions(-) diff --git a/src/arrayvec.rs b/src/arrayvec.rs index 1c007d9..5a64cff 100644 --- a/src/arrayvec.rs +++ b/src/arrayvec.rs @@ -276,7 +276,8 @@ impl ArrayVec { /// index. /// /// ## Panics - /// * If `index` > `len` + /// * If `index` > `len` or + /// * If the capacity is exhausted /// /// ## Example /// ```rust @@ -289,26 +290,17 @@ impl ArrayVec { /// ``` #[inline] pub fn insert(&mut self, index: usize, item: A::Item) { - use core::cmp::Ordering; - match index.cmp(&self.len) { - Ordering::Less => { - let targets: &mut [A::Item] = &mut self.as_mut_slice()[index..]; - let mut temp = item; - for target in targets.iter_mut() { - temp = replace(target, temp); - } - self.push(temp); - } - Ordering::Equal => { - self.push(item); - } - Ordering::Greater => { - panic!( - "ArrayVec::insert> index {} is out of bounds {}", - index, self.len + if index > self.len { + panic!( + "ArrayVec::insert> index {} is out of bounds {}", + index, self.len ); - } } + + // Try to push the element. + self.push(item); + // And move it into its place. + self.as_mut_slice()[index..].rotate_right(1); } /// If the vec is empty.