common/rust: fix possible-panic clippy lint

This commit is contained in:
Xiretza 2023-12-18 18:22:02 +00:00
parent ed41d840f5
commit 839b787de2
2 changed files with 17 additions and 9 deletions

View file

@ -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)
}
}

View file

@ -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()?;