Copilot commented on code in PR #194: URL: https://github.com/apache/sedona-db/pull/194#discussion_r2413793826
########## rust/sedona-geo-traits-ext/src/line_string.rs: ########## @@ -0,0 +1,198 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// Extend LineStringTrait traits for the `geo-traits` crate + +use geo_traits::{GeometryTrait, LineStringTrait, UnimplementedLineString}; +use geo_types::{Coord, CoordNum, Line, LineString, Triangle}; + +use crate::{CoordTraitExt, GeoTraitExtWithTypeTag, LineStringTag}; + +/// Additional convenience methods for [`LineStringTrait`] implementers that mirror `geo-types`. +pub trait LineStringTraitExt: + LineStringTrait + GeoTraitExtWithTypeTag<Tag = LineStringTag> +where + <Self as GeometryTrait>::T: CoordNum, +{ + type CoordTypeExt<'a>: 'a + CoordTraitExt<T = <Self as GeometryTrait>::T> + where + Self: 'a; + + /// Returns the coordinate at the provided index. + fn coord_ext(&self, i: usize) -> Option<Self::CoordTypeExt<'_>>; + + /// Returns a coordinate by index without bounds checking. + /// + /// # Safety + /// The caller must ensure that `i` is a valid index less than the number of coordinates. + /// Otherwise, this function may cause undefined behavior. + unsafe fn coord_unchecked_ext(&self, i: usize) -> Self::CoordTypeExt<'_>; + + /// Returns an iterator over all coordinates as extension trait instances. + fn coords_ext(&self) -> impl Iterator<Item = Self::CoordTypeExt<'_>>; + + /// Returns a coordinate by index without bounds checking. + /// + /// # Safety + /// The caller must ensure that `i` is a valid index less than the number of coordinates. + /// Otherwise, this function may cause undefined behavior. + #[inline] + unsafe fn geo_coord_unchecked(&self, i: usize) -> Coord<Self::T> { + self.coord_unchecked_ext(i).geo_coord() + } + + /// Return an iterator yielding one [`Line`] for each line segment + /// in the [`LineString`][`geo_types::LineString`]. + #[inline] + fn lines(&'_ self) -> impl ExactSizeIterator<Item = Line<<Self as GeometryTrait>::T>> + '_ { + let num_coords = self.num_coords(); + (0..num_coords.saturating_sub(1)).map(|i| unsafe { + let coord1 = self.coord_unchecked_ext(i); + let coord2 = self.coord_unchecked_ext(i + 1); + Line::new(coord1.geo_coord(), coord2.geo_coord()) + }) + } + + /// Return an iterator yielding one [`Line`] for each line segment in the [`LineString`][`geo_types::LineString`], + /// starting from the **end** point of the LineString, working towards the start. + /// + /// Note: This is like [`Self::lines`], but the sequence **and** the orientation of + /// segments are reversed. + #[inline] + fn rev_lines(&'_ self) -> impl ExactSizeIterator<Item = Line<<Self as GeometryTrait>::T>> + '_ { + let num_coords = self.num_coords(); + (num_coords - 1..0).map(|i| unsafe { Review Comment: The range `(num_coords - 1..0)` is invalid and will always be empty because the start is greater than the end. This should be `(0..num_coords - 1).rev()` to iterate backwards. ```suggestion (0..num_coords - 1).rev().map(|i| unsafe { ``` ########## rust/sedona-geo-traits-ext/src/wkb_ext.rs: ########## @@ -0,0 +1,557 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +use std::marker::PhantomData; + +use crate::*; +use byteorder::{BigEndian, ByteOrder, LittleEndian}; +use geo_traits::{ + GeometryCollectionTrait, GeometryTrait, GeometryType, LineStringTrait, MultiLineStringTrait, + MultiPointTrait, MultiPolygonTrait, PointTrait, PolygonTrait, +}; +use geo_types::{Coord as GeoCoord, Line}; +use wkb::reader::{ + Coord, Dimension, GeometryCollection, LineString, LinearRing, MultiLineString, MultiPoint, + MultiPolygon, Point, Polygon, Wkb, +}; +use wkb::Endianness; + +// ┌──────────────────────────────────────────────────────────┐ +// │ Coord │ +// └──────────────────────────────────────────────────────────┘ +impl CoordTraitExt for Coord<'_> { + #[inline] + fn geo_coord(&self) -> geo_types::Coord<f64> { + let coord_slice = self.coord_slice(); Review Comment: Similar to the iterator, this unsafe code assumes the coordinate slice has at least 16 bytes available without bounds checking. If `coord_slice` is shorter than expected, this could cause undefined behavior. ```suggestion let coord_slice = self.coord_slice(); if coord_slice.len() < 16 { panic!("coord_slice too short: expected at least 16 bytes, got {}", coord_slice.len()); } ``` ########## rust/sedona-geo-traits-ext/src/wkb_ext.rs: ########## @@ -0,0 +1,557 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +use std::marker::PhantomData; + +use crate::*; +use byteorder::{BigEndian, ByteOrder, LittleEndian}; +use geo_traits::{ + GeometryCollectionTrait, GeometryTrait, GeometryType, LineStringTrait, MultiLineStringTrait, + MultiPointTrait, MultiPolygonTrait, PointTrait, PolygonTrait, +}; +use geo_types::{Coord as GeoCoord, Line}; +use wkb::reader::{ + Coord, Dimension, GeometryCollection, LineString, LinearRing, MultiLineString, MultiPoint, + MultiPolygon, Point, Polygon, Wkb, +}; +use wkb::Endianness; + +// ┌──────────────────────────────────────────────────────────┐ +// │ Coord │ +// └──────────────────────────────────────────────────────────┘ +impl CoordTraitExt for Coord<'_> { + #[inline] + fn geo_coord(&self) -> geo_types::Coord<f64> { + let coord_slice = self.coord_slice(); + unsafe { + let x_bytes = std::slice::from_raw_parts(coord_slice.as_ptr(), 8); + let y_bytes = std::slice::from_raw_parts(coord_slice.as_ptr().add(8), 8); + match self.byte_order() { + Endianness::BigEndian => { + let x = BigEndian::read_f64(x_bytes); + let y = BigEndian::read_f64(y_bytes); + geo_types::Coord { x, y } + } + Endianness::LittleEndian => { + let x = LittleEndian::read_f64(x_bytes); + let y = LittleEndian::read_f64(y_bytes); + geo_types::Coord { x, y } + } + } + } + } +} + +impl GeoTraitExtWithTypeTag for Coord<'_> { + type Tag = CoordTag; +} + +// ┌──────────────────────────────────────────────────────────┐ +// │ Point │ +// └──────────────────────────────────────────────────────────┘ + +impl PointTraitExt for Point<'_> { + forward_point_trait_ext_funcs!(); +} + +impl GeoTraitExtWithTypeTag for Point<'_> { + type Tag = PointTag; +} + +impl PointTraitExt for &Point<'_> { + forward_point_trait_ext_funcs!(); +} + +impl GeoTraitExtWithTypeTag for &Point<'_> { + type Tag = PointTag; +} + +// ┌──────────────────────────────────────────────────────────┐ +// │ LineString │ +// └──────────────────────────────────────────────────────────┘ + +impl LineStringTraitExt for LineString<'_> { + forward_line_string_trait_ext_funcs!(); + + #[inline(always)] + fn lines(&'_ self) -> impl ExactSizeIterator<Item = Line<f64>> + '_ { + let buf = self.coords_slice(); + let dim_size = dimension_size(self.dimension()); + let num_coords = self.num_coords(); + match self.byte_order() { + Endianness::LittleEndian => { + EndianLineIter::LE(LineIter::new(buf, num_coords, dim_size)) + } + Endianness::BigEndian => EndianLineIter::BE(LineIter::new(buf, num_coords, dim_size)), + } + } + + #[inline(always)] + fn coord_iter(&self) -> impl Iterator<Item = GeoCoord<f64>> { + let buf = self.coords_slice(); + let dim_size = dimension_size(self.dimension()); + let num_coords = self.num_coords(); + match self.byte_order() { + Endianness::LittleEndian => { + EndianCoordIter::LE(CoordIter::new(buf, num_coords, dim_size)) + } + Endianness::BigEndian => EndianCoordIter::BE(CoordIter::new(buf, num_coords, dim_size)), + } + } +} + +impl GeoTraitExtWithTypeTag for LineString<'_> { + type Tag = LineStringTag; +} + +impl LineStringTraitExt for &LineString<'_> { + forward_line_string_trait_ext_funcs!(); + + #[inline(always)] + fn lines(&'_ self) -> impl ExactSizeIterator<Item = Line<f64>> + '_ { + (*self).lines() + } + + #[inline(always)] + fn coord_iter(&self) -> impl Iterator<Item = GeoCoord<f64>> { + (*self).coord_iter() + } +} + +impl GeoTraitExtWithTypeTag for &LineString<'_> { + type Tag = LineStringTag; +} + +// ┌──────────────────────────────────────────────────────────┐ +// │ LinearRing │ +// └──────────────────────────────────────────────────────────┘ + +impl LineStringTraitExt for LinearRing<'_> { + forward_line_string_trait_ext_funcs!(); + + #[inline(always)] + fn lines(&'_ self) -> impl ExactSizeIterator<Item = Line<f64>> + '_ { + let buf = self.coords_slice(); + let dim_size = dimension_size(self.dimension()); + let num_coords = self.num_coords(); + match self.byte_order() { + Endianness::LittleEndian => { + EndianLineIter::LE(LineIter::new(buf, num_coords, dim_size)) + } + Endianness::BigEndian => EndianLineIter::BE(LineIter::new(buf, num_coords, dim_size)), + } + } + + #[inline(always)] + fn coord_iter(&self) -> impl Iterator<Item = GeoCoord<f64>> { + let buf = self.coords_slice(); + let dim_size = dimension_size(self.dimension()); + let num_coords = self.num_coords(); + match self.byte_order() { + Endianness::LittleEndian => { + EndianCoordIter::LE(CoordIter::new(buf, num_coords, dim_size)) + } + Endianness::BigEndian => EndianCoordIter::BE(CoordIter::new(buf, num_coords, dim_size)), + } + } +} + +impl GeoTraitExtWithTypeTag for LinearRing<'_> { + type Tag = LineStringTag; +} + +impl LineStringTraitExt for &LinearRing<'_> { + forward_line_string_trait_ext_funcs!(); + + #[inline(always)] + fn lines(&'_ self) -> impl ExactSizeIterator<Item = Line<f64>> + '_ { + (*self).lines() + } + + #[inline(always)] + fn coord_iter(&self) -> impl Iterator<Item = GeoCoord<f64>> { + (*self).coord_iter() + } +} + +impl GeoTraitExtWithTypeTag for &LinearRing<'_> { + type Tag = LineStringTag; +} + +// ┌──────────────────────────────────────────────────────────┐ +// │ Polygon │ +// └──────────────────────────────────────────────────────────┘ + +impl PolygonTraitExt for Polygon<'_> { + forward_polygon_trait_ext_funcs!(); +} + +impl GeoTraitExtWithTypeTag for Polygon<'_> { + type Tag = PolygonTag; +} + +impl PolygonTraitExt for &Polygon<'_> { + forward_polygon_trait_ext_funcs!(); +} + +impl GeoTraitExtWithTypeTag for &Polygon<'_> { + type Tag = PolygonTag; +} + +// ┌──────────────────────────────────────────────────────────┐ +// │ MultiPoint │ +// └──────────────────────────────────────────────────────────┘ + +impl MultiPointTraitExt for MultiPoint<'_> { + forward_multi_point_trait_ext_funcs!(); +} + +impl GeoTraitExtWithTypeTag for MultiPoint<'_> { + type Tag = MultiPointTag; +} + +impl<'a, 'b> MultiPointTraitExt for &'b MultiPoint<'a> +where + 'a: 'b, +{ + forward_multi_point_trait_ext_funcs!(); +} + +impl<'a, 'b> GeoTraitExtWithTypeTag for &'b MultiPoint<'a> +where + 'a: 'b, +{ + type Tag = MultiPointTag; +} + +// ┌──────────────────────────────────────────────────────────┐ +// │ MultiLineString │ +// └──────────────────────────────────────────────────────────┘ + +impl MultiLineStringTraitExt for MultiLineString<'_> { + forward_multi_line_string_trait_ext_funcs!(); +} + +impl GeoTraitExtWithTypeTag for MultiLineString<'_> { + type Tag = MultiLineStringTag; +} + +impl<'a, 'b> MultiLineStringTraitExt for &'b MultiLineString<'a> +where + 'a: 'b, +{ + forward_multi_line_string_trait_ext_funcs!(); +} + +impl<'a, 'b> GeoTraitExtWithTypeTag for &'b MultiLineString<'a> +where + 'a: 'b, +{ + type Tag = MultiLineStringTag; +} + +// ┌──────────────────────────────────────────────────────────┐ +// │ MultiPolygon │ +// └──────────────────────────────────────────────────────────┘ + +impl MultiPolygonTraitExt for MultiPolygon<'_> { + forward_multi_polygon_trait_ext_funcs!(); +} + +impl GeoTraitExtWithTypeTag for MultiPolygon<'_> { + type Tag = MultiPolygonTag; +} + +impl<'a, 'b> MultiPolygonTraitExt for &'b MultiPolygon<'a> +where + 'a: 'b, +{ + forward_multi_polygon_trait_ext_funcs!(); +} + +impl<'a, 'b> GeoTraitExtWithTypeTag for &'b MultiPolygon<'a> +where + 'a: 'b, +{ + type Tag = MultiPolygonTag; +} + +// ┌──────────────────────────────────────────────────────────┐ +// │ GeometryCollection │ +// └──────────────────────────────────────────────────────────┘ + +impl GeometryCollectionTraitExt for GeometryCollection<'_> { + forward_geometry_collection_trait_ext_funcs!(); +} + +impl GeoTraitExtWithTypeTag for GeometryCollection<'_> { + type Tag = GeometryCollectionTag; +} + +// ┌──────────────────────────────────────────────────────────┐ +// │ Wkb/Geometry │ +// └──────────────────────────────────────────────────────────┘ + +impl<'a> GeometryTraitExt for Wkb<'a> { + forward_geometry_trait_ext_funcs!(f64); + + type InnerGeometryRef<'b> + = &'b Wkb<'a> + where + Self: 'b; + + #[inline] + fn geometry_ext(&self, i: usize) -> Option<Self::InnerGeometryRef<'_>> { + let GeometryType::GeometryCollection(gc) = self.as_type() else { + return None; + }; + gc.geometry(i) + } + + #[inline] + unsafe fn geometry_unchecked_ext(&self, i: usize) -> Self::InnerGeometryRef<'_> { + let GeometryType::GeometryCollection(gc) = self.as_type() else { + panic!("Called geometry_unchecked_ext on a non-GeometryCollection geometry"); + }; + gc.geometry_unchecked(i) + } + + #[inline] + fn geometries_ext(&self) -> impl Iterator<Item = Self::InnerGeometryRef<'_>> { + let GeometryType::GeometryCollection(gc) = self.as_type() else { + panic!("Called geometries_ext on a non-GeometryCollection geometry"); + }; + gc.geometries() + } +} + +impl<'a, 'b> GeometryTraitExt for &'b Wkb<'a> +where + 'a: 'b, +{ + forward_geometry_trait_ext_funcs!(f64); + + type InnerGeometryRef<'c> + = &'b Wkb<'a> + where + Self: 'c; + + #[inline] + fn geometry_ext(&self, i: usize) -> Option<Self::InnerGeometryRef<'_>> { + (*self).geometry_ext(i) + } + + #[inline] + unsafe fn geometry_unchecked_ext(&self, i: usize) -> Self::InnerGeometryRef<'_> { + (*self).geometry_unchecked_ext(i) + } + + #[inline] + fn geometries_ext(&self) -> impl Iterator<Item = Self::InnerGeometryRef<'_>> { + (*self).geometries_ext() + } +} + +impl GeoTraitExtWithTypeTag for Wkb<'_> { + type Tag = GeometryTag; +} + +impl<'a, 'b> GeoTraitExtWithTypeTag for &'b Wkb<'a> +where + 'a: 'b, +{ + type Tag = GeometryTag; +} + +// ┌──────────────────────────────────────────────────────────┐ +// │ Iterators │ +// └──────────────────────────────────────────────────────────┘ + +/// Iterator over coordinates in a WKB buffer using a compile-time endianness. +pub struct CoordIter<'a, B: ByteOrder> { + buf: &'a [u8], + current_offset: usize, + remaining: usize, + dim_size: usize, + _marker: PhantomData<B>, +} + +impl<'a, B: ByteOrder> CoordIter<'a, B> { + #[inline] + /// Creates a new coordinate iterator over the provided buffer. + pub fn new(buf: &'a [u8], num_coords: usize, dim_size: usize) -> Self { + Self { + buf, + current_offset: 0, + remaining: num_coords, + dim_size, + _marker: PhantomData, + } + } +} + +impl<B: ByteOrder> Iterator for CoordIter<'_, B> { + type Item = GeoCoord<f64>; + + #[inline] + fn next(&mut self) -> Option<Self::Item> { + if self.remaining == 0 { + return None; + } + + // SAFETY: We're reading raw memory from the buffer at calculated offsets. + // This assumes the buffer contains valid data and offsets are within bounds. + let coord = unsafe { + let x_bytes = std::slice::from_raw_parts(self.buf.as_ptr().add(self.current_offset), 8); + let y_bytes = + std::slice::from_raw_parts(self.buf.as_ptr().add(self.current_offset + 8), 8); + let x = B::read_f64(x_bytes); + let y = B::read_f64(y_bytes); + GeoCoord { x, y } + }; Review Comment: The unsafe code reads from raw memory without validating that `self.current_offset + 16` is within the buffer bounds. This could lead to buffer overflow if the WKB data is malformed or if `dim_size` calculations are incorrect. ########## rust/sedona-geo-traits-ext/src/line_string.rs: ########## @@ -0,0 +1,198 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// Extend LineStringTrait traits for the `geo-traits` crate + +use geo_traits::{GeometryTrait, LineStringTrait, UnimplementedLineString}; +use geo_types::{Coord, CoordNum, Line, LineString, Triangle}; + +use crate::{CoordTraitExt, GeoTraitExtWithTypeTag, LineStringTag}; + +/// Additional convenience methods for [`LineStringTrait`] implementers that mirror `geo-types`. +pub trait LineStringTraitExt: + LineStringTrait + GeoTraitExtWithTypeTag<Tag = LineStringTag> +where + <Self as GeometryTrait>::T: CoordNum, +{ + type CoordTypeExt<'a>: 'a + CoordTraitExt<T = <Self as GeometryTrait>::T> + where + Self: 'a; + + /// Returns the coordinate at the provided index. + fn coord_ext(&self, i: usize) -> Option<Self::CoordTypeExt<'_>>; + + /// Returns a coordinate by index without bounds checking. + /// + /// # Safety + /// The caller must ensure that `i` is a valid index less than the number of coordinates. + /// Otherwise, this function may cause undefined behavior. + unsafe fn coord_unchecked_ext(&self, i: usize) -> Self::CoordTypeExt<'_>; + + /// Returns an iterator over all coordinates as extension trait instances. + fn coords_ext(&self) -> impl Iterator<Item = Self::CoordTypeExt<'_>>; + + /// Returns a coordinate by index without bounds checking. + /// + /// # Safety + /// The caller must ensure that `i` is a valid index less than the number of coordinates. + /// Otherwise, this function may cause undefined behavior. + #[inline] + unsafe fn geo_coord_unchecked(&self, i: usize) -> Coord<Self::T> { + self.coord_unchecked_ext(i).geo_coord() + } + + /// Return an iterator yielding one [`Line`] for each line segment + /// in the [`LineString`][`geo_types::LineString`]. + #[inline] + fn lines(&'_ self) -> impl ExactSizeIterator<Item = Line<<Self as GeometryTrait>::T>> + '_ { + let num_coords = self.num_coords(); + (0..num_coords.saturating_sub(1)).map(|i| unsafe { + let coord1 = self.coord_unchecked_ext(i); + let coord2 = self.coord_unchecked_ext(i + 1); + Line::new(coord1.geo_coord(), coord2.geo_coord()) + }) + } + + /// Return an iterator yielding one [`Line`] for each line segment in the [`LineString`][`geo_types::LineString`], + /// starting from the **end** point of the LineString, working towards the start. + /// + /// Note: This is like [`Self::lines`], but the sequence **and** the orientation of + /// segments are reversed. + #[inline] + fn rev_lines(&'_ self) -> impl ExactSizeIterator<Item = Line<<Self as GeometryTrait>::T>> + '_ { + let num_coords = self.num_coords(); + (num_coords - 1..0).map(|i| unsafe { + let coord1 = self.coord_unchecked_ext(i); + let coord2 = self.coord_unchecked_ext(i - 1); + Line::new(coord2.geo_coord(), coord1.geo_coord()) + }) + } + + /// An iterator which yields the coordinates of a [`LineString`][`geo_types::LineString`] as [Triangle]s + #[inline] + fn triangles( + &'_ self, + ) -> impl ExactSizeIterator<Item = Triangle<<Self as GeometryTrait>::T>> + '_ { + let num_coords = self.num_coords(); + (0..num_coords - 2).map(|i| unsafe { + let coord1 = self.coord_unchecked_ext(i); + let coord2 = self.coord_unchecked_ext(i + 1); + let coord3 = self.coord_unchecked_ext(i + 2); + Triangle::new(coord1.geo_coord(), coord2.geo_coord(), coord3.geo_coord()) + }) + } + + /// Returns an iterator yielding the coordinates of this line string as [`geo_types::Coord`] values. + #[inline] + fn coord_iter(&self) -> impl Iterator<Item = Coord<<Self as GeometryTrait>::T>> { + self.coords_ext().map(|c| c.geo_coord()) + } + + #[inline] + /// Returns true when the line string is closed (its first and last coordinates are equal). + fn is_closed(&self) -> bool { + match (self.coords_ext().next(), self.coords_ext().last()) { Review Comment: The `is_closed` method calls `coords_ext()` twice, which creates two separate iterators. The `last()` call on the second iterator will consume the entire iterator again. This should use a single iterator or call the method once and store the result. ```suggestion let mut coords = self.coords_ext(); let first = coords.next(); let last = coords.last().or(first.clone()); match (first, last) { ``` ########## rust/sedona-geo-traits-ext/src/rect.rs: ########## @@ -0,0 +1,331 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// Extend RectTrait traits for the `geo-traits` crate + +use geo_traits::{CoordTrait, GeometryTrait, RectTrait, UnimplementedRect}; +use geo_types::{coord, Coord, CoordFloat, CoordNum, Line, LineString, Polygon, Rect}; +use num_traits::One; + +use crate::{CoordTraitExt, GeoTraitExtWithTypeTag, RectTag}; + +static RECT_INVALID_BOUNDS_ERROR: &str = "Failed to create Rect: 'min' coordinate's x/y value must be smaller or equal to the 'max' x/y value"; + +/// Extension trait that augments [`geo_traits::RectTrait`] with additional +/// helpers for working with axis-aligned bounding boxes. +pub trait RectTraitExt: RectTrait + GeoTraitExtWithTypeTag<Tag = RectTag> +where + <Self as GeometryTrait>::T: CoordNum, +{ + /// Extension-aware coordinate type returned from accessors. + type CoordTypeExt<'a>: 'a + CoordTraitExt<T = <Self as GeometryTrait>::T> + where + Self: 'a; + + /// Returns the minimum corner using the extension trait wrapper. + fn min_ext(&self) -> Self::CoordTypeExt<'_>; + + /// Returns the maximum corner using the extension trait wrapper. + fn max_ext(&self) -> Self::CoordTypeExt<'_>; + + #[inline] + /// Returns the minimum corner as a `geo-types::Coord`. + fn min_coord(&self) -> Coord<<Self as GeometryTrait>::T> { + self.min_ext().geo_coord() + } + + #[inline] + /// Returns the maximum corner as a `geo-types::Coord`. + fn max_coord(&self) -> Coord<<Self as GeometryTrait>::T> { + self.max_ext().geo_coord() + } + + #[inline] + /// Constructs a [`geo_types::Rect`] from the extension trait accessors. + fn geo_rect(&self) -> Rect<<Self as GeometryTrait>::T> { + Rect::new(self.min_coord(), self.max_coord()) + } + + #[inline] + /// Returns the width of the rectangle. + fn width(&self) -> <Self as GeometryTrait>::T { + self.max().x() - self.min().x() + } + + #[inline] + /// Returns the height of the rectangle. + fn height(&self) -> <Self as GeometryTrait>::T { + self.max().y() - self.min().y() + } + + /// Converts the rectangle into a polygon with four corners. + fn to_polygon(&self) -> Polygon<<Self as GeometryTrait>::T> + where + <Self as GeometryTrait>::T: Clone, + { + let min_coord = self.min_coord(); + let max_coord = self.max_coord(); + + let min_x = min_coord.x; + let min_y = min_coord.y; + let max_x = max_coord.x; + let max_y = max_coord.y; + + let line_string = LineString::new(vec![ + Coord { x: min_x, y: min_y }, + Coord { x: min_x, y: max_y }, + Coord { x: max_x, y: max_y }, + Coord { x: max_x, y: min_y }, + Coord { x: min_x, y: min_y }, + ]); + + Polygon::new(line_string, vec![]) + } + + /// Returns the four outer edges as line segments. + fn to_lines(&self) -> [Line<<Self as GeometryTrait>::T>; 4] { + let min_coord = self.min_coord(); + let max_coord = self.max_coord(); + [ + Line::new( + coord! { + x: max_coord.x, + y: min_coord.y, + }, + coord! { + x: max_coord.x, + y: max_coord.y, + }, + ), + Line::new( + coord! { + x: max_coord.x, + y: min_coord.y, + }, + coord! { + x: min_coord.x, + y: max_coord.y, + }, + ), Review Comment: This line connects opposite corners diagonally, which is incorrect for rectangle edges. It should connect adjacent corners like `(max_x, min_y) -> (min_x, min_y)` to form the bottom edge. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
