Skip to main content

anathema_geometry/
size.rs

1use std::ops::{Add, AddAssign, Sub};
2
3/// Size
4#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
5pub struct Size {
6    /// Width
7    pub width: u16,
8    /// Height
9    pub height: u16,
10}
11
12impl Size {
13    /// Max size
14    pub const MAX: Self = Self::new(u16::MAX, u16::MAX);
15    /// Zero size
16    pub const ZERO: Self = Self::new(0, 0);
17
18    /// Create a new Size
19    pub const fn new(width: u16, height: u16) -> Self {
20        Self { width, height }
21    }
22
23    pub const fn area(self) -> usize {
24        (self.width * self.height) as usize
25    }
26}
27
28impl From<(u16, u16)> for Size {
29    fn from(parts: (u16, u16)) -> Self {
30        Size::new(parts.0, parts.1)
31    }
32}
33
34impl From<(usize, usize)> for Size {
35    fn from(parts: (usize, usize)) -> Self {
36        Size::new(parts.0 as u16, parts.1 as u16)
37    }
38}
39
40impl From<(i32, i32)> for Size {
41    fn from(parts: (i32, i32)) -> Self {
42        Size::new(parts.0 as u16, parts.1 as u16)
43    }
44}
45
46impl From<Size> for (i32, i32) {
47    fn from(size: Size) -> Self {
48        (size.width as i32, size.height as i32)
49    }
50}
51
52impl AddAssign for Size {
53    fn add_assign(&mut self, rhs: Self) {
54        self.width += rhs.width;
55        self.height += rhs.height;
56    }
57}
58
59impl Add for Size {
60    type Output = Self;
61
62    fn add(self, other: Self) -> Self {
63        Self {
64            width: self.width + other.width,
65            height: self.height + other.height,
66        }
67    }
68}
69
70impl Sub for Size {
71    type Output = Self;
72
73    fn sub(self, other: Self) -> Self {
74        Self {
75            width: self.width - other.width,
76            height: self.height - other.height,
77        }
78    }
79}