1use std::ops::{Add, Div, Mul, Sub};
2
3#[derive(Debug, PartialEq, Eq, Hash, Default, Clone, Copy)]
4pub struct Vec2d {
5 pub x: u32,
6 pub y: u32,
7}
8
9impl Vec2d {
10 pub fn square(size: u32) -> Vec2d {
11 Vec2d { x: size, y: size }
12 }
13 pub fn max<T: Into<Vec2d>>(self, other: T) -> Vec2d {
14 let other = other.into();
15 Vec2d {
16 x: self.x.max(other.x),
17 y: self.y.max(other.y),
18 }
19 }
20 pub fn min<T: Into<Vec2d>>(self, other: T) -> Vec2d {
21 let other = other.into();
22 Vec2d {
23 x: self.x.min(other.x),
24 y: self.y.min(other.y),
25 }
26 }
27 pub fn ceil_div<T: Into<Vec2d>>(self, other: T) -> Vec2d {
28 let other = other.into();
29 let x: u32 = self.x / other.x + (self.x % other.x != 0) as u32;
30 let y: u32 = self.y / other.y + (self.y % other.y != 0) as u32;
31 Vec2d { x, y }
32 }
33
34 pub fn area(self) -> u64 {
35 u64::from(self.x) * u64::from(self.y)
36 }
37
38 pub fn fits_inside(self, other: Vec2d) -> bool {
39 self.x <= other.x && self.y <= other.y
40 }
41}
42
43impl From<u32> for Vec2d {
44 fn from(size: u32) -> Self { Vec2d::square(size) }
45}
46
47impl From<(u32, u32)> for Vec2d {
48 fn from((x, y): (u32, u32)) -> Self { Vec2d { x, y } }
49}
50
51impl std::fmt::Display for Vec2d {
52 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
53 write!(f, "x={} y={}", self.x, self.y)
54 }
55}
56
57impl Add<Vec2d> for Vec2d {
58 type Output = Vec2d;
59
60 fn add(self, rhs: Vec2d) -> Self::Output {
61 Vec2d {
62 x: self.x + rhs.x,
63 y: self.y + rhs.y,
64 }
65 }
66}
67
68impl Sub<Vec2d> for Vec2d {
69 type Output = Vec2d;
70
71 fn sub(self, rhs: Vec2d) -> Self::Output {
72 Vec2d {
73 x: self.x.saturating_sub(rhs.x),
74 y: self.y.saturating_sub(rhs.y),
75 }
76 }
77}
78
79impl Mul<Vec2d> for Vec2d {
80 type Output = Vec2d;
81
82 fn mul(self, rhs: Vec2d) -> Self::Output {
83 Vec2d {
84 x: self.x * rhs.x,
85 y: self.y * rhs.y,
86 }
87 }
88}
89
90impl Mul<u32> for Vec2d {
91 type Output = Vec2d;
92
93 fn mul(self, rhs: u32) -> Self::Output {
94 Vec2d {
95 x: self.x * rhs,
96 y: self.y * rhs,
97 }
98 }
99}
100
101impl Div<Vec2d> for Vec2d {
102 type Output = Vec2d;
103
104 fn div(self, rhs: Vec2d) -> Self::Output {
105 Vec2d {
106 x: self.x / rhs.x,
107 y: self.y / rhs.y,
108 }
109 }
110}
111
112impl Div<u32> for Vec2d {
113 type Output = Vec2d;
114
115 fn div(self, rhs: u32) -> Self::Output {
116 Vec2d {
117 x: self.x / rhs,
118 y: self.y / rhs,
119 }
120 }
121}