Skip to content

Commit b1d2814

Browse files
committed
Fix UB on out-of-bounds insert()
Fixes #343.
1 parent 3057362 commit b1d2814

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

src/lib.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1372,13 +1372,14 @@ impl<A: Array> SmallVec<A> {
13721372
}
13731373
let mut ptr = ptr.as_ptr();
13741374
let len = *len_ptr;
1375+
if index > len {
1376+
panic!("index exceeds length");
1377+
}
1378+
// SAFETY: add is UB if index > len, but we panicked first
13751379
ptr = ptr.add(index);
13761380
if index < len {
1381+
// Shift element to the right of `index`.
13771382
ptr::copy(ptr, ptr.add(1), len - index);
1378-
} else if index == len {
1379-
// No elements need shifting.
1380-
} else {
1381-
panic!("index exceeds length");
13821383
}
13831384
*len_ptr = len + 1;
13841385
ptr::write(ptr, element);

src/tests.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1049,3 +1049,10 @@ fn max_swap_remove() {
10491049
let mut sv: SmallVec<[i32; 2]> = smallvec![0];
10501050
sv.swap_remove(usize::MAX);
10511051
}
1052+
1053+
#[test]
1054+
#[should_panic]
1055+
fn test_insert_out_of_bounds() {
1056+
let mut v: SmallVec<[i32; 4]> = SmallVec::new();
1057+
v.insert(10, 6);
1058+
}

0 commit comments

Comments
 (0)