common_stdx/
lib.rs

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