ailloli_ui_core/geometry/
size.rs

1//! Logical width and height pairs.
2
3/// Width and height in logical pixels.
4///
5/// # Examples
6///
7/// ```
8/// use ailloli_ui_core::Size;
9/// assert_eq!(Size::new(20.0, 10.0), Size { w: 20.0, h: 10.0 });
10/// ```
11#[derive(Debug, Clone, Copy, Default, PartialEq)]
12pub struct Size {
13    /// Width in logical pixels.
14    pub w: f32,
15    /// Height in logical pixels.
16    pub h: f32,
17}
18
19impl Size {
20    /// Creates a size `(w, h)` without rejecting negative or non-finite values.
21    ///
22    /// # Examples
23    ///
24    /// ```
25    /// use ailloli_ui_core::Size;
26    /// assert_eq!(Size::new(20.0, 10.0).w, 20.0);
27    /// ```
28    pub fn new(w: f32, h: f32) -> Self {
29        Self { w, h }
30    }
31
32    /// Returns `true` when either dimension is zero or negative.
33    ///
34    /// NaN is not classified as empty because comparisons with it are false.
35    ///
36    /// # Examples
37    ///
38    /// ```
39    /// use ailloli_ui_core::Size;
40    /// assert!(Size::new(0.0, 10.0).is_empty());
41    /// ```
42    pub fn is_empty(&self) -> bool {
43        self.w <= 0.0 || self.h <= 0.0
44    }
45
46    /// Returns the component-wise floating-point minimum.
47    ///
48    /// # Examples
49    ///
50    /// ```
51    /// use ailloli_ui_core::Size;
52    /// assert_eq!(Size::new(3.0, 8.0).min(Size::new(5.0, 4.0)), Size::new(3.0, 4.0));
53    /// ```
54    pub fn min(self, other: Self) -> Self {
55        Self::new(self.w.min(other.w), self.h.min(other.h))
56    }
57
58    /// Returns the component-wise floating-point maximum.
59    ///
60    /// # Examples
61    ///
62    /// ```
63    /// use ailloli_ui_core::Size;
64    /// assert_eq!(Size::new(3.0, 8.0).max(Size::new(5.0, 4.0)), Size::new(5.0, 8.0));
65    /// ```
66    pub fn max(self, other: Self) -> Self {
67        Self::new(self.w.max(other.w), self.h.max(other.h))
68    }
69
70    /// Clamps each component between the corresponding inclusive bounds.
71    ///
72    /// # Panics
73    ///
74    /// Panics if either interval is reversed or contains a NaN bound.
75    ///
76    /// # Examples
77    ///
78    /// ```
79    /// use ailloli_ui_core::Size;
80    /// assert_eq!(Size::new(20.0, 2.0).clamp(Size::new(4.0, 4.0), Size::new(10.0, 10.0)), Size::new(10.0, 4.0));
81    /// ```
82    pub fn clamp(self, min: Self, max: Self) -> Self {
83        Self::new(self.w.clamp(min.w, max.w), self.h.clamp(min.h, max.h))
84    }
85}