From 8547ad9c2f2867da9b0e655dd4ff0fe78f04ffba Mon Sep 17 00:00:00 2001 From: Ben Bridle Date: Sun, 24 Dec 2023 20:03:12 +1300 Subject: First commit --- src/dimensions.rs | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 src/dimensions.rs (limited to 'src/dimensions.rs') diff --git a/src/dimensions.rs b/src/dimensions.rs new file mode 100644 index 0000000..feb5bab --- /dev/null +++ b/src/dimensions.rs @@ -0,0 +1,94 @@ +use crate::*; +use std::fmt; + +#[derive(Copy, Clone, PartialEq)] +pub struct Dimensions { + pub width: D, + pub height: D, +} + +pub trait HasDimensions { + fn dimensions(&self) -> Dimensions; + + fn width(&self) -> D { + self.dimensions().width + } + + fn height(&self) -> D { + self.dimensions().height + } + + fn area_usize(&self) -> usize { + self.dimensions().width.as_usize() * self.dimensions().height.as_usize() + } + + fn area_f64(&self) -> f64 { + self.dimensions().width.as_f64() * self.dimensions().height.as_f64() + } + + fn contains_point(&self, point: Point) -> bool { + point.x < self.width() && point.y < self.height() + } +} + +impl Dimensions { + pub const ZERO: Self = Self { width: D::ZERO, height: D::ZERO }; + + pub const fn new(width: D, height: D) -> Self { + Dimensions { width, height } + } + + pub fn is_zero(&self) -> bool { + self.width == D::ZERO && self.height == D::ZERO + } +} + +impl HasDimensions for Dimensions { + fn dimensions(&self) -> Dimensions { + *self + } +} + +impl From> for Dimensions { + fn from(rect: Rect) -> Self { + rect.dimensions + } +} + +impl fmt::Debug for Dimensions { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Dimensions {{ w:{:?} h:{:?} }}", self.width, self.height) + } +} + +impl std::ops::Mul for Dimensions { + type Output = Self; + fn mul(mut self, scale: D) -> Self { + self.width *= scale; + self.height *= scale; + return self; + } +} + +impl std::ops::MulAssign for Dimensions { + fn mul_assign(&mut self, scale: D) { + self.width *= scale; + self.height *= scale; + } +} + +impl std::ops::Div for Dimensions { + type Output = Self; + fn div(mut self, scale: D) -> Self { + self.width /= scale; + self.height /= scale; + return self; + } +} + +impl std::ops::DivAssign for Dimensions { + fn div_assign(&mut self, scale: D) { + self.width /= scale; + self.height /= scale; + } +} -- cgit v1.2.3-70-g09d2