#![allow(dead_code)]
use serde_json::Value;
pub(crate) fn has(value: &Value, property: &str, expected: Option<Value>) -> bool {
match (value.get(property), expected) {
(Some(actual), Some(expected)) => *actual == expected,
(actual, _) => actual.is_some(),
}
}
pub(crate) fn best_match(value: &Value, candidates: &[(&[&str], &[&str])]) -> Option<usize> {
let object = value.as_object()?;
let mut best: Option<(usize, usize)> = None;
for (index, (required, known)) in candidates.iter().enumerate() {
if !required.iter().all(|p| object.contains_key(*p)) {
continue;
}
let score = known.iter().filter(|p| object.contains_key(**p)).count();
if best.is_none_or(|(_, top)| score > top) {
best = Some((index, score));
}
}
best.map(|(index, _)| index)
}
pub(crate) enum ItemShape {
Any,
String,
Integer,
Number,
Boolean,
Object,
Array(&'static ItemShape),
}
impl ItemShape {
pub(crate) fn matches(&self, value: &Value) -> bool {
match self {
Self::Any => true,
Self::String => value.is_string(),
Self::Integer => value.is_i64() || value.is_u64(),
Self::Number => value.is_number(),
Self::Boolean => value.is_boolean(),
Self::Object => value.is_object(),
Self::Array(items) => array_of(value, items),
}
}
}
pub(crate) fn array_of(value: &Value, items: &ItemShape) -> bool {
value
.as_array()
.is_some_and(|array| array.first().is_none_or(|first| items.matches(first)))
}
pub(crate) fn decode<T: serde::de::DeserializeOwned>(matches: bool, value: &Value) -> Option<T> {
if matches {
serde_json::from_value(value.clone()).ok()
} else {
None
}
}
pub(crate) fn ranked(value: &Value, candidates: &[(&[&str], &[&str])]) -> Vec<usize> {
let Some(object) = value.as_object() else {
return Vec::new();
};
let mut scored: Vec<(usize, usize)> = candidates
.iter()
.enumerate()
.filter(|(_, (required, _))| required.iter().all(|p| object.contains_key(*p)))
.map(|(index, (_, known))| {
(
index,
known.iter().filter(|p| object.contains_key(**p)).count(),
)
})
.collect();
scored.sort_by_key(|&(_, score)| std::cmp::Reverse(score));
scored.into_iter().map(|(index, _)| index).collect()
}