-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathjs_op.rs
1307 lines (1210 loc) · 40.9 KB
/
js_op.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Implementations of JavaScript operators for JSON Values
use serde_json::{Number, Value};
use std::f64;
use std::str::FromStr;
use crate::error::Error;
// numeric characters according to parseFloat
const NUMERICS: &'static [char] = &[
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.', '-', '+', 'e', 'E',
];
// TODOS:
// - there are too many tests in docstrings
// - the docstrings are too sarcastic about JS equality
pub fn to_string(value: &Value) -> String {
match value {
Value::Object(_) => String::from("[object Object]"),
Value::Bool(val) => val.to_string(),
Value::Null => String::from("null"),
Value::Number(val) => val.to_string(),
Value::String(val) => String::from(val),
Value::Array(val) => val
.iter()
.map(|i| match i {
Value::Null => String::from(""),
_ => to_string(i),
})
.collect::<Vec<String>>()
.join(","),
}
}
/// Implement something like OrdinaryToPrimitive() with a Number hint.
///
/// If it's possible to return a numeric primitive, returns Some<f64>.
/// Otherwise, return None.
fn to_primitive_number(value: &Value) -> Option<f64> {
match value {
// .valueOf() returns the object itself, which is not a primitive
Value::Object(_) => None,
// .valueOf() returns the array itself
Value::Array(_) => None,
Value::Bool(val) => {
if *val {
Some(1.0)
} else {
Some(0.0)
}
}
Value::Null => Some(0.0),
Value::Number(val) => val.as_f64(),
Value::String(_) => None, // already a primitive
}
}
pub fn str_to_number<S: AsRef<str>>(string: S) -> Option<f64> {
let s = string.as_ref();
if s == "" {
Some(0.0)
} else {
f64::from_str(s).ok()
}
}
enum Primitive {
String(String),
Number(f64),
}
#[allow(dead_code)]
enum PrimitiveHint {
String,
Number,
Default,
}
fn to_primitive(value: &Value, hint: PrimitiveHint) -> Primitive {
match hint {
PrimitiveHint::String => Primitive::String(to_string(value)),
_ => to_primitive_number(value)
.map(Primitive::Number)
.unwrap_or(Primitive::String(to_string(value))),
}
}
/// Do our best to convert something into a number.
///
/// Should be pretty much equivalent to calling Number(value) in JS,
/// returning None where that would return NaN.
pub fn to_number(value: &Value) -> Option<f64> {
match to_primitive(value, PrimitiveHint::Number) {
Primitive::Number(num) => Some(num),
Primitive::String(string) => str_to_number(string),
}
}
/// Compare values in the JavaScript `==` style
///
/// Implements the Abstract Equality Comparison algorithm (`==` in JS)
/// as defined [here](https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3).
///
/// ```rust
/// use serde_json::json;
/// use jsonlogic_rs::js_op::abstract_eq;
///
/// assert!(
/// abstract_eq(
/// &json!(null),
/// &json!(null),
/// )
/// );
/// assert!(
/// abstract_eq(
/// &json!(1.0),
/// &json!(1),
/// )
/// );
/// assert!(
/// abstract_eq(
/// &json!("foo"),
/// &json!("foo"),
/// )
/// );
/// assert!(
/// abstract_eq(
/// &json!(true),
/// &json!(true),
/// )
/// );
/// assert!(
/// abstract_eq(
/// &json!("1"),
/// &json!(1.0),
/// )
/// );
/// assert!(
/// abstract_eq(
/// &json!(1.0),
/// &json!("1"),
/// )
/// );
/// assert!(
/// abstract_eq(
/// &json!(true),
/// &json!("1"),
/// )
/// );
/// assert!(
/// abstract_eq(
/// &json!(true),
/// &json!(1.0),
/// )
/// );
/// assert!(
/// abstract_eq(
/// &json!({}),
/// &json!("[object Object]"),
/// )
/// );
///
/// assert!(
/// ! abstract_eq(
/// &json!({}),
/// &json!({}),
/// )
/// );
/// assert!(
/// ! abstract_eq(
/// &json!([]),
/// &json!([]),
/// )
/// );
/// ```
pub fn abstract_eq(first: &Value, second: &Value) -> bool {
// Follows the ECMA specification 2019:7.2.14 (Abstract Equality Comparison)
match (first, second) {
// 1. If Type(x) is the same as Type(y), then
// a. If Type(x) is Undefined, return true.
// - No need to handle this case, b/c undefined is not in JSON
// b. If Type(x) is Null, return true.
(Value::Null, Value::Null) => true,
// c. If Type(x) is Number, then
(Value::Number(x), Value::Number(y)) => {
// i. If x is NaN, return false.
// - we can ignore this case, b/c NaN is not in JSON
// ii. If y is NaN, return false.
// - same here
// iii. If x is the same Number value as y, return true.
x.as_f64()
.map(|x_val| y.as_f64().map(|y_val| x_val == y_val).unwrap_or(false))
.unwrap_or(false)
// x.as_f64() == y.as_f64()
// iv. If x is +0 and y is −0, return true.
// - with serde's Number, this is handled by the above
// v. If x is −0 and y is +0, return true.
// - same here
// vi. Return false.
// - done!
}
// d. If Type(x) is String, then return true if x and y are exactly
// the same sequence of characters (same length and same characters
// in corresponding positions). Otherwise, return false.
(Value::String(x), Value::String(y)) => x == y,
// e. If Type(x) is Boolean, return true if x and y are both true
// or both false. Otherwise, return false.
(Value::Bool(x), Value::Bool(y)) => x == y,
// f. Return true if x and y refer to the same object. Otherwise, return false.
// - not applicable to comparisons from JSON
// 2. If x is null and y is undefined, return true.
// - not applicable to JSON b/c there is no undefined
// 3. If x is undefined and y is null, return true.
// - not applicable to JSON b/c there is no undefined
// 4. If Type(x) is Number and Type(y) is String, return the result of
// the comparison x == ToNumber(y).
(Value::Number(x), Value::String(y)) => {
// the empty string is 0
let y_res = str_to_number(y);
y_res
.map(|y_number| {
x.as_f64()
.map(|x_number| x_number == y_number)
.unwrap_or(false)
})
.unwrap_or(false)
}
// 5. If Type(x) is String and Type(y) is Number, return the result
// of the comparison ToNumber(x) == y.
(Value::String(x), Value::Number(y)) => {
let x_res = str_to_number(x);
x_res
.map(|x_number| {
y.as_f64()
.map(|y_number| x_number == y_number)
.unwrap_or(false)
})
.unwrap_or(false)
}
// 6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
(Value::Bool(x), _) => match x {
true => Number::from_f64(1 as f64)
.map(|num| {
let value = Value::Number(num);
abstract_eq(&value, second)
})
.unwrap_or(false),
false => Number::from_f64(0 as f64)
.map(|num| {
let value = Value::Number(num);
abstract_eq(&value, second)
})
.unwrap_or(false),
},
// 7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
(_, Value::Bool(y)) => match y {
true => Number::from_f64(1 as f64)
.map(|num| {
let value = Value::Number(num);
abstract_eq(first, &value)
})
.unwrap_or(false),
false => Number::from_f64(0 as f64)
.map(|num| {
let value = Value::Number(num);
abstract_eq(first, &value)
})
.unwrap_or(false),
},
// 8. If Type(x) is either String, Number, or Symbol and Type(y) is
// Object, return the result of the comparison x == ToPrimitive(y).
// NB: the only type of Objects we get in JSON are regular old arrays
// and regular old objects. ToPrimitive on the former yields a
// stringification of its values, stuck together with commands,
// but with no brackets on the outside. ToPrimitive on the later
// is just always [object Object].
(Value::String(_), Value::Array(_)) | (Value::Number(_), Value::Array(_)) => {
abstract_eq(first, &Value::String(to_string(second)))
}
(Value::String(_), Value::Object(_)) | (Value::Number(_), Value::Object(_)) => {
abstract_eq(first, &Value::String(to_string(second)))
}
// 9. If Type(x) is Object and Type(y) is either String, Number, or
// Symbol, return the result of the comparison ToPrimitive(x) == y.
(Value::Object(_), Value::String(_)) | (Value::Object(_), Value::Number(_)) => {
abstract_eq(&Value::String(to_string(first)), second)
}
(Value::Array(_), Value::String(_)) | (Value::Array(_), Value::Number(_)) => {
abstract_eq(&Value::String(to_string(first)), second)
}
_ => false,
}
}
/// Perform JS-style strict equality
///
/// Items are strictly equal if:
/// - They are the same non-primitive object
/// - They are a primitive object of the same type with the same value
///
/// ```rust
/// use serde_json::json;
/// use jsonlogic_rs::js_op::strict_eq;
///
/// // References of the same type and value are strictly equal
/// assert!(strict_eq(&json!(1), &json!(1)));
/// assert!(strict_eq(&json!(false), &json!(false)));
/// assert!(strict_eq(&json!("foo"), &json!("foo")));
///
/// // "Abstract" type conversion is not performed for strict equality
/// assert!(!strict_eq(&json!(0), &json!(false)));
/// assert!(!strict_eq(&json!(""), &json!(0)));
///
/// // Objects only compare equal if they are the same reference
/// assert!(!strict_eq(&json!([]), &json!([])));
/// assert!(!strict_eq(&json!({}), &json!({})));
///
/// let arr = json!([]);
/// let obj = json!({});
/// assert!(strict_eq(&arr, &arr));
/// assert!(strict_eq(&obj, &obj));
/// ```
///
pub fn strict_eq(first: &Value, second: &Value) -> bool {
if std::ptr::eq(first, second) {
return true;
};
match (first, second) {
(Value::Null, Value::Null) => true,
(Value::Bool(x), Value::Bool(y)) => x == y,
(Value::Number(x), Value::Number(y)) => x
.as_f64()
.and_then(|x_val| y.as_f64().map(|y_val| x_val == y_val))
.unwrap_or(false),
(Value::String(x), Value::String(y)) => x == y,
_ => false,
}
}
pub fn strict_ne(first: &Value, second: &Value) -> bool {
!strict_eq(first, second)
}
/// Perform JS-style abstract less-than
///
///
/// ```rust
/// use serde_json::json;
/// use jsonlogic_rs::js_op::abstract_lt;
///
/// assert_eq!(abstract_lt(&json!(-1), &json!(0)), true);
/// assert_eq!(abstract_lt(&json!("-1"), &json!(0)), true);
/// assert_eq!(abstract_lt(&json!(0), &json!(1)), true);
/// assert_eq!(abstract_lt(&json!(0), &json!("1")), true);
/// assert_eq!(abstract_lt(&json!(0), &json!("a")), false);
/// ```
pub fn abstract_lt(first: &Value, second: &Value) -> bool {
match (
to_primitive(first, PrimitiveHint::Number),
to_primitive(second, PrimitiveHint::Number),
) {
(Primitive::String(f), Primitive::String(s)) => f < s,
(Primitive::Number(f), Primitive::Number(s)) => f < s,
(Primitive::String(f), Primitive::Number(s)) => {
if let Some(f) = str_to_number(f) {
f < s
} else {
false
}
}
(Primitive::Number(f), Primitive::String(s)) => {
if let Some(s) = str_to_number(s) {
f < s
} else {
false
}
}
}
}
/// JS-style abstract gt
///
/// ```rust
/// use serde_json::json;
/// use jsonlogic_rs::js_op::abstract_gt;
///
/// assert_eq!(abstract_gt(&json!(0), &json!(-1)), true);
/// assert_eq!(abstract_gt(&json!(0), &json!("-1")), true);
/// assert_eq!(abstract_gt(&json!(1), &json!(0)), true);
/// assert_eq!(abstract_gt(&json!("1"), &json!(0)), true);
/// ```
pub fn abstract_gt(first: &Value, second: &Value) -> bool {
match (
to_primitive(first, PrimitiveHint::Number),
to_primitive(second, PrimitiveHint::Number),
) {
(Primitive::String(f), Primitive::String(s)) => f > s,
(Primitive::Number(f), Primitive::Number(s)) => f > s,
(Primitive::String(f), Primitive::Number(s)) => {
if let Some(f) = str_to_number(f) {
f > s
} else {
false
}
}
(Primitive::Number(f), Primitive::String(s)) => {
if let Some(s) = str_to_number(s) {
f > s
} else {
false
}
}
}
}
/// Abstract inequality
pub fn abstract_ne(first: &Value, second: &Value) -> bool {
!abstract_eq(first, second)
}
/// Provide abstract <= comparisons
pub fn abstract_lte(first: &Value, second: &Value) -> bool {
abstract_lt(first, second) || abstract_eq(first, second)
}
/// Provide abstract >= comparisons
pub fn abstract_gte(first: &Value, second: &Value) -> bool {
abstract_gt(first, second) || abstract_eq(first, second)
}
/// Get the max of an array of values, performing abstract type conversion
pub fn abstract_max(items: &Vec<&Value>) -> Result<f64, Error> {
items
.into_iter()
.map(|v| {
to_number(v).ok_or_else(|| Error::InvalidArgument {
value: (*v).clone(),
operation: "max".into(),
reason: "Could not convert value to number".into(),
})
})
.fold(Ok(f64::NEG_INFINITY), |acc, cur| {
let max = acc?;
match cur {
Ok(num) => {
if num > max {
Ok(num)
} else {
Ok(max)
}
}
_ => cur,
}
})
}
/// Get the max of an array of values, performing abstract type conversion
pub fn abstract_min(items: &Vec<&Value>) -> Result<f64, Error> {
items
.into_iter()
.map(|v| {
to_number(v).ok_or_else(|| Error::InvalidArgument {
value: (*v).clone(),
operation: "max".into(),
reason: "Could not convert value to number".into(),
})
})
.fold(Ok(f64::INFINITY), |acc, cur| {
let min = acc?;
match cur {
Ok(num) => {
if num < min {
Ok(num)
} else {
Ok(min)
}
}
_ => cur,
}
})
}
/// Do plus
pub fn abstract_plus(first: &Value, second: &Value) -> Value {
let first_num = to_primitive_number(first);
let second_num = to_primitive_number(second);
match (first_num, second_num) {
(Some(f), Some(s)) => {
return Value::Number(Number::from_f64(f + s).unwrap());
}
_ => {}
};
let first_string = to_string(first);
let second_string = to_string(second);
Value::String(first_string.chars().chain(second_string.chars()).collect())
}
/// Add values, parsing to floats first.
///
/// The JSONLogic reference implementation uses the JS `parseFloat` operation
/// on the parameters, which behaves quite differently from the normal JS
/// numeric conversion with `Number(val)`. While the latter uses the
/// `toPrimitive` method on the base object Prototype, the former first
/// converts any incoming value to a string, and then tries to parse it
/// as a float. The upshot is that things that normally parse fine into
/// numbers in JS, like bools and null, convert to NaN, because you can't
/// make "false" into a number.
///
/// The JSONLogic reference implementation deals with any values that
/// evaluate to NaN by returning null. We instead will return an error,
/// the behavior for non-numeric inputs is not specified in the spec,
/// and returning errors seems like a more reasonable course of action
/// than returning null.
pub fn parse_float_add(vals: &Vec<&Value>) -> Result<f64, Error> {
vals.into_iter()
.map(|&v| {
parse_float(v).ok_or_else(|| Error::InvalidArgument {
value: v.clone(),
operation: "+".into(),
reason: "Argument could not be converted to a float".into(),
})
})
.fold(Ok(0.0), |acc, cur| {
let total = acc?;
match cur {
Ok(num) => Ok(total + num),
_ => cur,
}
})
}
/// Multiply values, parsing to floats first
///
/// See notes for parse_float_add on how this differs from normal number
/// conversion as is done for _other_ arithmetic operators in the reference
/// implementation
pub fn parse_float_mul(vals: &Vec<&Value>) -> Result<f64, Error> {
vals.into_iter()
.map(|&v| {
parse_float(v).ok_or_else(|| Error::InvalidArgument {
value: v.clone(),
operation: "*".into(),
reason: "Argument could not be converted to a float".into(),
})
})
.fold(Ok(1.0), |acc, cur| {
let total = acc?;
match cur {
Ok(num) => Ok(total * num),
_ => cur,
}
})
}
/// Do minus
pub fn abstract_minus(first: &Value, second: &Value) -> Result<f64, Error> {
let first_num = to_number(first);
let second_num = to_number(second);
if let None = first_num {
return Err(Error::InvalidArgument {
value: first.clone(),
operation: "-".into(),
reason: "Could not convert value to number.".into(),
});
}
if let None = second_num {
return Err(Error::InvalidArgument {
value: second.clone(),
operation: "-".into(),
reason: "Could not convert value to number.".into(),
});
}
Ok(first_num.unwrap() - second_num.unwrap())
}
/// Do division
pub fn abstract_div(first: &Value, second: &Value) -> Result<f64, Error> {
let first_num = to_number(first);
let second_num = to_number(second);
if let None = first_num {
return Err(Error::InvalidArgument {
value: first.clone(),
operation: "/".into(),
reason: "Could not convert value to number.".into(),
});
}
if let None = second_num {
return Err(Error::InvalidArgument {
value: second.clone(),
operation: "/".into(),
reason: "Could not convert value to number.".into(),
});
}
Ok(first_num.unwrap() / second_num.unwrap())
}
/// Do modulo
pub fn abstract_mod(first: &Value, second: &Value) -> Result<f64, Error> {
let first_num = to_number(first);
let second_num = to_number(second);
if let None = first_num {
return Err(Error::InvalidArgument {
value: first.clone(),
operation: "%".into(),
reason: "Could not convert value to number.".into(),
});
}
if let None = second_num {
return Err(Error::InvalidArgument {
value: second.clone(),
operation: "%".into(),
reason: "Could not convert value to number.".into(),
});
}
Ok(first_num.unwrap() % second_num.unwrap())
}
/// Attempt to convert a value to a negative number
pub fn to_negative(val: &Value) -> Result<f64, Error> {
to_number(val)
.map(|v| -1.0 * v)
.ok_or_else(|| Error::InvalidArgument {
value: val.clone(),
operation: "to_negative".into(),
reason: "Could not convert value to a number".into(),
})
}
/// Try to parse a string as a float, javascript style
///
/// Strip whitespace, accumulate any potentially numeric characters at the
/// start of the string and try to convert them into a float. We don't
/// quite follow the spec exactly: we don't deal with infinity
/// and NaN. That is okay, because this is only used in a context dealing
/// with JSON values, which can't be Infinity or NaN.
fn parse_float_string(val: &String) -> Option<f64> {
let (mut leading_numerics, _, _) = val.trim().chars().fold(
(Vec::new(), false, false),
|(mut acc, broke, saw_decimal), c| {
if broke {
// if we hit a nonnumeric last iter, just return what we've got
(acc, broke, saw_decimal)
} else if NUMERICS.contains(&c) {
let is_decimal = c == '.';
if saw_decimal && is_decimal {
// if we're a decimal and we've seen one before, break
(acc, true, is_decimal)
} else {
// if we're a numeric, stick it on the acc
acc.push(c);
(acc, broke, saw_decimal || is_decimal)
}
} else {
// return the acc as is and let 'em know we hit a nonnumeric
(acc, true, saw_decimal)
}
},
);
// don't bother collecting into a string if we don't need to
if leading_numerics.len() == 0 {
return None;
};
if let Some('e') | Some('E') = leading_numerics.last() {
// If the last character is an 'e' or an `E`, remove it, to match
// edge case where JS ignores a trailing `e` rather than treating it
// as bad exponential notation, e.g. JS treats 1e as just 1.
leading_numerics.pop();
}
// collect into a string, try to parse as a float, return an option
leading_numerics
.iter()
.collect::<String>()
.parse::<f64>()
.ok()
}
/// Attempt to parse a value into a float.
///
/// The implementation should match https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
/// as closely as is reasonable.
pub fn parse_float(val: &Value) -> Option<f64> {
match val {
Value::Number(num) => num.as_f64(),
Value::String(string) => parse_float_string(string),
_ => parse_float(&Value::String(to_string(&val))),
}
}
// =====================================================================
// Unit Tests
// =====================================================================
#[cfg(test)]
mod abstract_operations {
use super::*;
use serde_json::json;
fn equal_values() -> Vec<(Value, Value)> {
vec![
(json!(null), json!(null)),
(json!(1), json!(1)),
(json!(1), json!(1.0)),
(json!(1.0), json!(1)),
(json!(0), json!(-0)),
(json!(-0), json!(0)),
(json!("foo"), json!("foo")),
(json!(""), json!("")),
(json!(true), json!(true)),
(json!(false), json!(false)),
(json!(1), json!("1")),
(json!(1), json!("1.0")),
(json!(1.0), json!("1.0")),
(json!(1.0), json!("1")),
(json!(0), json!("")),
(json!(0), json!("0")),
(json!(0), json!("-0")),
(json!(0), json!("+0")),
(json!(-1), json!("-1")),
(json!(-1.0), json!("-1")),
(json!(true), json!(1)),
(json!(true), json!("1")),
(json!(true), json!("1.0")),
(json!(true), json!([1])),
(json!(true), json!(["1"])),
(json!(false), json!(0)),
(json!(false), json!([])),
(json!(false), json!([0])),
(json!(false), json!("")),
(json!(false), json!("0")),
(json!("[object Object]"), json!({})),
(json!("[object Object]"), json!({"a": "a"})),
(json!(""), json!([])),
(json!(""), json!([null])),
(json!(","), json!([null, null])),
(json!("1,2"), json!([1, 2])),
(json!("a,b"), json!(["a", "b"])),
(json!(0), json!([])),
(json!(false), json!([])),
(json!(true), json!([1])),
(json!([]), json!("")),
(json!([null]), json!("")),
(json!([null, null]), json!(",")),
(json!([1, 2]), json!("1,2")),
(json!(["a", "b"]), json!("a,b")),
(json!([]), json!(0)),
(json!([0]), json!(0)),
(json!([]), json!(false)),
(json!([0]), json!(false)),
(json!([1]), json!(true)),
]
}
fn lt_values() -> Vec<(Value, Value)> {
vec![
(json!(-1), json!(0)),
(json!("-1"), json!(0)),
(json!(0), json!(1)),
(json!(0), json!("1")),
(json!("foo"), json!("foos")),
(json!(""), json!("a")),
(json!(""), json!([1])),
(json!(""), json!([1, 2])),
(json!(""), json!("1")),
(json!(""), json!({})),
(json!(""), json!({"a": 1})),
(json!(false), json!(true)),
(json!(false), json!(1)),
(json!(false), json!("1")),
(json!(false), json!([1])),
(json!(null), json!(1)),
(json!(null), json!(true)),
(json!(null), json!("1")),
(json!([]), json!([1])),
(json!([]), json!([1, 2])),
(json!(0), json!([1])),
(json!("0"), json!({})),
(json!("0"), json!({"a": 1})),
(json!("0"), json!([1, 2])),
]
}
fn gt_values() -> Vec<(Value, Value)> {
vec![
(json!(0), json!(-1)),
(json!(0), json!("-1")),
(json!(1), json!(0)),
(json!("1"), json!(0)),
(json!("foos"), json!("foo")),
(json!("a"), json!("")),
(json!([1]), json!("")),
(json!("1"), json!("")),
(json!("1"), json!("0")),
(json!(true), json!(false)),
(json!(1), json!(false)),
(json!("1"), json!(false)),
(json!([1]), json!(false)),
(json!(1), json!(null)),
(json!(true), json!(null)),
(json!("1"), json!(null)),
(json!([1]), json!([])),
(json!([1, 2]), json!([])),
]
}
fn ne_values() -> Vec<(Value, Value)> {
vec![
(json!([]), json!([])),
(json!([1]), json!([1])),
(json!([1, 1]), json!([1, 1])),
(json!({}), json!({})),
(json!({"a": 1}), json!({"a": 1})),
(json!([]), json!({})),
(json!(0), json!(1)),
(json!("a"), json!("b")),
(json!(true), json!(false)),
(json!(true), json!([0])),
(json!(1.0), json!(1.1)),
(json!(null), json!(0)),
(json!(null), json!("")),
(json!(null), json!(false)),
(json!(null), json!(true)),
]
}
/// Values that do not compare true for anything other than ne.
fn not_gt_not_lt_not_eq() -> Vec<(Value, Value)> {
vec![
(json!(null), json!("")),
(json!(null), json!("a")),
(json!(0), json!("a")),
(json!(0), json!([1, 2])),
(json!([]), json!([])),
(json!([1]), json!([1])),
(json!([1, 2]), json!([1, 2])),
(json!({}), json!({})),
(json!(false), json!({})),
(json!(true), json!({})),
(json!(false), json!([1, 2])),
(json!(true), json!([1, 2])),
]
}
fn plus_cases() -> Vec<(Value, Value, Value)> {
vec![
(json!(1), json!(1), json!(2.0)),
(json!(1), json!(true), json!(2.0)),
(json!(true), json!(true), json!(2.0)),
(json!(1), json!(false), json!(1.0)),
(json!(false), json!(false), json!(0.0)),
(json!(1), json!(null), json!(1.0)),
(json!(null), json!(null), json!(0.0)),
(json!(1), json!("1"), json!("11")),
(json!(1), json!([1]), json!("11")),
(json!(1), json!([1, 2]), json!("11,2")),
(json!(1), json!([1, null, 3]), json!("11,,3")),
(json!(1), json!({}), json!("1[object Object]")),
]
}
#[test]
fn test_to_string_obj() {
assert_eq!(&to_string(&json!({})), "[object Object]");
assert_eq!(&to_string(&json!({"a": "b"})), "[object Object]");
}
#[test]
fn test_to_string_array() {
assert_eq!(&to_string(&json!([])), "");
assert_eq!(&to_string(&json!([1, 2, 3])), "1,2,3");
assert_eq!(&to_string(&json!([1, [2, 3], 4])), "1,2,3,4");
assert_eq!(&to_string(&json!([1, {}, 2])), "1,[object Object],2");
assert_eq!(&to_string(&json!(["a", "b"])), "a,b");
assert_eq!(&to_string(&json!([null])), "");
assert_eq!(&to_string(&json!([null, 1, 2, null])), ",1,2,");
assert_eq!(&to_string(&json!([true, false])), "true,false");
}
#[test]
fn test_to_string_null() {
assert_eq!(&to_string(&json!(null)), "null");
}
#[test]
fn test_to_string_bool() {
assert_eq!(&to_string(&json!(true)), "true");
assert_eq!(&to_string(&json!(false)), "false");
}
#[test]
fn test_to_string_number() {
assert_eq!(&to_string(&json!(1.0)), "1.0");
assert_eq!(&to_string(&json!(1)), "1");
}
#[test]
fn test_abstract_eq() {
equal_values().iter().for_each(|(first, second)| {
println!("{:?}-{:?}", &first, &second);
assert!(abstract_eq(&first, &second), true);
})
}
#[test]
fn test_abstract_ne() {
ne_values().iter().for_each(|(first, second)| {
println!("{:?}-{:?}", &first, &second);
assert_eq!(abstract_ne(&first, &second), true);
})
}
#[test]
fn test_abstract_lt() {
lt_values().iter().for_each(|(first, second)| {
println!("{:?}-{:?}", &first, &second);
assert_eq!(abstract_lt(&first, &second), true);
})
}
#[test]
fn test_abstract_gt() {
gt_values().iter().for_each(|(first, second)| {
println!("{:?}-{:?}", &first, &second);
assert_eq!(abstract_gt(&first, &second), true);
})
}
#[test]
fn test_eq_values_are_not_lt() {
equal_values().iter().for_each(|(first, second)| {
println!("{:?}-{:?}", &first, &second);
assert_eq!(abstract_lt(&first, &second), false);
})
}
#[test]
fn test_eq_values_are_not_gt() {
equal_values().iter().for_each(|(first, second)| {
println!("{:?}-{:?}", &first, &second);
assert_eq!(abstract_gt(&first, &second), false);
})
}
#[test]
fn test_eq_values_are_not_ne() {
equal_values().iter().for_each(|(first, second)| {
println!("{:?}-{:?}", &first, &second);
assert_eq!(abstract_ne(&first, &second), false);
})
}
#[test]
fn test_lt_values_are_not_eq() {
lt_values().iter().for_each(|(first, second)| {
println!("{:?}-{:?}", &first, &second);
assert_eq!(abstract_eq(&first, &second), false);
})
}
#[test]
fn test_lt_values_are_not_gt() {
lt_values().iter().for_each(|(first, second)| {
println!("{:?}-{:?}", &first, &second);
assert_eq!(abstract_gt(&first, &second), false);
})
}
#[test]
fn test_lt_values_are_ne() {
lt_values().iter().for_each(|(first, second)| {
println!("{:?}-{:?}", &first, &second);
assert_eq!(abstract_ne(&first, &second), true);
})
}
#[test]
fn test_gt_values_are_not_eq() {
gt_values().iter().for_each(|(first, second)| {
println!("{:?}-{:?}", &first, &second);
assert_eq!(abstract_eq(&first, &second), false);
})
}
#[test]
fn test_gt_values_are_not_lt() {
gt_values().iter().for_each(|(first, second)| {
println!("{:?}-{:?}", &first, &second);
assert_eq!(abstract_lt(&first, &second), false);
})