dmvs 0.1.1

Async high-level client for selected Czech ČÚZK DMVS SOAP services
Documentation
use std::fmt;

use geo_types::{LineString, MultiPolygon, Polygon};

use crate::{Error, Result};

/// Coordinate reference system attached to a DMVS area.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum CoordinateReferenceSystem {
    /// S-JTSK / EPSG:5514, serialized as `urn:ogc:def:crs:EPSG::5514`.
    Sjtsk,
    /// Another explicitly supplied GML `srsName`, preserved without reprojection.
    Other(String),
}

impl CoordinateReferenceSystem {
    /// Creates a CRS from an explicit GML `srsName`.
    pub fn new(srs_name: impl Into<String>) -> Result<Self> {
        let value = srs_name.into();
        if value.is_empty()
            || value.len() > 2048
            || value.trim() != value
            || value.chars().any(char::is_control)
        {
            return Err(Error::invalid_input(
                "area.crs",
                "expected a non-empty, trimmed GML srsName without control characters",
            ));
        }
        Ok(match value.as_str() {
            "urn:ogc:def:crs:EPSG::5514" => Self::Sjtsk,
            _ => Self::Other(value),
        })
    }

    /// Returns the exact GML `srsName`.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Sjtsk => "urn:ogc:def:crs:EPSG::5514",
            Self::Other(value) => value,
        }
    }
}

/// Public geometry variants accepted by DMVS area operations.
#[derive(Clone, PartialEq)]
pub enum AreaGeometry {
    /// One `geo-types` polygon.
    Polygon(Polygon<f64>),
    /// A polygon-only multi-surface represented by `geo-types`.
    MultiPolygon(MultiPolygon<f64>),
}

impl fmt::Debug for AreaGeometry {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (variant, polygon_count) = match self {
            Self::Polygon(_) => ("Polygon", 1),
            Self::MultiPolygon(value) => ("MultiPolygon", value.0.len()),
        };
        formatter
            .debug_struct("AreaGeometry")
            .field("variant", &variant)
            .field("polygon_count", &polygon_count)
            .finish()
    }
}

impl From<Polygon<f64>> for AreaGeometry {
    fn from(value: Polygon<f64>) -> Self {
        Self::Polygon(value)
    }
}

impl From<MultiPolygon<f64>> for AreaGeometry {
    fn from(value: MultiPolygon<f64>) -> Self {
        Self::MultiPolygon(value)
    }
}

/// A validated polygon or multipolygon with an explicit coordinate reference system.
///
/// Coordinates are never reordered or reprojected. Validation covers finite
/// coordinates, nonempty geometry, closed rings, and at least four positions per
/// ring; it is not a claim of complete OGC validity.
#[derive(Clone, PartialEq)]
pub struct Area {
    geometry: AreaGeometry,
    crs: CoordinateReferenceSystem,
}

impl Area {
    /// Validates an area and attaches its explicit CRS.
    pub fn new(geometry: impl Into<AreaGeometry>, crs: CoordinateReferenceSystem) -> Result<Self> {
        let area = Self {
            geometry: geometry.into(),
            crs,
        };
        area.validate()?;
        Ok(area)
    }

    /// Creates an area in the documented S-JTSK / EPSG:5514 CRS.
    pub fn s_jtsk(geometry: impl Into<AreaGeometry>) -> Result<Self> {
        Self::new(geometry, CoordinateReferenceSystem::Sjtsk)
    }

    /// Returns the public `geo-types` geometry.
    pub fn geometry(&self) -> &AreaGeometry {
        &self.geometry
    }

    /// Returns the explicit CRS.
    pub fn crs(&self) -> &CoordinateReferenceSystem {
        &self.crs
    }

    /// Consumes the area and returns its geometry and CRS.
    pub fn into_parts(self) -> (AreaGeometry, CoordinateReferenceSystem) {
        (self.geometry, self.crs)
    }

    pub(crate) fn validate(&self) -> Result<()> {
        match &self.geometry {
            AreaGeometry::Polygon(polygon) => validate_polygon(polygon),
            AreaGeometry::MultiPolygon(multipolygon) => {
                if multipolygon.0.is_empty() {
                    return Err(Error::invalid_input(
                        "area.geometry",
                        "a multipolygon must contain at least one polygon",
                    ));
                }
                for polygon in &multipolygon.0 {
                    validate_polygon(polygon)?;
                }
                Ok(())
            }
        }
    }

    pub(crate) fn ensure_maximum_s_jtsk_area(&self, maximum_square_metres: f64) -> Result<()> {
        if self.crs != CoordinateReferenceSystem::Sjtsk {
            return Err(Error::invalid_input(
                "area.crs",
                "the client-side area limit can only be evaluated for S-JTSK coordinates",
            ));
        }
        let area = match &self.geometry {
            AreaGeometry::Polygon(polygon) => polygon_area(polygon),
            AreaGeometry::MultiPolygon(multipolygon) => {
                multipolygon.0.iter().map(polygon_area).sum()
            }
        };
        if !area.is_finite() {
            return Err(Error::invalid_input(
                "area.geometry",
                "planar area must be finite",
            ));
        }
        if area > maximum_square_metres {
            return Err(Error::invalid_input(
                "area.geometry",
                format!("planar area exceeds the {maximum_square_metres} m² limit"),
            ));
        }
        Ok(())
    }
}

impl fmt::Debug for Area {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let polygon_count = match &self.geometry {
            AreaGeometry::Polygon(_) => 1,
            AreaGeometry::MultiPolygon(value) => value.0.len(),
        };
        formatter
            .debug_struct("Area")
            .field("polygon_count", &polygon_count)
            .field("crs", &self.crs)
            .finish_non_exhaustive()
    }
}

fn validate_polygon(polygon: &Polygon<f64>) -> Result<()> {
    validate_ring(polygon.exterior())?;
    for ring in polygon.interiors() {
        validate_ring(ring)?;
    }
    Ok(())
}

fn validate_ring(ring: &LineString<f64>) -> Result<()> {
    if ring.0.len() < 4 {
        return Err(Error::invalid_input(
            "area.geometry",
            "each polygon ring needs at least four positions",
        ));
    }
    if ring.0.first() != ring.0.last() {
        return Err(Error::invalid_input(
            "area.geometry",
            "each polygon ring must be explicitly closed",
        ));
    }
    if ring
        .0
        .iter()
        .any(|coordinate| !coordinate.x.is_finite() || !coordinate.y.is_finite())
    {
        return Err(Error::invalid_input(
            "area.geometry",
            "polygon coordinates must be finite",
        ));
    }
    Ok(())
}

fn polygon_area(polygon: &Polygon<f64>) -> f64 {
    let exterior = ring_area(polygon.exterior());
    let holes: f64 = polygon.interiors().iter().map(ring_area).sum();
    (exterior - holes).abs()
}

fn ring_area(ring: &LineString<f64>) -> f64 {
    ring.0
        .windows(2)
        .map(|pair| pair[0].x * pair[1].y - pair[1].x * pair[0].y)
        .sum::<f64>()
        .abs()
        / 2.0
}

#[cfg(test)]
mod tests {
    use geo_types::coord;

    use super::*;

    pub(crate) fn square() -> Polygon<f64> {
        Polygon::new(
            LineString::from(vec![
                coord! { x: 0.0, y: 0.0 },
                coord! { x: 100.0, y: 0.0 },
                coord! { x: 100.0, y: 100.0 },
                coord! { x: 0.0, y: 100.0 },
                coord! { x: 0.0, y: 0.0 },
            ]),
            Vec::new(),
        )
    }

    #[test]
    fn validates_rings_and_redacts_coordinates_from_debug() {
        let area = Area::s_jtsk(square()).unwrap();
        let debug = format!("{area:?}");
        assert!(!debug.contains("100.0"));
        assert_eq!(area.crs(), &CoordinateReferenceSystem::Sjtsk);

        let open = Polygon::new(
            LineString::from(vec![
                coord! { x: 0.0, y: 0.0 },
                coord! { x: 1.0, y: 0.0 },
                coord! { x: 1.0, y: 1.0 },
                coord! { x: 0.0, y: 1.0 },
            ]),
            Vec::new(),
        );
        // geo-types closes Polygon::new rings before the Area boundary.
        assert!(Area::s_jtsk(open).is_ok());
        assert!(Area::s_jtsk(Polygon::empty()).is_err());
        assert!(Area::s_jtsk(MultiPolygon(Vec::new())).is_err());
    }

    #[test]
    fn area_geometry_debug_contains_only_variant_and_polygon_count() {
        let polygon = Polygon::new(
            LineString::from(vec![
                coord! { x: 123_456.789, y: 987_654.321 },
                coord! { x: 123_456.789, y: 0.0 },
                coord! { x: 0.0, y: 0.0 },
                coord! { x: 123_456.789, y: 987_654.321 },
            ]),
            Vec::new(),
        );
        let area = Area::s_jtsk(polygon.clone()).unwrap();
        let polygon_debug = format!("{:?}", area.geometry());
        assert_eq!(
            polygon_debug,
            "AreaGeometry { variant: \"Polygon\", polygon_count: 1 }"
        );
        assert!(!polygon_debug.contains("123456.789"));
        assert!(!polygon_debug.contains("987654.321"));

        let multi_debug = format!(
            "{:?}",
            AreaGeometry::MultiPolygon(MultiPolygon(vec![polygon.clone(), polygon]))
        );
        assert_eq!(
            multi_debug,
            "AreaGeometry { variant: \"MultiPolygon\", polygon_count: 2 }"
        );
        assert!(!multi_debug.contains("123456.789"));
    }

    #[test]
    fn rejects_nonfinite_area_from_extreme_finite_coordinates() {
        let ring = LineString::from(vec![
            coord! { x: 0.0, y: 0.0 },
            coord! { x: f64::MAX, y: 0.0 },
            coord! { x: f64::MAX, y: f64::MAX },
            coord! { x: 0.0, y: f64::MAX },
            coord! { x: 0.0, y: 0.0 },
        ]);
        let polygon = Polygon::new(ring.clone(), vec![ring]);
        assert!(polygon_area(&polygon).is_nan());

        let area = Area::s_jtsk(polygon).unwrap();
        assert!(area.ensure_maximum_s_jtsk_area(f64::MAX).is_err());
    }

    #[test]
    fn computes_only_explicit_s_jtsk_planar_area_limit() {
        let area = Area::s_jtsk(square()).unwrap();
        assert!(area.ensure_maximum_s_jtsk_area(10_000.0).is_ok());
        assert!(area.ensure_maximum_s_jtsk_area(9_999.0).is_err());
        let other = Area::new(
            square(),
            CoordinateReferenceSystem::new("urn:ogc:def:crs:EPSG::4326").unwrap(),
        )
        .unwrap();
        assert!(other.ensure_maximum_s_jtsk_area(20_000.0).is_err());
    }
}