diff --git a/showbits-common/src/vec2.rs b/showbits-common/src/vec2.rs index 8b9820f..b3e160d 100644 --- a/showbits-common/src/vec2.rs +++ b/showbits-common/src/vec2.rs @@ -20,12 +20,24 @@ impl Vec2 { Self { x, y } } + pub fn from_u32_checked(x: u32, y: u32) -> Option { + let x: i32 = x.try_into().ok()?; + let y: i32 = y.try_into().ok()?; + Some(Self::new(x, y)) + } + pub fn from_u32(x: u32, y: u32) -> Self { let x: i32 = x.try_into().expect("x too large"); let y: i32 = y.try_into().expect("y too large"); Self::new(x, y) } + pub fn to_u32_checked(self) -> Option<(u32, u32)> { + let x: u32 = self.x.try_into().ok()?; + let y: u32 = self.y.try_into().ok()?; + Some((x, y)) + } + pub fn to_u32(self) -> (u32, u32) { let x: u32 = self.x.try_into().expect("x too small"); let y: u32 = self.y.try_into().expect("y too small"); diff --git a/showbits-common/src/view.rs b/showbits-common/src/view.rs index 359eabc..4623887 100644 --- a/showbits-common/src/view.rs +++ b/showbits-common/src/view.rs @@ -40,24 +40,34 @@ impl<'a> View<'a> { } pub fn get(&self, pos: Vec2) -> Option { - let (x, y) = self.pos_to_buffer_pos(pos).to_u32(); + let (x, y) = self.pos_to_buffer_pos(pos).to_u32_checked()?; let pixel = self.buffer.get_pixel_checked(x, y)?; Some(color::from_image_color(*pixel)) } pub fn set(&mut self, pos: Vec2, color: Srgba) { - let (x, y) = self.pos_to_buffer_pos(pos).to_u32(); - if let Some(pixel) = self.buffer.get_pixel_mut_checked(x, y) { - let below = color::from_image_color(*pixel); - *pixel = color::to_image_color(color.atop(below)); - } + let Some((x, y)) = self.pos_to_buffer_pos(pos).to_u32_checked() else { + return; + }; + + let Some(pixel) = self.buffer.get_pixel_mut_checked(x, y) else { + return; + }; + + let below = color::from_image_color(*pixel); + *pixel = color::to_image_color(color.atop(below)); } pub fn replace(&mut self, pos: Vec2, color: Srgba) { - let (x, y) = self.pos_to_buffer_pos(pos).to_u32(); - if let Some(pixel) = self.buffer.get_pixel_mut_checked(x, y) { - *pixel = color::to_image_color(color); - } + let Some((x, y)) = self.pos_to_buffer_pos(pos).to_u32_checked() else { + return; + }; + + let Some(pixel) = self.buffer.get_pixel_mut_checked(x, y) else { + return; + }; + + *pixel = color::to_image_color(color); } // More complicated drawing primitives