#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Bounds {
pub min_x: f64,
pub max_x: f64,
pub min_y: f64,
pub max_y: f64,
}
impl Bounds {
pub fn from_corners(a: [f64; 2], b: [f64; 2]) -> Self {
Self {
min_x: a[0].min(b[0]),
max_x: a[0].max(b[0]),
min_y: a[1].min(b[1]),
max_y: a[1].max(b[1]),
}
}
pub const NOTHING: Self = Self {
min_x: f64::INFINITY,
max_x: f64::NEG_INFINITY,
min_y: f64::INFINITY,
max_y: f64::NEG_INFINITY,
};
pub fn is_valid(&self) -> bool {
self.min_x.is_finite()
&& self.max_x.is_finite()
&& self.min_y.is_finite()
&& self.max_y.is_finite()
&& self.min_x <= self.max_x
&& self.min_y <= self.max_y
}
pub fn extend(&mut self, point: [f64; 2]) {
if point[0].is_finite() && point[1].is_finite() {
self.min_x = self.min_x.min(point[0]);
self.max_x = self.max_x.max(point[0]);
self.min_y = self.min_y.min(point[1]);
self.max_y = self.max_y.max(point[1]);
}
}
pub fn union(&mut self, other: &Self) {
if other.is_valid() {
self.extend([other.min_x, other.min_y]);
self.extend([other.max_x, other.max_y]);
}
}
pub fn width(&self) -> f64 {
self.max_x - self.min_x
}
pub fn height(&self) -> f64 {
self.max_y - self.min_y
}
pub fn contains(&self, point: [f64; 2]) -> bool {
(self.min_x..=self.max_x).contains(&point[0]) && (self.min_y..=self.max_y).contains(&point[1])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn corners_normalize_and_contain() {
let bounds = Bounds::from_corners([2.0, 5.0], [0.0, 1.0]);
assert_eq!(bounds.width(), 2.0);
assert_eq!(bounds.height(), 4.0);
assert!(bounds.contains([1.0, 1.0]));
assert!(!bounds.contains([3.0, 1.0]));
}
#[test]
fn nothing_grows_with_finite_points_only() {
let mut bounds = Bounds::NOTHING;
assert!(!bounds.is_valid());
bounds.extend([1.0, 2.0]);
bounds.extend([f64::NAN, 4.0]);
assert_eq!(bounds, Bounds::from_corners([1.0, 2.0], [1.0, 2.0]));
}
}