Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add non-panicking get_pixel/mut methods to ImageBuffer #1500

Merged
merged 2 commits into from
Jul 15, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions src/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,22 @@ where
}
}

/// Gets a reference to the pixel at location `(x, y)` or returns `None` if
/// the index is out of the bounds `(width, height)`.
pub fn get_pixel_checked(&self, x: u32, y: u32) -> Option<&P> {
if x >= self.width {
return None;
}
let num_channels = <P as Pixel>::CHANNEL_COUNT as usize;
let i = (y as usize)
.saturating_mul(self.width as usize)
.saturating_add(x as usize);

self.data
.get(i..i + num_channels)
.map(|pixel_indices| <P as Pixel>::from_slice(pixel_indices))
}

/// Test that the image fits inside the buffer.
///
/// Verifies that the maximum image of pixels inside the bounds is smaller than the provided
Expand Down Expand Up @@ -877,6 +893,22 @@ where
}
}

/// Gets a reference to the mutable pixel at location `(x, y)` or returns
/// `None` if the index is out of the bounds `(width, height)`.
pub fn get_pixel_mut_checked(&mut self, x: u32, y: u32) -> Option<&mut P> {
if x >= self.width {
return None;
}
let num_channels = <P as Pixel>::CHANNEL_COUNT as usize;
let i = (y as usize)
.saturating_mul(self.width as usize)
.saturating_add(x as usize);

self.data
.get_mut(i..i + num_channels)
.map(|pixel_indices| <P as Pixel>::from_slice_mut(pixel_indices))
}

/// Puts a pixel at location `(x, y)`
///
/// # Panics
Expand Down Expand Up @@ -1363,6 +1395,19 @@ mod test {
assert_eq!(a.get_pixel(0, 1)[0], 255)
}

#[test]
fn get_pixel_checked() {
let mut a: RgbImage = ImageBuffer::new(10, 10);
{
if let Some(b) = a.get_pixel_mut_checked(0, 1) {
b[0] = 255;
}
}
assert_eq!(a.get_pixel_checked(0, 1), Some(&Rgb([255, 0, 0])));
assert_eq!(a.get_pixel_checked(100, 0), None);
assert_eq!(a.get_pixel_mut_checked(0, 100), None);
}

#[test]
fn mut_iter() {
let mut a: RgbImage = ImageBuffer::new(10, 10);
Expand Down