meteroid-rs 0.31.4

Official Rust SDK for Meteroid, the open-source billing platform: subscriptions, invoicing, usage-based billing and webhooks.
Documentation
// this file is @generated by Perseid; edit the shared runtime template.
//! Picks the variant of an object in a union of several objects without a discriminator.
#![allow(dead_code)]
use serde_json::Value;

/// Whether the object `value` has `property`, equal to `expected` when set.
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(),
    }
}

/// The candidate, as its required and known properties, whose required properties the object
/// `value` all has and which knows the most of its properties; the first one on ties.
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)
}

/// The JSON shape of the items of an array variant, which tells arrays of different items apart.
pub(crate) enum ItemShape {
    Any,
    String,
    Integer,
    Number,
    Boolean,
    Object,
    Array(&'static ItemShape),
}

impl ItemShape {
    /// Whether `value` has this shape; for arrays, whether it is empty or its first item has the
    /// shape of the items.
    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),
        }
    }
}

/// Whether `value` is an array that is empty or whose first item has the shape `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)))
}

/// `value` read as `T`, when `matches` and it decodes.
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
    }
}

/// The candidates, as their required and known properties, that the object `value` can be
/// read as, best first: the most known properties it has, the first one on ties.
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()
}