use std::sync::OnceLock;
use crate::GeometryError;
use crate::exact::kernel as exact;
use crate::types::coord::{Bbox, Coord2d, CoordSeq, bbox_of, check_coords};
use crate::types::envelope::Envelope;
#[derive(Clone)]
pub struct LinearRing {
coords: CoordSeq,
bbox: OnceLock<Bbox>,
}
impl PartialEq for LinearRing {
fn eq(&self, other: &Self) -> bool {
self.coords == other.coords
}
}
#[allow(clippy::missing_fields_in_debug)]
impl core::fmt::Debug for LinearRing {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("LinearRing")
.field("coords", &self.coords)
.finish()
}
}
impl LinearRing {
pub(crate) fn from_valid(coords: CoordSeq) -> Self {
debug_assert!(coords.len() >= 3);
Self {
coords,
bbox: OnceLock::new(),
}
}
pub fn new(coords: CoordSeq) -> Result<Self, GeometryError> {
let coords = if coords.len() >= 2 && coords[0] == coords[coords.len() - 1] {
CoordSeq::new(coords.as_slice()[..coords.len() - 1].to_vec())
} else {
coords
};
Self::from_distinct(coords)
}
pub(crate) fn from_distinct(coords: CoordSeq) -> Result<Self, GeometryError> {
check_coords(&coords)?;
if coords.len() < 3 {
return Err(GeometryError::InsufficientVertices {
required: 3,
found: coords.len(),
});
}
let n = coords.len();
if coords[n - 1] == coords[0] {
return Err(GeometryError::ConsecutiveDuplicateVertices { index: n - 1 });
}
Ok(Self {
coords,
bbox: OnceLock::new(),
})
}
pub fn coords(&self) -> &CoordSeq {
&self.coords
}
pub fn num_vertices(&self) -> usize {
self.coords.len()
}
pub fn edges(&self) -> impl Iterator<Item = (Coord2d, Coord2d)> + Clone + '_ {
let n = self.coords.len();
(0..n).map(move |i| (self.coords[i], self.coords[(i + 1) % n]))
}
pub fn signed_area(&self) -> f64 {
crate::ops::signed_area_ring(self)
}
pub fn envelope(&self) -> Result<Envelope, GeometryError> {
let (min_x, min_y, max_x, max_y) = self.bbox();
Envelope::new(Coord2d::new(min_x, min_y), Coord2d::new(max_x, max_y))
}
pub(crate) fn bbox(&self) -> Bbox {
*self.bbox.get_or_init(|| bbox_of(self.coords.as_slice()))
}
pub fn is_simple(&self) -> bool {
let edges: Vec<(Coord2d, Coord2d)> = self.edges().collect();
let n = edges.len();
for i in 0..n {
for j in (i + 2)..n {
if i == 0 && j == n - 1 {
continue;
}
if exact::segments_properly_cross(edges[i].0, edges[i].1, edges[j].0, edges[j].1) {
return false;
}
}
}
true
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
#[allow(
clippy::float_cmp,
clippy::cast_possible_truncation,
clippy::cast_precision_loss,
clippy::cast_possible_wrap,
clippy::range_plus_one,
clippy::no_effect_underscore_binding
)]
mod tests {
use super::*;
fn c(x: f64, y: f64) -> Coord2d {
Coord2d::new(x, y)
}
fn seq(pts: &[(f64, f64)]) -> CoordSeq {
CoordSeq::new(pts.iter().map(|&(x, y)| c(x, y)).collect())
}
fn unit_square_ccw() -> CoordSeq {
seq(&[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)])
}
fn unit_square_cw() -> CoordSeq {
seq(&[(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)])
}
#[test]
fn accepts_ogc_format_strips_closing_vertex() {
let ogc = seq(&[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)]);
let ring = LinearRing::new(ogc).unwrap();
assert_eq!(ring.num_vertices(), 4);
assert_eq!(ring.coords()[0], c(0.0, 0.0));
assert_eq!(ring.coords()[3], c(0.0, 1.0));
}
#[test]
fn rejects_fewer_than_three_distinct_vertices() {
let err = LinearRing::new(seq(&[(0.0, 0.0), (1.0, 0.0)])).unwrap_err();
assert_eq!(
err,
GeometryError::InsufficientVertices {
required: 3,
found: 2
}
);
}
#[test]
fn rejects_fewer_than_three_after_ogc_strip() {
let err = LinearRing::new(seq(&[(0.0, 0.0), (1.0, 0.0), (0.0, 0.0)])).unwrap_err();
assert_eq!(
err,
GeometryError::InsufficientVertices {
required: 3,
found: 2
}
);
}
#[test]
fn edges_yields_n_edges_including_closing() {
let ring = LinearRing::new(unit_square_ccw()).unwrap();
let edges: Vec<(Coord2d, Coord2d)> = ring.edges().collect();
assert_eq!(edges.len(), 4);
assert_eq!(edges[3], (c(0.0, 1.0), c(0.0, 0.0)));
assert_eq!(edges[0], (c(0.0, 0.0), c(1.0, 0.0)));
}
#[test]
fn signed_area_positive_for_ccw_ring() {
let ring = LinearRing::new(unit_square_ccw()).unwrap();
assert!(
ring.signed_area() > 0.0,
"CCW ring must have positive signed area"
);
}
#[test]
fn signed_area_negative_for_cw_ring() {
let ring = LinearRing::new(unit_square_cw()).unwrap();
assert!(
ring.signed_area() < 0.0,
"CW ring must have negative signed area"
);
}
#[test]
fn signed_area_magnitude_correct() {
let ring = LinearRing::new(unit_square_ccw()).unwrap();
assert!((ring.signed_area() - 1.0).abs() < 1e-12);
}
#[test]
fn rejects_consecutive_duplicate_in_middle() {
let err =
LinearRing::new(seq(&[(0.0, 0.0), (1.0, 0.0), (1.0, 0.0), (1.0, 1.0)])).unwrap_err();
assert_eq!(
err,
GeometryError::ConsecutiveDuplicateVertices { index: 1 }
);
}
#[test]
fn rejects_non_finite_coordinate() {
let err =
LinearRing::new(seq(&[(0.0, 0.0), (f64::INFINITY, 0.0), (1.0, 1.0)])).unwrap_err();
assert!(matches!(
err,
GeometryError::NonFiniteCoordinate { axis: 0, .. }
));
}
fn fresh_box(cs: &[Coord2d]) -> [u64; 4] {
let (mut x0, mut y0, mut x1, mut y1) = (cs[0].x, cs[0].y, cs[0].x, cs[0].y);
for p in cs {
x0 = x0.min(p.x);
y0 = y0.min(p.y);
x1 = x1.max(p.x);
y1 = y1.max(p.y);
}
[x0.to_bits(), y0.to_bits(), x1.to_bits(), y1.to_bits()]
}
fn box_bits(b: Bbox) -> [u64; 4] {
[b.0.to_bits(), b.1.to_bits(), b.2.to_bits(), b.3.to_bits()]
}
#[test]
fn the_cached_box_is_the_box_of_the_coordinates() {
use crate::types::{LineString, Polygon};
let mut state = 0x0B0C_5EEDu64;
let mut next = || {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
state >> 33
};
for case in 0..2000 {
let n = 3 + case % 13;
let pts: Vec<Coord2d> = (0..n)
.map(|_| c((next() % 41) as f64 - 20.0, (next() % 41) as f64 - 20.0))
.collect();
let Ok(ring) = LinearRing::new(CoordSeq::new(pts.clone())) else {
continue;
};
let cs = ring.coords().as_slice();
assert_eq!(box_bits(ring.bbox()), fresh_box(cs), "case {case}");
let e = ring.envelope().unwrap();
assert_eq!(
[e.min().x, e.min().y, e.max().x, e.max().y].map(f64::to_bits),
fresh_box(cs)
);
let k = case % cs.len();
let rotated: Vec<Coord2d> = cs[k..].iter().chain(&cs[..k]).copied().collect();
let r2 = LinearRing::from_valid(CoordSeq::new(rotated.clone()));
assert_eq!(box_bits(r2.bbox()), fresh_box(&rotated), "case {case}");
if let Ok(p) = Polygon::new_simple(ring.clone()) {
let back: Polygon = crate::codec::decode(&crate::codec::encode(&p)).unwrap();
assert_eq!(
box_bits(back.exterior().bbox()),
fresh_box(cs),
"case {case}"
);
}
let Ok(line) = LineString::new(CoordSeq::new(pts.clone())) else {
continue;
};
assert_eq!(box_bits(line.bbox()), fresh_box(&pts), "case {case}");
let back: LineString = crate::codec::decode(&crate::codec::encode(&line)).unwrap();
assert_eq!(box_bits(back.bbox()), fresh_box(&pts), "case {case}");
let l2 = LineString::from_valid(CoordSeq::new(pts.clone()));
assert_eq!(box_bits(l2.bbox()), fresh_box(&pts), "case {case}");
}
}
#[test]
fn equality_and_debug_are_the_coordinates_alone() {
let ring = LinearRing::new(unit_square_ccw()).unwrap();
assert_eq!(
format!("{ring:?}"),
format!("LinearRing {{ coords: {:?} }}", ring.coords())
);
let line = crate::types::LineString::new(unit_square_ccw()).unwrap();
assert_eq!(
format!("{line:?}"),
format!("LineString {{ coords: {:?} }}", line.coords())
);
assert_eq!(ring, LinearRing::new(unit_square_ccw()).unwrap());
}
}