use std::cmp::Ordering;
use std::collections::BTreeMap;
use serde_json::{Map, Value};
use crate::core::decimal_opt;
const RESERVED: &[&str] = &[
"fields", "offset", "limit", "sort", "after", "before", "filter",
];
#[must_use]
pub fn is_reserved(parameter: &str) -> bool {
RESERVED.contains(¶meter)
}
const OPERATORS: &[&str] = &["eq", "ne", "gt", "gte", "lt", "lte", "regex"];
#[must_use]
pub fn matches_filters(resource: &Value, query: &BTreeMap<String, String>) -> bool {
query
.iter()
.filter(|(key, _)| !is_reserved(key))
.all(|(parameter, expected)| {
let (path, op) = split_operator(parameter);
let actual = resolve_path_multi(resource, path);
if actual.is_empty() {
return false;
}
if op == "ne" {
return !actual.iter().any(|value| {
expected
.split(',')
.any(|candidate| scalar_eq(value, candidate))
});
}
actual.iter().any(|value| {
expected
.split(',')
.any(|candidate| compare(value, op, candidate))
})
})
}
fn split_operator(parameter: &str) -> (&str, &str) {
match parameter.rsplit_once('.') {
Some((path, suffix)) if OPERATORS.contains(&suffix) => (path, suffix),
_ => (parameter, "eq"),
}
}
fn compare(actual: &Value, op: &str, expected: &str) -> bool {
match op {
"eq" => scalar_eq(actual, expected),
"regex" => actual.as_str().is_some_and(|s| matches_glob(s, expected)),
"gt" | "gte" | "lt" | "lte" => match order(actual, expected) {
Some(Ordering::Less) => op == "lt" || op == "lte",
Some(Ordering::Equal) => op == "gte" || op == "lte",
Some(Ordering::Greater) => op == "gt" || op == "gte",
None => false,
},
_ => false,
}
}
fn order(actual: &Value, expected: &str) -> Option<Ordering> {
if let Value::Number(number) = actual {
return decimal_opt::compare(number.as_str(), expected);
}
if let Value::String(s) = actual
&& let (Some(a), Some(b)) = (instant(s), instant(expected))
{
return Some(a.cmp(&b));
}
match actual {
Value::String(s) => Some(s.as_str().cmp(expected)),
_ => None,
}
}
fn instant(raw: &str) -> Option<jiff::Timestamp> {
if let Ok(parsed) = raw.parse::<crate::core::Timestamp>() {
return Some(parsed.instant());
}
let shaped = raw.len() == 10
&& raw.bytes().enumerate().all(|(i, b)| match i {
4 | 7 => b == b'-',
_ => b.is_ascii_digit(),
});
if !shaped {
return None;
}
let date: jiff::civil::Date = raw.parse().ok()?;
jiff::tz::Offset::UTC
.to_timestamp(date.to_datetime(jiff::civil::Time::midnight()))
.ok()
}
fn matches_glob(haystack: &str, pattern: &str) -> bool {
let pattern = pattern.trim_start_matches('^').trim_end_matches('$');
let (text, pattern) = (haystack.as_bytes(), pattern.as_bytes());
let (mut star, mut resume_at) = (None, 0);
let (mut t, mut p) = (0, 0);
while t < text.len() {
if p < pattern.len() && (pattern[p] == b'?' || pattern[p] == text[t]) {
t += 1;
p += 1;
} else if p < pattern.len() && pattern[p] == b'*' {
star = Some(p);
resume_at = t;
p += 1;
} else if let Some(last_star) = star {
p = last_star + 1;
resume_at += 1;
t = resume_at;
} else {
return false;
}
}
pattern[p..].iter().all(|byte| *byte == b'*')
}
pub fn sort_resources(resources: &mut [Value], sort: &str) {
let keys: Vec<(bool, &str)> = sort
.split(',')
.map(str::trim)
.filter(|k| !k.is_empty())
.map(|k| match k.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, k.strip_prefix('+').unwrap_or(k)),
})
.collect();
resources.sort_by(|a, b| {
for (descending, key) in &keys {
let left = resolve_path(a, key);
let right = resolve_path(b, key);
let ordering = match (left, right) {
(Some(l), Some(r)) => compare_values(l, r),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => Ordering::Equal,
};
let ordering = if *descending {
ordering.reverse()
} else {
ordering
};
if ordering != Ordering::Equal {
return ordering;
}
}
Ordering::Equal
});
}
fn compare_values(left: &Value, right: &Value) -> Ordering {
match (left, right) {
(Value::Number(a), Value::Number(b)) => {
decimal_opt::compare(a.as_str(), b.as_str()).expect("valid JSON numbers")
}
(Value::String(a), Value::String(b)) => match (instant(a), instant(b)) {
(Some(a), Some(b)) => a.cmp(&b),
_ => a.cmp(b),
},
(Value::Bool(a), Value::Bool(b)) => a.cmp(b),
_ => left.to_string().cmp(&right.to_string()),
}
}
#[must_use]
pub fn project_fields(resource: &Value, fields: Option<&str>) -> Value {
let Some(fields) = fields.map(str::trim).filter(|f| !f.is_empty()) else {
return resource.clone();
};
let mut selection = FieldTree::default();
for name in fields.split(',') {
selection.insert(name.trim());
}
for always in ["id", "href", "@type"] {
selection.insert(always);
}
selection.project(resource)
}
#[derive(Default)]
struct FieldTree {
whole: bool,
children: BTreeMap<String, FieldTree>,
}
impl FieldTree {
fn insert(&mut self, name: &str) {
let Some((head, rest)) = split_field(name) else {
return;
};
let child = self.children.entry(head.to_owned()).or_default();
match rest {
Some(rest) => child.insert(rest),
None => child.whole = true,
}
}
fn project(&self, value: &Value) -> Value {
match value {
Value::Array(items) => Value::Array(
items
.iter()
.map(|item| self.project(item))
.collect::<Vec<_>>(),
),
Value::Object(map) => {
let mut out = Map::new();
for (key, member) in map {
let Some(child) = self.children.get(key) else {
continue;
};
if child.whole || child.children.is_empty() {
out.insert(key.clone(), member.clone());
} else {
out.insert(key.clone(), child.project(member));
}
}
Value::Object(out)
}
other => other.clone(),
}
}
}
fn split_field(name: &str) -> Option<(&str, Option<&str>)> {
if name.is_empty() {
return None;
}
Some(match name.split_once('.') {
Some((head, rest)) if !head.is_empty() && !rest.is_empty() => (head, Some(rest)),
_ => (name, None),
})
}
pub fn apply_merge_patch(target: &mut Value, patch: &Value) {
let Some(patch_object) = patch.as_object() else {
*target = patch.clone();
return;
};
if !target.is_object() {
*target = Value::Object(Map::new());
}
let Some(target_object) = target.as_object_mut() else {
return;
};
for (key, value) in patch_object {
if value.is_null() {
target_object.shift_remove(key);
} else if let Some(existing) = target_object.get_mut(key) {
apply_merge_patch(existing, value);
} else {
let mut fresh = Value::Null;
apply_merge_patch(&mut fresh, value);
target_object.insert(key.clone(), fresh);
}
}
}
pub fn apply_json_patch(target: &mut Value, patch: &Value) -> Result<(), String> {
let Some(operations) = patch.as_array() else {
return Err("JSON Patch body must be an array of operations".to_owned());
};
let mut draft = target.clone();
for operation in operations {
apply_one(&mut draft, operation)?;
}
*target = draft;
Ok(())
}
fn apply_one(target: &mut Value, operation: &Value) -> Result<(), String> {
let op = operation
.get("op")
.and_then(Value::as_str)
.ok_or_else(|| "operation is missing 'op'".to_owned())?;
let pointer = operation
.get("path")
.and_then(Value::as_str)
.ok_or_else(|| "operation is missing 'path'".to_owned())?;
match op {
"add" => {
let value = operation
.get("value")
.ok_or_else(|| "'add' is missing 'value'".to_owned())?;
add_path(target, pointer, value.clone())
}
"replace" => {
let value = operation
.get("value")
.ok_or_else(|| "'replace' is missing 'value'".to_owned())?;
replace_path(target, pointer, value.clone())
}
"remove" => remove_path(target, pointer),
"test" => {
let expected = operation
.get("value")
.ok_or_else(|| "'test' is missing 'value'".to_owned())?;
let actual = resolve_pointer(target, pointer)
.ok_or_else(|| format!("path '{pointer}' does not exist"))?;
if patch_values_equal(actual, expected) {
Ok(())
} else {
Err(format!("test failed at '{pointer}'"))
}
}
"move" | "copy" => {
let from = operation
.get("from")
.and_then(Value::as_str)
.ok_or_else(|| format!("'{op}' is missing 'from'"))?;
if op == "move" && is_proper_prefix(from, pointer) {
return Err(format!(
"cannot move '{from}' into its own child '{pointer}'"
));
}
let value = resolve_pointer(target, from)
.ok_or_else(|| format!("path '{from}' does not exist"))?
.clone();
if op == "move" {
remove_path(target, from)?;
}
add_path(target, pointer, value)
}
other => Err(format!("unsupported operation '{other}'")),
}
}
fn resolve_path_multi<'a>(resource: &'a Value, path: &str) -> Vec<&'a Value> {
let mut current = vec![resource];
for segment in path.split('.') {
let mut next = Vec::new();
for value in current {
match value {
Value::Object(map) => next.extend(map.get(segment)),
Value::Array(items) => match segment.parse::<usize>() {
Ok(index) => next.extend(items.get(index)),
Err(_) => next.extend(
items
.iter()
.filter_map(|item| item.as_object()?.get(segment)),
),
},
_ => {}
}
}
if next.is_empty() {
return Vec::new();
}
current = next;
}
current
}
fn resolve_path<'a>(resource: &'a Value, path: &str) -> Option<&'a Value> {
resolve_path_multi(resource, path).into_iter().next()
}
fn resolve_pointer<'a>(root: &'a Value, pointer: &str) -> Option<&'a Value> {
if pointer.is_empty() {
return Some(root);
}
root.pointer(pointer)
}
fn split_pointer(pointer: &str) -> Result<(&str, String), String> {
let (parent, token) = pointer
.rsplit_once('/')
.ok_or_else(|| format!("'{pointer}' is not a JSON Pointer"))?;
Ok((parent, token.replace("~1", "/").replace("~0", "~")))
}
fn is_proper_prefix(prefix: &str, pointer: &str) -> bool {
pointer.len() > prefix.len()
&& pointer.starts_with(prefix)
&& pointer.as_bytes().get(prefix.len()) == Some(&b'/')
}
fn add_path(root: &mut Value, pointer: &str, value: Value) -> Result<(), String> {
if pointer.is_empty() {
*root = value;
return Ok(());
}
let (parent_pointer, token) = split_pointer(pointer)?;
let parent = root
.pointer_mut(parent_pointer)
.ok_or_else(|| format!("path '{parent_pointer}' does not exist"))?;
match parent {
Value::Object(map) => {
map.insert(token, value);
Ok(())
}
Value::Array(items) => {
if token == "-" {
items.push(value);
return Ok(());
}
let index = array_index(&token)?;
if index > items.len() {
return Err(format!("index {index} is out of bounds"));
}
items.insert(index, value);
Ok(())
}
_ => Err(format!("path '{parent_pointer}' is not a container")),
}
}
fn replace_path(root: &mut Value, pointer: &str, value: Value) -> Result<(), String> {
if pointer.is_empty() {
*root = value;
return Ok(());
}
let (parent_pointer, token) = split_pointer(pointer)?;
let parent = root
.pointer_mut(parent_pointer)
.ok_or_else(|| format!("path '{parent_pointer}' does not exist"))?;
match parent {
Value::Object(map) => match map.get_mut(&token) {
Some(slot) => {
*slot = value;
Ok(())
}
None => Err(format!("path '{pointer}' does not exist")),
},
Value::Array(items) => {
let index = array_index(&token)?;
match items.get_mut(index) {
Some(slot) => {
*slot = value;
Ok(())
}
None => Err(format!("index {index} is out of bounds")),
}
}
_ => Err(format!("path '{parent_pointer}' is not a container")),
}
}
fn array_index(token: &str) -> Result<usize, String> {
let invalid = || format!("'{token}' is not an array index");
let valid = match token.as_bytes() {
[] => false,
[b'0'] => true,
[first, ..] if !first.is_ascii_digit() || *first == b'0' => false,
rest => rest.iter().all(u8::is_ascii_digit),
};
if !valid {
return Err(invalid());
}
token.parse().map_err(|_| invalid())
}
fn remove_path(root: &mut Value, pointer: &str) -> Result<(), String> {
let (parent_pointer, token) = split_pointer(pointer)?;
let parent = root
.pointer_mut(parent_pointer)
.ok_or_else(|| format!("path '{parent_pointer}' does not exist"))?;
match parent {
Value::Object(map) => map
.shift_remove(&token)
.map(|_| ())
.ok_or_else(|| format!("path '{pointer}' does not exist")),
Value::Array(items) => {
let index = array_index(&token)?;
if index >= items.len() {
return Err(format!("index {index} is out of bounds"));
}
items.remove(index);
Ok(())
}
_ => Err(format!("path '{parent_pointer}' is not a container")),
}
}
fn patch_values_equal(actual: &Value, expected: &Value) -> bool {
match (actual, expected) {
(Value::Number(a), Value::Number(b)) => {
a == b || decimal_opt::compare(a.as_str(), b.as_str()) == Some(Ordering::Equal)
}
(Value::Array(a), Value::Array(b)) => {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| patch_values_equal(x, y))
}
(Value::Object(a), Value::Object(b)) => {
a.len() == b.len()
&& a.iter()
.all(|(key, x)| b.get(key).is_some_and(|y| patch_values_equal(x, y)))
}
_ => actual == expected,
}
}
fn scalar_eq(actual: &Value, expected: &str) -> bool {
match actual {
Value::String(s) => s == expected,
Value::Number(n) => decimal_opt::compare(n.as_str(), expected) == Some(Ordering::Equal),
Value::Bool(b) => b.to_string() == expected,
Value::Null => expected == "null",
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn query(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
pairs
.iter()
.map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
.collect()
}
#[test]
fn filters_on_nested_and_non_string_attributes() {
let resource = json!({
"lifecycleStatus": "Active",
"isBundle": false,
"productSpecification": {"id": "9881"},
});
assert!(matches_filters(
&resource,
&query(&[("lifecycleStatus", "Active")])
));
assert!(matches_filters(&resource, &query(&[("isBundle", "false")])));
assert!(matches_filters(
&resource,
&query(&[("productSpecification.id", "9881")])
));
assert!(!matches_filters(
&resource,
&query(&[("lifecycleStatus", "Retired")])
));
assert!(!matches_filters(&resource, &query(&[("missing", "x")])));
}
#[test]
fn a_nested_path_is_not_mistaken_for_an_operator() {
let resource = json!({"productSpecification": {"id": "9881"}});
assert!(matches_filters(
&resource,
&query(&[("productSpecification.id", "9881")])
));
}
#[test]
fn comparison_operators_bound_a_range() {
let resource = json!({"orderDate": "2026-06-15T00:00:00Z", "quantity": 5});
assert!(matches_filters(
&resource,
&query(&[("orderDate.gte", "2026-01-01")])
));
assert!(matches_filters(
&resource,
&query(&[("orderDate.lt", "2027-01-01")])
));
assert!(!matches_filters(
&resource,
&query(&[("orderDate.gt", "2027-01-01")])
));
assert!(matches_filters(&resource, &query(&[("quantity.lt", "10")])));
assert!(matches_filters(&resource, &query(&[("quantity.gte", "5")])));
assert!(!matches_filters(&resource, &query(&[("quantity.gt", "5")])));
}
#[test]
fn timestamps_compare_as_instants_not_as_text() {
let resource = json!({"orderDate": "2026-01-01T01:00:00+02:00"});
assert!(matches_filters(
&resource,
&query(&[("orderDate.lt", "2026-01-01T00:00:00Z")])
));
assert!(!matches_filters(
&resource,
&query(&[("orderDate.gt", "2026-01-01T00:00:00Z")])
));
let same = json!({"orderDate": "2026-01-01T02:00:00+02:00"});
assert!(matches_filters(
&same,
&query(&[("orderDate.gte", "2026-01-01T00:00:00Z")])
));
assert!(matches_filters(
&same,
&query(&[("orderDate.lte", "2026-01-01T00:00:00Z")])
));
}
#[test]
fn a_date_only_bound_is_that_days_midnight_utc() {
let resource = json!({"orderDate": "2026-06-15T10:00:00Z"});
assert!(matches_filters(
&resource,
&query(&[("orderDate.gte", "2026-01-01")])
));
assert!(matches_filters(
&resource,
&query(&[("orderDate.lt", "2027-01-01")])
));
assert!(!matches_filters(
&resource,
&query(&[("orderDate.lt", "2026-06-15")])
));
}
#[test]
fn precise_numbers_compare_by_value_in_filters_sorting_and_patch_tests() {
let mut bills: Vec<Value> =
serde_json::from_str(r#"[{"n":9007199254740992.02},{"n":9007199254740992.01}]"#)
.unwrap();
assert!(matches_filters(
&bills[0],
&query(&[("n.gt", "9007199254740992.01")])
));
assert!(matches_filters(
&bills[1],
&query(&[("n", "900719925474099201e-2")])
));
sort_resources(&mut bills, "n");
assert_eq!(bills[0]["n"].to_string(), "9007199254740992.01");
let mut target: Value =
serde_json::from_str(r#"{"items":[{"a":11.90,"b":-1e999999999999999999999,"c":0}]}"#)
.unwrap();
let patch: Value = serde_json::from_str(r#"[{"op":"test","path":"/items","value":[{"c":-0.0,"b":-10e999999999999999999998,"a":11.9}]}]"#).unwrap();
apply_json_patch(&mut target, &patch).unwrap();
let unequal: Value =
serde_json::from_str(r#"[{"op":"test","path":"/n","value":9007199254740992.02}]"#)
.unwrap();
assert!(apply_json_patch(&mut bills[0], &unequal).is_err());
}
#[test]
fn sorting_by_a_timestamp_orders_by_instant() {
let mut resources = vec![
json!({"id": "a", "orderDate": "2026-01-01T01:00:00+02:00"}),
json!({"id": "b", "orderDate": "2026-01-01T00:00:00Z"}),
];
sort_resources(&mut resources, "orderDate");
assert_eq!(resources[0]["id"], "a", "23:00Z the previous day is first");
}
#[test]
fn a_lifecycle_name_is_not_read_as_a_date() {
let resource = json!({"lifecycleStatus": "Launched"});
assert!(matches_filters(
&resource,
&query(&[("lifecycleStatus.gt", "Active")])
));
assert!(!matches_filters(
&resource,
&query(&[("lifecycleStatus.gt", "Retired")])
));
}
#[test]
fn a_comma_list_matches_any_of_its_values() {
let resource = json!({"state": "pending"});
assert!(matches_filters(
&resource,
&query(&[("state", "held,pending")])
));
assert!(!matches_filters(
&resource,
&query(&[("state", "held,failed")])
));
}
#[test]
fn ne_and_regex_are_supported() {
let resource = json!({"name": "Basic Firewall", "state": "held"});
assert!(matches_filters(
&resource,
&query(&[("state.ne", "pending")])
));
assert!(!matches_filters(&resource, &query(&[("state.ne", "held")])));
assert!(matches_filters(
&resource,
&query(&[("name.regex", "Basic*")])
));
assert!(!matches_filters(
&resource,
&query(&[("name.regex", "Adv*")])
));
}
#[test]
fn reserved_parameters_do_not_filter() {
let resource = json!({"id": "1"});
assert!(matches_filters(
&resource,
&query(&[("limit", "20"), ("fields", "id"), ("sort", "name")])
));
}
#[test]
fn sorting_applies_keys_in_order_and_honours_the_minus_prefix() {
let mut items = vec![
json!({"name": "b", "version": 2}),
json!({"name": "a", "version": 1}),
json!({"name": "a", "version": 3}),
];
sort_resources(&mut items, "name,-version");
assert_eq!(
items,
vec![
json!({"name": "a", "version": 3}),
json!({"name": "a", "version": 1}),
json!({"name": "b", "version": 2}),
]
);
}
#[test]
fn resources_missing_the_sort_key_go_last() {
let mut items = vec![json!({"id": "1"}), json!({"id": "2", "name": "a"})];
sort_resources(&mut items, "name");
assert_eq!(items[0]["id"], "2");
}
#[test]
fn projection_always_keeps_identity_members() {
let resource = json!({"id": "1", "href": "/x/1", "@type": "ProductOffering", "name": "n", "description": "d"});
let projected = project_fields(&resource, Some("name"));
assert_eq!(
projected,
json!({"id": "1", "href": "/x/1", "@type": "ProductOffering", "name": "n"})
);
}
#[test]
fn merge_patch_deletes_with_null_and_merges_nested() {
let mut target = json!({"name": "old", "drop": 1, "nested": {"keep": 1, "change": 2}});
apply_merge_patch(
&mut target,
&json!({"name": "new", "drop": null, "nested": {"change": 3}}),
);
assert_eq!(
target,
json!({"name": "new", "nested": {"keep": 1, "change": 3}})
);
}
#[test]
fn json_patch_supports_the_full_operation_set() {
let mut target = json!({"a": 1, "list": [1, 2, 3]});
apply_json_patch(
&mut target,
&json!([{"op": "replace", "path": "/a", "value": 9}]),
)
.unwrap();
assert_eq!(target["a"], 9);
apply_json_patch(&mut target, &json!([{"op": "remove", "path": "/list/1"}])).unwrap();
assert_eq!(target["list"], json!([1, 3]));
apply_json_patch(
&mut target,
&json!([{"op": "add", "path": "/list/-", "value": 4}]),
)
.unwrap();
assert_eq!(target["list"], json!([1, 3, 4]));
apply_json_patch(
&mut target,
&json!([{"op": "copy", "from": "/a", "path": "/b"}]),
)
.unwrap();
assert_eq!(target["b"], 9);
apply_json_patch(
&mut target,
&json!([{"op": "move", "from": "/b", "path": "/c"}]),
)
.unwrap();
assert!(target.get("b").is_none());
assert_eq!(target["c"], 9);
}
#[test]
fn json_patch_is_all_or_nothing() {
let mut target = json!({"a": 1, "b": 2});
let patch = json!([
{"op": "replace", "path": "/a", "value": 9},
{"op": "remove", "path": "/nope"},
]);
assert!(apply_json_patch(&mut target, &patch).is_err());
assert_eq!(
target,
json!({"a": 1, "b": 2}),
"the first op must be undone"
);
}
#[test]
fn json_patch_reports_failures() {
let mut target = json!({"a": 1});
assert!(apply_json_patch(&mut target, &json!({"not": "an array"})).is_err());
assert!(
apply_json_patch(
&mut target,
&json!([{"op": "test", "path": "/a", "value": 2}])
)
.is_err()
);
assert!(
apply_json_patch(&mut target, &json!([{"op": "frobnicate", "path": "/a"}])).is_err()
);
assert!(
apply_json_patch(&mut target, &json!([{"op": "remove", "path": "/nope"}])).is_err()
);
}
#[test]
fn json_pointer_escapes_are_decoded() {
let mut target = json!({"a/b": 1, "c~d": 2});
apply_json_patch(&mut target, &json!([{"op": "remove", "path": "/a~1b"}])).unwrap();
apply_json_patch(&mut target, &json!([{"op": "remove", "path": "/c~0d"}])).unwrap();
assert_eq!(target, json!({}));
}
#[test]
fn replace_overwrites_an_array_element_rather_than_inserting_one() {
let mut target = json!({"list": [1, 2, 3]});
apply_json_patch(
&mut target,
&json!([{"op": "replace", "path": "/list/1", "value": 9}]),
)
.unwrap();
assert_eq!(target["list"], json!([1, 9, 3]));
let mut target = json!({"list": [1, 2, 3]});
apply_json_patch(
&mut target,
&json!([{"op": "add", "path": "/list/1", "value": 9}]),
)
.unwrap();
assert_eq!(target["list"], json!([1, 9, 2, 3]), "add still inserts");
}
#[test]
fn replace_requires_the_target_to_exist() {
let mut target = json!({"a": 1, "list": [1]});
assert!(
apply_json_patch(
&mut target,
&json!([{"op": "replace", "path": "/nope", "value": 9}])
)
.is_err()
);
assert!(
apply_json_patch(
&mut target,
&json!([{"op": "replace", "path": "/list/5", "value": 9}])
)
.is_err()
);
assert!(
apply_json_patch(
&mut target,
&json!([{"op": "replace", "path": "/list/-", "value": 9}])
)
.is_err(),
"'-' addresses the position after the last element, which holds nothing"
);
assert_eq!(target, json!({"a": 1, "list": [1]}));
}
#[test]
fn a_location_may_not_be_moved_into_its_own_child() {
let mut target = json!({"a": {"b": {}}});
assert!(
apply_json_patch(
&mut target,
&json!([{"op": "move", "from": "/a", "path": "/a/b/c"}])
)
.is_err()
);
let mut target = json!({"ab": 1});
apply_json_patch(
&mut target,
&json!([{"op": "move", "from": "/ab", "path": "/abc"}]),
)
.unwrap();
assert_eq!(target, json!({"abc": 1}));
}
#[test]
fn array_indices_reject_the_forms_rfc_6901_excludes() {
let mut target = json!({"list": [1, 2, 3]});
for path in ["/list/01", "/list/+1", "/list/ 1"] {
assert!(
apply_json_patch(&mut target, &json!([{"op": "remove", "path": path}])).is_err(),
"{path} is not an array index"
);
}
}
#[test]
fn a_filter_descends_into_a_collection() {
let resource = json!({
"relatedParty": [
{"id": "7", "role": "seller"},
{"id": "42", "role": "buyer"},
],
"characteristic": [{"name": "speed", "value": 100}],
});
assert!(matches_filters(
&resource,
&query(&[("relatedParty.id", "42")])
));
assert!(matches_filters(
&resource,
&query(&[("relatedParty.id", "7")])
));
assert!(!matches_filters(
&resource,
&query(&[("relatedParty.id", "99")])
));
assert!(matches_filters(
&resource,
&query(&[("characteristic.name", "speed")])
));
assert!(matches_filters(
&resource,
&query(&[
("relatedParty.role", "buyer"),
("characteristic.value.gte", "50")
])
));
}
#[test]
fn an_explicit_index_still_selects_one_element() {
let resource = json!({"relatedParty": [{"id": "7"}, {"id": "42"}]});
assert!(matches_filters(
&resource,
&query(&[("relatedParty.0.id", "7")])
));
assert!(!matches_filters(
&resource,
&query(&[("relatedParty.0.id", "42")])
));
}
#[test]
fn ne_over_a_collection_means_no_element_matches() {
let resource = json!({"relatedParty": [{"role": "seller"}, {"role": "buyer"}]});
assert!(!matches_filters(
&resource,
&query(&[("relatedParty.role.ne", "buyer")])
));
assert!(matches_filters(
&resource,
&query(&[("relatedParty.role.ne", "auditor")])
));
}
#[test]
fn projection_selects_into_a_nested_member() {
let resource = json!({
"id": "1",
"name": "n",
"productSpecification": {"id": "9", "name": "spec", "version": "1.0"},
"characteristic": [{"name": "speed", "value": 100}],
});
let projected = project_fields(&resource, Some("productSpecification.id"));
assert_eq!(
projected,
json!({"id": "1", "productSpecification": {"id": "9"}})
);
let projected = project_fields(&resource, Some("characteristic.name"));
assert_eq!(
projected,
json!({"id": "1", "characteristic": [{"name": "speed"}]})
);
let projected = project_fields(
&resource,
Some("productSpecification,productSpecification.id"),
);
assert_eq!(
projected["productSpecification"],
json!({"id": "9", "name": "spec", "version": "1.0"})
);
}
#[test]
fn glob_matching_covers_prefix_suffix_and_single_characters() {
assert!(matches_glob("Basic Firewall", "Basic*"));
assert!(matches_glob("Basic Firewall", "*Firewall"));
assert!(matches_glob("Basic Firewall", "^Basic*ll$"));
assert!(matches_glob("abc", "a?c"));
assert!(!matches_glob("abc", "a?"));
}
}