{ } JustinGeoSci

Geometry types

The validated geometry types: every constructor checks its input, so a value that exists has passed its checks, and a result that cannot be vouched for is refused or explicitly marked.

Coordinates

Coordinates are scalar primitives rather than geometries. Coord2d and CoordSeq carry f64 values into the geometry constructors and back out of their accessors, and make no validity guarantees of their own. Both live in geometres::types and are re-exported at the crate root.

Coord2d

pub struct Coord2d { pub x: f64, pub y: f64 }

Coord2d is a pair of f64 values with public fields. Coord2d::new(x, y) performs no validation: NaN and ±infinity are accepted here and rejected later, by the constructor of whichever validated geometry receives the coordinate. A standalone Coord2d has no geometric meaning.

use geometres::types::{Coord2d, Point};

let c = Coord2d::new(3.0, 4.0);
assert_eq!((c.x, c.y), (3.0, 4.0));

// A non-finite coordinate is a legal Coord2d, but no geometry accepts it.
let bad = Coord2d::new(f64::NAN, 0.0);
assert!(Point::new(bad).is_err());

CoordSeq

pub struct CoordSeq(Vec<Coord2d>);

CoordSeq is a read-only, ordered buffer of Coord2d values with no closure semantics. CoordSeq::new(coords) stores the coordinates as given, without validation, and the type has no mutation methods: every coordinate is fixed at construction. Closure is a property of LinearRing, not of the sequence.

Read access is through len(), is_empty(), as_slice(), iter() and indexing.

use geometres::types::{Coord2d, CoordSeq};

let seq = CoordSeq::new(vec![Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 2.0)]);
assert_eq!(seq.len(), 2);
assert_eq!(seq[1], Coord2d::new(1.0, 2.0));
assert_eq!(seq.iter().map(|c| c.y).sum::<f64>(), 2.0);

Geometries

Every geometry constructor validates, so a value that exists has passed its checks: every coordinate is finite; every line and ring has enough distinct vertices, with no consecutive duplicates; every ring's winding is correct and its exact signed area is nonzero; every hole lies inside its exterior, holes are interior-disjoint, and a multipolygon's parts meet at most at finitely many points. The area signs are certified and the placement tests are exact.

The constructors are deliberately permissive beyond that. A value that exists may still be invalid in the OGC sense in exactly two ways: a ring may touch or cross itself, since simplicity is not checked at construction, and a polygon's interior may be disconnected, since holes touching the exterior and each other at points can chain into a cut. geometres::ops::is_valid and geometres::ops::validity_issues decide both exactly. All the types below live in geometres::types; all but ring_is_degenerate are re-exported at the crate root.

Point

pub fn new(coord: Coord2d) -> Result<Point, GeometryError>

Point wraps exactly one Coord2d whose components are both finite. The field is private, so no Point with a non-finite coordinate can exist, including one decoded from the native binary format. The exact predicates refuse non-finite input, and a non-finite coordinate that reached topology code as a zero sign would give a plausible wrong answer; making it unrepresentable removes that failure from every consumer at once.

The accessors are x(), y() and coord(). Point::try_from(coord) is equivalent to Point::new, and Coord2d::from(point) recovers the coordinate.

Errors: GeometryError::NonFiniteCoordinate, with coord_index 0 and axis 0 for x or 1 for y, if either component is NaN or infinite. When both are non-finite, x is reported.

use geometres::GeometryError;
use geometres::types::{Coord2d, Point};

let p = Point::new(Coord2d::new(1.5, -2.0)).unwrap();
assert_eq!((p.x(), p.y()), (1.5, -2.0));

assert_eq!(
    Point::new(Coord2d::new(0.0, f64::INFINITY)),
    Err(GeometryError::NonFiniteCoordinate { coord_index: 0, axis: 1 })
);

LineString

pub fn new(coords: CoordSeq) -> Result<LineString, GeometryError>

LineString is a polyline: an ordered list of two or more vertices joined by straight segments. The constructor checks, in order, that every coordinate is finite, that there are at least two vertices, and that no two consecutive vertices are identical. A line string may cross itself; simplicity is not a validity condition for it.

The accessors are coords(), num_points(), start() and end().

Errors: NonFiniteCoordinate (with the offending position and axis), InsufficientVertices for fewer than two coordinates, and ConsecutiveDuplicateVertices naming the first of two equal consecutive vertices.

use geometres::GeometryError;
use geometres::types::{Coord2d, CoordSeq, LineString};

let line = LineString::new(CoordSeq::new(vec![
    Coord2d::new(0.0, 0.0), Coord2d::new(3.0, 0.0), Coord2d::new(3.0, 4.0),
])).unwrap();
assert_eq!(line.num_points(), 3);
assert_eq!(line.end(), Coord2d::new(3.0, 4.0));

let one = CoordSeq::new(vec![Coord2d::new(0.0, 0.0)]);
assert_eq!(
    LineString::new(one).unwrap_err(),
    GeometryError::InsufficientVertices { required: 2, found: 1 }
);

let repeated = CoordSeq::new(vec![
    Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 1.0), Coord2d::new(1.0, 1.0),
]);
assert_eq!(
    LineString::new(repeated).unwrap_err(),
    GeometryError::ConsecutiveDuplicateVertices { index: 1 }
);

LinearRing

pub fn new(coords: CoordSeq) -> Result<LinearRing, GeometryError>

LinearRing is a closed ring of three or more distinct vertices. It closes implicitly: the edge from the last vertex back to the first is always present, and the closing vertex is not stored. If the input repeats its first coordinate at the end (the OGC closing vertex), that last coordinate is stripped before validation; it is the only implicit removal.

After stripping, the constructor checks finiteness, the minimum length, and consecutive duplicates including the wrap-around pair. It does not enforce winding, which is Polygon::new's job, and it does not check simplicity: a constructed ring may touch or cross itself.

Method Returns
coords(), num_vertices() The stored distinct vertices (closing vertex not included) and their count, which is also the number of edges.
edges() All n edges as (start, end) pairs, the implied closing edge last. The iterator is Clone.
signed_area() The shoelace area: positive for counterclockwise, negative for clockwise, zero for exactly zero area. The sign is exact for every finite result; the magnitude is accurate to about one rounding of the exact value, except where a product underflows below about 10−292. An overflowing product makes the result non-finite.
envelope() The ring's bounding box, computed on first use and kept. Returns Result, but cannot fail for a constructed ring.
is_simple() Whether no two edges properly cross, decided by exact orientation signs on the stored coordinates. Collinear overlapping non-consecutive edges are not reported, a documented limit.

Errors: NonFiniteCoordinate, InsufficientVertices if fewer than three vertices remain after stripping, and ConsecutiveDuplicateVertices.

use geometres::types::{Coord2d, CoordSeq, LinearRing};

// The closing vertex (0, 0) is stripped, leaving three stored vertices.
let ring = LinearRing::new(CoordSeq::new(vec![
    Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 0.0), Coord2d::new(0.0, 1.0), Coord2d::new(0.0, 0.0),
])).unwrap();
assert_eq!(ring.num_vertices(), 3);
assert_eq!(ring.edges().last(), Some((Coord2d::new(0.0, 1.0), Coord2d::new(0.0, 0.0))));
assert_eq!(ring.signed_area(), 0.5); // counterclockwise

Polygon

pub fn new(exterior: LinearRing, holes: Vec<LinearRing>) -> Result<Polygon, GeometryError>

Polygon is an exterior ring with zero or more hole rings, under the OGC winding convention: the exterior is counterclockwise and every hole is clockwise. Winding is read from the certified sign of the shoelace area, and a ring whose exact area is zero is refused before its winding is checked. Polygon::new_simple(exterior) is Polygon::new(exterior, vec![]).

The constructor also establishes that every hole lies inside the exterior and that holes are interior-disjoint. A hole is refused if it is disjoint from the exterior, crosses it, shares a stretch of its boundary, or surrounds it; one that lies inside and touches the exterior at isolated points is accepted. These tests are arithmetica::orient2d on the stored coordinates: no intersection point is constructed and no tolerance is applied. Together they make the net area of every Polygon strictly positive by construction.

The accessors are exterior(), holes() and num_holes().

Errors: checked on the exterior first, then on the holes in order, naming the first offender:

  • DegenerateRing if any ring has exact signed area zero;
  • IncorrectWindingOrder if the exterior is clockwise;
  • IncorrectHoleWindingOrder { hole_index } if a hole is counterclockwise;
  • HoleNotInsideExterior { hole_index } if a hole is not inside the exterior;
  • OverlappingHoles { first, second } if two holes have overlapping interiors.
use geometres::GeometryError;
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};

let ring = |v: &[(f64, f64)]| {
    LinearRing::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect())).unwrap()
};
let exterior = ring(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)]); // counterclockwise
let hole = ring(&[(1.0, 1.0), (1.0, 3.0), (3.0, 3.0), (3.0, 1.0)]);     // clockwise

let p = Polygon::new(exterior.clone(), vec![hole.clone()]).unwrap();
assert_eq!(p.num_holes(), 1);

// A clockwise exterior is refused rather than silently reversed.
let clockwise = ring(&[(0.0, 0.0), (0.0, 4.0), (4.0, 4.0), (4.0, 0.0)]);
assert_eq!(Polygon::new_simple(clockwise), Err(GeometryError::IncorrectWindingOrder));

// A clockwise ring outside the exterior is not a hole of it.
let outside = ring(&[(5.0, 1.0), (5.0, 2.0), (6.0, 2.0)]);
assert_eq!(
    Polygon::new(exterior.clone(), vec![outside]),
    Err(GeometryError::HoleNotInsideExterior { hole_index: 0 })
);

// Two holes whose interiors meet.
let other = ring(&[(2.0, 2.0), (2.0, 3.5), (3.5, 3.5), (3.5, 2.0)]);
assert_eq!(
    Polygon::new(exterior, vec![hole, other]),
    Err(GeometryError::OverlappingHoles { first: 0, second: 1 })
);

MultiPoint and MultiLineString

pub fn new(points: Vec<Point>) -> MultiPoint pub fn new(line_strings: Vec<LineString>) -> MultiLineString

MultiPoint and MultiLineString are assembled from already-validated elements, so their constructors are infallible. The collection adds no constraint of its own: there is no minimum count, duplicate points are permitted, and component lines may touch, cross, overlap or repeat. An empty collection is valid and represents the empty geometry; empty() builds one. Element order is preserved.

The accessors are points() and num_points() on MultiPoint, line_strings() and num_line_strings() on MultiLineString, and is_empty() on both.

use geometres::types::{Coord2d, CoordSeq, LineString, MultiLineString, MultiPoint, Point};

let p = Point::new(Coord2d::new(1.0, 1.0)).unwrap();
let mp = MultiPoint::new(vec![p, p]); // duplicates are permitted
assert_eq!(mp.num_points(), 2);
assert!(MultiPoint::empty().is_empty());

let a = LineString::new(CoordSeq::new(vec![Coord2d::new(0.0, 0.0), Coord2d::new(2.0, 2.0)])).unwrap();
let b = LineString::new(CoordSeq::new(vec![Coord2d::new(0.0, 2.0), Coord2d::new(2.0, 0.0)])).unwrap();
let crossing = MultiLineString::new(vec![a, b]); // components may cross
assert_eq!(crossing.num_line_strings(), 2);

MultiPolygon

pub fn new(polygons: Vec<Polygon>) -> Result<MultiPolygon, GeometryError>

MultiPolygon is a collection of polygons whose parts meet at most at finitely many points: their interiors are disjoint and their boundaries share no stretch of positive length. The constructor checks every pair of parts with a closed bounding-box prefilter and then the exact ring-placement predicate. An empty vector is accepted. The DE-9IM matrix rests on this invariant, so a multipolygon that broke it cannot be built.

The accessors are polygons(), num_polygons(), is_empty() and try_into_polygon(), which returns the single part when there is exactly one. MultiPolygon::from(polygon) always succeeds, and Polygon::try_from(multi) is the fallible converse. MultiPolygon::from_retained_parts(operand, keep) keeps the parts a closure accepts, in order, without re-running the pairwise check, since any subset of a valid multipolygon's parts is valid. from_parts runs the same check as new and returns the offending pair of part indices as its error.

Errors: OverlappingParts { first, second }, naming the first pair of parts whose interiors overlap or whose boundaries share a stretch.

use geometres::GeometryError;
use geometres::types::{Coord2d, CoordSeq, LinearRing, MultiPolygon, Polygon};

let square = |x: f64, y: f64| {
    let ring = LinearRing::new(CoordSeq::new(vec![
        Coord2d::new(x, y), Coord2d::new(x + 1.0, y),
        Coord2d::new(x + 1.0, y + 1.0), Coord2d::new(x, y + 1.0),
    ])).unwrap();
    Polygon::new_simple(ring).unwrap()
};

// Squares touching at one corner meet at a single point: accepted.
let corner = MultiPolygon::new(vec![square(0.0, 0.0), square(1.0, 1.0)]).unwrap();
assert_eq!(corner.num_polygons(), 2);

// Squares sharing an edge share a stretch of boundary: refused.
assert_eq!(
    MultiPolygon::new(vec![square(0.0, 0.0), square(1.0, 0.0)]),
    Err(GeometryError::OverlappingParts { first: 0, second: 1 })
);

// One part converts back to a Polygon.
let one = MultiPolygon::from(square(5.0, 5.0));
assert_eq!(one.try_into_polygon(), Some(square(5.0, 5.0)));

ring_is_degenerate

pub fn ring_is_degenerate(ring: &LinearRing) -> bool

ring_is_degenerate decides whether a ring's exact signed area is zero, the test Polygon::new applies to every ring. It is a permanent contract: exactly the rings whose vertices are all collinear, or whose lobes cancel exactly, are degenerate. No tolerance is involved, so a ring with nonzero area is never refused, however thin.

The test is exact because LinearRing::signed_area returns exactly 0.0 if and only if the exact area is zero: a compensated result of zero is never certified, so it always falls through to exact expansion arithmetic, which returns zero only for an exact zero. A non-finite area from overflow is not degenerate; Polygon::new refuses such a ring with NonFiniteResult instead. The function is reached as geometres::types::ring_is_degenerate.

use geometres::GeometryError;
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon, ring_is_degenerate};

// Three collinear vertices: a valid LinearRing, but one with zero area.
let flat = LinearRing::new(CoordSeq::new(vec![
    Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 1.0), Coord2d::new(2.0, 2.0),
])).unwrap();
assert!(ring_is_degenerate(&flat));
assert_eq!(Polygon::new_simple(flat), Err(GeometryError::DegenerateRing));

// A sliver one ulp off the line has nonzero area and is not degenerate.
let sliver = LinearRing::new(CoordSeq::new(vec![
    Coord2d::new(0.0, 0.0), Coord2d::new(2.0, 2.0), Coord2d::new(1.0, 1.0_f64.next_up()),
])).unwrap();
assert!(!ring_is_degenerate(&sliver));
assert!(Polygon::new_simple(sliver).is_ok());

Collections and operands

The Geometry enum holds a value of any geometry type, and GeometryCollection holds many, of any types. The Lineal and Polygonal traits let one function accept a single part or many. All are in geometres::types.

Geometry

#[non_exhaustive] pub enum Geometry { Point(Point), LineString(LineString), Polygon(Polygon), MultiPoint(MultiPoint), MultiLineString(MultiLineString), MultiPolygon(MultiPolygon), GeometryCollection(GeometryCollection) }

Geometry is a heterogeneous geometry value. Each variant wraps an already-validated type, so building a Geometry is infallible and adds no invariants of its own. The enum is #[non_exhaustive], so new variants can arrive in minor versions; a match on it needs a catch-all arm.

use geometres::types::{Coord2d, Geometry, Point};

let g = Geometry::Point(Point::new(Coord2d::new(2.0, 3.0)).unwrap());
let x = match &g {
    Geometry::Point(p) => p.x(),
    _ => f64::NAN, // required: the enum is non_exhaustive
};
assert_eq!(x, 2.0);

GeometryCollection

pub fn new(geometries: Vec<Geometry>) -> Result<GeometryCollection, GeometryError>

GeometryCollection holds geometries of any types, in order, including other collections. OGC imposes no condition between elements, so elements may overlap, repeat or touch; every element is valid by its own construction, and the only check here is the nesting depth. The depth counts collection levels: a collection of non-collections (or of nothing) has depth 1, and each level of collections inside it adds one.

The depth is at most GeometryCollection::MAX_NESTING, which is 32, a permanent contract of the type and of the native format. It bounds the recursion of the derived traits and of any caller's code that matches its way down. Because it is checked at construction, every collection that exists also encodes and decodes.

Method Returns
empty() The collection with no elements, of depth 1.
geometries(), into_geometries() The elements in construction order, borrowed or by value.
len(), depth() The number of direct elements (a nested collection counts as one) and the nesting depth.
is_empty() true if the collection has no points at all: no elements, or only empty ones, at any depth (OGC IsEmpty).
dimension() The highest dimension of any non-empty element at any depth, or Dimension::Empty.
envelope() The closed box of every element's coordinates, or None if empty. Each bound is an input coordinate selected by exact comparison.
leaves() A Leaves iterator over the non-collection elements (&Geometry), depth first in element order, at every depth. Nested collections are entered, not yielded. It walks an explicit stack and never recurses.

Errors: NestingTooDeep { limit } if an element is itself a collection of depth MAX_NESTING, so that the result would be deeper than the limit.

The predicates accept a collection when its polygonal leaves together form a valid MultiPolygon, and refuse it with CollectionElementsOverlap otherwise (see Predicates). The collection itself is still valid; the refusal belongs to relate, not to construction.

use geometres::GeometryError;
use geometres::topology::label::Dimension;
use geometres::types::{Coord2d, CoordSeq, Geometry, GeometryCollection, LineString, Point};

let p = Geometry::Point(Point::new(Coord2d::new(0.0, 0.0)).unwrap());
let l = Geometry::LineString(
    LineString::new(CoordSeq::new(vec![Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 0.0)])).unwrap(),
);
let inner = GeometryCollection::new(vec![p.clone()]).unwrap();
let outer = GeometryCollection::new(vec![Geometry::GeometryCollection(inner), l]).unwrap();

assert_eq!((outer.len(), outer.depth()), (2, 2));
assert_eq!(outer.leaves().count(), 2); // the point and the line
assert_eq!(outer.dimension(), Dimension::Line);

// Nest to the limit; one more level is refused.
let mut g = GeometryCollection::empty();
while g.depth() < GeometryCollection::MAX_NESTING {
    g = GeometryCollection::new(vec![Geometry::GeometryCollection(g)]).unwrap();
}
assert_eq!(
    GeometryCollection::new(vec![Geometry::GeometryCollection(g)]),
    Err(GeometryError::NestingTooDeep { limit: 32 })
);

Lineal and Polygonal

pub trait Lineal: sealed::Sealed { fn components(&self) -> &[LineString]; } pub trait Polygonal: sealed::Sealed { fn parts(&self) -> &[Polygon]; }

The operand traits let one function take a single part or many without a second family of entry points. Lineal is implemented by LineString (one component) and MultiLineString; Polygonal by Polygon (one part) and MultiPolygon. A Polygonal's parts are interior-disjoint and meet at most at finitely many points.

Both traits are sealed, implementable only inside the crate, because the operations rely on that promise and an outside implementation could hand back overlapping parts.

use geometres::types::{Coord2d, CoordSeq, LinearRing, MultiPolygon, Polygon, Polygonal};

fn part_count(g: &impl Polygonal) -> usize {
    g.parts().len()
}

let ring = LinearRing::new(CoordSeq::new(vec![
    Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 0.0), Coord2d::new(0.0, 1.0),
])).unwrap();
let p = Polygon::new_simple(ring).unwrap();
assert_eq!(part_count(&p), 1);
assert_eq!(part_count(&MultiPolygon::empty()), 0);

Envelope

Envelope is an axis-aligned rectangle with closed intervals, in geometres::types.

Envelope

pub fn new(min: Coord2d, max: Coord2d) -> Result<Envelope, GeometryError>

Envelope is given by its lower-left and upper-right corners. All four bounds are finite, with min_x ≤ max_x and min_y ≤ max_y. A degenerate envelope (zero width, zero height, or both) is valid: a point-sized or line-shaped query rectangle is legitimate. Only non-finite or inverted bounds are errors, since an inverted box would make every containment test silently false.

Envelope::from_points(points) returns the smallest envelope containing every point, or Ok(None) for an empty iterator. Each bound is chosen by exact comparison from the input values, so every bound is an input coordinate and nothing is computed. On a tie such as -0.0 against 0.0, the value met first is kept.

Method Returns
min(), max() The lower-left and upper-right corners.
width(), height() The extents. Exact when the subtraction is exact, correctly rounded otherwise; always finite and non-negative.
is_point() true if the extent is zero on both axes.
contains_coord(c) Whether c is inside or on the boundary. Closed on all four sides, by exact f64 comparison rather than a tolerance.
contains_envelope(other) Whether other lies entirely within, boundary included.
intersects(other) Whether the two share at least one point; envelopes touching only along an edge or at a corner intersect.

Errors: new returns NonFiniteCoordinate (coord_index 0 for min, 1 for max) or InvertedEnvelope. from_points returns NonFiniteCoordinate for the first non-finite value, checked before the bounds are updated, so a NaN can never be absorbed by a comparison that is false for it.

use geometres::GeometryError;
use geometres::types::{Coord2d, Envelope};

let e = Envelope::new(Coord2d::new(0.0, 0.0), Coord2d::new(4.0, 2.0)).unwrap();
assert_eq!((e.width(), e.height()), (4.0, 2.0));
assert!(e.contains_coord(Coord2d::new(4.0, 2.0))); // a corner is contained

// Touching along an edge counts as intersecting.
let right = Envelope::new(Coord2d::new(4.0, 0.0), Coord2d::new(6.0, 1.0)).unwrap();
assert!(e.intersects(&right));

// Degenerate is valid; inverted is not.
assert!(Envelope::new(Coord2d::new(1.0, 0.0), Coord2d::new(1.0, 5.0)).is_ok());
assert_eq!(
    Envelope::new(Coord2d::new(4.0, 0.0), Coord2d::new(0.0, 2.0)),
    Err(GeometryError::InvertedEnvelope)
);

// The bounds of from_points are input values, selected rather than computed.
let pts = [Coord2d::new(3.0, -1.0), Coord2d::new(-2.0, 5.0), Coord2d::new(0.5, 0.5)];
let b = Envelope::from_points(pts).unwrap().unwrap();
assert_eq!((b.min(), b.max()), (Coord2d::new(-2.0, -1.0), Coord2d::new(3.0, 5.0)));
assert_eq!(Envelope::from_points(Vec::new()), Ok(None));

3D types

The 3D types live in geometres::types3d and are available only under the 3d feature. They mirror the 2D types with an added z component, as separate types rather than 2D types with an optional Z: Coord3d, CoordSeq3d, Point3d, LineString3d, LinearRing3d, Polygon3d, MultiPoint3d, MultiLineString3d and MultiPolygon3d.

Polygon3d and the XY projection

pub fn new(exterior: LinearRing3d, holes: Vec<LinearRing3d>) -> Result<Polygon3d, GeometryError>

All topology in geometres operates on the XY projection. Z is stored and round-tripped but takes no part in any predicate. Consequently Polygon3d::new decides winding relative to the +Z axis: the exterior must be counterclockwise viewed from above and every hole clockwise, with the sign certified as the sign of the exact area of the ring's XY projection. Hole placement is decided exactly on the projection with the same primitives Polygon::new uses. Planarity is not verified.

The convention is tied to the global +Z axis, not to the polygon's own plane. A ring in a vertical plane has a zero-area projection and is always refused with DegenerateRing. Likewise MultiPolygon3d::new refuses parts whose projections overlap, even at different heights: the rule is the 2D rule applied in plan, not a rule about solids.

Errors: as Polygon::new, decided on the projection, plus DegenerateRing when two consecutive vertices are equal in x and y, and NonFiniteResult when a projected area overflows. The 3D constructors report a non-finite z with axis: 2.

use geometres::GeometryError;
use geometres::types3d::{Coord3d, CoordSeq3d, LinearRing3d, MultiPolygon3d, Polygon3d};

let ring = |v: &[(f64, f64, f64)]| {
    LinearRing3d::new(CoordSeq3d::new(v.iter().map(|&(x, y, z)| Coord3d::new(x, y, z)).collect())).unwrap()
};

// A tilted unit square, counterclockwise when viewed from above.
let roof = Polygon3d::new_simple(ring(&[
    (0.0, 0.0, 5.0), (1.0, 0.0, 6.0), (1.0, 1.0, 7.0), (0.0, 1.0, 6.0),
])).unwrap();
assert_eq!(roof.exterior().num_vertices(), 4);

// A wall: its XY projection has no area, so no winding can be read.
let wall = ring(&[(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.0, 1.0)]);
assert_eq!(Polygon3d::new_simple(wall), Err(GeometryError::DegenerateRing));

// Two triangles stacked at different heights overlap in plan.
let low = Polygon3d::new_simple(ring(&[(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0)])).unwrap();
let high = Polygon3d::new_simple(ring(&[(0.0, 0.0, 9.0), (1.0, 0.0, 9.0), (1.0, 1.0, 9.0)])).unwrap();
assert_eq!(
    MultiPolygon3d::new(vec![low, high]),
    Err(GeometryError::OverlappingParts { first: 0, second: 1 })
);

Errors and vouched results

A result is either vouched for exactly or refused. Where an operation can produce a geometry that fails its vouch, the default entry point returns an error, and the broken value is offered only through an explicit *_unvouched entry point, wrapped so that it cannot pass for a valid one. The types for this are in geometres::types; GeometryError is at the crate root.

GeometryError

#[non_exhaustive] pub enum GeometryError

GeometryError is the error of the geometry constructors and validators. Each variant carries enough context (an index, an axis, a pair) to identify the failing coordinate or element without re-examining the input. It implements Display and std::error::Error, and is #[non_exhaustive], so a match needs a catch-all arm.

Variant Meaning
InsufficientVertices { required, found } Fewer vertices than the type requires.
ConsecutiveDuplicateVertices { index } Two consecutive vertices are identical; index is the first.
NonFiniteCoordinate { coord_index, axis } A NaN or infinite value; axis is 0 for x, 1 for y, 2 for z.
IncorrectWindingOrder The exterior ring is not counterclockwise.
IncorrectHoleWindingOrder { hole_index } A hole ring is not clockwise.
HoleNotInsideExterior { hole_index } A hole is disjoint from the exterior, crosses it, shares a stretch of it, or surrounds it.
OverlappingHoles { first, second } Two holes have overlapping interiors.
DegenerateRing A ring has exact signed area zero and cannot be oriented.
OverlappingParts { first, second } Two parts of a multipolygon overlap or share a stretch of boundary.
NotASinglePolygon A multipolygon converted to a polygon does not hold exactly one part.
InvertedEnvelope An envelope with min > max on some axis.
NestingTooDeep { limit } A collection would nest deeper than MAX_NESTING.
CollectionElementsOverlap { first, second } relate refused a collection whose polygonal leaves overlap; the fields are the two leaves' paths.
NonFiniteResult A value of the computation overflowed; no finite answer can be vouched for.
Unvouched { reason, inputs } A vouched entry point refused its result; reason is the same UnvouchedReason the unvouched entry point would attach.
InvalidTolerance, InvalidCoverage, NotNoded, EmptyOperand, NotSequenceable, PointNotOnLineInterior, TooManyEntries Raised by the operations, the index and preparation, and documented with them.
use geometres::GeometryError;
use geometres::types::{Coord2d, CoordSeq, LineString};

let err = LineString::new(CoordSeq::new(vec![
    Coord2d::new(0.0, 0.0), Coord2d::new(f64::NAN, 1.0),
])).unwrap_err();
assert_eq!(err, GeometryError::NonFiniteCoordinate { coord_index: 1, axis: 0 });
assert_eq!(err.to_string(), "non-finite x coordinate at index 1");

Unvouched

pub struct Unvouched<T>

Unvouched<T> wraps a geometry that could be produced but not vouched for, because it is invalid. A caller that asks for it states that it would rather inspect a broken answer than have none. The wrapper keeps that choice explicit: it implements no Deref, AsRef, Borrow or Into, has no public field, and does not satisfy a signature expecting T, so an invalid result cannot reenter an exact computation without notice.

reason() reads the UnvouchedReason without touching the value, so a caller can decide whether to accept the geometry before extracting it. inner() borrows the value, into_inner() takes it, and into_parts() splits value and reason. Unvouched::new(value, reason) wraps a value known to be invalid.

use geometres::GeometryError;
use geometres::types::{Coord2d, CoordSeq, LinearRing, MaybeVouched, Polygon, UnvouchedReason};

let ring = |v: &[(f64, f64)]| {
    LinearRing::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect())).unwrap()
};
// A valid, simple pentagon.
let p = Polygon::new_simple(ring(&[(6.0, 5.0), (5.0, 6.0), (2.0, 2.0), (5.0, 5.0), (4.0, 1.0)])).unwrap();

// Simplifying at tolerance 1.5 drops (5, 6), and the remaining edge
// (6, 5)-(2, 2) crosses the edge (5, 5)-(4, 1). The vouched entry point refuses.
let reason = UnvouchedReason::SelfIntersecting { edges: (0, 2) };
assert_eq!(p.simplify(1.5), Err(GeometryError::Unvouched { reason, inputs: vec![] }));

// The unvouched entry point hands the broken polygon back, marked.
let MaybeVouched::Unvouched(u) = p.simplify_unvouched(1.5).unwrap() else { panic!() };
assert_eq!(*u.reason(), reason);
assert!(u.reason().is_locally_invalid());
assert_eq!(u.inner().exterior().num_vertices(), 4);

UnvouchedReason

#[non_exhaustive] pub enum UnvouchedReason

UnvouchedReason records why a geometry could not be vouched for, in one of two classes that a consumer must be able to tell apart without string matching:

  • Locally invalid (is_locally_invalid()): roughly the right answer, locally broken. A consumer may repair it, snap it, or accept it with a warning. Examples are SelfIntersecting { edges }, RingSelfIntersecting { ring, edges }, PartSelfIntersecting { part, ring, edges } and DegenerateRing { ring }.
  • Structurally wrong (is_structurally_wrong()): the true answer has a different shape than the return type can express, such as RequiresMultiplePolygons, RequiresHole or HoleExceedsExterior { hole }. This is a different answer rather than a degraded one, and a consumer should refuse it whatever its tolerance for local damage.

is_structurally_wrong is defined as the complement of is_locally_invalid, so a variant added later without classification defaults to the refusing class. Diagnostics name edges by index rather than by a crossing point: an index is exact and requires no construction, while an intersection point requires a division and is approximate.

use geometres::types::UnvouchedReason;

let crossing = UnvouchedReason::SelfIntersecting { edges: (0, 2) };
assert!(crossing.is_locally_invalid());
assert!(!crossing.is_structurally_wrong());

// Two polygons are not a degraded single polygon.
assert!(UnvouchedReason::RequiresMultiplePolygons.is_structurally_wrong());

MaybeVouched

pub enum MaybeVouched<T, U = T> { Vouched(T), Unvouched(Unvouched<U>) }

MaybeVouched is the answer of an *_unvouched entry point. Such an entry point runs the same vouch as its default counterpart and reports what it found: Vouched for a result that passed every check, Unvouched with the reason for one that did not. The two outcomes are kept apart because wrapping a valid result in Unvouched would mean inventing a reason. The unvouched type U may differ from T when the refused value is not an instance of T; it defaults to T.

vouched() returns the vouched value, or the refusal the default entry point would have returned (GeometryError::Unvouched with the reason). is_vouched() tests the outcome, and into_parts(), available when both arms hold the same type, returns the value with Some(reason) if it was not vouched.

Errors: vouched() returns Err when the result was not vouched for.

use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};

let square = Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
    Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 0.0), Coord2d::new(1.0, 1.0), Coord2d::new(0.0, 1.0),
])).unwrap()).unwrap();

// Tolerance zero is the identity, and the vouch passes.
let r = square.simplify_unvouched(0.0).unwrap();
assert!(r.is_vouched());
let (value, reason) = r.into_parts();
assert_eq!(value, square);
assert_eq!(reason, None);