-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
marshal.go
83 lines (74 loc) · 1.42 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
package jsonb
import (
"encoding"
"encoding/json"
"reflect"
"github.com/si3nloong/sqlike/reflext"
)
// Marshaler :
type Marshaler interface {
MarshalJSONB() ([]byte, error)
}
// Marshal :
func Marshal(src interface{}) (b []byte, err error) {
v := reflext.ValueOf(src)
if src == nil || !v.IsValid() || reflext.IsNull(v) {
b = []byte(null)
return
}
encoder, err := registry.LookupEncoder(v)
if err != nil {
return nil, err
}
w := NewWriter()
if err := encoder(w, v); err != nil {
return nil, err
}
b = w.Bytes()
return
}
// marshalerEncoder
func marshalerEncoder() ValueEncoder {
return func(w *Writer, v reflect.Value) error {
x := v.Interface().(Marshaler)
b, err := x.MarshalJSONB()
if err != nil {
return err
}
w.Write(b)
return nil
}
}
func jsonMarshalerEncoder() ValueEncoder {
return func(w *Writer, v reflect.Value) error {
x := v.Interface().(json.Marshaler)
b, err := x.MarshalJSON()
if err != nil {
return err
}
w.Write(b)
return nil
}
}
func textMarshalerEncoder() ValueEncoder {
return func(w *Writer, v reflect.Value) error {
x := v.Interface().(encoding.TextMarshaler)
b, err := x.MarshalText()
if err != nil {
return err
}
length := len(b)
w.WriteByte('"')
for i := 0; i < length; i++ {
char := b[0]
b = b[1:]
if x, ok := escapeCharMap[char]; ok {
w.Write(x)
continue
}
w.WriteByte(char)
}
w.WriteByte('"')
return nil
}
}