delaunay 0.8.0

D-dimensional Delaunay triangulations and convex hulls in Rust, with exact predicates, deterministic degeneracy handling, explicit topology validation, and bistellar flips for finite point sets.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! Validated coordinate-range types.

#![forbid(unsafe_code)]

use crate::geometry::traits::coordinate::FiniteCheck;
pub use crate::geometry::traits::coordinate::InvalidCoordinateValue;
use core::fmt::{self, Debug, Display};

/// Identifies which coordinate-range bound failed validation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum CoordinateRangeBound {
    /// Lower coordinate bound.
    Minimum,
    /// Upper coordinate bound.
    Maximum,
}

impl fmt::Display for CoordinateRangeBound {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Minimum => f.write_str("minimum"),
            Self::Maximum => f.write_str("maximum"),
        }
    }
}

/// The ordering failure for a coordinate range whose bounds are finite.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum CoordinateRangeOrdering {
    /// The bounds are equal.
    Equal,
    /// The minimum bound is greater than the maximum bound.
    Decreasing,
    /// The bounds cannot be ordered.
    Incomparable,
}

impl fmt::Display for CoordinateRangeOrdering {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Equal => f.write_str("equal"),
            Self::Decreasing => f.write_str("decreasing"),
            Self::Incomparable => f.write_str("incomparable"),
        }
    }
}

/// Errors that can occur while constructing validated coordinate ranges.
///
/// Non-finite bounds are reported as [`InvalidCoordinateValue`] categories.
/// Finite but non-increasing bounds preserve their typed `min` and `max`
/// values so callers can inspect the rejected range without parsing a display
/// string. Bounds that cannot be compared are rejected as
/// [`CoordinateRangeOrdering::Incomparable`].
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::geometry::{CoordinateRangeError, CoordinateRangeOrdering};
///
/// let err = CoordinateRangeError::NonIncreasing {
///     ordering: CoordinateRangeOrdering::Decreasing,
///     min: 1.0,
///     max: 0.0,
/// };
/// std::assert_matches!(err, CoordinateRangeError::NonIncreasing { .. });
/// ```
#[derive(Clone, Debug, thiserror::Error, PartialEq)]
#[non_exhaustive]
pub enum CoordinateRangeError<T = f64> {
    /// A coordinate range bound is non-finite.
    #[error("Invalid coordinate range: {bound} bound is non-finite: {value}")]
    NonFiniteBound {
        /// Which bound failed validation.
        bound: CoordinateRangeBound,
        /// The non-finite bound value.
        value: InvalidCoordinateValue,
    },

    /// Finite coordinate bounds are not strictly increasing.
    #[error(
        "Invalid coordinate range: minimum {min:?} and maximum {max:?} must satisfy min < max ({ordering})"
    )]
    NonIncreasing {
        /// Ordering failure category.
        ordering: CoordinateRangeOrdering,
        /// The minimum value of the range.
        min: T,
        /// The maximum value of the range.
        max: T,
    },
}

/// Finite, strictly increasing coordinate bounds.
///
/// `CoordinateRange<T>` carries the invariant that both bounds are finite and
/// `min < max`, so callers and geometry internals can pass validated bounds
/// inward without rechecking raw tuple bounds at every use site.
///
/// # Examples
///
/// ```
/// use delaunay::prelude::geometry::{CoordinateRange, CoordinateRangeError};
///
/// # fn main() -> Result<(), CoordinateRangeError> {
/// let range = CoordinateRange::try_new(-1.0_f64, 1.0)?;
/// assert_eq!(range.min(), -1.0);
/// assert_eq!(range.max(), 1.0);
/// assert_eq!(range.bounds(), (-1.0, 1.0));
/// # Ok(())
/// # }
/// ```
#[must_use]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CoordinateRange<T> {
    min: T,
    max: T,
}

impl<T> CoordinateRange<T>
where
    T: Debug + FiniteCheck + PartialOrd,
{
    /// Creates a coordinate range from raw bounds.
    ///
    /// # Errors
    ///
    /// Returns [`CoordinateRangeError::NonFiniteBound`] if either bound is
    /// non-finite, or [`CoordinateRangeError::NonIncreasing`] if the bounds are
    /// equal, decreasing, or incomparable.
    ///
    /// # Examples
    ///
    /// ```
    /// use delaunay::prelude::geometry::{CoordinateRange, CoordinateRangeError};
    ///
    /// # fn main() -> Result<(), CoordinateRangeError> {
    /// let range = CoordinateRange::try_new(0.0_f64, 1.0)?;
    /// assert_eq!(range.bounds(), (0.0, 1.0));
    /// # Ok(())
    /// # }
    /// ```
    pub fn try_new(min: T, max: T) -> Result<Self, CoordinateRangeError<T>> {
        if !min.is_finite_generic() {
            return Err(CoordinateRangeError::NonFiniteBound {
                bound: CoordinateRangeBound::Minimum,
                value: InvalidCoordinateValue::from_debug(&min),
            });
        }

        if !max.is_finite_generic() {
            return Err(CoordinateRangeError::NonFiniteBound {
                bound: CoordinateRangeBound::Maximum,
                value: InvalidCoordinateValue::from_debug(&max),
            });
        }

        let ordering = match min.partial_cmp(&max) {
            Some(core::cmp::Ordering::Less) => return Ok(Self { min, max }),
            Some(core::cmp::Ordering::Equal) => CoordinateRangeOrdering::Equal,
            Some(core::cmp::Ordering::Greater) => CoordinateRangeOrdering::Decreasing,
            None => CoordinateRangeOrdering::Incomparable,
        };

        Err(CoordinateRangeError::NonIncreasing { ordering, min, max })
    }
}

impl<T> CoordinateRange<T> {
    /// Creates a coordinate range from finite bounds already proven to satisfy `min < max`.
    ///
    /// This constructor is restricted to the geometry module so public callers
    /// must still use [`CoordinateRange::try_new`] or [`TryFrom`].
    pub(in crate::geometry) const fn from_validated_bounds(min: T, max: T) -> Self {
        Self { min, max }
    }

    /// Consumes the range and returns it as a raw `(min, max)` tuple.
    ///
    /// # Examples
    ///
    /// ```
    /// use delaunay::prelude::geometry::{CoordinateRange, CoordinateRangeError};
    ///
    /// # fn main() -> Result<(), CoordinateRangeError> {
    /// let range = CoordinateRange::try_new(-1.0_f64, 2.0)?;
    /// assert_eq!(range.bounds(), (-1.0, 2.0));
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn bounds(self) -> (T, T) {
        (self.min, self.max)
    }

    /// Returns the lower coordinate bound.
    ///
    /// # Examples
    ///
    /// ```
    /// use delaunay::prelude::geometry::{CoordinateRange, CoordinateRangeError};
    ///
    /// # fn main() -> Result<(), CoordinateRangeError> {
    /// let range = CoordinateRange::try_new(-1.0_f64, 2.0)?;
    /// assert_eq!(range.min(), -1.0);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn min(self) -> T {
        self.min
    }

    /// Returns the upper coordinate bound.
    ///
    /// # Examples
    ///
    /// ```
    /// use delaunay::prelude::geometry::{CoordinateRange, CoordinateRangeError};
    ///
    /// # fn main() -> Result<(), CoordinateRangeError> {
    /// let range = CoordinateRange::try_new(-1.0_f64, 2.0)?;
    /// assert_eq!(range.max(), 2.0);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn max(self) -> T {
        self.max
    }
}

impl<T> TryFrom<(T, T)> for CoordinateRange<T>
where
    T: Debug + FiniteCheck + PartialOrd,
{
    type Error = CoordinateRangeError<T>;

    fn try_from(bounds: (T, T)) -> Result<Self, Self::Error> {
        Self::try_new(bounds.0, bounds.1)
    }
}

impl<T> From<CoordinateRange<T>> for (T, T) {
    fn from(range: CoordinateRange<T>) -> Self {
        (range.min, range.max)
    }
}

impl<T: Display> fmt::Display for CoordinateRange<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[{}, {}]", self.min, self.max)
    }
}

#[cfg(test)]
mod tests {
    use super::{
        CoordinateRange, CoordinateRangeBound, CoordinateRangeError, CoordinateRangeOrdering,
        InvalidCoordinateValue,
    };
    use crate::geometry::traits::coordinate::FiniteCheck;
    use approx::assert_relative_eq;
    use std::assert_matches;

    #[derive(Debug, PartialEq, PartialOrd)]
    struct NonCopyFiniteScalar(i32);

    impl FiniteCheck for NonCopyFiniteScalar {
        fn is_finite_generic(&self) -> bool {
            true
        }
    }

    #[derive(Debug, PartialEq, PartialOrd)]
    struct CustomNonFiniteScalar(&'static str);

    impl FiniteCheck for CustomNonFiniteScalar {
        fn is_finite_generic(&self) -> bool {
            false
        }
    }

    #[derive(Debug, PartialEq)]
    struct IncomparableFiniteScalar(i32);

    impl PartialOrd for IncomparableFiniteScalar {
        fn partial_cmp(&self, _other: &Self) -> Option<core::cmp::Ordering> {
            None
        }
    }

    impl FiniteCheck for IncomparableFiniteScalar {
        fn is_finite_generic(&self) -> bool {
            true
        }
    }

    /// Asserts that finite raw coordinate bounds are rejected with the exact diagnostic payload.
    fn assert_non_increasing_bounds(
        result: &Result<CoordinateRange<f64>, CoordinateRangeError>,
        expected_ordering: CoordinateRangeOrdering,
        expected_min: f64,
        expected_max: f64,
    ) {
        let Err(CoordinateRangeError::NonIncreasing { ordering, min, max }) = result else {
            panic!("expected non-increasing coordinate bounds");
        };
        assert_eq!(*ordering, expected_ordering);
        assert_relative_eq!(*min, expected_min, epsilon = f64::EPSILON);
        assert_relative_eq!(*max, expected_max, epsilon = f64::EPSILON);
    }

    /// Asserts that a non-finite coordinate bound is rejected with the typed payload.
    fn assert_non_finite_bound(
        result: Result<CoordinateRange<f64>, CoordinateRangeError>,
        expected_bound: CoordinateRangeBound,
        expected_value: &InvalidCoordinateValue,
    ) {
        let Err(CoordinateRangeError::NonFiniteBound { bound, value }) = result else {
            panic!("expected non-finite coordinate bound");
        };
        assert_eq!(bound, expected_bound);
        assert_eq!(&value, expected_value);
    }

    #[test]
    fn accepts_f64_finite_increasing_bounds() {
        let range = CoordinateRange::try_new(-2.0_f64, 3.5).unwrap();
        let converted = CoordinateRange::try_from((-2.0_f64, 3.5)).unwrap();
        let raw_bounds = <(f64, f64)>::from(range);

        assert_relative_eq!(range.min(), -2.0, epsilon = f64::EPSILON);
        assert_relative_eq!(range.max(), 3.5, epsilon = f64::EPSILON);
        assert_relative_eq!(range.bounds().0, -2.0, epsilon = f64::EPSILON);
        assert_relative_eq!(range.bounds().1, 3.5, epsilon = f64::EPSILON);
        assert_relative_eq!(converted.min(), range.min(), epsilon = f64::EPSILON);
        assert_relative_eq!(converted.max(), range.max(), epsilon = f64::EPSILON);
        assert_relative_eq!(raw_bounds.0, -2.0, epsilon = f64::EPSILON);
        assert_relative_eq!(raw_bounds.1, 3.5, epsilon = f64::EPSILON);
    }

    #[test]
    fn bounds_does_not_require_copy_scalar() {
        let range = CoordinateRange::try_new(NonCopyFiniteScalar(1), NonCopyFiniteScalar(2))
            .expect("test scalar is finite and increasing");

        let (min, max) = range.bounds();

        assert_eq!(min, NonCopyFiniteScalar(1));
        assert_eq!(max, NonCopyFiniteScalar(2));
    }

    #[test]
    fn rejects_incomparable_finite_bounds() {
        assert_matches!(
            CoordinateRange::try_new(IncomparableFiniteScalar(0), IncomparableFiniteScalar(1)),
            Err(CoordinateRangeError::NonIncreasing {
                ordering: CoordinateRangeOrdering::Incomparable,
                min: IncomparableFiniteScalar(0),
                max: IncomparableFiniteScalar(1),
            })
        );
    }

    #[test]
    fn display_formats_validated_bounds() {
        let range = CoordinateRange::try_new(-2.0_f64, 3.5).unwrap();
        assert_eq!(range.to_string(), "[-2, 3.5]");
    }

    #[test]
    fn rejects_non_increasing_or_non_finite_bounds_with_exact_payloads() {
        assert_non_increasing_bounds(
            &CoordinateRange::try_new(2.0_f64, 1.0),
            CoordinateRangeOrdering::Decreasing,
            2.0,
            1.0,
        );
        assert_non_increasing_bounds(
            &CoordinateRange::try_new(1.0_f64, 1.0),
            CoordinateRangeOrdering::Equal,
            1.0,
            1.0,
        );
        assert_non_finite_bound(
            CoordinateRange::try_new(f64::NAN, 1.0),
            CoordinateRangeBound::Minimum,
            &InvalidCoordinateValue::Nan,
        );
        assert_non_finite_bound(
            CoordinateRange::try_new(0.0_f64, f64::NAN),
            CoordinateRangeBound::Maximum,
            &InvalidCoordinateValue::Nan,
        );
        assert_non_finite_bound(
            CoordinateRange::try_new(f64::NEG_INFINITY, 1.0),
            CoordinateRangeBound::Minimum,
            &InvalidCoordinateValue::NegativeInfinity,
        );
        assert_non_finite_bound(
            CoordinateRange::try_new(0.0_f64, f64::INFINITY),
            CoordinateRangeBound::Maximum,
            &InvalidCoordinateValue::PositiveInfinity,
        );
    }

    #[test]
    fn custom_non_finite_bound_preserves_debug_payload() {
        let result = CoordinateRange::try_new(
            CustomNonFiniteScalar("custom-lower"),
            CustomNonFiniteScalar("custom-upper"),
        );

        let Err(CoordinateRangeError::NonFiniteBound { bound, value }) = result else {
            panic!("expected custom non-finite coordinate bound");
        };
        assert_eq!(bound, CoordinateRangeBound::Minimum);
        assert_eq!(
            value,
            InvalidCoordinateValue::Other("CustomNonFiniteScalar(\"custom-lower\")".to_string())
        );
    }

    #[test]
    fn try_from_tuple_uses_same_validation_as_constructor() {
        assert_non_increasing_bounds(
            &CoordinateRange::try_from((3.0_f64, 2.0)),
            CoordinateRangeOrdering::Decreasing,
            3.0,
            2.0,
        );

        let range = CoordinateRange::try_from((-3.0_f64, -2.0)).unwrap();
        assert_relative_eq!(range.min(), -3.0, epsilon = f64::EPSILON);
        assert_relative_eq!(range.max(), -2.0, epsilon = f64::EPSILON);
    }

    #[test]
    fn invalid_bounds_display_names_the_invariant() {
        let err = CoordinateRange::try_new(1.0_f64, 1.0).unwrap_err();

        assert_eq!(
            err.to_string(),
            "Invalid coordinate range: minimum 1.0 and maximum 1.0 must satisfy min < max (equal)"
        );
        assert_matches!(err, CoordinateRangeError::NonIncreasing { .. });
    }
}