1use std::cmp::Ordering;
4
5use serde_json::{Map, Number as JsonNumber, Value as Json};
6
7use super::{Array, ArrayKey, EngineError, Extension, KeyRef, Never, Str};
8use crate::format::str_to_float;
9use crate::number;
10use crate::value::{Number, numeric_bytes_ex};
11
12#[derive(Clone, PartialEq, Debug, Default)]
14pub enum Value<X: Extension = Never> {
15 #[default]
17 Null,
18 Bool(bool),
20 Int(i64),
22 Float(f64),
24 Str(Str),
26 Array(Array<X>),
28 Object(Array<X>),
30 Ext(X),
32}
33
34impl<X: Extension> From<bool> for Value<X> {
35 fn from(b: bool) -> Self {
37 Value::Bool(b)
38 }
39}
40
41impl<X: Extension> From<i64> for Value<X> {
42 fn from(i: i64) -> Self {
44 Value::Int(i)
45 }
46}
47
48impl<X: Extension> From<f64> for Value<X> {
49 fn from(f: f64) -> Self {
51 Value::Float(f)
52 }
53}
54
55impl<X: Extension> From<&str> for Value<X> {
56 fn from(s: &str) -> Self {
58 Value::Str(Str::from(s))
59 }
60}
61
62impl<X: Extension> From<Str> for Value<X> {
63 fn from(s: Str) -> Self {
65 Value::Str(s)
66 }
67}
68
69impl<X: Extension> From<Array<X>> for Value<X> {
70 fn from(a: Array<X>) -> Self {
72 Value::Array(a)
73 }
74}
75
76fn int_string(i: i64) -> Str {
78 let mut buf = [0u8; 20];
79 let mut pos = buf.len();
80 let mut n = i.unsigned_abs();
81 loop {
82 pos -= 1;
83 buf[pos] = b'0' + (n % 10) as u8;
84 n /= 10;
85 if n == 0 {
86 break;
87 }
88 }
89 if i < 0 {
90 pos -= 1;
91 buf[pos] = b'-';
92 }
93 Str::copy_from(&buf[pos..])
94}
95
96fn threeway(a: f64, b: f64) -> i32 {
98 if a == b {
99 0
100 } else if a < b {
101 -1
102 } else {
103 1
104 }
105}
106
107pub(crate) fn normalize(i: i32) -> i32 {
108 i.signum()
109}
110
111pub(crate) fn binary_strcmp(a: &[u8], b: &[u8]) -> i32 {
113 match a.cmp(b) {
114 Ordering::Less => -1,
115 Ordering::Equal => 0,
116 Ordering::Greater => 1,
117 }
118}
119
120pub(crate) fn numeric(s: &[u8]) -> Option<(Number, i8)> {
122 numeric_bytes_ex(s)
123}
124
125pub(crate) fn smart_strcmp(s1: &[u8], s2: &[u8]) -> i32 {
127 smart_strcmp_parsed(s1, numeric(s1), s2, numeric(s2))
128}
129
130pub(crate) fn smart_strcmp_parsed(s1: &[u8], p1: Option<(Number, i8)>, s2: &[u8], p2: Option<(Number, i8)>) -> i32 {
132 if let (Some((n1, o1)), Some((n2, o2))) = (p1, p2) {
133 let (d1, d2) = (n1.as_f64(), n2.as_f64());
134 if o1 != 0 && o1 == o2 && d1 - d2 == 0.0 {
135 return binary_strcmp(s1, s2);
136 }
137 return match (n1, n2) {
138 (Number::Int(a), Number::Int(b)) => match a.cmp(&b) {
139 Ordering::Less => -1,
140 Ordering::Equal => 0,
141 Ordering::Greater => 1,
142 },
143 (Number::Int(_), Number::Float(_)) if o2 != 0 => -i32::from(o2),
144 (Number::Float(_), Number::Int(_)) if o1 != 0 => i32::from(o1),
145 (Number::Float(a), Number::Float(b)) if a == b && !a.is_finite() => binary_strcmp(s1, s2),
146 _ => {
147 let d = d1 - d2;
148 if d > 0.0 {
149 1
150 } else if d < 0.0 {
151 -1
152 } else {
153 0
154 }
155 }
156 };
157 }
158 binary_strcmp(s1, s2)
159}
160
161fn compare_long_to_string(l: i64, s: &[u8]) -> i32 {
163 compare_long_to_string_parsed(l, s, numeric(s))
164}
165
166pub(crate) fn compare_long_to_string_parsed(l: i64, s: &[u8], parsed: Option<(Number, i8)>) -> i32 {
168 match parsed {
169 Some((Number::Int(i), _)) => match l.cmp(&i) {
170 Ordering::Less => -1,
171 Ordering::Equal => 0,
172 Ordering::Greater => 1,
173 },
174 Some((Number::Float(d), _)) => threeway(l as f64, d),
175 None => binary_strcmp(l.to_string().as_bytes(), s),
176 }
177}
178
179fn compare_double_to_string(d: f64, s: &[u8]) -> i32 {
181 compare_double_to_string_parsed(d, s, numeric(s))
182}
183
184pub(crate) fn compare_double_to_string_parsed(d: f64, s: &[u8], parsed: Option<(Number, i8)>) -> i32 {
186 match parsed {
187 Some((Number::Int(i), _)) => threeway(d, i as f64),
188 Some((Number::Float(f), _)) => threeway(d, f),
189 None => binary_strcmp(number::to_string(d).as_bytes(), s),
190 }
191}
192
193fn compare_tables<X: Extension>(a: &Array<X>, b: &Array<X>) -> i32 {
196 if a.len() != b.len() {
197 return if a.len() > b.len() { 1 } else { -1 };
198 }
199 for (k, v) in a.iter() {
200 let Some(w) = b.get_ref(k) else { return 1 };
201 let r = v.compare(w);
202 if r != 0 {
203 return r;
204 }
205 }
206 0
207}
208
209fn identical_tables<X: Extension>(a: &Array<X>, b: &Array<X>) -> bool {
211 a.len() == b.len() && a.iter().zip(b.iter()).all(|((ka, va), (kb, vb))| ka == kb && va.strict_eq(vb))
212}
213
214impl<X: Extension> Value<X> {
215 pub fn type_name(&self) -> &'static str {
217 match self {
218 Value::Null => "NULL",
219 Value::Bool(_) => "boolean",
220 Value::Int(_) => "integer",
221 Value::Float(_) => "double",
222 Value::Str(_) => "string",
223 Value::Array(_) => "array",
224 Value::Object(_) | Value::Ext(_) => "object",
225 }
226 }
227
228 pub fn debug_type(&self) -> &str {
230 match self {
231 Value::Null => "null",
232 Value::Bool(_) => "bool",
233 Value::Int(_) => "int",
234 Value::Float(_) => "float",
235 Value::Str(_) => "string",
236 Value::Array(_) => "array",
237 Value::Object(_) => "stdClass",
238 Value::Ext(x) => x.class(),
239 }
240 }
241
242 pub fn truthy(&self) -> bool {
244 match self {
245 Value::Null => false,
246 Value::Bool(b) => *b,
247 Value::Int(i) => *i != 0,
248 Value::Float(f) => *f != 0.0,
249 Value::Str(s) => !(s.is_empty() || s.as_bytes() == b"0"),
250 Value::Array(a) => !a.is_empty(),
251 Value::Object(_) | Value::Ext(_) => true,
252 }
253 }
254
255 pub fn to_php_string(&self) -> Result<Str, EngineError> {
258 Ok(match self {
259 Value::Null | Value::Bool(false) => Str::EMPTY,
260 Value::Bool(true) => Str::from_static("1"),
261 Value::Int(i) => int_string(*i),
262 Value::Float(f) => Str::from(number::to_string(*f)),
263 Value::Str(s) => s.clone(),
264 Value::Array(_) => Str::from_static("Array"),
265 Value::Object(_) | Value::Ext(_) => {
266 return Err(EngineError::new(
267 "Error",
268 format!("Object of class {} could not be converted to string", self.debug_type()),
269 ));
270 }
271 })
272 }
273
274 pub fn to_double(&self) -> f64 {
277 match self {
278 Value::Null | Value::Bool(false) => 0.0,
279 Value::Bool(true) => 1.0,
280 Value::Int(i) => *i as f64,
281 Value::Float(f) => *f,
282 Value::Str(s) => str_to_float(s),
283 Value::Array(a) => {
284 if a.is_empty() {
285 0.0
286 } else {
287 1.0
288 }
289 }
290 Value::Object(_) | Value::Ext(_) => 1.0,
291 }
292 }
293
294 pub fn loose_eq(&self, o: &Self) -> bool {
296 self.compare(o) == 0
297 }
298
299 pub fn strict_eq(&self, o: &Self) -> bool {
303 match (self, o) {
304 (Value::Null, Value::Null) => true,
305 (Value::Bool(a), Value::Bool(b)) => a == b,
306 (Value::Int(a), Value::Int(b)) => a == b,
307 (Value::Float(a), Value::Float(b)) => a == b,
308 (Value::Str(a), Value::Str(b)) => a == b,
309 (Value::Array(a), Value::Array(b)) => identical_tables(a, b),
310 _ => false,
311 }
312 }
313
314 pub fn cmp_php(&self, o: &Self) -> Ordering {
317 self.compare(o).cmp(&0)
318 }
319
320 pub fn compare(&self, o: &Self) -> i32 {
322 use Value::*;
323 match (self, o) {
324 (Int(a), Int(b)) => match a.cmp(b) {
325 Ordering::Less => -1,
326 Ordering::Equal => 0,
327 Ordering::Greater => 1,
328 },
329 (Float(a), Int(b)) => threeway(*a, *b as f64),
330 (Int(a), Float(b)) => threeway(*a as f64, *b),
331 (Float(a), Float(b)) => threeway(*a, *b),
332 (Array(a), Array(b)) => compare_tables(a, b),
333 (Null | Bool(false), Null | Bool(false)) | (Bool(true), Bool(true)) => 0,
334 (Null, Bool(true)) => -1,
335 (Bool(true), Null) => 1,
336 (Str(a), Str(b)) => smart_strcmp(a, b),
337 (Null, Str(s)) => {
338 if s.is_empty() {
339 0
340 } else {
341 -1
342 }
343 }
344 (Str(s), Null) => i32::from(!s.is_empty()),
345 (Int(l), Str(s)) => compare_long_to_string(*l, s),
346 (Str(s), Int(l)) => normalize(-compare_long_to_string(*l, s)),
347 (Float(d), Str(_)) if d.is_nan() => 1,
348 (Float(d), Str(s)) => compare_double_to_string(*d, s),
349 (Str(_), Float(d)) if d.is_nan() => 1,
350 (Str(s), Float(d)) => normalize(-compare_double_to_string(*d, s)),
351 (Object(_) | Ext(_), Null) => 1,
352 (Null, Object(_) | Ext(_)) => -1,
353 (Object(a), Object(b)) => compare_tables(a, b),
354 (Ext(a), Ext(b)) => {
355 let r = compare_tables(&a.to_array(), &b.to_array());
357 if r == 0 && a.class() != b.class() { 1 } else { r }
358 }
359 (Object(_), Ext(_)) | (Ext(_), Object(_)) => 1,
361 (Object(_) | Ext(_), other) => object_vs(other, true),
362 (other, Object(_) | Ext(_)) => object_vs(other, false),
363 (Null | Bool(false), other) => -i32::from(other.truthy()),
365 (Bool(true), other) => i32::from(!other.truthy()),
366 (other, Null | Bool(false)) => i32::from(other.truthy()),
367 (other, Bool(true)) => -i32::from(!other.truthy()),
368 (Array(_), _) => 1,
370 (_, Array(_)) => -1,
371 }
372 }
373
374 pub fn from_json(v: &Json) -> Self {
378 match v {
379 Json::Null => Value::Null,
380 Json::Bool(b) => Value::Bool(*b),
381 Json::Number(n) => match n.as_i64() {
382 Some(i) => Value::Int(i),
383 None => Value::Float(n.as_f64().unwrap_or(0.0)),
384 },
385 Json::String(s) => Value::Str(Str::from(s.as_str())),
386 Json::Array(a) => Value::Array(a.iter().map(Value::from_json).collect()),
387 Json::Object(o) if o.is_empty() => Value::Object(Array::new()),
388 Json::Object(o) => Value::Array(
389 o.iter().map(|(k, v)| (ArrayKey::normalize(Str::from(k.as_str())), Value::from_json(v))).collect(),
390 ),
391 }
392 }
393
394 pub fn to_json(&self) -> Json {
399 fn text(b: &[u8]) -> String {
400 String::from_utf8_lossy(b).into_owned()
401 }
402 fn object<X: Extension>(a: &Array<X>) -> Json {
403 let mut m = Map::with_capacity(a.len());
404 for (k, v) in a.iter() {
405 let key = match k {
406 KeyRef::Int(i) => i.to_string(),
407 KeyRef::Str(s) => text(s),
408 };
409 m.insert(key, v.to_json());
410 }
411 Json::Object(m)
412 }
413 match self {
414 Value::Null => Json::Null,
415 Value::Bool(b) => Json::Bool(*b),
416 Value::Int(i) => Json::from(*i),
417 Value::Float(f) => JsonNumber::from_f64(*f).map_or(Json::Null, Json::Number),
418 Value::Str(s) => Json::String(text(s)),
419 Value::Array(a) if a.is_list() => Json::Array(a.values().map(Value::to_json).collect()),
420 Value::Array(a) | Value::Object(a) => object(a),
421 Value::Ext(x) => object(&x.to_array()),
422 }
423 }
424}
425
426fn object_vs<X: Extension>(other: &Value<X>, object_lhs: bool) -> i32 {
430 let casted: Value<X> = match other {
431 Value::Bool(_) => Value::Bool(true),
432 Value::Int(_) => Value::Int(1),
433 Value::Float(_) => Value::Float(1.0),
434 _ => return if object_lhs { 1 } else { -1 },
435 };
436 if object_lhs { casted.compare(other) } else { other.compare(&casted) }
437}
438
439impl<X: Extension> Value<X> {
440 pub fn try_to_json(&self) -> Option<Json> {
456 fn text(b: &[u8]) -> Option<String> {
457 std::str::from_utf8(b).ok().map(str::to_owned)
458 }
459 fn object<X: Extension>(a: &Array<X>) -> Option<Json> {
460 let mut m = Map::with_capacity(a.len());
461 for (k, v) in a.iter() {
462 let key = match k {
463 KeyRef::Int(i) => i.to_string(),
464 KeyRef::Str(s) => text(s)?,
465 };
466 m.insert(key, v.try_to_json()?);
467 }
468 Some(Json::Object(m))
469 }
470 Some(match self {
471 Value::Null => Json::Null,
472 Value::Bool(b) => Json::Bool(*b),
473 Value::Int(i) => Json::from(*i),
474 Value::Float(f) => Json::Number(JsonNumber::from_f64(*f)?),
475 Value::Str(s) => Json::String(text(s)?),
476 Value::Array(a) if a.is_list() => Json::Array(a.values().map(Value::try_to_json).collect::<Option<_>>()?),
477 Value::Array(a) | Value::Object(a) => object(a)?,
478 Value::Ext(x) => {
479 let a = x.to_array();
480 if a.is_list() { Value::Array(a).try_to_json()? } else { object(&a)? }
481 }
482 })
483 }
484}
485
486#[cfg(test)]
487mod tests {
488 use super::*;
489 use serde_json::json;
490
491 type V = Value<Never>;
492
493 fn v(j: Json) -> V {
494 V::from_json(&j)
495 }
496
497 #[test]
498 fn juggling_like_php() {
499 assert!(v(json!("false")).truthy());
500 assert!(!v(json!("0")).truthy());
501 assert!(v(json!({})).truthy());
502 assert!(!v(json!([])).truthy());
503 assert_eq!(v(json!(1e25)).to_php_string().unwrap(), *"1.0E+25");
504 assert_eq!(v(json!([1])).to_php_string().unwrap(), *"Array");
505 assert_eq!(v(json!({})).to_php_string().unwrap_err().class, "Error");
506 assert_eq!(v(json!(" 1.5x")).to_double(), 1.5);
507 }
508
509 #[test]
510 fn comparisons_like_php() {
511 assert!(!v(json!("abc")).loose_eq(&v(json!(0))));
512 assert!(v(json!("1e3")).loose_eq(&v(json!("1000"))));
513 assert!(v(json!(null)).loose_eq(&v(json!(0))));
514 assert!(v(json!(null)).loose_eq(&v(json!(""))));
515 assert_eq!(v(json!(0)).compare(&v(json!(""))), 1);
516 assert!(v(json!([])).loose_eq(&v(json!(false))));
517 assert!(!v(json!({})).loose_eq(&v(json!([]))));
518 assert!(v(json!({})).loose_eq(&v(json!(1))));
519 assert!(v(json!({"0": 1})).loose_eq(&v(json!([1]))));
520 assert_eq!(v(json!([1, 2])).compare(&v(json!([1]))), 1);
521 assert_eq!(v(json!({"a": 1})).compare(&v(json!({"b": 1}))), 1);
522 assert_eq!(v(json!({"b": 1})).compare(&v(json!({"a": 1}))), 1);
523 assert_eq!(V::Float(f64::NAN).compare(&V::Int(1)), 1);
524 assert_eq!(V::Int(1).compare(&V::Float(f64::NAN)), 1);
525 assert_eq!(v(json!("9223372036854775808")).compare(&v(json!("9223372036854775807"))), 1);
526 assert!(v(json!([1, "a"])).strict_eq(&v(json!([1, "a"]))));
527 assert!(!v(json!({"a": 1, "b": 2})).strict_eq(&v(json!({"b": 2, "a": 1}))));
528 assert!(v(json!({"a": 1, "b": 2})).loose_eq(&v(json!({"b": 2, "a": 1}))));
529 }
530
531 #[test]
532 fn request_model_round_trip() {
533 let j = json!({"0": "a", "1": {"x": []}, "k": {}});
534 assert_eq!(v(j.clone()).to_json(), j);
535 assert_eq!(v(json!({"0": 1, "1": 2})).to_json(), json!([1, 2]));
536 }
537}