1use std::cmp::Ordering;
8
9use serde_json::{Map, Value};
10
11use crate::number;
12
13pub fn is_object(value: &Value) -> bool {
15 matches!(value, Value::Object(map) if map.is_empty())
16}
17
18pub fn array_len(value: &Value) -> usize {
20 match value {
21 Value::Array(a) => a.len(),
22 Value::Object(o) => o.len(),
23 _ => 0,
24 }
25}
26
27pub fn array_values(value: &Value) -> Box<dyn Iterator<Item = &Value> + '_> {
29 match value {
30 Value::Array(a) => Box::new(a.iter()),
31 Value::Object(o) => Box::new(o.values()),
32 _ => Box::new(std::iter::empty()),
33 }
34}
35
36#[derive(Debug, Clone, Copy, PartialEq)]
38pub enum Number {
39 Int(i64),
41 Float(f64),
43}
44
45impl Number {
46 pub fn as_f64(self) -> f64 {
48 match self {
49 Number::Int(i) => i as f64,
50 Number::Float(f) => f,
51 }
52 }
53}
54
55pub fn json_number(n: &serde_json::Number) -> Number {
57 match n.as_i64() {
58 Some(i) => Number::Int(i),
59 None => Number::Float(n.as_f64().unwrap_or(0.0)),
60 }
61}
62
63pub fn numeric(value: &Value) -> Option<Number> {
65 match value {
66 Value::Number(n) => Some(json_number(n)),
67 Value::String(s) => numeric_str(s),
68 _ => None,
69 }
70}
71
72pub fn numeric_str(s: &str) -> Option<Number> {
74 numeric_str_ex(s).map(|(n, _)| n)
75}
76
77pub fn numeric_str_ex(s: &str) -> Option<(Number, i8)> {
85 numeric_bytes_ex(s.as_bytes())
86}
87
88pub fn numeric_bytes_ex(s: &[u8]) -> Option<(Number, i8)> {
91 let is_ws = |c: &u8| matches!(c, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C);
92 let lead = s.iter().position(|c| !is_ws(c))?;
93 let trail = s.iter().rposition(|c| !is_ws(c)).map_or(0, |i| i + 1);
94 let bytes = &s[lead..trail];
95 let mut i = 0;
96 if bytes[i] == b'+' || bytes[i] == b'-' {
97 i += 1;
98 }
99 let int_start = i;
100 while i < bytes.len() && bytes[i].is_ascii_digit() {
101 i += 1;
102 }
103 let int_digits = i - int_start;
104 let mut is_float = false;
105 let mut frac_digits = 0;
106 if i < bytes.len() && bytes[i] == b'.' {
107 is_float = true;
108 i += 1;
109 let frac_start = i;
110 while i < bytes.len() && bytes[i].is_ascii_digit() {
111 i += 1;
112 }
113 frac_digits = i - frac_start;
114 }
115 if int_digits == 0 && frac_digits == 0 {
116 return None;
117 }
118 if i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') {
119 let mut j = i + 1;
120 if j < bytes.len() && (bytes[j] == b'+' || bytes[j] == b'-') {
121 j += 1;
122 }
123 let exp_start = j;
124 while j < bytes.len() && bytes[j].is_ascii_digit() {
125 j += 1;
126 }
127 if j == exp_start {
128 return None;
129 }
130 is_float = true;
131 i = j;
132 }
133 if i != bytes.len() {
134 return None;
135 }
136 let float = || std::str::from_utf8(bytes).ok().and_then(|t| t.parse::<f64>().ok());
138 if !is_float {
139 let negative = bytes[0] == b'-';
140 let parsed = bytes[int_start..].iter().try_fold(0i64, |v, d| {
141 let v = v.checked_mul(10)?;
142 let d = i64::from(d - b'0');
143 if negative { v.checked_sub(d) } else { v.checked_add(d) }
144 });
145 if let Some(v) = parsed {
146 let trailing_ws = trail != s.len();
150 if v == i64::MIN && trailing_ws {
151 return Some((Number::Float(v as f64), -1));
152 }
153 return Some((Number::Int(v), 0));
154 }
155 let oflow = if negative { -1 } else { 1 };
156 return float().map(|f| (Number::Float(f), oflow));
157 }
158 float().map(|f| (Number::Float(f), 0))
159}
160
161pub fn truthy(value: &Value) -> bool {
163 match value {
164 Value::Null => false,
165 Value::Bool(b) => *b,
166 Value::Number(n) => json_number(n).as_f64() != 0.0,
167 Value::String(s) => !(s.is_empty() || s == "0"),
168 Value::Array(a) => !a.is_empty(),
169 Value::Object(_) => true,
171 }
172}
173
174pub fn to_string(value: &Value) -> Option<String> {
176 match value {
177 Value::Null | Value::Bool(false) => Some(String::new()),
178 Value::Bool(true) => Some("1".to_owned()),
179 Value::Number(n) => Some(match json_number(n) {
180 Number::Int(i) => i.to_string(),
181 Number::Float(f) => number::to_string(f),
182 }),
183 Value::String(s) => Some(s.clone()),
184 _ => None,
185 }
186}
187
188pub fn empty(value: &Value) -> bool {
190 !truthy(value)
191}
192
193pub fn loose_eq(a: &Value, b: &Value) -> bool {
195 use Value::*;
196 match (a, b) {
197 (Bool(_), _) | (_, Bool(_)) => truthy(a) == truthy(b),
198 (Null, Null) => true,
199 (Null, String(s)) | (String(s), Null) => s.is_empty(),
200 (Null, other) | (other, Null) => !truthy(other),
201 (Number(x), Number(y)) => num_eq(json_number(x), json_number(y)),
202 (Number(n), String(s)) | (String(s), Number(n)) => number_eq_string(json_number(n), s),
203 (String(x), String(y)) => smart_str_eq(x, y),
204 (Object(x), Object(y)) if x.is_empty() || y.is_empty() => {
205 x.is_empty() && y.is_empty()
207 }
208 (Object(o), Array(_)) | (Array(_), Object(o)) if o.is_empty() => false,
209 (Array(_) | Object(_), Array(_) | Object(_)) => arrays_eq(a, b),
210 (Object(o), Number(n)) | (Number(n), Object(o)) if o.is_empty() => {
212 num_eq(crate::value::Number::Int(1), json_number(n))
213 }
214 _ => false,
216 }
217}
218
219fn num_eq(x: Number, y: Number) -> bool {
220 match (x, y) {
221 (Number::Int(p), Number::Int(q)) => p == q,
222 _ => x.as_f64() == y.as_f64(),
223 }
224}
225
226fn number_eq_string(n: Number, s: &str) -> bool {
228 match numeric_str(s) {
229 Some(m) => num_eq(n, m),
230 None => {
231 let as_string = match n {
232 Number::Int(i) => i.to_string(),
233 Number::Float(f) => number::to_string(f),
234 };
235 as_string == s
236 }
237 }
238}
239
240fn smart_str_eq(a: &str, b: &str) -> bool {
242 let (Some((x, ox)), Some((y, oy))) = (numeric_str_ex(a), numeric_str_ex(b)) else {
243 return a == b;
244 };
245 if ox != 0 && ox == oy && x.as_f64() - y.as_f64() == 0.0 {
246 return a == b;
248 }
249 match (x, y) {
250 (Number::Int(p), Number::Int(q)) => p == q,
251 (Number::Int(_), Number::Float(_)) if oy != 0 => false,
252 (Number::Float(_), Number::Int(_)) if ox != 0 => false,
253 (Number::Float(p), Number::Float(q)) if p == q && !p.is_finite() => a == b,
254 _ => x.as_f64() == y.as_f64(),
255 }
256}
257
258fn entries(v: &Value) -> Vec<(String, &Value)> {
260 match v {
261 Value::Array(a) => a.iter().enumerate().map(|(i, v)| (i.to_string(), v)).collect(),
262 Value::Object(o) => o.iter().map(|(k, v)| (k.clone(), v)).collect(),
263 _ => Vec::new(),
264 }
265}
266
267fn arrays_eq(a: &Value, b: &Value) -> bool {
269 let (ea, eb) = (entries(a), entries(b));
270 if ea.len() != eb.len() {
271 return false;
272 }
273 let mb: Map<String, Value> = eb.iter().map(|(k, v)| (k.clone(), (*v).clone())).collect();
274 ea.iter().all(|(k, v)| mb.get(k).is_some_and(|w| loose_eq(v, w)))
275}
276
277pub fn compare_numbers(x: Number, y: Number) -> Ordering {
279 match (x, y) {
280 (Number::Int(p), Number::Int(q)) => p.cmp(&q),
281 _ => x.as_f64().partial_cmp(&y.as_f64()).unwrap_or(Ordering::Equal),
282 }
283}
284
285pub fn loose_str_eq(a: &[u8], b: &[u8]) -> bool {
289 match (std::str::from_utf8(a), std::str::from_utf8(b)) {
290 (Ok(x), Ok(y)) => smart_str_eq(x, y),
291 _ => a == b,
292 }
293}
294
295pub fn le_numbers(a: Number, b: Number) -> bool {
299 match (a, b) {
300 (Number::Int(p), Number::Int(q)) => p <= q,
301 _ => a.as_f64() <= b.as_f64(),
303 }
304}
305
306#[cfg(test)]
307mod tests {
308 use super::*;
309 use serde_json::json;
310
311 #[test]
312 fn numeric_strings() {
313 assert_eq!(numeric_str("8"), Some(Number::Int(8)));
314 assert_eq!(numeric_str(" 8"), Some(Number::Int(8)));
315 assert_eq!(numeric_str("8 "), Some(Number::Int(8)));
316 assert_eq!(numeric_str("-1.5"), Some(Number::Float(-1.5)));
317 assert_eq!(numeric_str(".5"), Some(Number::Float(0.5)));
318 assert_eq!(numeric_str("1e3"), Some(Number::Float(1000.0)));
319 assert_eq!(numeric_str("abc"), None);
320 assert_eq!(numeric_str("0x1A"), None);
321 assert_eq!(numeric_str(""), None);
322 assert_eq!(numeric_str("."), None);
323 }
324
325 #[test]
326 fn truthiness() {
327 assert!(truthy(&json!("false")));
328 assert!(!truthy(&json!("0")));
329 assert!(!truthy(&json!("")));
330 assert!(truthy(&json!({})));
331 assert!(!truthy(&json!([])));
332 }
333
334 #[test]
335 fn loose_equality_matches_php() {
336 assert!(!loose_eq(&json!(1.5), &json!("1.5abc")));
337 assert!(!loose_eq(&json!(0.30000000000000004), &json!("0.3")));
338 assert!(!loose_eq(&json!("abc"), &json!(0)));
339 assert!(!loose_eq(&json!(null), &json!("0")));
340 assert!(loose_eq(&json!("1e3"), &json!("1000")));
341 assert!(!loose_eq(&json!("9223372036854775808"), &json!("9223372036854775809")));
342 assert!(loose_eq(&json!([]), &json!(false)));
343 assert!(!loose_eq(&json!({}), &json!([])));
344 assert!(loose_eq(&json!({}), &json!(1)));
345 assert!(loose_eq(&json!({"0": 1}), &json!([1])));
346 }
347
348 #[test]
349 fn strings_of_floats() {
350 assert_eq!(to_string(&json!(1.0)).unwrap(), "1");
351 assert_eq!(to_string(&json!(1e25)).unwrap(), "1.0E+25");
352 }
353}