Skip to content

Commit

Permalink
Add an explicit bounds check in move_index
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
cuviper committed Sep 27, 2024
1 parent d74a4da commit 267b83d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/map/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,7 @@ impl<K, V> IndexMapCore<K, V> {

pub(super) fn move_index(&mut self, from: usize, to: usize) {
let from_hash = self.entries[from].hash;
let _ = self.entries[to]; // explicit bounds check
if from != to {
// Use a sentinel index so other indices don't collide.
update_index(&mut self.indices, from_hash, from, usize::MAX);
Expand Down
15 changes: 15 additions & 0 deletions src/map/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -813,3 +813,18 @@ fn test_partition_point() {
assert_eq!(b.partition_point(|_, &x| x < 7), 4);
assert_eq!(b.partition_point(|_, &x| x < 8), 5);
}

macro_rules! move_index_oob {
($test:ident, $from:expr, $to:expr) => {
#[test]
#[should_panic(expected = "index out of bounds")]
fn $test() {
let mut map: IndexMap<i32, ()> = (0..10).map(|k| (k, ())).collect();
map.move_index($from, $to);
}
}
}
move_index_oob!(test_move_index_out_of_bounds_0_10, 0, 10);
move_index_oob!(test_move_index_out_of_bounds_0_max, 0, usize::MAX);
move_index_oob!(test_move_index_out_of_bounds_10_0, 10, 0);
move_index_oob!(test_move_index_out_of_bounds_max_0, usize::MAX, 0);

0 comments on commit 267b83d

Please sign in to comment.