Skip to main content

json_ld/syntax/
compare.rs

1use json_syntax::JsonValue;
2
3/// JSON-LD comparison.
4pub trait JsonLdCompare {
5	fn compare_json_ld(&self, other: &Self) -> bool;
6}
7
8impl JsonLdCompare for JsonValue {
9	fn compare_json_ld(&self, other: &Self) -> bool {
10		match (self, other) {
11			(Self::Null, Self::Null) => true,
12			(Self::Boolean(a), Self::Boolean(b)) => a == b,
13			(Self::Number(a), Self::Number(b)) => a == b,
14			(Self::String(a), Self::String(b)) => a == b,
15			(Self::Array(a), Self::Array(b)) if a.len() == b.len() => {
16				let mut selected = Vec::new();
17				selected.resize(b.len(), false);
18
19				'next_item: for item in a {
20					for (other, selected) in b.iter().zip(selected.iter_mut()) {
21						if !*selected && item.compare_json_ld(other) {
22							*selected = true;
23							continue 'next_item;
24						}
25					}
26
27					return false;
28				}
29
30				true
31			}
32			(Self::Object(a), Self::Object(b)) if a.len() == b.len() => {
33				for entry in a {
34					match b.get_unique(entry.0).expect("invalid JSON-LD") {
35						Some(value) => {
36							if !entry.1.compare_json_ld(value) {
37								return false;
38							}
39						}
40						None => return false,
41					}
42				}
43
44				true
45			}
46			_ => false,
47		}
48	}
49}