dimensions/
lib.rs

1use derive_more::{Add, Div, Mul, Sub};
2use rusttype::Scale;
3
4#[derive(Add, Sub, Div, Mul, Clone, Copy, Debug)]
5#[mul(forward)]
6#[div(forward)]
7pub struct Dimensions {
8    pub x: f32,
9    pub y: f32,
10}
11
12impl Dimensions {
13    pub fn new(x: impl Into<i32>, y: impl Into<i32>) -> Self {
14        let x = x.into() as f32;
15        let y = y.into() as f32;
16        Self { x, y }
17    }
18
19    pub fn width(&self) -> f32 {
20        self.x
21    }
22
23    pub fn height(&self) -> f32 {
24        self.y
25    }
26
27    pub fn i32_width(&self) -> i32 {
28        self.x as i32
29    }
30
31    pub fn i32_height(&self) -> i32 {
32        self.y as i32
33    }
34
35    pub fn zero() -> Self {
36        Self { x: 0f32, y: 0f32 }
37    }
38}
39
40impl std::ops::Add<i32> for Dimensions {
41    type Output = Dimensions;
42    fn add(self, rhs: i32) -> Self::Output {
43        Self {
44            x: self.x + rhs as f32,
45            y: self.y + rhs as f32,
46        }
47    }
48}
49
50impl From<f32> for Dimensions {
51    fn from(value: f32) -> Self {
52        Self { x: value, y: value }
53    }
54}
55
56impl From<i32> for Dimensions {
57    fn from(value: i32) -> Self {
58        Self {
59            x: value as f32,
60            y: value as f32,
61        }
62    }
63}
64
65impl std::ops::Sub<i32> for Dimensions {
66    type Output = Dimensions;
67    fn sub(self, rhs: i32) -> Self::Output {
68        Self {
69            x: self.x - rhs as f32,
70            y: self.y - rhs as f32,
71        }
72    }
73}
74
75impl std::ops::Mul<i32> for Dimensions {
76    type Output = Dimensions;
77
78    fn mul(self, rhs: i32) -> Self::Output {
79        Self {
80            x: self.x * rhs as f32,
81            y: self.y * rhs as f32,
82        }
83    }
84}
85
86impl std::ops::Div<f32> for Dimensions {
87    type Output = Dimensions;
88
89    fn div(self, rhs: f32) -> Self::Output {
90        Self {
91            x: self.x / rhs,
92            y: self.y / rhs,
93        }
94    }
95}
96
97impl Into<Scale> for Dimensions {
98    fn into(self) -> Scale {
99        Scale {
100            x: self.x,
101            y: self.y,
102        }
103    }
104}
105
106impl From<(i32, i32)> for Dimensions {
107    fn from(value: (i32, i32)) -> Self {
108        Self {
109            x: value.0 as f32,
110            y: value.1 as f32,
111        }
112    }
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    #[test]
120    fn it_works() {
121        let result = add(2, 2);
122        assert_eq!(result, 4);
123    }
124}