forked from itchyny/gojq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
normalize.go
84 lines (81 loc) · 1.47 KB
/
normalize.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
package gojq
import (
"encoding/json"
"math"
"math/big"
"strings"
)
func normalizeNumber(v json.Number) any {
if i, err := v.Int64(); err == nil && math.MinInt <= i && i <= math.MaxInt {
return int(i)
}
if strings.ContainsAny(v.String(), ".eE") {
if f, err := v.Float64(); err == nil {
return f
}
}
if bi, ok := new(big.Int).SetString(v.String(), 10); ok {
return bi
}
if strings.HasPrefix(v.String(), "-") {
return math.Inf(-1)
}
return math.Inf(1)
}
func normalizeNumbers(v any) any {
switch v := v.(type) {
case json.Number:
return normalizeNumber(v)
case *big.Int:
if v.IsInt64() {
if i := v.Int64(); math.MinInt <= i && i <= math.MaxInt {
return int(i)
}
}
return v
case int64:
if math.MinInt <= v && v <= math.MaxInt {
return int(v)
}
return big.NewInt(v)
case int32:
return int(v)
case int16:
return int(v)
case int8:
return int(v)
case uint:
if v <= math.MaxInt {
return int(v)
}
return new(big.Int).SetUint64(uint64(v))
case uint64:
if v <= math.MaxInt {
return int(v)
}
return new(big.Int).SetUint64(v)
case uint32:
if uint64(v) <= math.MaxInt {
return int(v)
}
return new(big.Int).SetUint64(uint64(v))
case uint16:
return int(v)
case uint8:
return int(v)
case float32:
return float64(v)
case []any:
for i, x := range v {
v[i] = normalizeNumbers(x)
}
return v
case map[string]any:
for k, x := range v {
v[k] = normalizeNumbers(x)
}
return v
default:
return v
}
}