Bug 1352863 - Add a DistanceTo() method to BaseRect. r=kats draft
authorBotond Ballo <botond@mozilla.com>
Fri, 19 May 2017 20:10:30 -0400
changeset 583907 d26190c57e396671f68f679aa33aa1df0bfe5bea
parent 583906 296db90f4a6376059961232c63ad2d27197fab51
child 583908 4c63269480154a95d5faedf1b4972f7d3373cb5a
push id60596
push userbballo@mozilla.com
push dateWed, 24 May 2017 19:49:24 +0000
reviewerskats
bugs1352863
milestone55.0a1
Bug 1352863 - Add a DistanceTo() method to BaseRect. r=kats MozReview-Commit-ID: BHGXvNFlfb4
gfx/2d/BaseRect.h
--- a/gfx/2d/BaseRect.h
+++ b/gfx/2d/BaseRect.h
@@ -562,25 +562,49 @@ struct BaseRect {
     return Sub(
       static_cast<T>(-std::numeric_limits<int32_t>::max() * 0.5),
       static_cast<T>(-std::numeric_limits<int32_t>::max() * 0.5),
       static_cast<T>(std::numeric_limits<int32_t>::max()),
       static_cast<T>(std::numeric_limits<int32_t>::max())
     );
   };
 
+  // Returns a point representing the distance, along each dimension, of the
+  // given point from this rectangle. The distance along a dimension is defined
+  // as zero if the point is within the bounds of the rectangle in that
+  // dimension; otherwise, it's the distance to the closer endpoint of the
+  // rectangle in that dimension.
+  Point DistanceTo(const Point& aPoint) const
+  {
+    return {DistanceFromInterval(aPoint.x, x, XMost()),
+            DistanceFromInterval(aPoint.y, y, YMost())};
+  }
+
   friend std::ostream& operator<<(std::ostream& stream,
       const BaseRect<T, Sub, Point, SizeT, MarginT>& aRect) {
     return stream << '(' << aRect.x << ',' << aRect.y << ','
                   << aRect.width << ',' << aRect.height << ')';
   }
 
 private:
   // Do not use the default operator== or operator!= !
   // Use IsEqualEdges or IsEqualInterior explicitly.
   bool operator==(const Sub& aRect) const { return false; }
   bool operator!=(const Sub& aRect) const { return false; }
+
+  // Helper function for DistanceTo() that computes the distance of a
+  // coordinate along one dimension from an interval in that dimension.
+  static T DistanceFromInterval(T aCoord, T aIntervalStart, T aIntervalEnd)
+  {
+    if (aCoord < aIntervalStart) {
+      return aIntervalStart - aCoord;
+    }
+    if (aCoord > aIntervalEnd) {
+      return aCoord - aIntervalEnd;
+    }
+    return 0;
+  }
 };
 
 } // namespace gfx
 } // namespace mozilla
 
 #endif /* MOZILLA_GFX_BASERECT_H_ */