-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdec_str_test.go
117 lines (100 loc) · 2.25 KB
/
dec_str_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
package jx
import (
"encoding/json"
"fmt"
"io"
"strings"
"testing"
"testing/iotest"
"unicode/utf8"
"github.com/stretchr/testify/require"
)
func TestDecoder_StrAppend(t *testing.T) {
s := `"Hello"`
d := DecodeStr(s)
var (
data []byte
err error
)
data, err = d.StrAppend(data)
require.NoError(t, err)
require.Equal(t, "Hello", string(data))
_, err = d.StrAppend(data)
require.ErrorIs(t, err, io.ErrUnexpectedEOF)
}
func TestUnexpectedTokenErr_Error(t *testing.T) {
e := &badTokenErr{
Token: 'c',
}
s := error(e).Error()
require.Equal(t, "unexpected byte 99 'c'", s)
}
func TestDecoder_Str(t *testing.T) {
testStr := func(d *Decoder, input string, valid bool) func(t *testing.T) {
return func(t *testing.T) {
t.Cleanup(func() {
if t.Failed() {
t.Logf("Input: %q", input)
}
})
_, err := d.Str()
if valid {
require.NoError(t, err)
} else {
require.Error(t, err)
}
}
}
for i, input := range testStrings {
valid := json.Valid([]byte(input))
t.Run(fmt.Sprintf("Test%d", i), func(t *testing.T) {
t.Run("Buffer", testStr(DecodeStr(input), input, valid))
r := strings.NewReader(input)
d := Decode(r, 512)
t.Run("Reader", testStr(d, input, valid))
r.Reset(input)
obr := iotest.OneByteReader(r)
d.Reset(obr)
t.Run("OneByteReader", testStr(d, input, valid))
})
}
}
func Benchmark_appendRune(b *testing.B) {
b.ReportAllocs()
buf := make([]byte, 0, 4)
for i := 0; i < b.N; i++ {
buf = buf[:0]
buf = appendRune(buf, 'f')
}
}
func benchmarkDecoderStrBytes(str string) func(b *testing.B) {
return func(b *testing.B) {
e := GetEncoder()
e.Str(str)
data := e.Bytes()
d := GetDecoder()
b.SetBytes(int64(len(data)))
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
d.ResetBytes(data)
if _, err := d.StrBytes(); err != nil {
b.Fatal(err)
}
}
}
}
func BenchmarkDecoder_StrBytes(b *testing.B) {
runBench := func(char string) func(b *testing.B) {
return func(b *testing.B) {
for _, size := range []int{
2, 8, 16, 64, 128, 1024,
} {
count := utf8.RuneCountInString(char)
b.Run(fmt.Sprintf("%db", size), benchmarkDecoderStrBytes(strings.Repeat(char, size/count)))
}
}
}
b.Run("Plain", runBench("a"))
b.Run("Escaped", runBench("ф"))
}