galileo_types/impls/
polygon.rs

1use serde::{Deserialize, Serialize};
2
3use crate::geometry_type::{GeometryType, PolygonGeometryType};
4use crate::impls::contour::ClosedContour;
5
6/// Simple implementation of the [`Polygon`](crate::Polygon) trait.
7#[derive(Debug, Clone, Default, PartialEq, PartialOrd, Eq, Ord, Hash, Deserialize, Serialize)]
8pub struct Polygon<P> {
9    /// Outer contour.
10    pub outer_contour: ClosedContour<P>,
11    /// Inner contours.
12    pub inner_contours: Vec<ClosedContour<P>>,
13}
14
15impl<P> Polygon<P> {
16    /// Creates a new polygon.
17    pub fn new(outer_contour: ClosedContour<P>, inner_contours: Vec<ClosedContour<P>>) -> Self {
18        Self {
19            outer_contour,
20            inner_contours,
21        }
22    }
23
24    /// Casts all points of the polygon into a different numeric type.
25    pub fn cast_points<T>(&self, mut cast: impl Fn(&P) -> T) -> Polygon<T> {
26        Polygon {
27            outer_contour: ClosedContour::new(
28                self.outer_contour.points.iter().map(&mut cast).collect(),
29            ),
30            inner_contours: self
31                .inner_contours
32                .iter()
33                .map(|c| ClosedContour::new(c.points.iter().map(&mut cast).collect()))
34                .collect(),
35        }
36    }
37}
38
39impl<P: Copy> crate::polygon::Polygon for Polygon<P> {
40    type Contour = ClosedContour<P>;
41
42    fn outer_contour(&self) -> &Self::Contour {
43        &self.outer_contour
44    }
45
46    fn inner_contours(&self) -> impl Iterator<Item = &'_ Self::Contour> {
47        Box::new(self.inner_contours.iter())
48    }
49}
50
51impl<P> From<ClosedContour<P>> for Polygon<P> {
52    fn from(value: ClosedContour<P>) -> Self {
53        Self {
54            outer_contour: value,
55            inner_contours: vec![],
56        }
57    }
58}
59
60impl<P: GeometryType> GeometryType for Polygon<P> {
61    type Type = PolygonGeometryType;
62    type Space = P::Space;
63}
64
65impl<P> From<Vec<P>> for Polygon<P> {
66    fn from(value: Vec<P>) -> Self {
67        Self {
68            outer_contour: ClosedContour::new(value),
69            inner_contours: vec![],
70        }
71    }
72}