use crate::CypherValue;
fn optional_arg<T>(
args: &crate::IndexMap<String, CypherValue>,
key: &str,
extract: impl Fn(&CypherValue) -> Option<T>,
contract: &str,
) -> Option<T> {
args.get(key).map(|value| {
extract(value)
.unwrap_or_else(|| panic!("plan wire {key} is {contract} when present, got {value:?}"))
})
}
pub(super) fn optional_int(args: &crate::IndexMap<String, CypherValue>, key: &str) -> Option<i64> {
optional_arg(
args,
key,
|value| match value {
CypherValue::Int(n) if *n >= 0 => Some(*n),
_ => None,
},
"a non-negative integer (ADR-0345)",
)
}
pub(super) fn optional_bool(
args: &crate::IndexMap<String, CypherValue>,
key: &str,
) -> Option<bool> {
optional_arg(
args,
key,
|value| match value {
CypherValue::Bool(flag) => Some(*flag),
_ => None,
},
"a boolean (LABS-369)",
)
}
pub(super) fn optional_fraction(
args: &crate::IndexMap<String, CypherValue>,
key: &str,
) -> Option<f64> {
optional_arg(
args,
key,
|value| match value {
CypherValue::Float(fraction) if *fraction >= 0.0 => Some(*fraction),
_ => None,
},
"a non-negative float (ADR-0516)",
)
}
pub(super) fn metric_set_ints<const N: usize>(
args: &crate::IndexMap<String, CypherValue>,
keys: [&str; N],
has_metrics: bool,
) -> Option<[i64; N]> {
match (has_metrics, metric_group_ints(args, keys)) {
(false, None) => None,
(true, Some(values)) => Some(values),
(false, Some(_)) => panic!(
"plan wire {keys:?} are present without the metric fields \
(all-or-none group policy)"
),
(true, None) => panic!(
"plan wire {keys:?} are absent from the metric fields \
(all-or-none group policy)"
),
}
}
pub(super) fn metric_group_ints<const N: usize>(
args: &crate::IndexMap<String, CypherValue>,
keys: [&str; N],
) -> Option<[i64; N]> {
let values = keys.map(|key| optional_int(args, key));
let present = values.iter().filter(|value| value.is_some()).count();
if present == 0 {
return None;
}
assert!(
present == N,
"plan wire {keys:?} are an all-or-none group, got a partial group: values={values:?}"
);
Some(values.map(|value| value.expect("the group is all-present")))
}