Skip to content

Commit

Permalink
feat: add boundary checks for indexing 'Map' with 'Vector2<i32>'
Browse files Browse the repository at this point in the history
This commit introduces boundary checks to the index and index_mut methods of the Map struct, implementing the Index and IndexMut traits for Vector2<i32>. The checks ensure that the provided position (consisting of x and y coordinates) falls within the valid range defined by the dimensions of the Map. This enhancement prevents potential out-of-bounds access errors and improves the code's robustness.
  • Loading branch information
ShenMian committed Mar 14, 2024
1 parent 99a485d commit c0e1918
Showing 1 changed file with 2 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/map.rs
Expand Up @@ -607,12 +607,14 @@ impl Index<Vector2<i32>> for Map {
type Output = Tiles;

fn index(&self, position: Vector2<i32>) -> &Tiles {
assert!(0 <= position.x && position.x < self.dimensions.x && 0 <= position.y);
&self.data[(position.y * self.dimensions.x + position.x) as usize]
}
}

impl IndexMut<Vector2<i32>> for Map {
fn index_mut(&mut self, position: Vector2<i32>) -> &mut Tiles {
assert!(0 <= position.x && position.x < self.dimensions.x && 0 <= position.y);
&mut self.data[(position.y * self.dimensions.x + position.x) as usize]
}
}
Expand Down

0 comments on commit c0e1918

Please sign in to comment.