-
Notifications
You must be signed in to change notification settings - Fork 98
/
position.go
142 lines (123 loc) · 2.35 KB
/
position.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
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
package jsonschema
import (
"strconv"
"strings"
)
// Position tells possible tokens in json.
type Position interface {
collect(v any, ptr jsonPointer) map[jsonPointer]any
}
// --
type AllProp struct{}
func (AllProp) collect(v any, ptr jsonPointer) map[jsonPointer]any {
obj, ok := v.(map[string]any)
if !ok {
return nil
}
m := map[jsonPointer]any{}
for pname, pvalue := range obj {
m[ptr.append(pname)] = pvalue
}
return m
}
// --
type AllItem struct{}
func (AllItem) collect(v any, ptr jsonPointer) map[jsonPointer]any {
arr, ok := v.([]any)
if !ok {
return nil
}
m := map[jsonPointer]any{}
for i, item := range arr {
m[ptr.append(strconv.Itoa(i))] = item
}
return m
}
// --
type Prop string
func (p Prop) collect(v any, ptr jsonPointer) map[jsonPointer]any {
obj, ok := v.(map[string]any)
if !ok {
return nil
}
pvalue, ok := obj[string(p)]
if !ok {
return nil
}
return map[jsonPointer]any{
ptr.append(string(p)): pvalue,
}
}
// --
type Item int
func (i Item) collect(v any, ptr jsonPointer) map[jsonPointer]any {
arr, ok := v.([]any)
if !ok {
return nil
}
if i < 0 || int(i) >= len(arr) {
return nil
}
return map[jsonPointer]any{
ptr.append(strconv.Itoa(int(i))): arr[int(i)],
}
}
// --
// SchemaPath tells where to look for subschema inside keyword.
type SchemaPath []Position
func schemaPath(path string) SchemaPath {
var sp SchemaPath
for _, tok := range strings.Split(path, "/") {
var pos Position
switch tok {
case "*":
pos = AllProp{}
case "[]":
pos = AllItem{}
default:
if i, err := strconv.Atoi(tok); err == nil {
pos = Item(i)
} else {
pos = Prop(tok)
}
}
sp = append(sp, pos)
}
return sp
}
func (sp SchemaPath) collect(v any, ptr jsonPointer) map[jsonPointer]any {
if len(sp) == 0 {
return map[jsonPointer]any{
ptr: v,
}
}
p, sp := sp[0], sp[1:]
m := p.collect(v, ptr)
mm := map[jsonPointer]any{}
for ptr, v := range m {
m = sp.collect(v, ptr)
for k, v := range m {
mm[k] = v
}
}
return mm
}
func (sp SchemaPath) String() string {
var sb strings.Builder
for _, pos := range sp {
if sb.Len() != 0 {
sb.WriteByte('/')
}
switch pos := pos.(type) {
case AllProp:
sb.WriteString("*")
case AllItem:
sb.WriteString("[]")
case Prop:
sb.WriteString(string(pos))
case Item:
sb.WriteString(strconv.Itoa(int(pos)))
}
}
return sb.String()
}