hs_hackathon_vision/raw/
bounding_box.rs

1use eyre::ensure;
2
3#[derive(Debug, PartialEq, Eq, Clone, Copy)]
4pub struct BoundingBox {
5    x_min: u32,
6    y_min: u32,
7    x_max: u32,
8    y_max: u32,
9}
10
11impl BoundingBox {
12    pub fn new(x_min: u32, y_min: u32, x_max: u32, y_max: u32) -> eyre::Result<Self> {
13        ensure!(x_min <= x_max, "x_min must be inferior or equal than x_max");
14        ensure!(y_min <= y_max, "y_min must be inferior or equal than y_max");
15        Ok(Self {
16            x_min,
17            y_min,
18            x_max,
19            y_max,
20        })
21    }
22
23    pub fn x_min(&self) -> u32 {
24        self.x_min
25    }
26    pub fn y_min(&self) -> u32 {
27        self.y_min
28    }
29    pub fn x_max(&self) -> u32 {
30        self.x_max
31    }
32    pub fn y_max(&self) -> u32 {
33        self.y_max
34    }
35
36    pub fn set_coordinates(
37        &mut self,
38        x_min: u32,
39        y_min: u32,
40        x_max: u32,
41        y_max: u32,
42    ) -> eyre::Result<()> {
43        ensure!(
44            x_min <= self.x_max,
45            "x_min must be inferior or equal than x_max"
46        );
47        self.x_min = x_min;
48        ensure!(
49            y_min <= self.y_max,
50            "y_min must be inferior or equal than y_max"
51        );
52        self.y_min = y_min;
53        ensure!(
54            x_max >= self.x_min,
55            "x_min must be inferior or equal than x_max"
56        );
57        self.x_max = x_max;
58        ensure!(
59            y_max >= self.y_min,
60            "y_min must be inferior or equal than y_max"
61        );
62        self.y_max = y_max;
63        Ok(())
64    }
65
66    pub fn iter(&self) -> impl Iterator<Item = (u32, u32)> + '_ {
67        (self.x_min..self.x_max).flat_map(move |x| (self.y_min..self.y_max).map(move |y| (x, y)))
68    }
69
70    pub fn is_within_size_bounds(&self, min_size: (u32, u32), max_size: (u32, u32)) -> bool {
71        !((self.x_max - self.x_min < min_size.0 || self.y_max - self.y_min < min_size.1)
72            || (self.x_max - self.x_min > max_size.0 || self.y_max - self.y_min > max_size.1))
73    }
74}