Module validation

Module validation 

Source
Expand description

§Numerical Value Validation Module

This module provides a framework for validating numerical scalar values, particularly floating-point and complex numbers, including those with arbitrary precision using the rug library (when the “rug” feature is enabled).

It defines:

  • Error Types: Such as ErrorsValidationRawReal, ErrorsValidationRawComplex, and ErrorsTryFromf64. These errors detail various validation failures like non-finite values, subnormal numbers (for f64 and rug::Float), and precision mismatches for rug types.
  • Validation Policies: Implemented via the ValidationPolicy trait from the try_create crate. The primary policy provided is StrictFinitePolicy, which ensures that numbers are finite (not NaN or Infinity) and, for f64 and rug::Float, not subnormal.
  • Floating-Point Checks Trait: The FpChecks trait, defined within this module, provides common classification methods like is_finite, is_nan, is_infinite, and is_normal. This trait is implemented for standard and rug-based scalar types.
  • Enhanced Type Safety for HashMap Keys: The GuaranteesFiniteValues marker trait enables full equality (Eq) and hashing (Hash) for validated types when their validation policy guarantees finite values. This allows validated types to be used as keys in HashMap and other hash-based collections.
  • Implementations: Validation logic for StrictFinitePolicy and implementations of FpChecks are provided for f64 and num::Complex<f64>. When the “rug” feature is enabled, support extends to rug::Float, rug::Complex, and indirectly to the wrapper types RealRugStrictFinite and ComplexRugStrictFinite (which utilize these underlying rug types).

The goal of this module is to ensure numerical stability and correctness by allowing functions to easily validate their inputs and outputs according to defined policies, and to provide a common interface for basic floating-point characteristic checks.

§Enhanced Type Safety with GuaranteesFiniteValues

One of the key innovations of this validation framework is the GuaranteesFiniteValues marker trait. This trait enables compile-time verification that a validation policy ensures all validated values are finite, which unlocks additional type system guarantees:

  • Full Equality: These types implement Eq, making equality comparisons well-defined and symmetric.
  • Hashing Support: With both Eq and Hash implemented, these types can be used as keys in hash-based collections like HashMap and HashSet.

Note on Ordering: The library intentionally does NOT implement Ord even for finite-guaranteed types, as our custom Max and Min traits provide more efficient reference-based operations compared to Ord’s value-based interface.

Currently, StrictFinitePolicy and DebugValidationPolicy<StrictFinitePolicy> implement this marker trait.

§Usage Examples

§Basic Validation

use num_valid::validation::{StrictFinitePolicy, ErrorsValidationRawReal};
use try_create::ValidationPolicy; // For the validate() method

// Valid finite number
assert!(StrictFinitePolicy::<f64, 53>::validate(1.0).is_ok());

// Invalid: NaN
let result = StrictFinitePolicy::<f64, 53>::validate(f64::NAN);
assert!(matches!(result, Err(ErrorsValidationRawReal::IsNaN { .. })));

// Invalid: Infinity  
let result = StrictFinitePolicy::<f64, 53>::validate(f64::INFINITY);
assert!(matches!(result, Err(ErrorsValidationRawReal::IsPosInfinity { .. })));

// Invalid: Subnormal
let subnormal_val = f64::from_bits(1); // Smallest positive subnormal f64
let result = StrictFinitePolicy::<f64, 53>::validate(subnormal_val);
assert!(matches!(result, Err(ErrorsValidationRawReal::IsSubnormal { .. })));

§Using FpChecks

use num_valid::validation::FpChecks;
use num::Complex;

let val_f64 = 1.0f64;
let nan_f64 = f64::NAN;
let inf_f64 = f64::INFINITY;

assert!(val_f64.is_finite());
assert!(val_f64.is_normal());
assert!(nan_f64.is_nan());
assert!(!nan_f64.is_finite());
assert!(inf_f64.is_infinite());

let val_complex = Complex::new(1.0, 2.0);
let nan_complex_real = Complex::new(f64::NAN, 2.0);
let inf_complex_imag = Complex::new(1.0, f64::NEG_INFINITY);

assert!(val_complex.is_finite());
assert!(val_complex.is_normal());
assert!(nan_complex_real.is_nan());
assert!(!nan_complex_real.is_finite());
assert!(inf_complex_imag.is_infinite());
assert!(!inf_complex_imag.is_finite());
assert!(!inf_complex_imag.is_nan());

§HashMap Usage with Finite Guarantees

use num_valid::kernels::native64_validated::RealNative64StrictFinite;
use std::collections::HashMap;
use try_create::TryNew;

let mut scores = HashMap::new();
let player1 = RealNative64StrictFinite::try_new(1.5).unwrap();
let player2 = RealNative64StrictFinite::try_new(2.0).unwrap();

scores.insert(player1, 100);  // Works because Eq + Hash are implemented
scores.insert(player2, 95);

assert_eq!(scores.len(), 2);

§Conditional Debug Validation

use num_valid::validation::{DebugValidationPolicy, Native64RawRealStrictFinitePolicy};
use try_create::ValidationPolicy;

type ConditionalPolicy = DebugValidationPolicy<Native64RawRealStrictFinitePolicy>;

let value = 42.0;
// Validates only in debug builds, no-op in release
assert!(ConditionalPolicy::validate(value).is_ok());

Structs§

DebugValidationPolicy
A validation policy that is active only in debug builds.
StrictFinitePolicy
A validation policy that checks for strict finiteness.

Enums§

ErrorsRawRealToInteger
ErrorsTryFromf64
Errors that can occur when trying to convert an f64 to another real-type scalar of type RawReal.
ErrorsValidationRawComplex
Errors that can occur during the validation of a complex number.
ErrorsValidationRawReal
Errors that can occur during the validation of a raw real number.

Traits§

FpChecks
Provides a set of fundamental floating-point classification checks.
GuaranteesFiniteValues
A marker trait for validation policies that guarantee finite real values.
ValidationPolicyComplex
A marker for policies that apply to complex types.
ValidationPolicyReal
A marker for policies that apply to real types.

Functions§

debug_validate
Validates a value using the given policy, but only in debug builds. In release builds, this function is a no-op and should be optimized away.

Type Aliases§

Native64RawComplexStrictFinitePolicy
A type alias for a validation policy that enforces strict finiteness for the raw num::Complex<f64> type.
Native64RawRealStrictFinitePolicy
A type alias for a validation policy that enforces strict finiteness for the raw f64 type.