forked from francoispqt/gojay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encode_embedded_json.go
93 lines (87 loc) · 2.37 KB
/
encode_embedded_json.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
package gojay
// EncodeEmbeddedJSON encodes an embedded JSON.
// is basically sets the internal buf as the value pointed by v and calls the io.Writer.Write()
func (enc *Encoder) EncodeEmbeddedJSON(v *EmbeddedJSON) error {
if enc.isPooled == 1 {
panic(InvalidUsagePooledEncoderError("Invalid usage of pooled encoder"))
}
enc.buf = *v
_, err := enc.Write()
if err != nil {
return err
}
return nil
}
func (enc *Encoder) encodeEmbeddedJSON(v *EmbeddedJSON) ([]byte, error) {
enc.writeBytes(*v)
return enc.buf, nil
}
// AddEmbeddedJSON adds an EmbeddedJSON to be encoded.
//
// It basically blindly writes the bytes to the final buffer. Therefore,
// it expects the JSON to be of proper format.
func (enc *Encoder) AddEmbeddedJSON(v *EmbeddedJSON) {
enc.grow(len(*v) + 4)
r := enc.getPreviousRune()
if r != '[' {
enc.writeByte(',')
}
enc.writeBytes(*v)
}
// AddEmbeddedJSONOmitEmpty adds an EmbeddedJSON to be encoded or skips it if nil pointer or empty.
//
// It basically blindly writes the bytes to the final buffer. Therefore,
// it expects the JSON to be of proper format.
func (enc *Encoder) AddEmbeddedJSONOmitEmpty(v *EmbeddedJSON) {
if v == nil || len(*v) == 0 {
return
}
r := enc.getPreviousRune()
if r != '[' {
enc.writeByte(',')
}
enc.writeBytes(*v)
}
// AddEmbeddedJSONKey adds an EmbeddedJSON and a key to be encoded.
//
// It basically blindly writes the bytes to the final buffer. Therefore,
// it expects the JSON to be of proper format.
func (enc *Encoder) AddEmbeddedJSONKey(key string, v *EmbeddedJSON) {
if enc.hasKeys {
if !enc.keyExists(key) {
return
}
}
enc.grow(len(key) + len(*v) + 5)
r := enc.getPreviousRune()
if r != '{' {
enc.writeByte(',')
}
enc.writeByte('"')
enc.writeStringEscape(key)
enc.writeBytes(objKey)
enc.writeBytes(*v)
}
// AddEmbeddedJSONKeyOmitEmpty adds an EmbeddedJSON and a key to be encoded or skips it if nil pointer or empty.
//
// It basically blindly writes the bytes to the final buffer. Therefore,
// it expects the JSON to be of proper format.
func (enc *Encoder) AddEmbeddedJSONKeyOmitEmpty(key string, v *EmbeddedJSON) {
if enc.hasKeys {
if !enc.keyExists(key) {
return
}
}
if v == nil || len(*v) == 0 {
return
}
enc.grow(len(key) + len(*v) + 5)
r := enc.getPreviousRune()
if r != '{' {
enc.writeByte(',')
}
enc.writeByte('"')
enc.writeStringEscape(key)
enc.writeBytes(objKey)
enc.writeBytes(*v)
}