image/math/
rect.rs

1use crate::{error, GenericImageView};
2
3/// A Rectangle defined by its top left corner, width and height.
4#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
5#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
6pub struct Rect {
7    /// The x coordinate of the top left corner.
8    pub x: u32,
9    /// The y coordinate of the top left corner.
10    pub y: u32,
11    /// The rectangle's width.
12    pub width: u32,
13    /// The rectangle's height.
14    pub height: u32,
15}
16
17impl Rect {
18    /// Construct a rectangle representing an image with its top-left corner.
19    pub(crate) fn from_image_at(image: &(impl GenericImageView + ?Sized), x: u32, y: u32) -> Self {
20        Self {
21            x,
22            y,
23            width: image.width(),
24            height: image.height(),
25        }
26    }
27
28    pub(crate) fn test_in_bounds(
29        &self,
30        image: &(impl GenericImageView + ?Sized),
31    ) -> Result<(), error::ImageError> {
32        if image.width().checked_sub(self.width) >= Some(self.x)
33            && image.height().checked_sub(self.height) >= Some(self.y)
34        {
35            Ok(())
36        } else {
37            Err(error::ImageError::Parameter(
38                error::ParameterError::from_kind(error::ParameterErrorKind::DimensionMismatch),
39            ))
40        }
41    }
42}