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