-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomparison.go
98 lines (80 loc) · 2.15 KB
/
comparison.go
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
/*
* Copyright 2020 VMware, Inc.
* Copyright 2023 SteelBridgeLabs, Inc.
*
* SPDX-License-Identifier: Apache-2.0
*
* Changes:
* - Changed package name from github.com/vmware-labs/yamlpath to github.com/SteelBridgeLabs/jsonpath
*/
package jsonpath
import "strconv"
type comparison int
const (
compareLessThan comparison = iota
compareEqual
compareGreaterThan
compareIncomparable
)
type orderingOperator string
const (
operatorLessThan orderingOperator = "<"
operatorLessThanOrEqual orderingOperator = "<="
operatorGreaterThan orderingOperator = ">"
operatorGreaterThanOrEqual orderingOperator = ">="
)
func (o orderingOperator) String() string {
return string(o)
}
type comparator func(comparison) bool
func equal(c comparison) bool {
return c == compareEqual
}
func notEqual(c comparison) bool {
return c != compareEqual
}
func greaterThan(c comparison) bool {
return c == compareGreaterThan
}
func greaterThanOrEqual(c comparison) bool {
return c == compareGreaterThan || c == compareEqual
}
func lessThan(c comparison) bool {
return c == compareLessThan
}
func lessThanOrEqual(c comparison) bool {
return c == compareLessThan || c == compareEqual
}
func compareStrings(a, b string) comparison {
if a == b {
return compareEqual
}
return compareIncomparable
}
func compareFloat64(lhs, rhs float64) comparison {
if lhs < rhs {
return compareLessThan
}
if lhs > rhs {
return compareGreaterThan
}
return compareEqual
}
// compareNodeValues compares two values each of which may be a string, integer, or float
func compareNodeValues(lhs, rhs typedValue) comparison {
if lhs.typ.isNumeric() && rhs.typ.isNumeric() {
return compareFloat64(mustParseFloat64(lhs.val), mustParseFloat64(rhs.val))
}
if (lhs.typ != stringValueType && !lhs.typ.isNumeric()) || (rhs.typ != stringValueType && !rhs.typ.isNumeric()) {
// we cannot compare values, @f1==@f2 and either value is a map or array
return compareIncomparable
}
return compareStrings(lhs.val, rhs.val)
}
func mustParseFloat64(s string) float64 {
f, err := strconv.ParseFloat(s, 64)
if err != nil {
panic("invalid numeric value " + s) // should never happen
}
return f
}