1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
use crate::circle::Circle;
use crate::coord::Coord;
use crate::{rotate_points, Shape};
#[cfg(feature = "serde_derive")]
use serde::{Deserialize, Serialize};
use std::ops::Div;
#[cfg_attr(feature = "serde_derive", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Rect {
top_left: Coord,
bottom_right: Coord,
}
impl Rect {
pub fn new<P1: Into<Coord>, P2: Into<Coord>>(top_left: P1, bottom_right: P2) -> Self {
Self {
top_left: top_left.into(),
bottom_right: bottom_right.into(),
}
}
pub fn new_with_size<P: Into<Coord>>(start: P, width: usize, height: usize) -> Self {
let top_left = start.into();
let bottom_right = Coord {
x: top_left.x + width as isize,
y: top_left.y + height as isize,
};
Self {
top_left,
bottom_right,
}
}
}
impl Rect {
pub fn width(&self) -> usize {
(self.bottom_right.x - self.top_left.x).unsigned_abs()
}
pub fn height(&self) -> usize {
(self.bottom_right.y - self.top_left.y).unsigned_abs()
}
#[inline]
pub fn top_left(&self) -> Coord {
self.top_left
}
#[inline]
pub fn bottom_right(&self) -> Coord {
self.bottom_right
}
#[inline]
pub fn is_square(&self) -> bool {
let diff = self.bottom_right - self.top_left;
diff.x == diff.y
}
}
impl Shape for Rect {
fn from_points(points: Vec<Coord>) -> Self
where
Self: Sized,
{
Rect::new(points[0], points[1])
}
fn contains<P: Into<Coord>>(&self, point: P) -> bool {
let point = point.into();
self.top_left.x <= point.x
&& self.bottom_right.x > point.x
&& self.top_left.y <= point.y
&& self.bottom_right.y > point.y
}
fn points(&self) -> Vec<Coord> {
vec![self.top_left, self.bottom_right]
}
fn rotate_around<P: Into<Coord>>(&self, degrees: isize, point: P) -> Self
where
Self: Sized,
{
let degrees = (degrees as f32 / 90.0).round() as isize;
let points = rotate_points(point.into(), &self.points(), degrees * 90);
Self::from_points(points)
}
fn center(&self) -> Coord {
self.top_left.mid_point(self.bottom_right)
}
fn left(&self) -> isize {
self.top_left.x.min(self.bottom_right.x)
}
fn right(&self) -> isize {
self.top_left.x.max(self.bottom_right.x)
}
fn top(&self) -> isize {
self.top_left.y.min(self.bottom_right.y)
}
fn bottom(&self) -> isize {
self.top_left.y.max(self.bottom_right.y)
}
}
impl Rect {
pub fn as_smallest_circle(&self) -> Circle {
let radius = self.width().div(2).min(self.height().div(2));
Circle::new(self.center(), radius)
}
pub fn as_biggest_circle(&self) -> Circle {
let radius = self.width().div(2).max(self.height().div(2));
Circle::new(self.center(), radius)
}
}