crisol_core/data/
bounds.rs1#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
5#[derive(Clone, Copy, Debug, PartialEq)]
6pub struct Bounds {
12 pub min_x: f64,
14 pub max_x: f64,
16 pub min_y: f64,
18 pub max_y: f64,
20}
21
22impl Bounds {
23 pub fn from_corners(a: [f64; 2], b: [f64; 2]) -> Self {
25 Self {
26 min_x: a[0].min(b[0]),
27 max_x: a[0].max(b[0]),
28 min_y: a[1].min(b[1]),
29 max_y: a[1].max(b[1]),
30 }
31 }
32
33 pub const NOTHING: Self = Self {
35 min_x: f64::INFINITY,
36 max_x: f64::NEG_INFINITY,
37 min_y: f64::INFINITY,
38 max_y: f64::NEG_INFINITY,
39 };
40
41 pub fn is_valid(&self) -> bool {
43 self.min_x.is_finite()
44 && self.max_x.is_finite()
45 && self.min_y.is_finite()
46 && self.max_y.is_finite()
47 && self.min_x <= self.max_x
48 && self.min_y <= self.max_y
49 }
50
51 pub fn extend(&mut self, point: [f64; 2]) {
53 if point[0].is_finite() && point[1].is_finite() {
54 self.min_x = self.min_x.min(point[0]);
55 self.max_x = self.max_x.max(point[0]);
56 self.min_y = self.min_y.min(point[1]);
57 self.max_y = self.max_y.max(point[1]);
58 }
59 }
60
61 pub fn union(&mut self, other: &Self) {
63 if other.is_valid() {
64 self.extend([other.min_x, other.min_y]);
65 self.extend([other.max_x, other.max_y]);
66 }
67 }
68
69 pub fn width(&self) -> f64 {
71 self.max_x - self.min_x
72 }
73
74 pub fn height(&self) -> f64 {
76 self.max_y - self.min_y
77 }
78
79 pub fn contains(&self, point: [f64; 2]) -> bool {
81 (self.min_x..=self.max_x).contains(&point[0]) && (self.min_y..=self.max_y).contains(&point[1])
82 }
83}
84
85#[cfg(test)]
86mod tests {
87 use super::*;
88
89 #[test]
90 fn corners_normalize_and_contain() {
91 let bounds = Bounds::from_corners([2.0, 5.0], [0.0, 1.0]);
92 assert_eq!(bounds.width(), 2.0);
93 assert_eq!(bounds.height(), 4.0);
94 assert!(bounds.contains([1.0, 1.0]));
95 assert!(!bounds.contains([3.0, 1.0]));
96 }
97
98 #[test]
99 fn nothing_grows_with_finite_points_only() {
100 let mut bounds = Bounds::NOTHING;
101 assert!(!bounds.is_valid());
102 bounds.extend([1.0, 2.0]);
103 bounds.extend([f64::NAN, 4.0]);
104 assert_eq!(bounds, Bounds::from_corners([1.0, 2.0], [1.0, 2.0]));
105 }
106}