Skip to main content

jsonschema_value/ext/
cmp.rs

1use num_cmp::NumCmp;
2use serde_json::{Map, Value};
3
4macro_rules! num_cmp {
5    ($left:expr, $right:expr) => {
6        if let Some(b) = $right.as_u64() {
7            NumCmp::num_eq($left, b)
8        } else if let Some(b) = $right.as_i64() {
9            NumCmp::num_eq($left, b)
10        } else {
11            #[cfg(feature = "arbitrary-precision")]
12            {
13                use crate::ext::numeric::bignum;
14                use fraction::BigFraction;
15
16                let left_frac = BigFraction::from($left);
17
18                // Check BigInt/BigFraction BEFORE f64 to avoid precision loss
19                if let Some(right_bigint) = bignum::try_parse_bigint($right) {
20                    let right_frac = BigFraction::from(right_bigint);
21                    left_frac == right_frac
22                } else if let Some(right_frac) = bignum::try_parse_bigfraction($right) {
23                    left_frac == right_frac
24                } else if let Some(b) = $right.as_f64() {
25                    // Fallback to f64 for scientific notation or other cases
26                    left_frac == BigFraction::from(b)
27                } else {
28                    // Can't parse right - not equal
29                    false
30                }
31            }
32            #[cfg(not(feature = "arbitrary-precision"))]
33            {
34                if let Some(b) = $right.as_f64() {
35                    NumCmp::num_eq($left, b)
36                } else {
37                    unreachable!("Numbers always fit in u64/i64/f64 without arbitrary-precision")
38                }
39            }
40        }
41    };
42}
43
44/// Compare two JSON numbers for equality with arbitrary precision support
45#[inline]
46#[doc(hidden)]
47#[must_use]
48pub fn equal_numbers(left: &serde_json::Number, right: &serde_json::Number) -> bool {
49    #[cfg(feature = "arbitrary-precision")]
50    {
51        use crate::ext::numeric::bignum;
52        use fraction::BigFraction;
53
54        // Check BigInt/BigFraction first to avoid precision loss from f64 conversion
55        if let Some(left_bigint) = bignum::try_parse_bigint(left) {
56            if let Some(right_bigint) = bignum::try_parse_bigint(right) {
57                left_bigint == right_bigint
58            } else if let Some(b) = right.as_u64() {
59                left_bigint == num_bigint::BigInt::from(b)
60            } else if let Some(b) = right.as_i64() {
61                left_bigint == num_bigint::BigInt::from(b)
62            } else if let Some(right_frac) = bignum::try_parse_bigfraction(right) {
63                BigFraction::from(left_bigint) == right_frac
64            } else if let Some(b) = right.as_f64() {
65                BigFraction::from(left_bigint) == BigFraction::from(b)
66            } else {
67                unreachable!("Right is not parseable as any numeric type - should not happen for valid JSON numbers")
68            }
69        } else if let Some(left_frac) = bignum::try_parse_bigfraction(left) {
70            if let Some(right_frac) = bignum::try_parse_bigfraction(right) {
71                left_frac == right_frac
72            } else if let Some(right_bigint) = bignum::try_parse_bigint(right) {
73                left_frac == BigFraction::from(right_bigint)
74            } else if let Some(b) = right.as_u64() {
75                left_frac == BigFraction::from(b)
76            } else if let Some(b) = right.as_i64() {
77                left_frac == BigFraction::from(b)
78            } else if let Some(b) = right.as_f64() {
79                left_frac == BigFraction::from(b)
80            } else {
81                unreachable!("Right is not parseable as any numeric type - should not happen for valid JSON numbers")
82            }
83        } else if let Some(a) = left.as_u64() {
84            num_cmp!(a, right)
85        } else if let Some(a) = left.as_i64() {
86            num_cmp!(a, right)
87        } else if let Some(a) = left.as_f64() {
88            num_cmp!(a, right)
89        } else {
90            // Left is a number in scientific notation that doesn't fit in f64
91            // (e.g., 1e309, 1e400). With arbitrary-precision, these are stored as
92            // strings but can't be converted to any numeric type we support.
93            // Return false as we can't reliably compare them.
94            false
95        }
96    }
97    #[cfg(not(feature = "arbitrary-precision"))]
98    {
99        if let Some(a) = left.as_u64() {
100            num_cmp!(a, right)
101        } else if let Some(a) = left.as_i64() {
102            num_cmp!(a, right)
103        } else if let Some(a) = left.as_f64() {
104            num_cmp!(a, right)
105        } else {
106            unreachable!("Numbers always fit in u64/i64/f64 without arbitrary-precision")
107        }
108    }
109}
110
111/// Tests for two JSON values to be equal using the JSON Schema semantic.
112#[must_use]
113#[allow(clippy::missing_panics_doc)]
114pub fn equal(left: &Value, right: &Value) -> bool {
115    match (left, right) {
116        (Value::String(left), Value::String(right)) => left == right,
117        (Value::Bool(left), Value::Bool(right)) => left == right,
118        (Value::Null, Value::Null) => true,
119        (Value::Number(left), Value::Number(right)) => equal_numbers(left, right),
120        (Value::Array(left), Value::Array(right)) => equal_arrays(left, right),
121        (Value::Object(left), Value::Object(right)) => equal_objects(left, right),
122        (_, _) => false,
123    }
124}
125
126#[inline]
127#[must_use]
128pub fn equal_arrays(left: &[Value], right: &[Value]) -> bool {
129    left.len() == right.len() && {
130        let mut idx = 0_usize;
131        while idx < left.len() {
132            if !equal(&left[idx], &right[idx]) {
133                return false;
134            }
135            idx += 1;
136        }
137        true
138    }
139}
140
141#[inline]
142#[must_use]
143pub fn equal_objects(left: &Map<String, Value>, right: &Map<String, Value>) -> bool {
144    left.len() == right.len()
145        && left
146            .iter()
147            .zip(right)
148            .all(|((ka, va), (kb, vb))| ka == kb && equal(va, vb))
149}
150
151#[cfg(test)]
152mod tests {
153    use super::equal;
154    use serde_json::{json, Value};
155    use test_case::test_case;
156
157    #[test_case(&json!(1), &json!(1.0))]
158    #[test_case(&json!([2]), &json!([2.0]))]
159    #[test_case(&json!([-3]), &json!([-3.0]))]
160    #[test_case(&json!({"a": 1}), &json!({"a": 1.0}))]
161    fn are_equal(left: &Value, right: &Value) {
162        assert!(equal(left, right));
163    }
164
165    #[test_case(&json!(1), &json!(2.0))]
166    #[test_case(&json!([]), &json!(["foo"]))]
167    #[test_case(&json!([-3]), &json!([-4.0]))]
168    #[test_case(&json!({"a": 1}), &json!({"a": 1.0, "b": 2}))]
169    fn are_not_equal(left: &Value, right: &Value) {
170        assert!(!equal(left, right));
171    }
172
173    #[cfg(feature = "arbitrary-precision")]
174    mod arbitrary_precision {
175        use super::equal;
176        use serde_json::Value;
177        use test_case::test_case;
178
179        fn parse_json(s: &str) -> Value {
180            serde_json::from_str(s).unwrap()
181        }
182        #[test_case("0.1", "0.1", true; "exact decimal match")]
183        #[test_case("0.1", "0.10", true; "decimal with trailing zero")]
184        #[test_case("0.1", "0.100000", true; "decimal with many trailing zeros")]
185        #[test_case("0.1", "0.2", false; "different decimals")]
186        #[test_case("0.3", "0.30", true; "another trailing zero case")]
187        #[test_case("1.0", "1", true; "decimal vs integer")]
188        #[test_case("1.00", "1.0", true; "decimals with different trailing zeros")]
189        #[test_case(
190            "99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999.5",
191            "99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999.5",
192            true;
193            "huge decimal self equality"
194        )]
195        #[test_case(
196            "99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999.5",
197            "99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999.6",
198            false;
199            "huge decimals different"
200        )]
201        #[test_case(
202            "99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999.5",
203            "100",
204            false;
205            "huge decimal vs small integer"
206        )]
207        #[test_case("18446744073709551616", "18446744073709551616", true; "large integer self equality")]
208        #[test_case("18446744073709551616", "18446744073709551617", false; "large integers different")]
209        #[test_case("99999999999999999999999999999999999999", "99999999999999999999999999999999999999", true; "very large integer equality")]
210        #[test_case("99999999999999999999999999999999999999", "100", false; "very large vs small integer")]
211        #[test_case("100", "100.0", true; "small integer vs decimal")]
212        #[test_case("0.1", "1", false; "small decimal vs integer")]
213        #[test_case("1.0", "1", true; "decimal one vs integer one")]
214        #[test_case("18446744073709551616", "100.5", false; "large int vs decimal")]
215        #[test_case("18446744073709551616.0", "18446744073709551616", true; "large int as decimal vs large int")]
216        #[test_case("-0.1", "-0.1", true; "negative decimal equality")]
217        #[test_case("-0.1", "-0.10", true; "negative decimal trailing zero")]
218        #[test_case("-18446744073709551616", "-18446744073709551616", true; "negative large int")]
219        #[test_case("-18446744073709551616", "18446744073709551616", false; "negative vs positive large")]
220        #[test_case("-100.5", "-100.5", true; "negative decimal match")]
221        #[test_case("-100.5", "100.5", false; "negative vs positive decimal")]
222        #[test_case("0", "0.0", true; "zero integer vs decimal")]
223        #[test_case("0.0", "0.00", true; "zero decimals with different precision")]
224        #[test_case("-0.0", "0.0", true; "negative zero vs positive zero")]
225        #[test_case("1e10", "10000000000", true; "scientific notation vs integer")]
226        #[test_case("1e19", "10000000000000000000", true; "scientific integer beyond i64")]
227        #[test_case("1e19", "10000000000000000001", false; "scientific integer mismatch")]
228        #[test_case("1.5e2", "150", true; "decimal scientific vs integer")]
229        #[test_case("1.5e2", "150.0", true; "decimal scientific vs decimal")]
230        #[test_case(r"[0.1, 0.2, 0.3]", r"[0.1, 0.2, 0.3]", true; "array exact match")]
231        #[test_case(r"[0.1, 0.2]", r"[0.10, 0.20]", true; "array with trailing zeros")]
232        #[test_case(r"[18446744073709551616]", r"[18446744073709551616]", true; "array with large integer")]
233        #[test_case(r"[0.1, 0.2]", r"[0.1, 0.3]", false; "array different values")]
234        #[test_case(r#"{"value": 0.1}"#, r#"{"value": 0.1}"#, true; "object exact match")]
235        #[test_case(r#"{"value": 0.1}"#, r#"{"value": 0.10}"#, true; "object with trailing zero")]
236        #[test_case(r#"{"id": 18446744073709551616}"#, r#"{"id": 18446744073709551616}"#, true; "object with large integer")]
237        #[test_case(r#"{"value": 0.1}"#, r#"{"value": 0.2}"#, false; "object different values")]
238        #[test_case("18446744073709551616", "-1", false; "large positive bigint vs negative i64")]
239        #[test_case("18446744073709551616", "-100", false; "large positive bigint vs negative i64 small")]
240        #[test_case("-18446744073709551616", "-1", false; "large negative bigint vs small negative i64")]
241        #[test_case("18446744073709551616", "1e10", false; "large bigint vs scientific notation f64")]
242        #[test_case("10000000000", "1e10", true; "bigint vs scientific notation equal")]
243        #[test_case("-18446744073709551616", "-1.5e3", false; "negative bigint vs scientific notation")]
244        #[test_case("0.5", "5e-1", true; "bigfraction vs scientific notation equal")]
245        #[test_case("0.3", "3e-1", true; "bigfraction vs scientific equal exact")]
246        #[test_case("123.456", "1.23456e2", true; "bigfraction vs scientific notation")]
247        #[test_case("0.1", "1e-2", false; "bigfraction vs scientific not equal")]
248        #[test_case("1e309", "1e309", true; "huge scientific notation now handled")]
249        #[test_case("1e400", "1e400", true; "extreme scientific notation now handled")]
250        #[test_case("1e-400", "1e-400", true; "extreme small scientific notation self equality")]
251        #[test_case("1e309", "1", false; "huge scientific notation vs integer")]
252        fn arbitrary_precision_equality(left_str: &str, right_str: &str, should_equal: bool) {
253            let left = parse_json(left_str);
254            let right = parse_json(right_str);
255            assert_eq!(equal(&left, &right), should_equal);
256        }
257    }
258}