Skip to main content

weirdnet_rules/
compare.rs

1//! How a condition compares a JSON value: numbers as numbers, text case-insensitively with
2//! `*` globs for `=`, arrays by any element (and by length for `<`/`>`), missing values only
3//! satisfying `!?`, `!=` and `!~`.
4use crate::model::Op;
5use serde_json::Value;
6
7/// A dotted path into a JSON value (`spec.query`, `files.0`); `null` counts as absent.
8pub fn path<'a>(mut v: &'a Value, p: &str) -> Option<&'a Value> {
9    for k in p.split('.').filter(|k| !k.is_empty()) {
10        v = match v {
11            Value::Object(m) => m.get(k)?,
12            Value::Array(a) => a.get(k.parse::<usize>().ok()?)?,
13            _ => return None,
14        };
15    }
16    (!v.is_null()).then_some(v)
17}
18
19/// A value as text: strings as they are, anything else as JSON.
20pub fn text(v: &Value) -> String {
21    match v {
22        Value::String(s) => s.clone(),
23        o => o.to_string(),
24    }
25}
26
27fn num(v: &Value) -> Option<f64> {
28    match v {
29        Value::Number(n) => n.as_f64(),
30        Value::String(s) => s.trim().parse().ok(),
31        Value::Bool(b) => Some(*b as u8 as f64),
32        _ => None,
33    }
34}
35
36/// `*` matches any run of characters; no other wildcards.
37pub fn glob(p: &str, s: &str) -> bool {
38    let parts: Vec<&str> = p.split('*').collect();
39    if parts.len() == 1 {
40        return p == s;
41    }
42    let mut rest = s;
43    for (i, part) in parts.iter().enumerate() {
44        if i == 0 {
45            let Some(r) = rest.strip_prefix(part) else { return false };
46            rest = r;
47        } else if i == parts.len() - 1 {
48            return rest.ends_with(part);
49        } else {
50            let Some(at) = rest.find(part) else { return false };
51            rest = &rest[at + part.len()..];
52        }
53    }
54    true
55}
56
57fn scalar_eq(v: &Value, want: &str) -> bool {
58    match (num(v), want.trim().parse::<f64>()) {
59        (Some(a), Ok(b)) if !matches!(v, Value::Bool(_)) => a == b,
60        _ => glob(&want.to_lowercase(), &text(v).to_lowercase()),
61    }
62}
63
64/// Does `actual` (absent: `None`) satisfy `op value`?
65pub fn compare(actual: Option<&Value>, op: Op, want: &str) -> bool {
66    let Some(v) = actual else { return matches!(op, Op::Missing | Op::Ne | Op::NotContains) };
67    let contains = |v: &Value| text(v).to_lowercase().contains(&want.to_lowercase());
68    let order = |v: &Value| -> Option<std::cmp::Ordering> {
69        let v = match v {
70            Value::Array(a) => Value::from(a.len()),
71            o => o.clone(),
72        };
73        match (num(&v), want.trim().parse::<f64>()) {
74            (Some(a), Ok(b)) => a.partial_cmp(&b),
75            _ => Some(text(&v).to_lowercase().cmp(&want.to_lowercase())),
76        }
77    };
78    let arr = v.as_array();
79    match op {
80        Op::Exists => true,
81        Op::Missing => false,
82        Op::Eq => arr.map_or_else(|| scalar_eq(v, want), |a| a.iter().any(|x| scalar_eq(x, want))),
83        Op::Ne => arr.map_or_else(|| !scalar_eq(v, want), |a| !a.iter().any(|x| scalar_eq(x, want))),
84        Op::Contains => arr.map_or_else(|| contains(v), |a| a.iter().any(contains)),
85        Op::NotContains => arr.map_or_else(|| !contains(v), |a| !a.iter().any(contains)),
86        Op::Gt => order(v).is_some_and(|o| o.is_gt()),
87        Op::Ge => order(v).is_some_and(|o| o.is_ge()),
88        Op::Lt => order(v).is_some_and(|o| o.is_lt()),
89        Op::Le => order(v).is_some_and(|o| o.is_le()),
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96    use serde_json::json;
97
98    #[test]
99    fn operators() {
100        assert!(compare(Some(&json!(401)), Op::Gt, "0"));
101        assert!(compare(Some(&json!("PDF")), Op::Eq, "pdf"));
102        assert!(compare(Some(&json!("/tmp/a.pdf")), Op::Eq, "*.pdf"));
103        assert!(compare(Some(&json!(["a.csv", "b.csv"])), Op::Contains, "b."));
104        assert!(compare(Some(&json!(["a", "b"])), Op::Ge, "2"), "arrays compare by length");
105        assert!(compare(None, Op::Missing, "") && compare(None, Op::Ne, "x") && !compare(None, Op::Eq, "x"));
106        assert!(compare(None, Op::NotContains, "x") && !compare(None, Op::Exists, "") && !compare(None, Op::Gt, "0"));
107        assert!(compare(Some(&json!("2026-10-29")), Op::Gt, "2026-01-01"));
108        assert!(compare(Some(&json!(true)), Op::Eq, "true") && !compare(Some(&json!(true)), Op::Eq, "1"), "booleans are text for =");
109        assert!(compare(Some(&json!("10")), Op::Eq, "10.0") && compare(Some(&json!(" 3 ")), Op::Lt, "4"));
110        assert!(compare(Some(&json!(["x", "y"])), Op::Ne, "z") && !compare(Some(&json!(["x", "y"])), Op::Ne, "Y"));
111        assert!(compare(Some(&json!("Hello")), Op::NotContains, "bye") && !compare(Some(&json!("Hello")), Op::NotContains, "ELL"));
112        assert!(compare(Some(&json!(1.5)), Op::Le, "1.5") && !compare(Some(&json!("abc")), Op::Lt, "abb"));
113        assert!(compare(Some(&json!({"a": 1})), Op::Exists, ""));
114    }
115
116    #[test]
117    fn paths_and_globs() {
118        let v = json!({"spec": {"query": "btc", "n": null}, "files": ["a", "b"]});
119        assert_eq!(path(&v, "spec.query"), Some(&json!("btc")));
120        assert_eq!(path(&v, "files.1"), Some(&json!("b")));
121        assert_eq!(path(&v, "spec.n"), None, "null is absent");
122        assert_eq!(path(&v, "files.x"), None);
123        assert_eq!(path(&v, "spec.query.deeper"), None);
124        assert!(glob("a*c*e", "abcde") && glob("*", "") && !glob("a*c", "abcd") && glob("a**", "a"));
125        assert_eq!(text(&json!(3)), "3");
126    }
127}