/
pointer.go
296 lines (271 loc) · 7.63 KB
/
pointer.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
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
package jsonpatch2
import (
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
"github.com/VictorLowther/jsonpatch2/utils"
)
// pointerSegment is an individual fragment of a pointer.
type pointerSegment string
var decode = strings.NewReplacer("~1", "/", "~0", "~")
var encode = strings.NewReplacer("~", "~0", "/", "~1")
// String translates a pointerSegment into a regular string, encoding it as we go.
func (s pointerSegment) String() string {
return encode.Replace(string(s))
}
// NewSegment creates a new segment from an encoded string.
func newSegment(s string) (pointerSegment, error) {
c := strings.Split(s, `~`)
if len(c) != 0 {
for i := 1; i < len(c); i++ {
if strings.HasPrefix(c[i], `0`) || strings.HasPrefix(c[i], `1`) {
continue
}
return pointerSegment(""), fmt.Errorf("`%s` has an illegal unescaped ~", s)
}
}
return pointerSegment(decode.Replace(s)), nil
}
// Pointer is a JSON Pointer
type Pointer []pointerSegment
// Contains tests to see if B is a subset of A
func (a Pointer) Contains(b Pointer) bool {
return len(b) >= len(a) && reflect.DeepEqual(a, b[:len(a)])
}
// newpointer takes a string that conforms to RFC6901 and turns it into a JSON pointer.
func NewPointer(s string) (Pointer, error) {
frags := strings.Split(s, `/`)[1:]
res := make(Pointer, len(frags))
// An empty pointer refers to the whole document, and so is valid.
if s == "" {
return res, nil
}
if !strings.HasPrefix(s, "/") {
return nil, fmt.Errorf("Initial character of a non-empty pointer must be `/`")
}
for i, frag := range frags {
q, err := newSegment(frag)
if err != nil {
return nil, err
}
res[i] = q
}
return res, nil
}
// Allow a pointer to be marshalled to valid JSON.
func (p Pointer) MarshalJSON() ([]byte, error) {
return json.Marshal(p.String())
}
// Allow unmarshalling from JSON
func (p *Pointer) UnmarshalJSON(buf []byte) error {
var b string
if err := json.Unmarshal(buf, &b); err != nil {
return err
}
ptr, err := NewPointer(b)
*p = ptr[:]
return err
}
// String takes a pointer and returns its string value.
func (p Pointer) String() string {
frags := make([]string, len(p)+1)
for i, frag := range p {
frags[i+1] = frag.String()
}
return strings.Join(frags, `/`)
}
// Shift extracts the first element in the pointer, returning it and the rest of the pointer.
func (p Pointer) Shift() (string, Pointer) {
if len(p) == 0 {
return "", p
}
return string(p[0]), Pointer(p[1:])
}
// Chop extracts the last element in the pointer, returning it and the rest of the pointer.
func (p Pointer) Chop() (string, Pointer) {
if len(p) == 0 {
return "", p
}
last := len(p) - 1
return string(p[last]), Pointer(p[:last])
}
func (p Pointer) Append(frag string) Pointer {
return append(p, pointerSegment(decode.Replace(frag)))
}
func normalizeOffset(selector string, bound int) (int, error) {
res, err := strconv.Atoi(selector)
if err != nil {
return -1, err
}
if res < 0 {
res = bound + res
}
if res >= bound || res < 0 {
return -1, fmt.Errorf("Index out of bounds")
}
return res, nil
}
// Get takes an unmarshalled JSON blob, and returns the value pointed at by the pointer.
// The unmarshalled blob is left unchanged.
func (p Pointer) Get(from interface{}) (interface{}, error) {
if len(p) == 0 {
return from, nil
}
selector, nextPointer := p.Shift()
switch t := from.(type) {
case map[string]interface{}:
found, ok := t[selector]
if !ok {
return nil, fmt.Errorf("Selector %v not a member of %#v", selector, t)
}
return nextPointer.Get(found)
case []interface{}:
index, err := normalizeOffset(selector, len(t))
if err != nil {
return nil, err
}
return nextPointer.Get(t[index])
default:
return nil, fmt.Errorf("Cannot index pointer %v for non-indexable JSON value", p.String())
}
}
func (p Pointer) toContainer(to interface{}) (string, interface{}, error) {
if len(p) == 0 {
return "", nil, fmt.Errorf("Cannot happen")
}
selector, getPointer := p.Chop()
operatrix, err := getPointer.Get(to)
return selector, operatrix, err
}
// Replace replaces the pointed at value (which must exist) with val.
func (p Pointer) Replace(to interface{}, val interface{}) (interface{}, error) {
if len(p) == 0 {
return val, nil
}
selector, operatrix, err := p.toContainer(to)
if err != nil {
return to, err
}
switch t := operatrix.(type) {
case map[string]interface{}:
if _, ok := t[selector]; ok {
t[selector] = val
} else {
return to, fmt.Errorf("%v does not refer to an existing location", p.String())
}
case []interface{}:
index, err := normalizeOffset(selector, len(t))
if err != nil {
return to, err
}
t[index] = val
default:
return to, fmt.Errorf("Cannot put to non-indexable JSON value")
}
return to, nil
}
func (p Pointer) handleChangedSlice(to interface{}, s []interface{}) (interface{}, error) {
if len(p) > 1 {
_, holdPtr := p.Chop()
return holdPtr.Replace(to, s)
} else {
return s, nil
}
}
// Put puts val into to at the position indicated by the pointer,
// returning a possibly new value for to. The position does not have
// to already exist or refer to a preexisting Value.
//
// Put may have to return a new to if to happens to be a slice, since
// the semantics of Put necessarily involve growing the Slice.
func (p Pointer) Put(to interface{}, val interface{}) (interface{}, error) {
selector, operatrix, err := p.toContainer(to)
if err != nil {
return to, err
}
switch t := operatrix.(type) {
case map[string]interface{}:
t[selector] = val
case []interface{}:
if selector == "-" {
t = append(t, val)
} else {
index, err := normalizeOffset(selector, len(t))
if err != nil {
return to, err
}
res := make([]interface{}, len(t)+1)
k := res[index+1:]
copy(res, t[:index])
copy(k, t[index:])
res[index] = val
t = res
}
return p.handleChangedSlice(to, t)
default:
return to, fmt.Errorf("Cannot put to non-indexable JSON value")
}
return to, nil
}
// Remove removes the value pointed to by the pointer from from,
// returning a possibly new value for from.
//
// Remove may have to return a new from if it is a slice, because the
// semantics for Reomve on a Slice involve shrinking it, which
// involves reallocation the way we do it.
func (p *Pointer) Remove(from interface{}) (interface{}, error) {
selector, operatrix, err := p.toContainer(from)
if err != nil {
return from, err
}
switch t := operatrix.(type) {
case map[string]interface{}:
if _, ok := t[selector]; !ok {
return from, fmt.Errorf("`%v` does not point to an existing location", p.String())
}
delete(t, selector)
case []interface{}:
index, err := normalizeOffset(selector, len(t))
if err != nil {
return from, err
}
// Shift everything after our target over by one.
k := t[index:]
k2 := t[index+1:]
copy(k, k2)
t = t[:len(t)-1]
return p.handleChangedSlice(from, t)
default:
return from, fmt.Errorf("Cannot remove non-indexable JSON value")
}
return from, nil
}
// Copy deep-copies the value pointed to by p in from to the location pointed to by at.
func (p Pointer) Copy(from interface{}, at Pointer) (interface{}, error) {
val, err := p.Get(from)
if err != nil {
return from, err
}
return at.Put(from, utils.Clone(val))
}
// Move moves the value pointed to by p in from to the location pointed to by at.
func (p Pointer) Move(from interface{}, at Pointer) (interface{}, error) {
val, err := p.Get(from)
if err != nil {
return from, err
}
val, err = at.Put(from, val)
if err != nil {
return val, err
}
return p.Remove(val)
}
func (p *Pointer) Test(from interface{}, sample interface{}) error {
val, err := p.Get(from)
if err == nil && !reflect.DeepEqual(val, sample) {
err = fmt.Errorf("Test op failed.")
}
return err
}