1use crate::json::{Value, stringify};
4use crate::strings;
5use std::cmp::Ordering;
6use std::fmt;
7
8#[derive(Clone, Debug, PartialEq, Eq)]
10pub struct IncomparableError(pub String);
11
12impl fmt::Display for IncomparableError {
13 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14 f.write_str(&self.0)
15 }
16}
17
18impl std::error::Error for IncomparableError {}
19
20fn type_of(v: &Value) -> &'static str {
22 match v {
23 Value::Array(_) => "object",
24 v => v.type_name(),
25 }
26}
27
28pub fn compare_checked(a: &Value, b: &Value) -> Result<Ordering, IncomparableError> {
32 match scalar_compare(a, b) {
33 Some(o) => Ok(o),
34 None if type_of(a) != type_of(b) => Err(IncomparableError(format!(
35 "Cannot compare values of different types: {} and {}",
36 type_of(a),
37 type_of(b)
38 ))),
39 None => Err(IncomparableError(format!(
40 "Unsupported type: {}",
41 type_of(a)
42 ))),
43 }
44}
45
46pub fn compare(a: &Value, b: &Value) -> Ordering {
50 scalar_compare(a, b).unwrap_or_else(|| {
51 let rank = |v: &Value| match v {
52 Value::Null => 0,
53 Value::Bool(_) => 1,
54 Value::Number(_) => 2,
55 Value::String(_) => 3,
56 Value::Array(_) => 4,
57 Value::Object(_) => 5,
58 };
59 rank(a)
60 .cmp(&rank(b))
61 .then_with(|| strings::utf8(&stringify(a), &stringify(b)))
62 })
63}
64
65fn scalar_compare(a: &Value, b: &Value) -> Option<Ordering> {
66 Some(match (a, b) {
67 (Value::String(x), Value::String(y)) => strings::utf8(x, y),
68 (Value::Number(x), Value::Number(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
70 (Value::Bool(x), Value::Bool(y)) => x.cmp(y),
71 (Value::Null, Value::Null) => Ordering::Equal,
72 (Value::Null, _) => Ordering::Less,
73 (_, Value::Null) => Ordering::Greater,
74 _ => return None,
75 })
76}
77
78pub fn equal(a: &Value, b: &Value) -> bool {
82 match (a, b) {
83 (Value::String(x), Value::String(y)) => x == y,
84 (Value::Number(x), Value::Number(y)) => x == y,
85 (Value::Bool(x), Value::Bool(y)) => x == y,
86 _ => false,
87 }
88}