use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "config")]
pub enum GatePredicate {
AlwaysTrue,
AlwaysFalse,
Equals(Value),
NotEquals(Value),
And(Vec<GatePredicate>),
Or(Vec<GatePredicate>),
Not(Box<GatePredicate>),
Threshold {
required: usize,
predicates: Vec<GatePredicate>,
},
}
impl GatePredicate {
pub fn evaluate(&self, input: &Value) -> bool {
match self {
Self::AlwaysTrue => true,
Self::AlwaysFalse => false,
Self::Equals(expected) => input == expected,
Self::NotEquals(expected) => input != expected,
Self::And(preds) => preds.iter().all(|p| p.evaluate(input)),
Self::Or(preds) => preds.iter().any(|p| p.evaluate(input)),
Self::Not(p) => !p.evaluate(input),
Self::Threshold { required, predicates } => {
let satisfied = predicates.iter().filter(|p| p.evaluate(input)).count();
satisfied >= *required
}
}
}
}
pub fn evaluate_gate_set(gates: &[(String, GatePredicate)], state: &Value) -> Vec<(String, bool)> {
gates
.iter()
.map(|(name, pred)| (name.clone(), pred.evaluate(state)))
.collect()
}