forked from wundergraph/astjson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
98 lines (85 loc) · 1.68 KB
/
util.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
package astjson
import (
"unsafe"
)
func b2s(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
func s2b(s string) (b []byte) {
return unsafe.Slice(unsafe.StringData(s), len(s))
}
const maxStartEndStringLen = 80
func startEndString(s string) string {
if len(s) <= maxStartEndStringLen {
return s
}
start := s[:40]
end := s[len(s)-40:]
return start + "..." + end
}
var (
NullValue = MustParse(`null`)
)
func AppendToArray(array, value *Value) {
if array.Type() != TypeArray {
return
}
items, _ := array.Array()
array.SetArrayItem(len(items), value)
}
func SetValue(v *Value, value *Value, path ...string) {
for i := 0; i < len(path)-1; i++ {
parent := v
v = v.Get(path[i])
if v == nil {
child := MustParse(`{}`)
parent.Set(path[i], child)
v = child
}
}
v.Set(path[len(path)-1], value)
}
func SetNull(v *Value, path ...string) {
SetValue(v, MustParse(`null`), path...)
}
func ValueIsNonNull(v *Value) bool {
if v == nil {
return false
}
if v.Type() == TypeNull {
return false
}
return true
}
func (v *Value) AppendArrayItems(right *Value) {
if v.t != TypeArray || right.t != TypeArray {
return
}
v.a = append(v.a, right.a...)
}
func ValueIsNull(v *Value) bool {
return !ValueIsNonNull(v)
}
func DeduplicateObjectKeysRecursively(v *Value) {
if v.Type() == TypeArray {
a := v.GetArray()
for _, e := range a {
DeduplicateObjectKeysRecursively(e)
}
}
if v.Type() != TypeObject {
return
}
o, _ := v.Object()
seen := make(map[string]struct{})
o.Visit(func(k []byte, v *Value) {
key := string(k)
if _, ok := seen[key]; ok {
o.Del(key)
return
} else {
seen[key] = struct{}{}
}
DeduplicateObjectKeysRecursively(v)
})
}