From 267b83d701b4d010e01089aa528e26f31c244293 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 27 Sep 2024 13:49:05 -0700 Subject: [PATCH] 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. --- src/map/core.rs | 1 + src/map/tests.rs | 15 +++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/map/core.rs b/src/map/core.rs index 16e87c7c..ef6d5727 100644 --- a/src/map/core.rs +++ b/src/map/core.rs @@ -480,6 +480,7 @@ impl IndexMapCore { 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); diff --git a/src/map/tests.rs b/src/map/tests.rs index d2707a44..ca7e9d6c 100644 --- a/src/map/tests.rs +++ b/src/map/tests.rs @@ -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 = (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);