-
-
Notifications
You must be signed in to change notification settings - Fork 148
/
encode.go
333 lines (295 loc) · 7.34 KB
/
encode.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
package json
import (
"bytes"
"encoding"
"encoding/base64"
"io"
"math"
"reflect"
"strconv"
"sync"
"sync/atomic"
"unsafe"
)
// An Encoder writes JSON values to an output stream.
type Encoder struct {
w io.Writer
ctx *encodeRuntimeContext
ptr unsafe.Pointer
buf []byte
enabledIndent bool
enabledHTMLEscape bool
unorderedMap bool
prefix []byte
indentStr []byte
}
type compiledCode struct {
code *opcode
}
const (
bufSize = 1024
)
const (
opCodeEscapedType = iota
opCodeEscapedIndentType
opCodeNoEscapeType
opCodeNoEscapeIndentType
)
type opcodeSet struct {
escapedCode *opcode
escapedCodeIndent *opcode
code *opcode
codeIndent *opcode
codeLength int
}
func loadOpcodeMap() map[uintptr]*opcodeSet {
p := atomic.LoadPointer(&cachedOpcode)
return *(*map[uintptr]*opcodeSet)(unsafe.Pointer(&p))
}
func storeOpcodeSet(typ uintptr, set *opcodeSet, m map[uintptr]*opcodeSet) {
newOpcodeMap := make(map[uintptr]*opcodeSet, len(m)+1)
newOpcodeMap[typ] = set
for k, v := range m {
newOpcodeMap[k] = v
}
atomic.StorePointer(&cachedOpcode, *(*unsafe.Pointer)(unsafe.Pointer(&newOpcodeMap)))
}
var (
encPool sync.Pool
codePool sync.Pool
cachedOpcode unsafe.Pointer // map[uintptr]*opcodeSet
marshalJSONType reflect.Type
marshalTextType reflect.Type
)
func init() {
encPool = sync.Pool{
New: func() interface{} {
return &Encoder{
ctx: &encodeRuntimeContext{
ptrs: make([]uintptr, 128),
keepRefs: make([]unsafe.Pointer, 0, 8),
},
buf: make([]byte, 0, bufSize),
}
},
}
marshalJSONType = reflect.TypeOf((*Marshaler)(nil)).Elem()
marshalTextType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
}
// NewEncoder returns a new encoder that writes to w.
func NewEncoder(w io.Writer) *Encoder {
enc := encPool.Get().(*Encoder)
enc.w = w
enc.reset()
return enc
}
// Encode writes the JSON encoding of v to the stream, followed by a newline character.
//
// See the documentation for Marshal for details about the conversion of Go values to JSON.
func (e *Encoder) Encode(v interface{}) error {
return e.EncodeWithOption(v)
}
// EncodeWithOption call Encode with EncodeOption.
func (e *Encoder) EncodeWithOption(v interface{}, opts ...EncodeOption) error {
for _, opt := range opts {
if err := opt(e); err != nil {
return err
}
}
buf, err := e.encode(v)
if err != nil {
return err
}
if e.enabledIndent {
buf = buf[:len(buf)-2]
} else {
buf = buf[:len(buf)-1]
}
buf = append(buf, '\n')
if _, err := e.w.Write(buf); err != nil {
return err
}
e.buf = buf[:0]
return nil
}
// SetEscapeHTML specifies whether problematic HTML characters should be escaped inside JSON quoted strings.
// The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML.
//
// In non-HTML settings where the escaping interferes with the readability of the output, SetEscapeHTML(false) disables this behavior.
func (e *Encoder) SetEscapeHTML(on bool) {
e.enabledHTMLEscape = on
}
// SetIndent instructs the encoder to format each subsequent encoded value as if indented by the package-level function Indent(dst, src, prefix, indent).
// Calling SetIndent("", "") disables indentation.
func (e *Encoder) SetIndent(prefix, indent string) {
if prefix == "" && indent == "" {
e.enabledIndent = false
return
}
e.prefix = []byte(prefix)
e.indentStr = []byte(indent)
e.enabledIndent = true
}
func (e *Encoder) release() {
e.w = nil
encPool.Put(e)
}
func (e *Encoder) reset() {
e.enabledHTMLEscape = true
e.enabledIndent = false
e.unorderedMap = false
}
func (e *Encoder) encodeForMarshal(v interface{}) ([]byte, error) {
buf, err := e.encode(v)
if err != nil {
return nil, err
}
e.buf = buf
if e.enabledIndent {
copied := make([]byte, len(buf)-2)
copy(copied, buf)
return copied, nil
}
copied := make([]byte, len(buf)-1)
copy(copied, buf)
return copied, nil
}
func (e *Encoder) encode(v interface{}) ([]byte, error) {
b := e.buf[:0]
if v == nil {
b = encodeNull(b)
if e.enabledIndent {
b = encodeIndentComma(b)
} else {
b = encodeComma(b)
}
return b, nil
}
header := (*interfaceHeader)(unsafe.Pointer(&v))
typ := header.typ
typeptr := uintptr(unsafe.Pointer(typ))
opcodeMap := loadOpcodeMap()
if codeSet, exists := opcodeMap[typeptr]; exists {
var code *opcode
if e.enabledIndent {
if e.enabledHTMLEscape {
code = codeSet.escapedCodeIndent
} else {
code = codeSet.codeIndent
}
} else {
if e.enabledHTMLEscape {
code = codeSet.escapedCode
} else {
code = codeSet.code
}
}
ctx := e.ctx
p := uintptr(header.ptr)
ctx.init(p, codeSet.codeLength)
return e.run(ctx, b, code)
}
// noescape trick for header.typ ( reflect.*rtype )
copiedType := *(**rtype)(unsafe.Pointer(&typeptr))
code, err := e.compileHead(&encodeCompileContext{
typ: copiedType,
root: true,
structTypeToCompiledCode: map[uintptr]*compiledCode{},
})
if err != nil {
return nil, err
}
code = copyOpcode(code)
codeIndent := toIndent(code)
codeLength := code.totalLength()
codeSet := &opcodeSet{
escapedCode: toEscaped(code),
escapedCodeIndent: toEscaped(codeIndent),
code: code,
codeIndent: codeIndent,
codeLength: codeLength,
}
storeOpcodeSet(typeptr, codeSet, opcodeMap)
p := uintptr(header.ptr)
ctx := e.ctx
ctx.init(p, codeLength)
var c *opcode
if e.enabledIndent {
if e.enabledHTMLEscape {
c = codeSet.escapedCodeIndent
} else {
c = codeSet.codeIndent
}
} else {
if e.enabledHTMLEscape {
c = codeSet.escapedCode
} else {
c = codeSet.code
}
}
b, err = e.run(ctx, b, c)
if err != nil {
return nil, err
}
return b, nil
}
func encodeFloat32(b []byte, v float32) []byte {
f64 := float64(v)
abs := math.Abs(f64)
fmt := byte('f')
// Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right.
if abs != 0 {
f32 := float32(abs)
if f32 < 1e-6 || f32 >= 1e21 {
fmt = 'e'
}
}
return strconv.AppendFloat(b, f64, fmt, -1, 32)
}
func encodeFloat64(b []byte, v float64) []byte {
abs := math.Abs(v)
fmt := byte('f')
// Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right.
if abs != 0 {
if abs < 1e-6 || abs >= 1e21 {
fmt = 'e'
}
}
return strconv.AppendFloat(b, v, fmt, -1, 64)
}
func encodeBool(b []byte, v bool) []byte {
if v {
return append(b, "true"...)
}
return append(b, "false"...)
}
func encodeBytes(dst []byte, src []byte) []byte {
return append(dst, src...)
}
func encodeNull(b []byte) []byte {
return append(b, "null"...)
}
func encodeComma(b []byte) []byte {
return append(b, ',')
}
func encodeIndentComma(b []byte) []byte {
return append(b, ',', '\n')
}
func encodeByteSlice(b []byte, src []byte) []byte {
encodedLen := base64.StdEncoding.EncodedLen(len(src))
b = append(b, '"')
pos := len(b)
remainLen := cap(b[pos:])
var buf []byte
if remainLen > encodedLen {
buf = b[pos : pos+encodedLen]
} else {
buf = make([]byte, encodedLen)
}
base64.StdEncoding.Encode(buf, src)
return append(append(b, buf...), '"')
}
func (e *Encoder) encodeIndent(b []byte, indent int) []byte {
b = append(b, e.prefix...)
return append(b, bytes.Repeat(e.indentStr, indent)...)
}