orbtk_utils/
size.rs

1use derive_more::{Add, Constructor, From, Sub};
2use std::ops::Div;
3
4/// A `Size` specified by width and height.
5///
6/// # Examples
7/// ```rust
8/// # use orbtk_utils::Size;
9/// let size = Size::new(10., 10.);
10/// let other_size = Size::new(5., 7.);
11/// let result = size - other_size;
12///
13/// assert_eq!(result.width(), 5.);
14/// assert_eq!(result.height(), 3.);
15/// ```
16#[derive(Constructor, Add, Sub, Copy, From, Clone, Default, Debug, PartialEq)]
17pub struct Size {
18    width: f64,
19    height: f64,
20}
21
22impl Size {
23    /// Gets the width of the size.
24    pub fn width(&self) -> f64 {
25        self.width
26    }
27
28    /// Sets the width of the size.
29    pub fn set_width(&mut self, width: f64) {
30        self.width = width;
31    }
32
33    /// Gets the height of the size.
34    pub fn height(&self) -> f64 {
35        self.height
36    }
37
38    /// Sets the height of the size.
39    pub fn set_height(&mut self, height: f64) {
40        self.height = height;
41    }
42}
43
44// Operations
45
46impl Div<f64> for Size {
47    type Output = Size;
48
49    fn div(mut self, rhs: f64) -> Self::Output {
50        self.width /= rhs;
51        self.height /= rhs;
52        self
53    }
54}
55
56impl Div<Size> for f64 {
57    type Output = Size;
58
59    fn div(self, mut rhs: Size) -> Self::Output {
60        rhs.width /= self;
61        rhs.height /= self;
62        rhs
63    }
64}
65
66// --- Conversions ---
67
68impl From<f64> for Size {
69    fn from(t: f64) -> Self {
70        Size::new(t, t)
71    }
72}
73
74impl From<i32> for Size {
75    fn from(t: i32) -> Self {
76        Size::new(t as f64, t as f64)
77    }
78}
79
80impl From<(i32, i32)> for Size {
81    fn from(s: (i32, i32)) -> Size {
82        Size::from((s.0 as f64, s.1 as f64))
83    }
84}
85
86// --- Conversions ---
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91
92    #[test]
93    fn test_sub() {
94        let expected_result = Size::new(-3., 5.);
95        const ERROR_MARGIN: f64 = 0.00001;
96
97        let left_side = Size::new(5., 7.);
98        let right_side = Size::new(8., 2.);
99
100        let result = left_side - right_side;
101
102        assert!((result.width() - expected_result.width()).abs() < ERROR_MARGIN);
103        assert!((result.height() - expected_result.height()).abs() < ERROR_MARGIN);
104    }
105
106    #[test]
107    fn test_add() {
108        let expected_result = Size::new(13., 9.);
109        const ERROR_MARGIN: f64 = 0.00001;
110
111        let left_side = Size::new(5., 7.);
112        let right_side = Size::new(8., 2.);
113
114        let result = left_side + right_side;
115
116        assert!((result.width() - expected_result.width()).abs() < ERROR_MARGIN);
117        assert!((result.height() - expected_result.height()).abs() < ERROR_MARGIN);
118    }
119}