62 lines
1.7 KiB
Rust
62 lines
1.7 KiB
Rust
use super::Value;
|
|
use crate::fault::Fault;
|
|
|
|
/// Largest integer an f64 holds exactly.
|
|
const MAX_EXACT: f64 = 9007199254740992.0;
|
|
|
|
fn wrong(path: &str, expected: &str, found: &Value) -> Fault {
|
|
Fault::Invalid {
|
|
field: path.to_string(),
|
|
detail: format!("expected {expected}, found {}", found.kind()),
|
|
}
|
|
}
|
|
|
|
pub fn number(value: &Value, path: &str) -> Result<f64, Fault> {
|
|
match value {
|
|
Value::Number(n) => Ok(*n),
|
|
other => Err(wrong(path, "a number", other)),
|
|
}
|
|
}
|
|
|
|
pub fn text<'a>(value: &'a Value, path: &str) -> Result<&'a str, Fault> {
|
|
match value {
|
|
Value::String(s) => Ok(s),
|
|
other => Err(wrong(path, "a string", other)),
|
|
}
|
|
}
|
|
|
|
pub fn flag(value: &Value, path: &str) -> Result<bool, Fault> {
|
|
match value {
|
|
Value::Bool(b) => Ok(*b),
|
|
other => Err(wrong(path, "a boolean", other)),
|
|
}
|
|
}
|
|
|
|
pub fn items<'a>(value: &'a Value, path: &str) -> Result<&'a [Value], Fault> {
|
|
match value {
|
|
Value::Array(v) => Ok(v),
|
|
other => Err(wrong(path, "an array", other)),
|
|
}
|
|
}
|
|
|
|
/// A non-negative whole number that f64 represents exactly.
|
|
pub fn whole_u64(value: &Value, path: &str) -> Result<u64, Fault> {
|
|
let n = number(value, path)?;
|
|
if n >= 0.0 && n.fract() == 0.0 && n <= MAX_EXACT {
|
|
Ok(n as u64)
|
|
} else {
|
|
Err(Fault::Invalid {
|
|
field: path.to_string(),
|
|
detail: format!("expected a non-negative whole number, found {n}"),
|
|
})
|
|
}
|
|
}
|
|
|
|
pub fn whole_u8(value: &Value, path: &str) -> Result<u8, Fault> {
|
|
let n = whole_u64(value, path)?;
|
|
u8::try_from(n).map_err(|_| Fault::Invalid {
|
|
field: path.to_string(),
|
|
detail: format!("{n} is out of range 0..=255"),
|
|
})
|
|
}
|