From 839b787de2c84992336914e193aefad2cce4c52f Mon Sep 17 00:00:00 2001 From: Xiretza Date: Mon, 18 Dec 2023 18:22:02 +0000 Subject: [PATCH] common/rust: fix possible-panic clippy lint --- 2022/day15/rust/src/main.rs | 2 +- common/rust/src/vec2.rs | 24 ++++++++++++++++-------- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/2022/day15/rust/src/main.rs b/2022/day15/rust/src/main.rs index 138ddef..6a66fc5 100644 --- a/2022/day15/rust/src/main.rs +++ b/2022/day15/rust/src/main.rs @@ -11,7 +11,7 @@ struct Sensor { } impl Sensor { - fn beacon_distance(self) -> usize { + fn beacon_distance(self) -> u32 { self.closest_beacon.manhattan_dist(self.position) } } diff --git a/common/rust/src/vec2.rs b/common/rust/src/vec2.rs index cd1c520..f54c714 100644 --- a/common/rust/src/vec2.rs +++ b/common/rust/src/vec2.rs @@ -24,22 +24,30 @@ impl Vec2 { } } + #[must_use] + pub fn map2(self, other: Vec2, mut f: impl FnMut(i32, i32) -> i32) -> Self { + Self { + x: f(self.x, other.x), + y: f(self.y, other.y), + } + } + #[must_use] pub fn len(self) -> f64 { (f64::from(self.x).powi(2) + f64::from(self.y).powi(2)).sqrt() } + /// Calculates the manhattan distance between `self` and `other`. #[must_use] - pub fn manhattan_dist(self, other: Vec2) -> usize { - let Vec2 { x, y } = (other - self).map(i32::abs); - let x = usize::try_from(x).unwrap(); - let y = usize::try_from(y).unwrap(); + pub fn manhattan_dist(self, other: Vec2) -> u32 { + let x = self.x.abs_diff(other.x); + let y = self.y.abs_diff(other.y); x + y } #[must_use] - pub fn on_x_with_manhattan_dist(self, x: i32, dist: usize) -> Option<(Vec2, Vec2)> { - let dx = usize::try_from((x - self.x).abs()).ok()?; + pub fn on_x_with_manhattan_dist(self, x: i32, dist: u32) -> Option<(Vec2, Vec2)> { + let dx = x.abs_diff(self.x); let dy = dist.checked_sub(dx)?; let dy = i32::try_from(dy).ok()?; @@ -55,8 +63,8 @@ impl Vec2 { } #[must_use] - pub fn on_y_with_manhattan_dist(self, y: i32, dist: usize) -> Option<(Vec2, Vec2)> { - let dy = usize::try_from((y - self.y).abs()).ok()?; + pub fn on_y_with_manhattan_dist(self, y: i32, dist: u32) -> Option<(Vec2, Vec2)> { + let dy = y.abs_diff(self.y); let dx = dist.checked_sub(dy)?; let dx = i32::try_from(dx).ok()?;