diff --git a/src/lib.rs b/src/lib.rs index cadb5d8..1ea3deb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1372,13 +1372,14 @@ impl SmallVec { } let mut ptr = ptr.as_ptr(); let len = *len_ptr; + if index > len { + panic!("index exceeds length"); + } + // SAFETY: add is UB if index > len, but we panicked first ptr = ptr.add(index); if index < len { + // Shift element to the right of `index`. ptr::copy(ptr, ptr.add(1), len - index); - } else if index == len { - // No elements need shifting. - } else { - panic!("index exceeds length"); } *len_ptr = len + 1; ptr::write(ptr, element); diff --git a/src/tests.rs b/src/tests.rs index 1de0a0d..f53100c 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -1049,3 +1049,10 @@ fn max_swap_remove() { let mut sv: SmallVec<[i32; 2]> = smallvec![0]; sv.swap_remove(usize::MAX); } + +#[test] +#[should_panic] +fn test_insert_out_of_bounds() { + let mut v: SmallVec<[i32; 4]> = SmallVec::new(); + v.insert(10, 6); +}