From 6a49a7ac40db5bc0c3216e43487ed2bd6f60d893 Mon Sep 17 00:00:00 2001 From: Corey Farwell Date: Sun, 22 Mar 2020 16:09:49 -0400 Subject: [PATCH] Introduce Rect#to_polygon and Triangle#to_polygon. Extracted from https://github.com/georust/geo/pull/421 --- geo-types/src/rect.rs | 35 ++++++++++++++++++++++++++++++++++- geo-types/src/triangle.rs | 29 ++++++++++++++++++++++++++++- 2 files changed, 62 insertions(+), 2 deletions(-) diff --git a/geo-types/src/rect.rs b/geo-types/src/rect.rs index c5d67cb71..ea76295ef 100644 --- a/geo-types/src/rect.rs +++ b/geo-types/src/rect.rs @@ -1,4 +1,4 @@ -use crate::{Coordinate, CoordinateType}; +use crate::{polygon, Coordinate, CoordinateType, Polygon}; /// A bounded 2D quadrilateral whose area is defined by minimum and maximum `Coordinates`. #[derive(PartialEq, Clone, Copy, Debug, Hash)] @@ -73,6 +73,39 @@ impl Rect { self.max().y - self.min().y } + /// Create a `Polygon` from the `Rect`. + /// + /// # Examples + /// + /// ```rust + /// use geo_types::{Coordinate, Rect, polygon}; + /// + /// let rect = Rect::new( + /// Coordinate { x: 0., y: 0. }, + /// Coordinate { x: 10., y: 20. }, + /// ); + /// + /// assert_eq!( + /// rect.to_polygon(), + /// polygon![ + /// (x: 0., y: 0.), + /// (x: 0., y: 20.), + /// (x: 10., y: 20.), + /// (x: 10., y: 0.), + /// (x: 0., y: 0.), + /// ], + /// ); + /// ``` + pub fn to_polygon(self) -> Polygon { + polygon![ + (x: self.min.x, y: self.min.y), + (x: self.min.x, y: self.max.y), + (x: self.max.x, y: self.max.y), + (x: self.max.x, y: self.min.y), + (x: self.min.x, y: self.min.y), + ] + } + fn assert_valid_bounds(min: Coordinate, max: Coordinate) { assert!( min.x <= max.x && min.y <= max.y, diff --git a/geo-types/src/triangle.rs b/geo-types/src/triangle.rs index 03233e555..3cd4f137f 100644 --- a/geo-types/src/triangle.rs +++ b/geo-types/src/triangle.rs @@ -1,4 +1,4 @@ -use crate::{Coordinate, CoordinateType, Line}; +use crate::{polygon, Coordinate, CoordinateType, Line, Polygon}; /// A bounded 2D area whose three vertices are defined by `Coordinate`s. #[derive(Copy, Clone, Debug, Hash)] @@ -17,6 +17,33 @@ impl Triangle { Line::new(self.2, self.0), ] } + + /// Create a `Polygon` from the `Triangle`. + /// + /// # Examples + /// + /// ```rust + /// use geo_types::{Coordinate, Triangle, polygon}; + /// + /// let triangle = Triangle( + /// Coordinate { x: 0., y: 0. }, + /// Coordinate { x: 10., y: 20. }, + /// Coordinate { x: 20., y: -10. }, + /// ); + /// + /// assert_eq!( + /// triangle.to_polygon(), + /// polygon![ + /// (x: 0., y: 0.), + /// (x: 10., y: 20.), + /// (x: 20., y: -10.), + /// (x: 0., y: 0.), + /// ], + /// ); + /// ``` + pub fn to_polygon(self) -> Polygon { + polygon![self.0, self.1, self.2, self.0] + } } impl> + Copy, T: CoordinateType> From<[IC; 3]> for Triangle {