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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
use std::cmp;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Rect {
left: i32,
top: i32,
width: u32,
height: u32,
}
pub trait Region<T> {
fn contains(&self, x: T, y: T) -> bool;
}
impl Rect {
pub fn at(x: i32, y: i32) -> RectPosition {
RectPosition { left: x, top: y }
}
pub fn top(&self) -> i32 {
self.top
}
pub fn left(&self) -> i32 {
self.left
}
pub fn bottom(&self) -> i32 {
self.top + (self.height as i32) - 1
}
pub fn right(&self) -> i32 {
self.left + (self.width as i32) - 1
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
pub fn intersect(&self, other: Rect) -> Option<Rect> {
let left = cmp::max(self.left, other.left);
let top = cmp::max(self.top, other.top);
let right = cmp::min(self.right(), other.right());
let bottom = cmp::min(self.bottom(), other.bottom());
if right < left || bottom < top {
return None;
}
Some(Rect {
left,
top,
width: (right - left) as u32 + 1,
height: (bottom - top) as u32 + 1,
})
}
}
impl Region<i32> for Rect {
fn contains(&self, x: i32, y: i32) -> bool {
self.left <= x && x <= self.right() && self.top <= y && y <= self.bottom()
}
}
impl Region<f32> for Rect {
fn contains(&self, x: f32, y: f32) -> bool {
self.left as f32 <= x
&& x <= self.right() as f32
&& self.top as f32 <= y
&& y <= self.bottom() as f32
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct RectPosition {
left: i32,
top: i32,
}
impl RectPosition {
pub fn of_size(self, width: u32, height: u32) -> Rect {
assert!(width > 0, "width must be strictly positive");
assert!(height > 0, "height must be strictly positive");
Rect {
left: self.left,
top: self.top,
width,
height,
}
}
}
#[cfg(test)]
mod tests {
use super::{Rect, Region};
#[test]
#[should_panic]
fn test_rejects_empty_rectangle() {
Rect::at(1, 2).of_size(0, 1);
}
#[test]
fn test_contains_i32() {
let r = Rect::at(5, 5).of_size(6, 6);
assert!(r.contains(5, 5));
assert!(r.contains(10, 10));
assert!(!r.contains(10, 11));
assert!(!r.contains(11, 10));
}
#[test]
fn test_contains_f32() {
let r = Rect::at(5, 5).of_size(6, 6);
assert!(r.contains(5f32, 5f32));
assert!(!r.contains(10.1f32, 10f32));
}
}