geometry: implement distance API for points

This commit is contained in:
Victoria Fischer 2024-11-24 18:59:16 +01:00
parent 450fbbf9c9
commit 60bcf4faa3

View File

@ -26,10 +26,17 @@ pub trait CoordLimits: PartialOrd + PartialEq + Sub + Clone + Mul + Copy + One +
type Data: CoordLimits; type Data: CoordLimits;
const MIN: Self::Data; const MIN: Self::Data;
const MAX: Self::Data; const MAX: Self::Data;
fn distance(x1: Self, y1: Self, x2: Self, y2: Self) -> Self;
} }
impl CoordLimits for u8 { impl CoordLimits for u8 {
type Data = u8; type Data = u8;
fn distance(x1: Self, y1: Self, x2: Self, y2: Self) -> Self {
(max(x2, x1) - min(x2, x1)).saturating_add(max(y2, y1) - min(y2, y1))
//(pow(x2 as u16 - x1 as u16, 2) + pow(y2 as u16 - y1 as u16, 2)).sqrt() as u8
}
const MIN: u8 = 0; const MIN: u8 = 0;
const MAX: u8 = 255; const MAX: u8 = 255;
} }
@ -38,12 +45,20 @@ impl CoordLimits for u16 {
type Data = u16; type Data = u16;
const MIN: u16 = u16::MIN; const MIN: u16 = u16::MIN;
const MAX: u16 = u16::MAX; const MAX: u16 = u16::MAX;
fn distance(x1: Self, y1: Self, x2: Self, y2: Self) -> Self {
(pow(x2 - x1, 2) + pow(y2 - y1, 2)).sqrt()
}
} }
impl CoordLimits for usize { impl CoordLimits for usize {
type Data = usize; type Data = usize;
const MIN: usize = usize::MIN; const MIN: usize = usize::MIN;
const MAX: usize = usize::MAX; const MAX: usize = usize::MAX;
fn distance(x1: Self, y1: Self, x2: Self, y2: Self) -> Self {
(pow(x2 - x1, 2) + pow(y2 - y1, 2)).sqrt()
}
} }
impl<T: CoordLimits<Data = T>, S: CoordinateSpace> Coordinates<T, S> { impl<T: CoordLimits<Data = T>, S: CoordinateSpace> Coordinates<T, S> {
@ -70,6 +85,10 @@ impl<T: CoordLimits<Data = T>, S: CoordinateSpace> Coordinates<T, S> {
fn bottom_right() -> Self { fn bottom_right() -> Self {
Self::new(T::MAX, T::MAX) Self::new(T::MAX, T::MAX)
} }
pub fn distance_to(&self, other: &Self) -> T {
T::distance(self.x, other.x, self.y, other.y)
}
} }
#[derive(PartialEq, Debug, Copy, Clone)] #[derive(PartialEq, Debug, Copy, Clone)]