delaunay 0.8.3

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.
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
//! Finite-coordinate checks and checked numeric conversions.
//!
//! Finite checks preserve the exact input bits and report indexed, typed errors.
//! Integer conversions additionally check precision before producing coordinates.

#![forbid(unsafe_code)]

use crate::geometry::traits::coordinate::{
    CoordinateConversionError, CoordinateConversionValue, F64_MANTISSA_DIGITS,
    InvalidCoordinateValue,
};
use num_traits::ToPrimitive;

/// Structured reason why a direct value conversion failed.
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum ValueConversionFailureReason {
    /// The target coordinate type rejected the input value.
    #[error("target type rejected value")]
    TargetTypeRejected,
}

/// Errors that can occur during value type conversions.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::geometry::{
///     CoordinateConversionValue, ValueConversionError, ValueConversionFailureReason,
/// };
///
/// let err = ValueConversionError::ConversionFailed {
///     value: CoordinateConversionValue::from_f64(1.0),
///     from_type: "f64",
///     to_type: "u32",
///     reason: ValueConversionFailureReason::TargetTypeRejected,
/// };
/// std::assert_matches!(err, ValueConversionError::ConversionFailed { .. });
/// ```
#[derive(Clone, Debug, thiserror::Error, PartialEq)]
#[non_exhaustive]
pub enum ValueConversionError {
    /// Failed to convert a value from one type to another.
    #[error("Cannot convert {value} from {from_type} to {to_type}: {reason}")]
    ConversionFailed {
        /// The value that failed to convert.
        value: CoordinateConversionValue,
        /// Source type name.
        from_type: &'static str,
        /// Target type name.
        to_type: &'static str,
        /// Structured reason for the conversion failure.
        reason: ValueConversionFailureReason,
    },
    /// A lower-level coordinate conversion failed while converting a derived value.
    #[error("Cannot convert {value} from {from_type} to {to_type}: {source}")]
    CoordinateConversion {
        /// The value that failed to convert.
        value: CoordinateConversionValue,
        /// Source type name.
        from_type: &'static str,
        /// Target type name.
        to_type: &'static str,
        /// Structured source conversion failure.
        #[source]
        source: Box<CoordinateConversionError>,
    },
}

/// Checks a coordinate while retaining its index for diagnostics.
fn try_finite_coordinate(
    value: f64,
    coordinate_index: usize,
) -> Result<f64, CoordinateConversionError> {
    if !value.is_finite() {
        return Err(CoordinateConversionError::NonFiniteValue {
            coordinate_index,
            coordinate_value: InvalidCoordinateValue::from_debug(&value),
        });
    }

    Ok(value)
}

/// Checks that every coordinate is finite and returns the unchanged values.
///
/// All finite values retain their exact bits, including signed zero. Empty
/// arrays are accepted.
///
/// # Errors
///
/// Returns [`CoordinateConversionError::NonFiniteValue`] for the first NaN or
/// infinite coordinate, with its zero-based index and typed value classification.
///
/// # Examples
///
/// ```
/// use delaunay::prelude::geometry::{
///     CoordinateConversionError, InvalidCoordinateValue, try_finite_coords,
/// };
///
/// # fn main() -> Result<(), CoordinateConversionError> {
/// let coords = try_finite_coords(&[1.5, -0.0, 3.5])?;
/// assert_eq!(coords[1].to_bits(), (-0.0_f64).to_bits());
/// std::assert_matches!(
///     try_finite_coords(&[1.0, f64::INFINITY, f64::NAN]),
///     Err(CoordinateConversionError::NonFiniteValue {
///         coordinate_index: 1,
///         coordinate_value: InvalidCoordinateValue::PositiveInfinity,
///     })
/// );
/// # Ok(())
/// # }
/// ```
pub fn try_finite_coords<const D: usize>(
    coords: &[f64; D],
) -> Result<[f64; D], CoordinateConversionError> {
    let mut result = [0.0_f64; D];
    for (i, &coord) in coords.iter().enumerate() {
        result[i] = try_finite_coordinate(coord, i)?;
    }
    Ok(result)
}

/// Checks that a scalar is finite and returns the unchanged value.
///
/// All finite values retain their exact bits, including signed zero.
///
/// # Errors
///
/// Returns [`CoordinateConversionError::NonFiniteValue`] for NaN or infinity,
/// with coordinate index zero and a typed value classification.
///
/// # Examples
///
/// ```
/// use delaunay::prelude::geometry::{CoordinateConversionError, try_finite_scalar};
///
/// # fn main() -> Result<(), CoordinateConversionError> {
/// let value = try_finite_scalar(-0.0)?;
/// assert_eq!(value.to_bits(), (-0.0_f64).to_bits());
/// # Ok(())
/// # }
/// ```
pub fn try_finite_scalar(value: f64) -> Result<f64, CoordinateConversionError> {
    try_finite_coordinate(value, 0)
}

/// Safely convert a `usize` value to the supported coordinate scalar type.
///
/// This function handles the conversion from `usize` to `f64` with proper
/// precision checking.
///
/// # Arguments
///
/// * `value` - The `usize` value to convert
///
/// # Returns
///
/// The converted T value or a `CoordinateConversionError`
///
/// # Errors
///
/// Returns `CoordinateConversionError::ConversionFailed` if:
/// - The `usize` value is too large and would lose precision in the conversion chain
/// - The conversion from `f64` to type T fails
///
/// # Examples
///
/// ```
/// use delaunay::prelude::geometry::{CoordinateConversionError, safe_usize_to_scalar};
///
/// # fn main() -> Result<(), CoordinateConversionError> {
/// // Normal case - small usize values
/// let result: Result<f64, _> = safe_usize_to_scalar(42_usize);
/// assert_eq!(result?, 42.0);
///
/// // Large values that fit within f64 precision
/// let large_value = (1_u64 << 50) as usize; // 2^50, well within f64 precision
/// let result: Result<f64, _> = safe_usize_to_scalar(large_value);
/// assert!(result.is_ok());
///
/// // Values that would lose precision (if usize is large enough)
/// // This test may not trigger on all platforms depending on usize size
/// # Ok(())
/// # }
/// ```
///
/// # Precision Limits
///
/// The function uses the minimum mantissa bits between f64 and the target type:
/// - `f64` integers are exact up to and including 2^53 (9,007,199,254,740,992)
/// - For f64 targets: `usize` values larger than 2^53 will cause an error
/// - On 64-bit platforms, `usize` can be up to 64 bits, so f64 precision loss is possible
pub fn safe_usize_to_scalar(value: usize) -> Result<f64, CoordinateConversionError> {
    let max_precise_u128: u128 = 1u128 << F64_MANTISSA_DIGITS;

    // Use try_from to safely convert usize to u64 for comparison
    let value_u64 =
        u64::try_from(value).map_err(|_| CoordinateConversionError::ConversionFailed {
            coordinate_index: 0,
            coordinate_value: CoordinateConversionValue::from_usize(value),
            from_type: "usize",
            to_type: "f64",
        })?;

    if u128::from(value_u64) > max_precise_u128 {
        return Err(CoordinateConversionError::ConversionFailed {
            coordinate_index: 0,
            coordinate_value: CoordinateConversionValue::from_usize(value),
            from_type: "usize",
            to_type: "f64",
        });
    }

    value
        .to_f64()
        .ok_or_else(|| CoordinateConversionError::ConversionFailed {
            coordinate_index: 0,
            coordinate_value: CoordinateConversionValue::from_usize(value),
            from_type: "usize",
            to_type: "f64",
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry::traits::coordinate::CoordinateConversionError;
    use approx::assert_relative_eq;
    use num_traits::cast;
    use std::assert_matches;

    #[test]
    fn test_safe_usize_to_scalar_basic_success() {
        // Test successful conversion of small usize values
        let small_value = 42_usize;
        let result: Result<f64, _> = safe_usize_to_scalar(small_value);
        assert!(result.is_ok());
        assert_relative_eq!(result.unwrap(), 42.0f64, epsilon = 1e-15);
    }

    #[test]
    fn test_safe_usize_to_scalar_within_f64_precision() {
        // Test values that are within f64 precision limits but relatively large
        let safe_large_values = [
            usize::try_from(1_u64 << 50).unwrap_or(usize::MAX), // 2^50, well within f64 precision
            usize::try_from(1_u64 << 51).unwrap_or(usize::MAX), // 2^51, still safe
            usize::try_from(1_u64 << 53).unwrap_or(usize::MAX), // 2^53 is still exactly representable
        ];

        for &value in &safe_large_values {
            let result: Result<f64, _> = safe_usize_to_scalar(value);
            assert!(result.is_ok(), "Failed to convert safe large value {value}");

            // Verify that the conversion is exact
            let converted = result.unwrap();
            let back_converted: usize =
                cast(converted).expect("f64 should convert back to usize exactly");
            assert_eq!(
                back_converted, value,
                "Conversion was not exact for {value}"
            );
        }
    }

    #[test]
    fn test_safe_usize_to_scalar_precision_boundary() {
        // Test the exact boundary value: 2^53.
        const MAX_PRECISE_USIZE_IN_F64: u64 = 1_u64 << 53;

        // This should succeed (exactly at the boundary)
        if usize::try_from(MAX_PRECISE_USIZE_IN_F64).is_ok() {
            let boundary_value = usize::try_from(MAX_PRECISE_USIZE_IN_F64).unwrap();
            let result: Result<f64, _> = safe_usize_to_scalar(boundary_value);
            assert!(result.is_ok(), "Boundary value 2^53 should be convertible");

            let converted = result.unwrap();
            let back_converted: usize =
                cast(converted).expect("Boundary f64 should convert back to usize exactly");
            assert_eq!(
                back_converted, boundary_value,
                "Boundary conversion should be exact"
            );
        }
    }

    #[test]
    fn test_safe_usize_to_scalar_precision_loss_detection() {
        // Test values that would lose precision (only on 64-bit platforms where usize can exceed 2^53)
        const MAX_PRECISE_USIZE_IN_F64: u64 = 1_u64 << 53;

        if std::mem::size_of::<usize>() >= 8 {
            // On 64-bit platforms, test values that would lose precision
            let precision_loss_values = [
                usize::try_from(MAX_PRECISE_USIZE_IN_F64 + 1).unwrap_or(usize::MAX), // Just over 2^53
                usize::try_from(MAX_PRECISE_USIZE_IN_F64 + 100).unwrap_or(usize::MAX), // Well over 2^53
            ];

            for &value in &precision_loss_values {
                // Skip if the value would overflow usize on this platform
                let value_u64 = u64::try_from(value).unwrap_or(u64::MAX);
                if value_u64 > u64::try_from(usize::MAX).unwrap_or(u64::MAX) {
                    continue;
                }

                let result: Result<f64, _> = safe_usize_to_scalar(value);
                assert!(
                    result.is_err(),
                    "Value {value} should fail conversion due to precision loss"
                );

                assert_matches!(
                    result,
                    Err(CoordinateConversionError::ConversionFailed {
                        coordinate_index: 0,
                        coordinate_value,
                        from_type: "usize",
                        to_type: "f64",
                    }) if coordinate_value == CoordinateConversionValue::from_usize(value)
                );
            }
        }
    }

    #[test]
    fn test_safe_usize_to_scalar_error_message_format() {
        // Test that error messages are properly formatted
        const MAX_PRECISE_USIZE_IN_F64: u64 = 1_u64 << 53;

        if std::mem::size_of::<usize>() >= 8 {
            let large_value = usize::try_from(MAX_PRECISE_USIZE_IN_F64 + 1).unwrap_or(usize::MAX);
            if u64::try_from(large_value).unwrap_or(u64::MAX)
                <= u64::try_from(usize::MAX).unwrap_or(u64::MAX)
            {
                let result: Result<f64, _> = safe_usize_to_scalar(large_value);
                assert!(result.is_err());

                let error_message = format!("{}", result.unwrap_err());
                assert!(error_message.contains("Failed to convert"));
                assert!(error_message.contains(&format!("{large_value}")));
                assert!(error_message.contains("usize"));
                assert!(error_message.contains("f64"));
            }
        }
    }

    #[test]
    fn test_safe_usize_to_scalar_consistency_with_direct_cast() {
        // For values that should not lose precision, verify consistency with direct casting
        let safe_values = [0, 1, 42, 100, 1000, 10_000, 100_000];

        for &value in &safe_values {
            let safe_result: Result<f64, _> = safe_usize_to_scalar(value);
            assert!(safe_result.is_ok());

            let safe_converted = safe_result.unwrap();
            let direct_cast: f64 = cast(value).expect("Small values should convert to f64 safely");

            assert_relative_eq!(safe_converted, direct_cast, epsilon = 1e-15);
        }
    }

    #[test]
    fn test_safe_usize_to_scalar_platform_independence() {
        // Test that the function behaves correctly on different platforms
        tracing::debug!(
            "Testing on platform with usize size: {} bytes",
            std::mem::size_of::<usize>()
        );
        tracing::debug!("usize::MAX = {}", usize::MAX);
        tracing::debug!("2^53 = {}", 1_u64 << 53);

        // Values that should work on any platform
        let universal_safe_values = [0, 1, 100, 10000];

        for &value in &universal_safe_values {
            let result: Result<f64, _> = safe_usize_to_scalar(value);
            assert!(
                result.is_ok(),
                "Universal safe value {value} should convert on any platform"
            );
        }

        // Test the maximum safe value for this platform
        let _usize_max_u64 = u64::try_from(usize::MAX).unwrap_or(u64::MAX);
    }

    #[test]
    fn test_safe_usize_to_scalar_precision_boundary_extended() {
        // Test values at the precision boundary (additional edge cases)
        const MAX_PRECISE: u64 = 1_u64 << 53;

        // Test maximum precise value (should work)
        let result: Result<f64, _> =
            safe_usize_to_scalar(usize::try_from(MAX_PRECISE).unwrap_or(usize::MAX));
        assert!(result.is_ok());

        // Test beyond precision limit (if usize is large enough)
        if std::mem::size_of::<usize>() >= 8 {
            // Only test on 64-bit platforms
            let large_value = usize::try_from(MAX_PRECISE + 1).unwrap_or(usize::MAX);
            let result: Result<f64, _> = safe_usize_to_scalar(large_value);
            assert_matches!(
                result,
                Err(CoordinateConversionError::ConversionFailed { .. })
            );
        }

        // Test normal values
        let result: Result<f64, _> = safe_usize_to_scalar(42_usize);
        assert!(result.is_ok());
        assert_relative_eq!(result.unwrap(), 42.0);

        // Test zero
        let result: Result<f64, _> = safe_usize_to_scalar(0_usize);
        assert!(result.is_ok());
        assert_relative_eq!(result.unwrap(), 0.0);
    }

    #[test]
    fn value_conversion_error_display_names_conversion() {
        let value_error = ValueConversionError::ConversionFailed {
            value: CoordinateConversionValue::from_usize(42),
            from_type: "i32",
            to_type: "u32",
            reason: ValueConversionFailureReason::TargetTypeRejected,
        };
        let display = format!("{value_error}");
        assert!(display.contains("Cannot convert 42 from i32 to u32"));
        assert!(display.contains("target type rejected value"));
    }
}