-
Notifications
You must be signed in to change notification settings - Fork 4
/
any_test.go
411 lines (379 loc) · 7.68 KB
/
any_test.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package jx
import (
hexEnc "encoding/hex"
"encoding/json"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/go-faster/errors"
)
// NB: Any left intentionally unexported
// AnyType is type of Any value.
type AnyType byte
// Possible types for Any.
const (
AnyInvalid AnyType = iota
AnyStr
AnyNumber
AnyNull
AnyObj
AnyArr
AnyBool
)
// Any represents any json value as sum type.
type Any struct {
Type AnyType // zero value if AnyInvalid, can be AnyNull
Str string // AnyStr
Bool bool // AnyBool
Number Num // AnyNumber
// Key in object. Valid only if KeyValid.
Key string
// KeyValid denotes whether Any is element of object.
// Needed for representing Key that is blank.
//
// Can be true only for Child of AnyObj.
KeyValid bool
Child []Any // AnyArr or AnyObj
}
// Equal reports whether v is equal to b.
func (v Any) Equal(b Any) bool {
if v.KeyValid && v.Key != b.Key {
return false
}
if v.Type != b.Type {
return false
}
switch v.Type {
case AnyNull, AnyInvalid:
return true
case AnyBool:
return v.Bool == b.Bool
case AnyStr:
return v.Str == b.Str
case AnyNumber:
return v.Number.Equal(b.Number)
}
if len(v.Child) != len(b.Child) {
return false
}
for i := range v.Child {
if !v.Child[i].Equal(b.Child[i]) {
return false
}
}
return true
}
// Any reads Any value.
func (d *Decoder) Any() (Any, error) {
var v Any
if err := v.Read(d); err != nil {
return Any{}, err
}
return v, nil
}
// Any encodes Any value.
func (e *Encoder) Any(a Any) {
a.Write(e)
}
func (v *Any) Read(d *Decoder) error {
switch d.Next() {
case Invalid:
return errors.New("invalid")
case Number:
n, err := d.NumAppend(nil)
if err != nil {
return errors.Wrap(err, "number")
}
v.Number = n
v.Type = AnyNumber
case String:
s, err := d.Str()
if err != nil {
return errors.Wrap(err, "str")
}
v.Str = s
v.Type = AnyStr
case Null:
if err := d.Null(); err != nil {
return errors.Wrap(err, "null")
}
v.Type = AnyNull
case Bool:
b, err := d.Bool()
if err != nil {
return errors.Wrap(err, "bool")
}
v.Bool = b
v.Type = AnyBool
case Object:
v.Type = AnyObj
if err := d.Obj(func(r *Decoder, s string) error {
var elem Any
if err := elem.Read(r); err != nil {
return errors.Wrap(err, "elem")
}
elem.Key = s
elem.KeyValid = true
v.Child = append(v.Child, elem)
return nil
}); err != nil {
return errors.Wrap(err, "obj")
}
return nil
case Array:
v.Type = AnyArr
if err := d.Arr(func(r *Decoder) error {
var elem Any
if err := elem.Read(r); err != nil {
return errors.Wrap(err, "elem")
}
v.Child = append(v.Child, elem)
return nil
}); err != nil {
return errors.Wrap(err, "array")
}
return nil
}
return nil
}
// Write json representation of Any to Encoder.
func (v Any) Write(w *Encoder) {
if v.KeyValid {
w.FieldStart(v.Key)
}
switch v.Type {
case AnyStr:
w.Str(v.Str)
case AnyNumber:
w.Num(v.Number)
case AnyBool:
w.Bool(v.Bool)
case AnyNull:
w.Null()
case AnyArr:
w.ArrStart()
for _, c := range v.Child {
c.Write(w)
}
w.ArrEnd()
case AnyObj:
w.ObjStart()
for _, c := range v.Child {
c.Write(w)
}
w.ObjEnd()
}
}
func (v Any) String() string {
var b strings.Builder
if v.KeyValid {
if v.Key == "" {
b.WriteString("<blank>")
}
b.WriteString(v.Key)
b.WriteString(": ")
}
switch v.Type {
case AnyStr:
b.WriteString(`'` + v.Str + `'`)
case AnyNumber:
b.WriteString(v.Number.String())
case AnyBool:
b.WriteString(strconv.FormatBool(v.Bool))
case AnyNull:
b.WriteString("null")
case AnyArr:
b.WriteString("[")
for i, c := range v.Child {
if i != 0 {
b.WriteString(", ")
}
b.WriteString(c.String())
}
b.WriteString("]")
case AnyObj:
b.WriteString("{")
for i, c := range v.Child {
if i != 0 {
b.WriteString(", ")
}
b.WriteString(c.String())
}
b.WriteString("}")
default:
b.WriteString("<invalid>")
}
return b.String()
}
// Reset Any value to reuse.
func (v *Any) Reset() {
v.Type = AnyInvalid
v.Child = v.Child[:0]
v.KeyValid = false
v.Str = ""
v.Key = ""
}
// Obj calls f for any child that is field if v is AnyObj.
func (v Any) Obj(f func(k string, v Any)) {
if v.Type != AnyObj {
return
}
for _, c := range v.Child {
if !c.KeyValid {
continue
}
f(c.Key, c)
}
}
func TestAny_Read(t *testing.T) {
t.Run("Obj", func(t *testing.T) {
var v Any
const input = `{"foo":{"bar":1,"baz":[1,2,3.14],"200":null,"f":"s","t":true,"":""}}`
r := DecodeStr(input)
assert.NoError(t, v.Read(r))
assert.Equal(t, "{foo: {bar: 1, baz: [1, 2, 3.14], 200: null, f: 's', t: true, <blank>: ''}}", v.String())
e := GetEncoder()
e.Any(v)
require.Equal(t, input, e.String(), "encoded value should equal to input")
})
t.Run("Inputs", func(t *testing.T) {
for _, tt := range []struct {
Input string
}{
{Input: "1"},
{Input: "0.0"},
} {
t.Run(tt.Input, func(t *testing.T) {
input := []byte(tt.Input)
r := DecodeBytes(input)
v, err := r.Any()
require.NoError(t, err)
e := GetEncoder()
v.Write(e)
var otherValue Any
r.ResetBytes(e.Bytes())
if err := otherValue.Read(r); err != nil {
t.Error(err)
t.Log(hexEnc.Dump(input))
t.Log(hexEnc.Dump(e.Bytes()))
}
require.True(t, otherValue.Equal(v))
})
}
})
t.Run("Negative", func(t *testing.T) {
for _, s := range []string{
`foo`,
`bar`,
`tier`,
`{]`,
`[}`,
`[foo]`,
`[tier]`,
`{foo:"`,
`{"foo": tier`,
`"baz`,
`nil`,
} {
t.Run(s, func(t *testing.T) {
d := DecodeStr(s)
v, err := d.Any()
require.Error(t, err)
require.Equal(t, AnyInvalid, v.Type)
require.Equal(t, "<invalid>", v.String())
})
}
t.Run("Reader", func(t *testing.T) {
d := Decode(errReader{}, -1)
// Manually set internal buffer.
d.tail = 1
d.buf = []byte{'1'}
// Trigger reading of number start from buffer
// and call to reader.
v, err := d.Any()
require.Error(t, err)
require.Equal(t, AnyInvalid, v.Type)
})
})
}
func TestAny_Equal(t *testing.T) {
t.Run("ZeroValues", func(t *testing.T) {
for _, typ := range []AnyType{
AnyInvalid,
AnyStr,
AnyNumber,
AnyNull,
AnyObj,
AnyArr,
AnyBool,
} {
a := Any{Type: typ}
t.Run("Equal", func(t *testing.T) {
b := Any{Type: typ}
require.True(t, a.Equal(b))
t.Run("Child", func(t *testing.T) {
aArr := Any{
Type: AnyArr,
Child: []Any{a},
}
bArr := Any{
Type: AnyArr,
}
require.False(t, aArr.Equal(bArr))
bArr.Child = []Any{b}
require.True(t, aArr.Equal(bArr))
})
})
t.Run("NotEqual", func(t *testing.T) {
b := Any{Type: typ + 1}
require.False(t, a.Equal(b))
t.Run("Child", func(t *testing.T) {
aArr := Any{
Type: AnyArr,
Child: []Any{a},
}
bArr := Any{
Type: AnyArr,
Child: []Any{b},
}
require.False(t, aArr.Equal(bArr))
})
})
t.Run("Keys", func(t *testing.T) {
a.KeyValid = true
b := Any{Type: typ, KeyValid: true}
require.True(t, a.Equal(b))
b.Key = "1"
require.False(t, a.Equal(b))
})
}
})
}
func BenchmarkAny(b *testing.B) {
buf := []byte(`[true, null, false, 100, "false"]`)
r := GetDecoder()
b.ReportAllocs()
b.SetBytes(int64(len(buf)))
var v Any
for i := 0; i < b.N; i++ {
v.Reset()
r.ResetBytes(buf)
if err := v.Read(r); err != nil {
b.Fatal(err)
}
}
}
func BenchmarkAnyStd(b *testing.B) {
buf := []byte(`[true, null, false, 100, "false"]`)
b.ReportAllocs()
b.SetBytes(int64(len(buf)))
var v []interface{}
for i := 0; i < b.N; i++ {
v = v[:0]
if err := json.Unmarshal(buf, &v); err != nil {
b.Fatal(err)
}
}
}