Skip to content

Commit

Permalink
Fix UB on out-of-bounds insert()
Browse files Browse the repository at this point in the history
Fixes #343.
  • Loading branch information
mbrubeck committed Mar 20, 2024
1 parent 3057362 commit 7c83923
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1372,13 +1372,14 @@ impl<A: Array> SmallVec<A> {
}
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);
Expand Down
7 changes: 7 additions & 0 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

0 comments on commit 7c83923

Please sign in to comment.