1mod point;
2pub use point::Point;
3
4mod dualhash;
5pub use dualhash::DualHashMap;
6
7use std::ops::{Add, Sub};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct Rect<T> {
11 pub p1: Point<T>,
12 pub p2: Point<T>,
13}
14
15impl<T> Rect<T> {
16 pub fn new(p1: Point<T>, p2: Point<T>) -> Self {
17 Rect { p1, p2 }
18 }
19
20 pub fn from_coords(x1: T, y1: T, x2: T, y2: T) -> Self {
21 Rect {
22 p1: Point { x: x1, y: y1 },
23 p2: Point { x: x2, y: y2 },
24 }
25 }
26}
27
28impl<T> Rect<T>
29where
30 T: Copy + Ord,
31{
32 pub fn normalized(self) -> Self {
33 let min_x = self.p1.x.min(self.p2.x);
34 let max_x = self.p1.x.max(self.p2.x);
35 let min_y = self.p1.y.min(self.p2.y);
36 let max_y = self.p1.y.max(self.p2.y);
37
38 Rect {
39 p1: Point { x: min_x, y: min_y },
40 p2: Point { x: max_x, y: max_y },
41 }
42 }
43
44 pub fn contains(&self, point: Point<T>) -> bool {
45 let r = self.normalized();
46 point.x >= r.p1.x && point.x <= r.p2.x && point.y >= r.p1.y && point.y <= r.p2.y
47 }
48}
49
50impl<T> Rect<T>
51where
52 T: Copy + Ord + Sub<Output = T>,
53{
54 pub fn width(&self) -> T {
55 let r = self.normalized();
56 r.p2.x - r.p1.x
57 }
58
59 pub fn height(&self) -> T {
60 let r = self.normalized();
61 r.p2.y - r.p1.y
62 }
63}
64
65impl<T> Rect<T>
66where
67 T: Copy + Ord + Add<Output = T> + Sub<Output = T> + std::ops::Mul<Output = T>,
68{
69 pub fn area(&self) -> T {
70 self.width() * self.height()
71 }
72}
73
74impl<T> Rect<T> {
75 pub fn map<U, F>(self, mut f: F) -> Rect<U>
76 where
77 F: FnMut(T) -> U,
78 {
79 Rect {
80 p1: Point {
81 x: f(self.p1.x),
82 y: f(self.p1.y),
83 },
84 p2: Point {
85 x: f(self.p2.x),
86 y: f(self.p2.y),
87 },
88 }
89 }
90}