Skip to content

Commit f2c153b

Browse files
authored
Add min and max methods to Size. (#412)
This pull request adds a `min` and `max` method to the `Size` type. # Rational I found myself getting often the minimum of two size component-wise and thought I'd be nicer to have a `min` and `max` method added to the type directly. Those two methods go in pair with the already existing `.clamp` method, which does exactly that, but with a minimum and a maximum bound.
1 parent 54b74ee commit f2c153b

File tree

1 file changed

+39
-3
lines changed

1 file changed

+39
-3
lines changed

src/size.rs

+39-3
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,44 @@ impl Size {
8181
self.is_zero_area()
8282
}
8383

84+
/// Returns the component-wise minimum of `self` and `other`.
85+
///
86+
/// # Examples
87+
///
88+
/// ```
89+
/// use kurbo::Size;
90+
///
91+
/// let this = Size::new(0., 100.);
92+
/// let other = Size::new(10., 10.);
93+
///
94+
/// assert_eq!(this.min(other), Size::new(0., 10.));
95+
/// ```
96+
pub fn min(self, other: Size) -> Self {
97+
Size {
98+
width: self.width.min(other.width),
99+
height: self.height.min(other.height),
100+
}
101+
}
102+
103+
/// Returns the component-wise maximum of `self` and `other`.
104+
///
105+
/// # Examples
106+
///
107+
/// ```
108+
/// use kurbo::Size;
109+
///
110+
/// let this = Size::new(0., 100.);
111+
/// let other = Size::new(10., 10.);
112+
///
113+
/// assert_eq!(this.max(other), Size::new(10., 100.));
114+
/// ```
115+
pub fn max(self, other: Size) -> Self {
116+
Size {
117+
width: self.width.max(other.width),
118+
height: self.height.max(other.height),
119+
}
120+
}
121+
84122
/// Returns a new size bounded by `min` and `max.`
85123
///
86124
/// # Examples
@@ -94,9 +132,7 @@ impl Size {
94132
/// assert_eq!(this.clamp(min, max), Size::new(10., 50.))
95133
/// ```
96134
pub fn clamp(self, min: Size, max: Size) -> Self {
97-
let width = self.width.max(min.width).min(max.width);
98-
let height = self.height.max(min.height).min(max.height);
99-
Size { width, height }
135+
self.max(min).min(max)
100136
}
101137

102138
/// Convert this size into a [`Vec2`], with `width` mapped to `x` and `height`

0 commit comments

Comments
 (0)