use std::collections::BTreeMap;
use lgwks_std::json::serde::{Deserialize, Serialize};
use super::JsonValue;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(crate = "lgwks_std::json::serde")]
#[non_exhaustive]
pub struct SignalPattern {
kind_glob: String,
payload_predicate: Option<PayloadPredicate>,
}
impl SignalPattern {
#[must_use]
pub fn new(kind_glob: String, payload_predicate: Option<PayloadPredicate>) -> Self {
Self {
kind_glob,
payload_predicate,
}
}
#[must_use]
pub fn kind_glob(&self) -> &str {
&self.kind_glob
}
#[must_use]
pub const fn payload_predicate(&self) -> Option<&PayloadPredicate> {
self.payload_predicate.as_ref()
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum PayloadPredicate {
Eq {
keypath: String,
value: JsonValue,
},
Neq {
keypath: String,
value: JsonValue,
},
In {
keypath: String,
values: Vec<JsonValue>,
},
Exists {
keypath: String,
},
And(Vec<PayloadPredicate>),
Or(Vec<PayloadPredicate>),
}
impl PayloadPredicate {
#[must_use]
pub fn eq(keypath: String, value: JsonValue) -> Self {
Self::Eq { keypath, value }
}
#[must_use]
pub fn neq(keypath: String, value: JsonValue) -> Self {
Self::Neq { keypath, value }
}
#[must_use]
pub fn is_in(keypath: String, values: Vec<JsonValue>) -> Self {
Self::In { keypath, values }
}
#[must_use]
pub fn exists(keypath: String) -> Self {
Self::Exists { keypath }
}
}
impl Serialize for PayloadPredicate {
fn serialize<S: lgwks_std::json::serde::Serializer>(
&self,
serializer: S,
) -> Result<S::Ok, S::Error> {
match *self {
Self::Eq {
ref keypath,
ref value,
} => {
let pair = (JsonValue::String(keypath.clone()), value.clone());
Serialize::serialize(
&BTreeMap::from([("eq", JsonValue::Array(vec![pair.0, pair.1]))]),
serializer,
)
}
Self::Neq {
ref keypath,
ref value,
} => {
let pair = (JsonValue::String(keypath.clone()), value.clone());
Serialize::serialize(
&BTreeMap::from([("neq", JsonValue::Array(vec![pair.0, pair.1]))]),
serializer,
)
}
Self::In {
ref keypath,
ref values,
} => {
let items = vec![
JsonValue::String(keypath.clone()),
JsonValue::Array(values.clone()),
];
Serialize::serialize(
&BTreeMap::from([("in", JsonValue::Array(items))]),
serializer,
)
}
Self::Exists { ref keypath } => Serialize::serialize(
&BTreeMap::from([("exists", JsonValue::String(keypath.clone()))]),
serializer,
),
Self::And(ref clauses) => Serialize::serialize(
&BTreeMap::from([("and", JsonValue::Array(predicate_array(clauses)))]),
serializer,
),
Self::Or(ref clauses) => Serialize::serialize(
&BTreeMap::from([("or", JsonValue::Array(predicate_array(clauses)))]),
serializer,
),
}
}
}
fn predicate_array(clauses: &[PayloadPredicate]) -> Vec<JsonValue> {
clauses
.iter()
.map(|clause| {
match lgwks_std::json::to_value(clause) {
Ok(value) => JsonValue::from_json(&value),
Err(error) => JsonValue::String(format!("unserializable clause: {error}")),
}
})
.collect()
}
impl<'de> Deserialize<'de> for PayloadPredicate {
fn deserialize<D: lgwks_std::json::serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Self, D::Error> {
let raw = JsonValue::deserialize(deserializer)?;
decode_predicate(&raw)
.ok_or_else(|| lgwks_std::json::serde::de::Error::custom("unknown predicate operator"))
}
}
fn decode_predicate(raw: &JsonValue) -> Option<PayloadPredicate> {
decode_predicate_depth(raw, 0)
}
fn decode_predicate_depth(raw: &JsonValue, depth: usize) -> Option<PayloadPredicate> {
if depth >= 64 {
return None;
}
let map = raw.object_value()?;
if let Some(clause) = decode_pair_clause(map, "eq") {
return clause.map(|(keypath, value)| PayloadPredicate::eq(keypath, value));
}
if let Some(clause) = decode_pair_clause(map, "neq") {
return clause.map(|(keypath, value)| PayloadPredicate::neq(keypath, value));
}
if let Some(members) = map.get("in") {
if let Some(items) = members.array_value()
&& items.len() == 2
&& let Some(keypath) = items[0].string_value()
&& let Some(values) = items[1].array_value()
{
return Some(PayloadPredicate::is_in(keypath.clone(), values.clone()));
}
return None;
}
if let Some(keypath) = map.get("exists").and_then(|member| member.string_value()) {
return Some(PayloadPredicate::exists(keypath.clone()));
}
if let Some(children) = decode_children(map, "and", depth) {
return Some(PayloadPredicate::And(children));
}
if let Some(children) = decode_children(map, "or", depth) {
return Some(PayloadPredicate::Or(children));
}
None
}
fn decode_pair_clause(
map: &BTreeMap<String, JsonValue>,
operator: &str,
) -> Option<Option<(String, JsonValue)>> {
let candidate = map.get(operator)?;
let items = candidate.array_value()?;
let slice = items.as_slice();
if slice.len() == 2
&& let Some(keypath) = slice[0].string_value()
{
return Some(Some((keypath.clone(), slice[1].clone())));
}
Some(None)
}
fn decode_children(
map: &BTreeMap<String, JsonValue>,
operator: &str,
depth: usize,
) -> Option<Vec<PayloadPredicate>> {
let candidate = map.get(operator)?;
let items = candidate.array_value()?;
let mut children = Vec::with_capacity(items.len());
for item in items {
children.push(decode_predicate_depth(item, depth.saturating_add(1))?);
}
Some(children)
}