use std::sync::OnceLock;
use crate::GeometryError;
use crate::types::coord::{Bbox, Coord2d, CoordSeq, bbox_of, check_coords};
#[derive(Clone)]
pub struct LineString {
coords: CoordSeq,
bbox: OnceLock<Bbox>,
}
impl PartialEq for LineString {
fn eq(&self, other: &Self) -> bool {
self.coords == other.coords
}
}
#[allow(clippy::missing_fields_in_debug)]
impl core::fmt::Debug for LineString {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("LineString")
.field("coords", &self.coords)
.finish()
}
}
impl LineString {
pub(crate) fn from_valid(coords: CoordSeq) -> Self {
debug_assert!(coords.len() >= 2);
Self {
coords,
bbox: OnceLock::new(),
}
}
pub fn new(coords: CoordSeq) -> Result<Self, GeometryError> {
check_coords(&coords)?;
if coords.len() < 2 {
return Err(GeometryError::InsufficientVertices {
required: 2,
found: coords.len(),
});
}
Ok(Self {
coords,
bbox: OnceLock::new(),
})
}
pub(crate) fn bbox(&self) -> Bbox {
*self.bbox.get_or_init(|| bbox_of(self.coords.as_slice()))
}
pub fn coords(&self) -> &CoordSeq {
&self.coords
}
pub fn num_points(&self) -> usize {
self.coords.len()
}
pub fn start(&self) -> Coord2d {
self.coords[0]
}
pub fn end(&self) -> Coord2d {
self.coords[self.coords.len() - 1]
}
}
#[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())
}
#[test]
fn rejects_fewer_than_two_coords() {
let err = LineString::new(seq(&[(0.0, 0.0)])).unwrap_err();
assert_eq!(
err,
GeometryError::InsufficientVertices {
required: 2,
found: 1
}
);
let err2 = LineString::new(seq(&[])).unwrap_err();
assert_eq!(
err2,
GeometryError::InsufficientVertices {
required: 2,
found: 0
}
);
}
#[test]
fn rejects_consecutive_duplicate_vertices() {
let err =
LineString::new(seq(&[(0.0, 0.0), (1.0, 1.0), (1.0, 1.0), (2.0, 2.0)])).unwrap_err();
assert_eq!(
err,
GeometryError::ConsecutiveDuplicateVertices { index: 1 }
);
}
#[test]
fn rejects_non_finite_coordinate() {
let err = LineString::new(seq(&[(f64::NAN, 0.0), (1.0, 1.0)])).unwrap_err();
assert_eq!(
err,
GeometryError::NonFiniteCoordinate {
coord_index: 0,
axis: 0
}
);
let err2 = LineString::new(seq(&[(0.0, f64::INFINITY), (1.0, 1.0)])).unwrap_err();
assert_eq!(
err2,
GeometryError::NonFiniteCoordinate {
coord_index: 0,
axis: 1
}
);
}
#[test]
fn non_finite_checked_before_length() {
let err = LineString::new(seq(&[(f64::NAN, 0.0)])).unwrap_err();
assert!(matches!(err, GeometryError::NonFiniteCoordinate { .. }));
}
#[test]
fn valid_line_string_accessors() {
let ls = LineString::new(seq(&[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)])).unwrap();
assert_eq!(ls.num_points(), 3);
assert_eq!(ls.start(), c(0.0, 0.0));
assert_eq!(ls.end(), c(1.0, 1.0));
}
}