Skip to main content

euclid/
rect.rs

1// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution.
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10use super::UnknownUnit;
11use crate::box2d::Box2D;
12use crate::num::*;
13use crate::point::Point2D;
14use crate::scale::Scale;
15use crate::side_offsets::SideOffsets2D;
16use crate::size::Size2D;
17use crate::vector::Vector2D;
18
19#[cfg(feature = "bytemuck")]
20use bytemuck::{Pod, Zeroable};
21#[cfg(feature = "malloc_size_of")]
22use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
23#[cfg(any(feature = "std", feature = "libm"))]
24use num_traits::Float;
25use num_traits::NumCast;
26#[cfg(feature = "serde")]
27use serde::{Deserialize, Serialize};
28
29use core::borrow::Borrow;
30use core::cmp::PartialOrd;
31use core::fmt;
32use core::hash::{Hash, Hasher};
33use core::ops::{Add, Div, DivAssign, Mul, MulAssign, Range, Sub};
34
35/// A 2d Rectangle optionally tagged with a unit.
36///
37/// # Representation
38///
39/// `Rect` is represented by an origin point and a size.
40///
41/// See [`Box2D`] for a rectangle represented by two endpoints.
42///
43/// # Empty rectangle
44///
45/// A rectangle is considered empty (see [`is_empty`]) if any of the following is true:
46/// - it's area is empty,
47/// - it's area is negative (`size.x < 0` or `size.y < 0`),
48/// - it contains NaNs.
49///
50/// [`is_empty`]: Self::is_empty
51#[repr(C)]
52#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
53#[cfg_attr(
54    feature = "serde",
55    serde(bound(serialize = "T: Serialize", deserialize = "T: Deserialize<'de>"))
56)]
57pub struct Rect<T, U> {
58    pub origin: Point2D<T, U>,
59    pub size: Size2D<T, U>,
60}
61
62#[cfg(feature = "arbitrary")]
63impl<'a, T, U> arbitrary::Arbitrary<'a> for Rect<T, U>
64where
65    T: arbitrary::Arbitrary<'a>,
66{
67    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
68        let (origin, size) = arbitrary::Arbitrary::arbitrary(u)?;
69        Ok(Rect { origin, size })
70    }
71}
72
73#[cfg(feature = "bytemuck")]
74unsafe impl<T: Zeroable, U> Zeroable for Rect<T, U> {}
75
76#[cfg(feature = "bytemuck")]
77unsafe impl<T: Pod, U: 'static> Pod for Rect<T, U> {}
78
79impl<T: Hash, U> Hash for Rect<T, U> {
80    fn hash<H: Hasher>(&self, h: &mut H) {
81        self.origin.hash(h);
82        self.size.hash(h);
83    }
84}
85
86#[cfg(feature = "malloc_size_of")]
87impl<T: MallocSizeOf, U> MallocSizeOf for Rect<T, U> {
88    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
89        self.origin.size_of(ops) + self.size.size_of(ops)
90    }
91}
92
93impl<T: Copy, U> Copy for Rect<T, U> {}
94
95impl<T: Clone, U> Clone for Rect<T, U> {
96    fn clone(&self) -> Self {
97        Self::new(self.origin.clone(), self.size.clone())
98    }
99}
100
101impl<T: PartialEq, U> PartialEq for Rect<T, U> {
102    fn eq(&self, other: &Self) -> bool {
103        self.origin.eq(&other.origin) && self.size.eq(&other.size)
104    }
105}
106
107impl<T: Eq, U> Eq for Rect<T, U> {}
108
109impl<T: fmt::Debug, U> fmt::Debug for Rect<T, U> {
110    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
111        write!(f, "Rect(")?;
112        fmt::Debug::fmt(&self.size, f)?;
113        write!(f, " at ")?;
114        fmt::Debug::fmt(&self.origin, f)?;
115        write!(f, ")")
116    }
117}
118
119impl<T: Default, U> Default for Rect<T, U> {
120    fn default() -> Self {
121        Rect::new(Default::default(), Default::default())
122    }
123}
124
125impl<T, U> Rect<T, U> {
126    /// Constructor.
127    #[inline]
128    pub const fn new(origin: Point2D<T, U>, size: Size2D<T, U>) -> Self {
129        Rect { origin, size }
130    }
131}
132
133impl<T, U> Rect<T, U>
134where
135    T: Zero,
136{
137    /// Constructor, setting all sides to zero.
138    #[inline]
139    pub fn zero() -> Self {
140        Rect::new(Point2D::origin(), Size2D::zero())
141    }
142
143    /// Creates a rect of the given size, at offset zero.
144    #[inline]
145    pub fn from_size(size: Size2D<T, U>) -> Self {
146        Rect {
147            origin: Point2D::zero(),
148            size,
149        }
150    }
151}
152
153impl<T, U> Rect<T, U>
154where
155    T: Copy + Add<T, Output = T>,
156{
157    #[inline]
158    pub fn min(&self) -> Point2D<T, U> {
159        self.origin
160    }
161
162    #[inline]
163    pub fn max(&self) -> Point2D<T, U> {
164        self.origin + self.size
165    }
166
167    #[inline]
168    pub fn max_x(&self) -> T {
169        self.origin.x + self.size.width
170    }
171
172    #[inline]
173    pub fn min_x(&self) -> T {
174        self.origin.x
175    }
176
177    #[inline]
178    pub fn max_y(&self) -> T {
179        self.origin.y + self.size.height
180    }
181
182    #[inline]
183    pub fn min_y(&self) -> T {
184        self.origin.y
185    }
186
187    #[inline]
188    pub fn width(&self) -> T {
189        self.size.width
190    }
191
192    #[inline]
193    pub fn height(&self) -> T {
194        self.size.height
195    }
196
197    #[inline]
198    pub fn x_range(&self) -> Range<T> {
199        self.min_x()..self.max_x()
200    }
201
202    #[inline]
203    pub fn y_range(&self) -> Range<T> {
204        self.min_y()..self.max_y()
205    }
206
207    /// Returns the same rectangle, translated by a vector.
208    #[inline]
209    #[must_use]
210    pub fn translate(&self, by: Vector2D<T, U>) -> Self {
211        Self::new(self.origin + by, self.size)
212    }
213
214    #[inline]
215    pub fn to_box2d(&self) -> Box2D<T, U> {
216        Box2D {
217            min: self.min(),
218            max: self.max(),
219        }
220    }
221}
222
223impl<T, U> Rect<T, U>
224where
225    T: Copy + PartialOrd + Add<T, Output = T>,
226{
227    /// Returns `true` if this rectangle contains the point. Points are considered
228    /// in the rectangle if they are on the left or top edge, but outside if they
229    /// are on the right or bottom edge.
230    #[inline]
231    pub fn contains(&self, p: Point2D<T, U>) -> bool {
232        self.to_box2d().contains(p)
233    }
234
235    #[inline]
236    pub fn intersects(&self, other: &Self) -> bool {
237        self.to_box2d().intersects(&other.to_box2d())
238    }
239}
240
241impl<T, U> Rect<T, U>
242where
243    T: Copy + PartialOrd + Add<T, Output = T> + Sub<T, Output = T>,
244{
245    #[inline]
246    pub fn intersection(&self, other: &Self) -> Option<Self> {
247        let box2d = self.to_box2d().intersection_unchecked(&other.to_box2d());
248
249        if box2d.is_empty() {
250            return None;
251        }
252
253        Some(box2d.to_rect())
254    }
255}
256
257impl<T, U> Rect<T, U>
258where
259    T: Copy + Add<T, Output = T> + Sub<T, Output = T>,
260{
261    #[inline]
262    #[must_use]
263    pub fn inflate(&self, width: T, height: T) -> Self {
264        Rect::new(
265            Point2D::new(self.origin.x - width, self.origin.y - height),
266            Size2D::new(
267                self.size.width + width + width,
268                self.size.height + height + height,
269            ),
270        )
271    }
272}
273
274impl<T, U> Rect<T, U>
275where
276    T: Copy + Zero + PartialOrd + Add<T, Output = T>,
277{
278    /// Returns `true` if this rectangle contains the interior of `rect`. Always
279    /// returns `true` if `rect` is empty, and always returns `false` if `rect` is
280    /// nonempty but this rectangle is empty.
281    #[inline]
282    pub fn contains_rect(&self, rect: &Self) -> bool {
283        rect.is_empty()
284            || (self.min_x() <= rect.min_x()
285                && rect.max_x() <= self.max_x()
286                && self.min_y() <= rect.min_y()
287                && rect.max_y() <= self.max_y())
288    }
289}
290
291impl<T, U> Rect<T, U>
292where
293    T: Copy + Zero + PartialOrd + Add<T, Output = T> + Sub<T, Output = T>,
294{
295    /// Calculate the size and position of an inner rectangle.
296    ///
297    /// Subtracts the side offsets from all sides. The horizontal and vertical
298    /// offsets must not be larger than the original side length.
299    /// This method assumes y oriented downward.
300    pub fn inner_rect(&self, offsets: SideOffsets2D<T, U>) -> Self {
301        let rect = Rect::new(
302            Point2D::new(self.origin.x + offsets.left, self.origin.y + offsets.top),
303            Size2D::new(
304                self.size.width - offsets.horizontal(),
305                self.size.height - offsets.vertical(),
306            ),
307        );
308        debug_assert!(rect.size.width >= Zero::zero());
309        debug_assert!(rect.size.height >= Zero::zero());
310        rect
311    }
312}
313
314impl<T, U> Rect<T, U>
315where
316    T: Copy + Add<T, Output = T> + Sub<T, Output = T>,
317{
318    /// Calculate the size and position of an outer rectangle.
319    ///
320    /// Add the offsets to all sides. The expanded rectangle is returned.
321    /// This method assumes y oriented downward.
322    pub fn outer_rect(&self, offsets: SideOffsets2D<T, U>) -> Self {
323        Rect::new(
324            Point2D::new(self.origin.x - offsets.left, self.origin.y - offsets.top),
325            Size2D::new(
326                self.size.width + offsets.horizontal(),
327                self.size.height + offsets.vertical(),
328            ),
329        )
330    }
331}
332
333impl<T, U> Rect<T, U>
334where
335    T: Copy + Zero + PartialOrd + Sub<T, Output = T>,
336{
337    /// Returns the smallest rectangle defined by the top/bottom/left/right-most
338    /// points provided as parameter.
339    ///
340    /// Note: This function has a behavior that can be surprising because
341    /// the right-most and bottom-most points are exactly on the edge
342    /// of the rectangle while the [`Rect::contains`] function is has exclusive
343    /// semantic on these edges. This means that the right-most and bottom-most
344    /// points provided to [`Rect::from_points`] will count as not contained by the rect.
345    /// This behavior may change in the future.
346    ///
347    /// See [`Box2D::from_points`] for more details.
348    pub fn from_points<I>(points: I) -> Self
349    where
350        I: IntoIterator,
351        I::Item: Borrow<Point2D<T, U>>,
352    {
353        Box2D::from_points(points).to_rect()
354    }
355}
356
357impl<T, U> Rect<T, U>
358where
359    T: Copy + One + Add<Output = T> + Sub<Output = T> + Mul<Output = T>,
360{
361    /// Linearly interpolate between this rectangle and another rectangle.
362    #[inline]
363    pub fn lerp(&self, other: Self, t: T) -> Self {
364        Self::new(
365            self.origin.lerp(other.origin, t),
366            self.size.lerp(other.size, t),
367        )
368    }
369}
370
371impl<T, U> Rect<T, U>
372where
373    T: Copy + One + Add<Output = T> + Div<Output = T>,
374{
375    pub fn center(&self) -> Point2D<T, U> {
376        let two = T::one() + T::one();
377        self.origin + self.size.to_vector() / two
378    }
379}
380
381impl<T, U> Rect<T, U>
382where
383    T: Copy + PartialOrd + Add<T, Output = T> + Sub<T, Output = T> + Zero,
384{
385    #[inline]
386    pub fn union(&self, other: &Self) -> Self {
387        self.to_box2d().union(&other.to_box2d()).to_rect()
388    }
389}
390
391impl<T, U> Rect<T, U> {
392    #[inline]
393    pub fn scale<S: Copy>(&self, x: S, y: S) -> Self
394    where
395        T: Copy + Mul<S, Output = T>,
396    {
397        Rect::new(
398            Point2D::new(self.origin.x * x, self.origin.y * y),
399            Size2D::new(self.size.width * x, self.size.height * y),
400        )
401    }
402}
403
404impl<T: Copy + Mul<T, Output = T>, U> Rect<T, U> {
405    #[inline]
406    pub fn area(&self) -> T {
407        self.size.area()
408    }
409}
410
411impl<T: Copy + Zero + PartialOrd, U> Rect<T, U> {
412    #[inline]
413    pub fn is_empty(&self) -> bool {
414        self.size.is_empty()
415    }
416}
417
418impl<T: Copy + Zero + PartialOrd, U> Rect<T, U> {
419    #[inline]
420    pub fn to_non_empty(&self) -> Option<Self> {
421        if self.is_empty() {
422            return None;
423        }
424
425        Some(*self)
426    }
427}
428
429impl<T: Copy + Mul, U> Mul<T> for Rect<T, U> {
430    type Output = Rect<T::Output, U>;
431
432    #[inline]
433    fn mul(self, scale: T) -> Self::Output {
434        Rect::new(self.origin * scale, self.size * scale)
435    }
436}
437
438impl<T: Copy + MulAssign, U> MulAssign<T> for Rect<T, U> {
439    #[inline]
440    fn mul_assign(&mut self, scale: T) {
441        *self *= Scale::new(scale);
442    }
443}
444
445impl<T: Copy + Div, U> Div<T> for Rect<T, U> {
446    type Output = Rect<T::Output, U>;
447
448    #[inline]
449    fn div(self, scale: T) -> Self::Output {
450        Rect::new(self.origin / scale.clone(), self.size / scale)
451    }
452}
453
454impl<T: Copy + DivAssign, U> DivAssign<T> for Rect<T, U> {
455    #[inline]
456    fn div_assign(&mut self, scale: T) {
457        *self /= Scale::new(scale);
458    }
459}
460
461impl<T: Copy + Mul, U1, U2> Mul<Scale<T, U1, U2>> for Rect<T, U1> {
462    type Output = Rect<T::Output, U2>;
463
464    #[inline]
465    fn mul(self, scale: Scale<T, U1, U2>) -> Self::Output {
466        Rect::new(self.origin * scale.clone(), self.size * scale)
467    }
468}
469
470impl<T: Copy + MulAssign, U> MulAssign<Scale<T, U, U>> for Rect<T, U> {
471    #[inline]
472    fn mul_assign(&mut self, scale: Scale<T, U, U>) {
473        self.origin *= scale.clone();
474        self.size *= scale;
475    }
476}
477
478impl<T: Copy + Div, U1, U2> Div<Scale<T, U1, U2>> for Rect<T, U2> {
479    type Output = Rect<T::Output, U1>;
480
481    #[inline]
482    fn div(self, scale: Scale<T, U1, U2>) -> Self::Output {
483        Rect::new(self.origin / scale.clone(), self.size / scale)
484    }
485}
486
487impl<T: Copy + DivAssign, U> DivAssign<Scale<T, U, U>> for Rect<T, U> {
488    #[inline]
489    fn div_assign(&mut self, scale: Scale<T, U, U>) {
490        self.origin /= scale.clone();
491        self.size /= scale;
492    }
493}
494
495impl<T: Copy, U> Rect<T, U> {
496    /// Drop the units, preserving only the numeric value.
497    #[inline]
498    pub fn to_untyped(&self) -> Rect<T, UnknownUnit> {
499        Rect::new(self.origin.to_untyped(), self.size.to_untyped())
500    }
501
502    /// Tag a unitless value with units.
503    #[inline]
504    pub fn from_untyped(r: &Rect<T, UnknownUnit>) -> Rect<T, U> {
505        Rect::new(
506            Point2D::from_untyped(r.origin),
507            Size2D::from_untyped(r.size),
508        )
509    }
510
511    /// Cast the unit
512    #[inline]
513    pub fn cast_unit<V>(&self) -> Rect<T, V> {
514        Rect::new(self.origin.cast_unit(), self.size.cast_unit())
515    }
516}
517
518impl<T: NumCast + Copy, U> Rect<T, U> {
519    /// Cast from one numeric representation to another, preserving the units.
520    ///
521    /// When casting from floating point to integer coordinates, the decimals are truncated
522    /// as one would expect from a simple cast, but this behavior does not always make sense
523    /// geometrically. Consider using [`round`], [`round_in`] or [`round_out`] before casting.
524    ///
525    /// [`round`]: Self::round
526    /// [`round_in`]: Self::round_in
527    /// [`round_out`]: Self::round_out
528    #[inline]
529    pub fn cast<NewT: NumCast>(&self) -> Rect<NewT, U> {
530        Rect::new(self.origin.cast(), self.size.cast())
531    }
532
533    /// Fallible cast from one numeric representation to another, preserving the units.
534    ///
535    /// When casting from floating point to integer coordinates, the decimals are truncated
536    /// as one would expect from a simple cast, but this behavior does not always make sense
537    /// geometrically. Consider using [`round`], [`round_in`] or [`round_out` before casting.
538    ///
539    /// [`round`]: Self::round
540    /// [`round_in`]: Self::round_in
541    /// [`round_out`]: Self::round_out
542    pub fn try_cast<NewT: NumCast>(&self) -> Option<Rect<NewT, U>> {
543        match (self.origin.try_cast(), self.size.try_cast()) {
544            (Some(origin), Some(size)) => Some(Rect::new(origin, size)),
545            _ => None,
546        }
547    }
548
549    // Convenience functions for common casts
550
551    /// Cast into an `f32` rectangle.
552    #[inline]
553    pub fn to_f32(&self) -> Rect<f32, U> {
554        self.cast()
555    }
556
557    /// Cast into an `f64` rectangle.
558    #[inline]
559    pub fn to_f64(&self) -> Rect<f64, U> {
560        self.cast()
561    }
562
563    /// Cast into an `usize` rectangle, truncating decimals if any.
564    ///
565    /// When casting from floating point rectangles, it is worth considering whether
566    /// to `round()`, `round_in()` or `round_out()` before the cast in order to
567    /// obtain the desired conversion behavior.
568    #[inline]
569    pub fn to_usize(&self) -> Rect<usize, U> {
570        self.cast()
571    }
572
573    /// Cast into an `u32` rectangle, truncating decimals if any.
574    ///
575    /// When casting from floating point rectangles, it is worth considering whether
576    /// to `round()`, `round_in()` or `round_out()` before the cast in order to
577    /// obtain the desired conversion behavior.
578    #[inline]
579    pub fn to_u32(&self) -> Rect<u32, U> {
580        self.cast()
581    }
582
583    /// Cast into an `u64` rectangle, truncating decimals if any.
584    ///
585    /// When casting from floating point rectangles, it is worth considering whether
586    /// to `round()`, `round_in()` or `round_out()` before the cast in order to
587    /// obtain the desired conversion behavior.
588    #[inline]
589    pub fn to_u64(&self) -> Rect<u64, U> {
590        self.cast()
591    }
592
593    /// Cast into an `i32` rectangle, truncating decimals if any.
594    ///
595    /// When casting from floating point rectangles, it is worth considering whether
596    /// to `round()`, `round_in()` or `round_out()` before the cast in order to
597    /// obtain the desired conversion behavior.
598    #[inline]
599    pub fn to_i32(&self) -> Rect<i32, U> {
600        self.cast()
601    }
602
603    /// Cast into an `i64` rectangle, truncating decimals if any.
604    ///
605    /// When casting from floating point rectangles, it is worth considering whether
606    /// to `round()`, `round_in()` or `round_out()` before the cast in order to
607    /// obtain the desired conversion behavior.
608    #[inline]
609    pub fn to_i64(&self) -> Rect<i64, U> {
610        self.cast()
611    }
612}
613
614#[cfg(any(feature = "std", feature = "libm"))]
615impl<T: Float, U> Rect<T, U> {
616    /// Returns `true` if all members are finite.
617    #[inline]
618    pub fn is_finite(self) -> bool {
619        self.origin.is_finite() && self.size.is_finite()
620    }
621}
622
623impl<T: Floor + Ceil + Round + Add<T, Output = T> + Sub<T, Output = T>, U> Rect<T, U> {
624    /// Return a rectangle with edges rounded to integer coordinates, such that
625    /// the returned rectangle has the same set of pixel centers as the original
626    /// one.
627    /// Edges at offset 0.5 round up.
628    /// Suitable for most places where integral device coordinates
629    /// are needed, but note that any translation should be applied first to
630    /// avoid pixel rounding errors.
631    /// Note that this is *not* rounding to nearest integer if the values are negative.
632    /// They are always rounding as floor(n + 0.5).
633    ///
634    /// # Usage notes
635    /// Note, that when using with floating-point `T` types that method can significantly
636    /// lose precision for large values, so if you need to call this method very often it
637    /// is better to use [`Box2D`].
638    #[must_use]
639    pub fn round(&self) -> Self {
640        self.to_box2d().round().to_rect()
641    }
642
643    /// Return a rectangle with edges rounded to integer coordinates, such that
644    /// the original rectangle contains the resulting rectangle.
645    ///
646    /// # Usage notes
647    /// Note, that when using with floating-point `T` types that method can significantly
648    /// lose precision for large values, so if you need to call this method very often it
649    /// is better to use [`Box2D`].
650    #[must_use]
651    pub fn round_in(&self) -> Self {
652        self.to_box2d().round_in().to_rect()
653    }
654
655    /// Return a rectangle with edges rounded to integer coordinates, such that
656    /// the original rectangle is contained in the resulting rectangle.
657    ///
658    /// # Usage notes
659    /// Note, that when using with floating-point `T` types that method can significantly
660    /// lose precision for large values, so if you need to call this method very often it
661    /// is better to use [`Box2D`].
662    #[must_use]
663    pub fn round_out(&self) -> Self {
664        self.to_box2d().round_out().to_rect()
665    }
666}
667
668impl<T, U> From<Size2D<T, U>> for Rect<T, U>
669where
670    T: Zero,
671{
672    fn from(size: Size2D<T, U>) -> Self {
673        Self::from_size(size)
674    }
675}
676
677impl<T, U> From<Box2D<T, U>> for Rect<T, U>
678where
679    T: Copy + Sub<T, Output = T>,
680{
681    fn from(b: Box2D<T, U>) -> Self {
682        b.to_rect()
683    }
684}
685
686/// Shorthand for `Rect::new(Point2D::new(x, y), Size2D::new(w, h))`.
687pub const fn rect<T, U>(x: T, y: T, w: T, h: T) -> Rect<T, U> {
688    Rect::new(Point2D::new(x, y), Size2D::new(w, h))
689}
690
691#[cfg(test)]
692#[cfg(any(feature = "std", feature = "libm"))]
693mod tests {
694    use crate::default::{Point2D, Rect, Size2D};
695    use crate::side_offsets::SideOffsets2D;
696    use crate::{point2, rect, size2, vec2};
697
698    #[test]
699    fn test_translate() {
700        let p = Rect::new(Point2D::new(0u32, 0u32), Size2D::new(50u32, 40u32));
701        let pp = p.translate(vec2(10, 15));
702
703        assert!(pp.size.width == 50);
704        assert!(pp.size.height == 40);
705        assert!(pp.origin.x == 10);
706        assert!(pp.origin.y == 15);
707
708        let r = Rect::new(Point2D::new(-10, -5), Size2D::new(50, 40));
709        let rr = r.translate(vec2(0, -10));
710
711        assert!(rr.size.width == 50);
712        assert!(rr.size.height == 40);
713        assert!(rr.origin.x == -10);
714        assert!(rr.origin.y == -15);
715    }
716
717    #[test]
718    fn test_union() {
719        let p = Rect::new(Point2D::new(0, 0), Size2D::new(50, 40));
720        let q = Rect::new(Point2D::new(20, 20), Size2D::new(5, 5));
721        let r = Rect::new(Point2D::new(-15, -30), Size2D::new(200, 15));
722        let s = Rect::new(Point2D::new(20, -15), Size2D::new(250, 200));
723
724        let pq = p.union(&q);
725        assert!(pq.origin == Point2D::new(0, 0));
726        assert!(pq.size == Size2D::new(50, 40));
727
728        let pr = p.union(&r);
729        assert!(pr.origin == Point2D::new(-15, -30));
730        assert!(pr.size == Size2D::new(200, 70));
731
732        let ps = p.union(&s);
733        assert!(ps.origin == Point2D::new(0, -15));
734        assert!(ps.size == Size2D::new(270, 200));
735    }
736
737    #[test]
738    fn test_intersection() {
739        let p = Rect::new(Point2D::new(0, 0), Size2D::new(10, 20));
740        let q = Rect::new(Point2D::new(5, 15), Size2D::new(10, 10));
741        let r = Rect::new(Point2D::new(-5, -5), Size2D::new(8, 8));
742
743        let pq = p.intersection(&q);
744        assert!(pq.is_some());
745        let pq = pq.unwrap();
746        assert!(pq.origin == Point2D::new(5, 15));
747        assert!(pq.size == Size2D::new(5, 5));
748
749        let pr = p.intersection(&r);
750        assert!(pr.is_some());
751        let pr = pr.unwrap();
752        assert!(pr.origin == Point2D::new(0, 0));
753        assert!(pr.size == Size2D::new(3, 3));
754
755        let qr = q.intersection(&r);
756        assert!(qr.is_none());
757    }
758
759    #[test]
760    fn test_intersection_overflow() {
761        // test some scenarios where the intersection can overflow but
762        // the min_x() and max_x() don't. Gecko currently fails these cases
763        let p = Rect::new(Point2D::new(-2147483648, -2147483648), Size2D::new(0, 0));
764        let q = Rect::new(
765            Point2D::new(2136893440, 2136893440),
766            Size2D::new(279552, 279552),
767        );
768        let r = Rect::new(Point2D::new(-2147483648, -2147483648), Size2D::new(1, 1));
769
770        assert!(p.is_empty());
771        let pq = p.intersection(&q);
772        assert!(pq.is_none());
773
774        let qr = q.intersection(&r);
775        assert!(qr.is_none());
776    }
777
778    #[test]
779    fn test_contains() {
780        let r = Rect::new(Point2D::new(-20, 15), Size2D::new(100, 200));
781
782        assert!(r.contains(Point2D::new(0, 50)));
783        assert!(r.contains(Point2D::new(-10, 200)));
784
785        // The `contains` method is inclusive of the top/left edges, but not the
786        // bottom/right edges.
787        assert!(r.contains(Point2D::new(-20, 15)));
788        assert!(!r.contains(Point2D::new(80, 15)));
789        assert!(!r.contains(Point2D::new(80, 215)));
790        assert!(!r.contains(Point2D::new(-20, 215)));
791
792        // Points beyond the top-left corner.
793        assert!(!r.contains(Point2D::new(-25, 15)));
794        assert!(!r.contains(Point2D::new(-15, 10)));
795
796        // Points beyond the top-right corner.
797        assert!(!r.contains(Point2D::new(85, 20)));
798        assert!(!r.contains(Point2D::new(75, 10)));
799
800        // Points beyond the bottom-right corner.
801        assert!(!r.contains(Point2D::new(85, 210)));
802        assert!(!r.contains(Point2D::new(75, 220)));
803
804        // Points beyond the bottom-left corner.
805        assert!(!r.contains(Point2D::new(-25, 210)));
806        assert!(!r.contains(Point2D::new(-15, 220)));
807
808        let r = Rect::new(Point2D::new(-20.0, 15.0), Size2D::new(100.0, 200.0));
809        assert!(r.contains_rect(&r));
810        assert!(!r.contains_rect(&r.translate(vec2(0.1, 0.0))));
811        assert!(!r.contains_rect(&r.translate(vec2(-0.1, 0.0))));
812        assert!(!r.contains_rect(&r.translate(vec2(0.0, 0.1))));
813        assert!(!r.contains_rect(&r.translate(vec2(0.0, -0.1))));
814        // Empty rectangles are always considered as contained in other rectangles,
815        // even if their origin is not.
816        let p = Point2D::new(1.0, 1.0);
817        assert!(!r.contains(p));
818        assert!(r.contains_rect(&Rect::new(p, Size2D::zero())));
819    }
820
821    #[test]
822    fn test_scale() {
823        let p = Rect::new(Point2D::new(0u32, 0u32), Size2D::new(50u32, 40u32));
824        let pp = p.scale(10, 15);
825
826        assert!(pp.size.width == 500);
827        assert!(pp.size.height == 600);
828        assert!(pp.origin.x == 0);
829        assert!(pp.origin.y == 0);
830
831        let r = Rect::new(Point2D::new(-10, -5), Size2D::new(50, 40));
832        let rr = r.scale(1, 20);
833
834        assert!(rr.size.width == 50);
835        assert!(rr.size.height == 800);
836        assert!(rr.origin.x == -10);
837        assert!(rr.origin.y == -100);
838    }
839
840    #[test]
841    fn test_inflate() {
842        let p = Rect::new(Point2D::new(0, 0), Size2D::new(10, 10));
843        let pp = p.inflate(10, 20);
844
845        assert!(pp.size.width == 30);
846        assert!(pp.size.height == 50);
847        assert!(pp.origin.x == -10);
848        assert!(pp.origin.y == -20);
849
850        let r = Rect::new(Point2D::new(0, 0), Size2D::new(10, 20));
851        let rr = r.inflate(-2, -5);
852
853        assert!(rr.size.width == 6);
854        assert!(rr.size.height == 10);
855        assert!(rr.origin.x == 2);
856        assert!(rr.origin.y == 5);
857    }
858
859    #[test]
860    fn test_inner_outer_rect() {
861        let inner_rect = Rect::new(point2(20, 40), size2(80, 100));
862        let offsets = SideOffsets2D::new(20, 10, 10, 10);
863        let outer_rect = inner_rect.outer_rect(offsets);
864        assert_eq!(outer_rect.origin.x, 10);
865        assert_eq!(outer_rect.origin.y, 20);
866        assert_eq!(outer_rect.size.width, 100);
867        assert_eq!(outer_rect.size.height, 130);
868        assert_eq!(outer_rect.inner_rect(offsets), inner_rect);
869    }
870
871    #[test]
872    fn test_min_max_x_y() {
873        let p = Rect::new(Point2D::new(0u32, 0u32), Size2D::new(50u32, 40u32));
874        assert!(p.max_y() == 40);
875        assert!(p.min_y() == 0);
876        assert!(p.max_x() == 50);
877        assert!(p.min_x() == 0);
878
879        let r = Rect::new(Point2D::new(-10, -5), Size2D::new(50, 40));
880        assert!(r.max_y() == 35);
881        assert!(r.min_y() == -5);
882        assert!(r.max_x() == 40);
883        assert!(r.min_x() == -10);
884    }
885
886    #[test]
887    fn test_width_height() {
888        let r = Rect::new(Point2D::new(-10, -5), Size2D::new(50, 40));
889        assert!(r.width() == 50);
890        assert!(r.height() == 40);
891    }
892
893    #[test]
894    fn test_is_empty() {
895        assert!(Rect::new(Point2D::new(0u32, 0u32), Size2D::new(0u32, 0u32)).is_empty());
896        assert!(Rect::new(Point2D::new(0u32, 0u32), Size2D::new(10u32, 0u32)).is_empty());
897        assert!(Rect::new(Point2D::new(0u32, 0u32), Size2D::new(0u32, 10u32)).is_empty());
898        assert!(!Rect::new(Point2D::new(0u32, 0u32), Size2D::new(1u32, 1u32)).is_empty());
899        assert!(Rect::new(Point2D::new(10u32, 10u32), Size2D::new(0u32, 0u32)).is_empty());
900        assert!(Rect::new(Point2D::new(10u32, 10u32), Size2D::new(10u32, 0u32)).is_empty());
901        assert!(Rect::new(Point2D::new(10u32, 10u32), Size2D::new(0u32, 10u32)).is_empty());
902        assert!(!Rect::new(Point2D::new(10u32, 10u32), Size2D::new(1u32, 1u32)).is_empty());
903    }
904
905    #[test]
906    fn test_round() {
907        let mut x = -2.0;
908        let mut y = -2.0;
909        let mut w = -2.0;
910        let mut h = -2.0;
911        while x < 2.0 {
912            while y < 2.0 {
913                while w < 2.0 {
914                    while h < 2.0 {
915                        let rect = Rect::new(Point2D::new(x, y), Size2D::new(w, h));
916
917                        assert!(rect.contains_rect(&rect.round_in()));
918                        assert!(rect.round_in().inflate(1.0, 1.0).contains_rect(&rect));
919
920                        assert!(rect.round_out().contains_rect(&rect));
921                        assert!(rect.inflate(1.0, 1.0).contains_rect(&rect.round_out()));
922
923                        assert!(rect.inflate(1.0, 1.0).contains_rect(&rect.round()));
924                        assert!(rect.round().inflate(1.0, 1.0).contains_rect(&rect));
925
926                        h += 0.1;
927                    }
928                    w += 0.1;
929                }
930                y += 0.1;
931            }
932            x += 0.1;
933        }
934    }
935
936    #[test]
937    fn test_center() {
938        let r: Rect<i32> = rect(-2, 5, 4, 10);
939        assert_eq!(r.center(), point2(0, 10));
940
941        let r: Rect<f32> = rect(1.0, 2.0, 3.0, 4.0);
942        assert_eq!(r.center(), point2(2.5, 4.0));
943    }
944
945    #[test]
946    fn test_nan() {
947        let r1: Rect<f32> = rect(-2.0, 5.0, 4.0, std::f32::NAN);
948        let r2: Rect<f32> = rect(std::f32::NAN, -1.0, 3.0, 10.0);
949
950        assert_eq!(r1.intersection(&r2), None);
951    }
952}