use toml::Value;
pub fn max(input: &str, max_value: &Value) -> Result<(), String> {
if let Some(max_int) = max_value.as_integer() {
if let Ok(input_int) = input.parse::<i64>() {
if input_int <= max_int {
return Ok(());
} else {
return Err(format!("Input must be less than or equal to {}", max_int));
}
}
}
if let Some(max_float) = max_value.as_float() {
if let Ok(input_float) = input.parse::<f64>() {
if input_float <= max_float {
return Ok(());
} else {
return Err(format!("Input must be less than or equal to {}", max_float));
}
}
}
Err(format!(
"Invalid max validation. Either '{}' is not a number or the maximum value is not specified correctly",
input
))
}
#[cfg(test)]
mod tests {
use super::*;
use toml::Value;
#[test]
fn test_max_integers() {
let max_value = Value::Integer(10);
assert!(max(10.to_string().as_str(), &max_value).is_ok());
assert!(max(5.to_string().as_str(), &max_value).is_ok());
let result = max(11.to_string().as_str(), &max_value);
assert!(result.is_err());
assert!(result
.unwrap_err()
.contains("must be less than or equal to 10"));
}
#[test]
fn test_max_floats() {
let max_value = Value::Float(7.5);
assert!(max(7.5.to_string().as_str(), &max_value).is_ok());
assert!(max(7.0.to_string().as_str(), &max_value).is_ok());
let result = max(8.0.to_string().as_str(), &max_value);
assert!(result.is_err());
assert!(result
.unwrap_err()
.contains("must be less than or equal to 7.5"));
}
}