geometry: require Ord for coordinates, to implement asserts in rectangles

This commit is contained in:
Victoria Fischer 2024-11-22 15:50:49 +01:00
parent e651608ecc
commit 7b6cf42e4f

View File

@ -3,14 +3,14 @@ use std::marker::PhantomData;
pub trait CoordinateSpace {} pub trait CoordinateSpace {}
#[derive(PartialEq, Eq, Clone, Copy)] #[derive(PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
pub struct Coordinates<T: CoordLimits<Data = T>, S: CoordinateSpace> { pub struct Coordinates<T: CoordLimits<Data = T>, S: CoordinateSpace> {
pub x: T, pub x: T,
pub y: T, pub y: T,
space: PhantomData<S>, space: PhantomData<S>,
} }
impl<T: CoordLimits<Data = T> + Debug, S: CoordinateSpace> Debug for Coordinates<T, S> { impl<T: CoordLimits<Data = T> + Debug + PartialOrd, S: CoordinateSpace> Debug for Coordinates<T, S> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("@") f.debug_tuple("@")
.field(&self.x) .field(&self.x)
@ -19,8 +19,8 @@ impl<T: CoordLimits<Data = T> + Debug, S: CoordinateSpace> Debug for Coordinates
} }
} }
pub trait CoordLimits { pub trait CoordLimits: PartialOrd + PartialEq {
type Data: Sized; type Data: Sized + PartialOrd + PartialEq;
const MIN: Self::Data; const MIN: Self::Data;
const MAX: Self::Data; const MAX: Self::Data;
} }
@ -87,7 +87,7 @@ pub struct Coord8<S: CoordinateSpace> {
pub type VirtualCoordinates = Coordinates<u8, Virtual>; pub type VirtualCoordinates = Coordinates<u8, Virtual>;
pub type PhysicalCoordinates = Coordinates<usize, Physical>; pub type PhysicalCoordinates = Coordinates<usize, Physical>;
#[derive(PartialEq, Eq, Copy, Clone, Debug)] #[derive(PartialEq, Eq, Copy, Clone, Debug, PartialOrd)]
pub struct Rectangle<CoordData: CoordLimits<Data = CoordData>, Space: CoordinateSpace> { pub struct Rectangle<CoordData: CoordLimits<Data = CoordData>, Space: CoordinateSpace> {
pub top_left: Coordinates<CoordData, Space>, pub top_left: Coordinates<CoordData, Space>,
pub bottom_right: Coordinates<CoordData, Space> pub bottom_right: Coordinates<CoordData, Space>
@ -95,6 +95,8 @@ pub struct Rectangle<CoordData: CoordLimits<Data = CoordData>, Space: Coordinate
impl<CoordData: CoordLimits<Data = CoordData>, Space: CoordinateSpace> Rectangle<CoordData, Space> { impl<CoordData: CoordLimits<Data = CoordData>, Space: CoordinateSpace> Rectangle<CoordData, Space> {
pub fn new(top_left: Coordinates<CoordData, Space>, bottom_right: Coordinates<CoordData, Space>) -> Self { pub fn new(top_left: Coordinates<CoordData, Space>, bottom_right: Coordinates<CoordData, Space>) -> Self {
assert!(top_left.x <= bottom_right.x);
assert!(top_left.y <= bottom_right.y);
Self { Self {
top_left, top_left,
bottom_right bottom_right