use std::cmp::Ordering;
use serde_json::{Map, Value};
use crate::number;
pub fn is_object(value: &Value) -> bool {
matches!(value, Value::Object(map) if map.is_empty())
}
pub fn array_len(value: &Value) -> usize {
match value {
Value::Array(a) => a.len(),
Value::Object(o) => o.len(),
_ => 0,
}
}
pub fn array_values(value: &Value) -> Box<dyn Iterator<Item = &Value> + '_> {
match value {
Value::Array(a) => Box::new(a.iter()),
Value::Object(o) => Box::new(o.values()),
_ => Box::new(std::iter::empty()),
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Number {
Int(i64),
Float(f64),
}
impl Number {
pub fn as_f64(self) -> f64 {
match self {
Number::Int(i) => i as f64,
Number::Float(f) => f,
}
}
}
pub fn json_number(n: &serde_json::Number) -> Number {
match n.as_i64() {
Some(i) => Number::Int(i),
None => Number::Float(n.as_f64().unwrap_or(0.0)),
}
}
pub fn numeric(value: &Value) -> Option<Number> {
match value {
Value::Number(n) => Some(json_number(n)),
Value::String(s) => numeric_str(s),
_ => None,
}
}
pub fn numeric_str(s: &str) -> Option<Number> {
numeric_str_ex(s).map(|(n, _)| n)
}
pub fn numeric_str_ex(s: &str) -> Option<(Number, i8)> {
numeric_bytes_ex(s.as_bytes())
}
pub fn numeric_bytes_ex(s: &[u8]) -> Option<(Number, i8)> {
let is_ws = |c: &u8| matches!(c, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C);
let lead = s.iter().position(|c| !is_ws(c))?;
let trail = s.iter().rposition(|c| !is_ws(c)).map_or(0, |i| i + 1);
let bytes = &s[lead..trail];
let mut i = 0;
if bytes[i] == b'+' || bytes[i] == b'-' {
i += 1;
}
let int_start = i;
while i < bytes.len() && bytes[i].is_ascii_digit() {
i += 1;
}
let int_digits = i - int_start;
let mut is_float = false;
let mut frac_digits = 0;
if i < bytes.len() && bytes[i] == b'.' {
is_float = true;
i += 1;
let frac_start = i;
while i < bytes.len() && bytes[i].is_ascii_digit() {
i += 1;
}
frac_digits = i - frac_start;
}
if int_digits == 0 && frac_digits == 0 {
return None;
}
if i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') {
let mut j = i + 1;
if j < bytes.len() && (bytes[j] == b'+' || bytes[j] == b'-') {
j += 1;
}
let exp_start = j;
while j < bytes.len() && bytes[j].is_ascii_digit() {
j += 1;
}
if j == exp_start {
return None;
}
is_float = true;
i = j;
}
if i != bytes.len() {
return None;
}
let float = || std::str::from_utf8(bytes).ok().and_then(|t| t.parse::<f64>().ok());
if !is_float {
let negative = bytes[0] == b'-';
let parsed = bytes[int_start..].iter().try_fold(0i64, |v, d| {
let v = v.checked_mul(10)?;
let d = i64::from(d - b'0');
if negative { v.checked_sub(d) } else { v.checked_add(d) }
});
if let Some(v) = parsed {
let trailing_ws = trail != s.len();
if v == i64::MIN && trailing_ws {
return Some((Number::Float(v as f64), -1));
}
return Some((Number::Int(v), 0));
}
let oflow = if negative { -1 } else { 1 };
return float().map(|f| (Number::Float(f), oflow));
}
float().map(|f| (Number::Float(f), 0))
}
pub fn truthy(value: &Value) -> bool {
match value {
Value::Null => false,
Value::Bool(b) => *b,
Value::Number(n) => json_number(n).as_f64() != 0.0,
Value::String(s) => !(s.is_empty() || s == "0"),
Value::Array(a) => !a.is_empty(),
Value::Object(_) => true,
}
}
pub fn to_string(value: &Value) -> Option<String> {
match value {
Value::Null | Value::Bool(false) => Some(String::new()),
Value::Bool(true) => Some("1".to_owned()),
Value::Number(n) => Some(match json_number(n) {
Number::Int(i) => i.to_string(),
Number::Float(f) => number::to_string(f),
}),
Value::String(s) => Some(s.clone()),
_ => None,
}
}
pub fn empty(value: &Value) -> bool {
!truthy(value)
}
pub fn loose_eq(a: &Value, b: &Value) -> bool {
use Value::*;
match (a, b) {
(Bool(_), _) | (_, Bool(_)) => truthy(a) == truthy(b),
(Null, Null) => true,
(Null, String(s)) | (String(s), Null) => s.is_empty(),
(Null, other) | (other, Null) => !truthy(other),
(Number(x), Number(y)) => num_eq(json_number(x), json_number(y)),
(Number(n), String(s)) | (String(s), Number(n)) => number_eq_string(json_number(n), s),
(String(x), String(y)) => smart_str_eq(x, y),
(Object(x), Object(y)) if x.is_empty() || y.is_empty() => {
x.is_empty() && y.is_empty()
}
(Object(o), Array(_)) | (Array(_), Object(o)) if o.is_empty() => false,
(Array(_) | Object(_), Array(_) | Object(_)) => arrays_eq(a, b),
(Object(o), Number(n)) | (Number(n), Object(o)) if o.is_empty() => {
num_eq(crate::value::Number::Int(1), json_number(n))
}
_ => false,
}
}
fn num_eq(x: Number, y: Number) -> bool {
match (x, y) {
(Number::Int(p), Number::Int(q)) => p == q,
_ => x.as_f64() == y.as_f64(),
}
}
fn number_eq_string(n: Number, s: &str) -> bool {
match numeric_str(s) {
Some(m) => num_eq(n, m),
None => {
let as_string = match n {
Number::Int(i) => i.to_string(),
Number::Float(f) => number::to_string(f),
};
as_string == s
}
}
}
fn smart_str_eq(a: &str, b: &str) -> bool {
let (Some((x, ox)), Some((y, oy))) = (numeric_str_ex(a), numeric_str_ex(b)) else {
return a == b;
};
if ox != 0 && ox == oy && x.as_f64() - y.as_f64() == 0.0 {
return a == b;
}
match (x, y) {
(Number::Int(p), Number::Int(q)) => p == q,
(Number::Int(_), Number::Float(_)) if oy != 0 => false,
(Number::Float(_), Number::Int(_)) if ox != 0 => false,
(Number::Float(p), Number::Float(q)) if p == q && !p.is_finite() => a == b,
_ => x.as_f64() == y.as_f64(),
}
}
fn entries(v: &Value) -> Vec<(String, &Value)> {
match v {
Value::Array(a) => a.iter().enumerate().map(|(i, v)| (i.to_string(), v)).collect(),
Value::Object(o) => o.iter().map(|(k, v)| (k.clone(), v)).collect(),
_ => Vec::new(),
}
}
fn arrays_eq(a: &Value, b: &Value) -> bool {
let (ea, eb) = (entries(a), entries(b));
if ea.len() != eb.len() {
return false;
}
let mb: Map<String, Value> = eb.iter().map(|(k, v)| (k.clone(), (*v).clone())).collect();
ea.iter().all(|(k, v)| mb.get(k).is_some_and(|w| loose_eq(v, w)))
}
pub fn compare_numbers(x: Number, y: Number) -> Ordering {
match (x, y) {
(Number::Int(p), Number::Int(q)) => p.cmp(&q),
_ => x.as_f64().partial_cmp(&y.as_f64()).unwrap_or(Ordering::Equal),
}
}
pub fn loose_str_eq(a: &[u8], b: &[u8]) -> bool {
match (std::str::from_utf8(a), std::str::from_utf8(b)) {
(Ok(x), Ok(y)) => smart_str_eq(x, y),
_ => a == b,
}
}
pub fn le_numbers(a: Number, b: Number) -> bool {
match (a, b) {
(Number::Int(p), Number::Int(q)) => p <= q,
_ => a.as_f64() <= b.as_f64(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn numeric_strings() {
assert_eq!(numeric_str("8"), Some(Number::Int(8)));
assert_eq!(numeric_str(" 8"), Some(Number::Int(8)));
assert_eq!(numeric_str("8 "), Some(Number::Int(8)));
assert_eq!(numeric_str("-1.5"), Some(Number::Float(-1.5)));
assert_eq!(numeric_str(".5"), Some(Number::Float(0.5)));
assert_eq!(numeric_str("1e3"), Some(Number::Float(1000.0)));
assert_eq!(numeric_str("abc"), None);
assert_eq!(numeric_str("0x1A"), None);
assert_eq!(numeric_str(""), None);
assert_eq!(numeric_str("."), None);
}
#[test]
fn truthiness() {
assert!(truthy(&json!("false")));
assert!(!truthy(&json!("0")));
assert!(!truthy(&json!("")));
assert!(truthy(&json!({})));
assert!(!truthy(&json!([])));
}
#[test]
fn loose_equality_matches_php() {
assert!(!loose_eq(&json!(1.5), &json!("1.5abc")));
assert!(!loose_eq(&json!(0.30000000000000004), &json!("0.3")));
assert!(!loose_eq(&json!("abc"), &json!(0)));
assert!(!loose_eq(&json!(null), &json!("0")));
assert!(loose_eq(&json!("1e3"), &json!("1000")));
assert!(!loose_eq(&json!("9223372036854775808"), &json!("9223372036854775809")));
assert!(loose_eq(&json!([]), &json!(false)));
assert!(!loose_eq(&json!({}), &json!([])));
assert!(loose_eq(&json!({}), &json!(1)));
assert!(loose_eq(&json!({"0": 1}), &json!([1])));
}
#[test]
fn strings_of_floats() {
assert_eq!(to_string(&json!(1.0)).unwrap(), "1");
assert_eq!(to_string(&json!(1e25)).unwrap(), "1.0E+25");
}
}