Skip to content

Commit 267b83d

Browse files
committed
Add an explicit bounds check in move_index
It did already panic as expected, but with a confusing message if the `to` index was out of bounds. Now we have a direct bounds check for that at the start, just as there already was for the `from` index.
1 parent d74a4da commit 267b83d

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

src/map/core.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,7 @@ impl<K, V> IndexMapCore<K, V> {
480480

481481
pub(super) fn move_index(&mut self, from: usize, to: usize) {
482482
let from_hash = self.entries[from].hash;
483+
let _ = self.entries[to]; // explicit bounds check
483484
if from != to {
484485
// Use a sentinel index so other indices don't collide.
485486
update_index(&mut self.indices, from_hash, from, usize::MAX);

src/map/tests.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -813,3 +813,18 @@ fn test_partition_point() {
813813
assert_eq!(b.partition_point(|_, &x| x < 7), 4);
814814
assert_eq!(b.partition_point(|_, &x| x < 8), 5);
815815
}
816+
817+
macro_rules! move_index_oob {
818+
($test:ident, $from:expr, $to:expr) => {
819+
#[test]
820+
#[should_panic(expected = "index out of bounds")]
821+
fn $test() {
822+
let mut map: IndexMap<i32, ()> = (0..10).map(|k| (k, ())).collect();
823+
map.move_index($from, $to);
824+
}
825+
}
826+
}
827+
move_index_oob!(test_move_index_out_of_bounds_0_10, 0, 10);
828+
move_index_oob!(test_move_index_out_of_bounds_0_max, 0, usize::MAX);
829+
move_index_oob!(test_move_index_out_of_bounds_10_0, 10, 0);
830+
move_index_oob!(test_move_index_out_of_bounds_max_0, usize::MAX, 0);

0 commit comments

Comments
 (0)