From 508148af2160a2e11caba9c0dbb70ebfa1039a02 Mon Sep 17 00:00:00 2001 From: Armin Becher Date: Sun, 5 Apr 2020 15:03:31 +0200 Subject: [PATCH] Add get unchecked --- src/lib.rs | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 5c38ca4..63a6731 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -134,11 +134,26 @@ impl Grid { } } + /// Returns a reference to an element, without performing bound checks. + /// Generally not recommended, use with caution! + /// Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used. + pub unsafe fn get_unchecked(&self, row: usize, col: usize) -> &T { + self.data.get_unchecked(row * self.cols() + col) + } + + /// Returns a mutable reference to an element, without performing bound checks. + /// Generally not recommended, use with caution! + /// Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used. + pub unsafe fn get_unchecked_mut(&mut self, row: usize, col: usize) -> &mut T { + let cols = self.cols; + self.data.get_unchecked_mut(row * cols + col) + } + /// Access a certain element in the grid. /// Returns None if an element beyond the grid bounds is tried to be accessed. pub fn get(&self, row: usize, col: usize) -> Option<&T> { - if row < self.rows && col < self.cols() { - unsafe { Some(&self.data.get_unchecked(row * self.cols() + col)) } + if row < self.rows && col < self.cols { + unsafe { Some(self.get_unchecked(row, col)) } } else { None } @@ -147,9 +162,8 @@ impl Grid { /// Mutable access to a certain element in the grid. /// Returns None if an element beyond the grid bounds is tried to be accessed. pub fn get_mut(&mut self, row: usize, col: usize) -> Option<&mut T> { - if row < self.rows && col < self.cols() { - let cols = self.cols(); - unsafe { Some(self.data.get_unchecked_mut(row * cols + col)) } + if row < self.rows && col < self.cols { + unsafe { Some(self.get_unchecked_mut(row, col)) } } else { None }