/
marshal.go
381 lines (358 loc) · 9.87 KB
/
marshal.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
// MIT License
//
// Copyright (c) 2021 Xiantu Li
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package json
import (
"encoding"
stdjson "encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
lxterrs "github.com/lxt1045/errors"
)
/*
fget 函数 list ,打入slice中,然后依次遍历slice,避免了遍历struct 的多个for循环!! greate!
golang不支持尾递归,可能嵌套调用性能没有fget list 方式好
*/
// bsGrow 在 slice marshal 的时候可以根据第一个的序列化结果计算出还需要的长度,如果 bs 不足则提前分配是比较好的选择
func bsGrow(in []byte, lNeed int) (out []byte) {
lNew := bsPoolN
if lNew < lNeed+len(in) {
lNew += lNeed + len(in)
}
bsNew := make([]byte, 0, lNew)
out = append(bsNew, in...)
return
}
// 排列一个 fM list,优化掉多个 for 循环
func marshalStruct(store Store, in []byte) (out []byte) {
out = append(in, '{')
for _, tag := range store.tag.ChildList {
out = append(out, tag.TagName...)
out = append(out, ':')
pObj := pointerOffset(store.obj, tag.Offset)
out = tag.fM(Store{obj: pObj, tag: tag}, out)
out = append(out, ',')
}
out[len(out)-1] = '}'
return
}
// marshalT 序列化明确的类型
func marshalT(in []byte, store Store) (out []byte) {
out = in
panic(lxterrs.Errorf("error tag, fM is nil:%+v", store.tag))
return
}
// TODO: 根据一个 marshal 的 len 乘以 len(m) ,达到还需要的空间,如果不足则 New?
func marshalSlice(bs []byte, store Store, l int) (out []byte) {
out = append(bs, '[')
if l <= 0 {
out = append(out, ']')
return
}
son := store.tag
size := son.TypeSize
lBefore := len(out)
out = son.fM(Store{obj: store.obj, tag: son}, out)
lObj := len(out) - lBefore + 1 + 16 // 16 随意取的值
// 解析还需要的空间
if lNeed := lObj * (l - 1); cap(out)-len(out) < lNeed {
out = bsGrow(out, lNeed)
}
for i := 1; i < l; i++ {
out = append(out, ',')
pSon := pointerOffset(store.obj, uintptr(i*size))
out = son.fM(Store{obj: pSon, tag: son}, out)
}
out = append(out, ']')
return
}
func marshalInterface(bs []byte, iface interface{}) (out []byte) {
if iface == nil {
out = append(bs, "null"...)
return
}
out = bs
switch v := iface.(type) {
case int8:
out = strconv.AppendInt(out, int64(v), 10)
case int16:
out = strconv.AppendInt(out, int64(v), 10)
case int32:
out = strconv.AppendInt(out, int64(v), 10)
case int64:
out = strconv.AppendInt(out, int64(v), 10)
case int:
out = strconv.AppendInt(out, int64(v), 10)
case uint8:
out = strconv.AppendUint(out, uint64(v), 10)
case uint16:
out = strconv.AppendUint(out, uint64(v), 10)
case uint32:
out = strconv.AppendUint(out, uint64(v), 10)
case uint64:
out = strconv.AppendUint(out, uint64(v), 10)
case uint:
out = strconv.AppendUint(out, uint64(v), 10)
case float32:
out = strconv.AppendFloat(out, float64(v), 'f', -1, 32)
case float64:
out = strconv.AppendFloat(out, v, 'f', -1, 64)
case string:
out = append(out, '"')
out = append(out, v...)
out = append(out, '"')
case stdjson.Number:
// TODO: 检查 numStr 的有效性?
out = append(out, v.String()...)
case map[string]interface{}:
out = marshalMapInterface(out, v)
case []interface{}:
out = append(out, '[')
for i, iface := range v {
if i != 0 {
out = append(out, ',')
}
marshalInterface(out, iface)
}
out = append(out, ']')
case []byte:
panic("TODO: []byte...")
default:
value := reflect.ValueOf(iface)
out = marshalValue(out, value)
}
return
}
// TODO: 根据一个 marshal 的 len 乘以 len(m) ,达到还需要的空间,如果不足则 New?
func marshalMapInterface(bs []byte, m map[string]interface{}) (out []byte) {
out = bs
out = append(out, '{')
if len(m) == 0 {
out = append(out, '}')
return
}
first := true
for k, v := range m {
if first {
first = false
lBefore := len(out)
out = append(out, '"')
out = append(out, k...)
out = append(out, `":`...)
out = marshalInterface(out, v)
lObj := len(out) - lBefore + 1 + 16 // 16 随意取的值
if lNeed := lObj * (len(m) - 1); cap(out)-len(out) < lNeed {
out = bsGrow(out, lNeed)
}
continue
}
out = append(out, `,"`...)
out = append(out, k...)
out = append(out, `":`...)
out = marshalInterface(out, v)
}
out = append(out, '}')
return
}
func marshalValue(bs []byte, value reflect.Value) (out []byte) {
out = bs
// 针对指针
for value.Kind() == reflect.Ptr {
if value.IsNil() {
out = append(out, "null"...)
return
}
value = value.Elem()
}
switch value.Kind() {
case reflect.Interface:
if value.IsNil() {
out = append(out, "null"...)
return
}
// UnpackEface(&value)
// 从 iterface{} 里取出原始类型
value := reflect.ValueOf(value.Interface())
out = marshalValue(bs, value)
return
case reflect.Map:
if value.IsNil() {
out = append(out, "null"...)
return
}
iter := value.MapRange()
if iter == nil {
return
}
out = append(out, '{')
l := len(out)
for iter.Next() {
out = marshalKey(out, iter.Key())
out = append(out, ':')
out = marshalValue(out, iter.Value())
out = append(out, ',')
}
if l < len(out) {
out = out[:len(out)-1]
}
out = append(out, '}')
return
case reflect.Slice:
if value.IsNil() {
out = append(out, "[]"...)
return
}
out = append(out, '[')
lBefore := len(out)
v := value.Index(0)
out = marshalValue(out, v)
lObj := len(out) - lBefore + 1 + 16 // 16 随意取的值
// 解析还需要的空间
if lNeed := lObj * (value.Len() - 1); cap(out)-len(out) < lNeed {
out = bsGrow(out, lNeed)
}
for i := 1; i < value.Len(); i++ {
out = append(out, ',')
v := value.Index(i)
out = marshalValue(out, v)
}
out = append(out, ']')
return
case reflect.Struct:
prv := reflectValueToValue(&value)
goType := prv.typ
tag, err := LoadTagNode(value, goType.Hash)
if err != nil {
return
}
store := Store{
tag: tag,
obj: prv.ptr, // eface.Value,
}
out = marshalStruct(store, out)
return
case reflect.Bool:
if value.Bool() {
out = append(out, "true"...)
} else {
out = append(out, "false"...)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
out = strconv.AppendUint(out, value.Uint(), 10)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
out = strconv.AppendInt(out, value.Int(), 10)
case reflect.Float64:
out = strconv.AppendFloat(out, value.Float(), 'f', -1, 64)
case reflect.Float32:
out = strconv.AppendFloat(out, value.Float(), 'f', -1, 32)
case reflect.String:
if value.Type() == jsonNumberType {
numStr := value.String()
// TODO: 检查 numStr 的有效性?
out = append(out, numStr...)
return
}
out = append(out, '"')
// out = append(out, value.String()...) // TODO 需要转义: \ --> \\
str := value.String()
nQuote := strings.Count(str, "\"") // 只处理 " , \ 可以不处理
if nQuote == 0 {
out = append(out, str...) // TODO 需要转义: \ --> \\
} else {
for {
i := strings.IndexByte(str, '"')
if i == -1 {
out = append(out, str...)
break
}
out = append(out, str[:i]...)
out = append(out, '\\', '"')
str = str[i+1:]
}
}
out = append(out, '"')
return
default:
// out = append(out, "null"...)
panic(fmt.Sprintf("TODO: kind:%d...", value.Kind()))
}
return
}
var jsonNumberType = reflect.TypeOf(stdjson.Number(""))
func marshalKey(in []byte, k reflect.Value) (out []byte) {
out = in
if k.Kind() == reflect.String {
// key = k.String()
out = append(out, '"')
// out = append(out, k.String()...) // TODO 需要转义: \ --> \\
str := k.String()
nQuote := strings.Count(str, "\"") // 只处理 " , \ 可以不处理
if nQuote == 0 {
out = append(out, str...) // TODO 需要转义: \ --> \\
} else {
for {
i := strings.IndexByte(str, '"')
if i == -1 {
out = append(out, str...)
break
}
out = append(out, str[:i]...)
out = append(out, '\\', '"')
str = str[i+1:]
}
}
out = append(out, '"')
return
}
if tm, ok := k.Interface().(encoding.TextMarshaler); ok {
if k.Kind() == reflect.Pointer && k.IsNil() {
return
}
bs, err := tm.MarshalText()
if err != nil {
err = lxterrs.Wrap(err, "MarshalText() got error")
panic(err)
}
// key = string(bs)
out = append(out, '"')
out = append(out, bs...)
out = append(out, '"')
return
}
switch k.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
// key = strconv.FormatInt(k.Int(), 10)
out = append(out, '"')
out = strconv.AppendInt(out, k.Int(), 10)
out = append(out, '"')
return
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
// key = strconv.FormatUint(k.Uint(), 10)
out = append(out, '"')
out = strconv.AppendUint(out, k.Uint(), 10)
out = append(out, '"')
return
}
err := lxterrs.New("unexpected map key type")
panic(err)
}