-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarshal_utils.go
More file actions
444 lines (377 loc) · 8.63 KB
/
marshal_utils.go
File metadata and controls
444 lines (377 loc) · 8.63 KB
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
package fxjson
import (
"fmt"
"reflect"
"time"
)
// CompactJSON 压缩JSON字符串(移除空白字符)
func CompactJSON(src []byte) []byte {
buf := getBuffer()
defer putBuffer(buf)
inString := false
escaped := false
for i := 0; i < len(src); i++ {
c := src[i]
if inString {
buf.WriteByte(c)
if escaped {
escaped = false
} else if c == '\\' {
escaped = true
} else if c == '"' {
inString = false
}
} else {
switch c {
case '"':
inString = true
buf.WriteByte(c)
case ' ', '\t', '\n', '\r':
// 跳过空白字符
continue
default:
buf.WriteByte(c)
}
}
}
result := make([]byte, len(buf.buf))
copy(result, buf.buf)
return result
}
// PrettyJSON 美化JSON字符串(添加缩进和换行)
func PrettyJSON(src []byte) []byte {
return PrettyJSONWithIndent(src, " ")
}
// PrettyJSONWithIndent 使用指定缩进美化JSON字符串
func PrettyJSONWithIndent(src []byte, indent string) []byte {
buf := getBuffer()
defer putBuffer(buf)
inString := false
escaped := false
depth := 0
for i := 0; i < len(src); i++ {
c := src[i]
if inString {
buf.WriteByte(c)
if escaped {
escaped = false
} else if c == '\\' {
escaped = true
} else if c == '"' {
inString = false
}
} else {
switch c {
case '"':
inString = true
buf.WriteByte(c)
case '{', '[':
buf.WriteByte(c)
depth++
// 检查下一个字符是否是结束符
if i+1 < len(src) {
next := src[i+1]
for next == ' ' || next == '\t' || next == '\n' || next == '\r' {
i++
if i+1 >= len(src) {
break
}
next = src[i+1]
}
if next != '}' && next != ']' {
buf.WriteByte('\n')
writeIndent(buf, indent, depth)
}
}
case '}', ']':
// 检查前一个字符是否是开始符
prevChar := byte(0)
if len(buf.buf) > 0 {
prevChar = buf.buf[len(buf.buf)-1]
}
depth--
if prevChar != '{' && prevChar != '[' {
buf.WriteByte('\n')
writeIndent(buf, indent, depth)
}
buf.WriteByte(c)
case ',':
buf.WriteByte(c)
buf.WriteByte('\n')
writeIndent(buf, indent, depth)
case ':':
buf.WriteByte(c)
buf.WriteByte(' ')
case ' ', '\t', '\n', '\r':
// 跳过现有的空白字符
continue
default:
buf.WriteByte(c)
}
}
}
result := make([]byte, len(buf.buf))
copy(result, buf.buf)
return result
}
// ValidateJSON 验证JSON格式是否正确
func ValidateJSON(data []byte) bool {
node := FromBytes(data)
return node.Exists()
}
// JSONSize 计算JSON数据大小(字节)
func JSONSize(v interface{}) int {
if data, err := Marshal(v); err == nil {
return len(data)
}
return 0
}
// EstimateJSONSize 估算JSON数据大小(不进行实际序列化)
func EstimateJSONSize(v interface{}) int {
return estimateSize(reflect.ValueOf(v))
}
// estimateSize 估算反射值的JSON大小
func estimateSize(rv reflect.Value) int {
if !rv.IsValid() {
return 4 // "null"
}
// 处理指针
for rv.Kind() == reflect.Ptr {
if rv.IsNil() {
return 4 // "null"
}
rv = rv.Elem()
}
switch rv.Kind() {
case reflect.Bool:
if rv.Bool() {
return 4 // "true"
}
return 5 // "false"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n := rv.Int()
if n == 0 {
return 1
}
size := 0
if n < 0 {
size = 1
n = -n
}
for n > 0 {
size++
n /= 10
}
return size
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n := rv.Uint()
if n == 0 {
return 1
}
size := 0
for n > 0 {
size++
n /= 10
}
return size
case reflect.Float32, reflect.Float64:
return 20 // 估算浮点数长度
case reflect.String:
return rv.Len() + 2 // 字符串长度 + 两个引号
case reflect.Slice, reflect.Array:
size := 2 // []
length := rv.Len()
for i := 0; i < length; i++ {
if i > 0 {
size++ // 逗号
}
size += estimateSize(rv.Index(i))
}
return size
case reflect.Map:
if rv.IsNil() {
return 4 // "null"
}
size := 2 // {}
keys := rv.MapKeys()
for i, key := range keys {
if i > 0 {
size++ // 逗号
}
size += estimateSize(key) + 1 // 键 + 冒号
size += estimateSize(rv.MapIndex(key))
}
return size
case reflect.Struct:
size := 2 // {}
structType := rv.Type()
typeInfo := getTypeInfo(structType)
fieldCount := 0
for _, field := range typeInfo.fields {
fieldValue := rv.Field(field.index)
if field.omitEmpty && isEmptyValue(fieldValue) {
continue
}
if fieldCount > 0 {
size++ // 逗号
}
size += len(field.jsonName) + 3 // 字段名 + 引号 + 冒号
size += estimateSize(fieldValue)
fieldCount++
}
return size
default:
return 10 // 默认估算
}
}
// JSONDepth 计算JSON数据的最大嵌套深度
func JSONDepth(data []byte) int {
node := FromBytes(data)
return calculateDepth(node, 0)
}
// calculateDepth 计算节点深度
func calculateDepth(node Node, currentDepth int) int {
if !node.Exists() {
return currentDepth
}
maxDepth := currentDepth
switch node.Type() {
case 'o':
node.ForEach(func(key string, value Node) bool {
depth := calculateDepth(value, currentDepth+1)
if depth > maxDepth {
maxDepth = depth
}
return true
})
case 'a':
for i := 0; i < node.Len(); i++ {
depth := calculateDepth(node.Index(i), currentDepth+1)
if depth > maxDepth {
maxDepth = depth
}
}
}
return maxDepth
}
// MarshalTime 序列化时间(RFC3339格式)
func MarshalTime(t time.Time) []byte {
return []byte(`"` + t.Format(time.RFC3339) + `"`)
}
// MarshalTimeUnix 序列化时间(Unix时间戳)
func MarshalTimeUnix(t time.Time) []byte {
buf := getBuffer()
defer putBuffer(buf)
writeInt(buf, t.Unix())
result := make([]byte, len(buf.buf))
copy(result, buf.buf)
return result
}
// MarshalDuration 序列化时间间隔(纳秒)
func MarshalDuration(d time.Duration) []byte {
buf := getBuffer()
defer putBuffer(buf)
writeInt(buf, int64(d))
result := make([]byte, len(buf.buf))
copy(result, buf.buf)
return result
}
// MarshalBinary 序列化二进制数据(Base64编码)
func MarshalBinary(data []byte) []byte {
// 简化的Base64编码
encoded := base64Encode(data)
result := make([]byte, len(encoded)+2)
result[0] = '"'
copy(result[1:], encoded)
result[len(result)-1] = '"'
return result
}
// base64Encode 简化的Base64编码
func base64Encode(src []byte) []byte {
if len(src) == 0 {
return nil
}
const base64Table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
n := len(src)
encoded := make([]byte, (n+2)/3*4)
si, ei := 0, 0
for si < n-2 {
val := uint32(src[si])<<16 | uint32(src[si+1])<<8 | uint32(src[si+2])
encoded[ei] = base64Table[val>>18&0x3F]
encoded[ei+1] = base64Table[val>>12&0x3F]
encoded[ei+2] = base64Table[val>>6&0x3F]
encoded[ei+3] = base64Table[val&0x3F]
si += 3
ei += 4
}
remain := n - si
if remain > 0 {
val := uint32(src[si]) << 16
if remain == 2 {
val |= uint32(src[si+1]) << 8
}
encoded[ei] = base64Table[val>>18&0x3F]
encoded[ei+1] = base64Table[val>>12&0x3F]
if remain == 2 {
encoded[ei+2] = base64Table[val>>6&0x3F]
} else {
encoded[ei+2] = '='
}
encoded[ei+3] = '='
}
return encoded
}
// StructToMap 将结构体转换为map[string]interface{}
func StructToMap(v interface{}) (map[string]interface{}, error) {
rv := reflect.ValueOf(v)
// 处理指针
for rv.Kind() == reflect.Ptr {
if rv.IsNil() {
return nil, nil
}
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct {
return nil, fmt.Errorf("expected struct, got %s", rv.Kind())
}
result := make(map[string]interface{})
structType := rv.Type()
typeInfo := getTypeInfo(structType)
for _, field := range typeInfo.fields {
fieldValue := rv.Field(field.index)
if field.omitEmpty && isEmptyValue(fieldValue) {
continue
}
value := fieldValue.Interface()
result[field.jsonName] = value
}
return result, nil
}
// MapToStruct 将map转换为结构体
func MapToStruct(m map[string]interface{}, v interface{}) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr {
return fmt.Errorf("v must be a pointer")
}
if rv.IsNil() {
return fmt.Errorf("v must be a non-nil pointer")
}
elem := rv.Elem()
if elem.Kind() != reflect.Struct {
return fmt.Errorf("v must point to a struct")
}
structType := elem.Type()
typeInfo := getTypeInfo(structType)
for _, field := range typeInfo.fields {
if value, exists := m[field.jsonName]; exists {
fieldValue := elem.Field(field.index)
if fieldValue.CanSet() {
valueRV := reflect.ValueOf(value)
if valueRV.Type().AssignableTo(fieldValue.Type()) {
fieldValue.Set(valueRV)
}
}
}
}
return nil
}