pub fn validate_range(
value: f64,
arg_name: &str,
min: Option<f64>,
max: Option<f64>,
) -> Result<()>Expand description
Validate that a numeric value is within specified bounds
This function checks if a value satisfies the range constraints:
- If
minis specified: value >= min - If
maxis specified: value <= max - If both are specified: min <= value <= max
§Arguments
value- The numeric value to validatearg_name- Name of the argument (for error messages)min- Optional minimum value (inclusive)max- Optional maximum value (inclusive)
§Returns
Ok(())if the value is within the specified rangeErr(ValidationError::OutOfRange)if the value is outside the range
§Range Types
The function supports several range configurations:
- Both bounds:
validate_range(x, "arg", Some(0.0), Some(100.0))→ 0 ≤ x ≤ 100 - Lower bound only:
validate_range(x, "arg", Some(0.0), None)→ x ≥ 0 - Upper bound only:
validate_range(x, "arg", None, Some(100.0))→ x ≤ 100 - No bounds:
validate_range(x, "arg", None, None)→ always valid
§Example
use dynamic_cli::validator::range_validator::validate_range;
// Validate percentage (0-100)
assert!(validate_range(50.0, "percentage", Some(0.0), Some(100.0)).is_ok());
assert!(validate_range(-10.0, "percentage", Some(0.0), Some(100.0)).is_err());
assert!(validate_range(150.0, "percentage", Some(0.0), Some(100.0)).is_err());
// Validate non-negative count
assert!(validate_range(5.0, "count", Some(0.0), None).is_ok());
assert!(validate_range(-1.0, "count", Some(0.0), None).is_err());
// Validate probability (0-1)
assert!(validate_range(0.5, "prob", Some(0.0), Some(1.0)).is_ok());§Error Messages
If the value is out of range, the error includes:
- The argument name
- The actual value
- The expected range (min and max)
Example: percentage must be between 0 and 100, got -10
§Special Values
The function handles special floating-point values:
- Infinity: Can be compared normally
- NaN: Always fails validation (NaN comparisons always return false)
§Edge Cases
- If both
minandmaxareNone, validation always succeeds - Boundary values are inclusive:
validate_range(0.0, "x", Some(0.0), Some(1.0))is valid - If
min > max, this is a configuration error (should be caught by config validation)