Skip to content

Commit

Permalink
Merge pull request #353 from cuviper/move_index
Browse files Browse the repository at this point in the history
Add an explicit bounds check in `move_index`
  • Loading branch information
cuviper authored Sep 27, 2024
2 parents d74a4da + 267b83d commit 09b48ec
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 09b48ec

Please sign in to comment.