-
Notifications
You must be signed in to change notification settings - Fork 0
/
arrayEncoder.go
129 lines (97 loc) · 2.29 KB
/
arrayEncoder.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
package jsoon
func newArrayEncoder(e *Encoder) *ArrayEncoder {
return &ArrayEncoder{e: e}
}
// ArrayEncoder is an encoder for arrays
// TODO: Use more helper funcs to reduce code duplication between Encoder and ArrayEncoder fn's
type ArrayEncoder struct {
e *Encoder
}
// Object will marshal an Encodee
func (a *ArrayEncoder) Object(value Encodee) (err error) {
if a.e.depth == 0 {
// Acquire buffer for this depth
a.e.buf = p.Acquire()
}
// Increase depth
a.e.depth++
// Get parent's child value
pc := a.e.child
if a.e.child > 0 {
a.e.buf.WriteByte(charComma)
}
// Set child value to 0, since this is a new object
a.e.child = 0
a.e.buf.WriteByte(charOpenCurly)
if err = value.MarshalJsoon(a.e); err != nil {
return
}
a.e.buf.WriteByte(charCloseCurly)
if _, err = a.e.w.Write(a.e.buf.Bytes()); err != nil {
return
}
a.e.buf.Reset()
// Set child value to parent's child value
a.e.child = pc
a.e.child++
// Reduce depth to the parent's level
a.e.depth--
return
}
// Array will marshal an array
func (a *ArrayEncoder) Array(value ArrayEncodee) (err error) {
if a.e.depth == 0 {
// Acquire buffer for this depth
a.e.buf = p.Acquire()
}
// Increase depth
a.e.depth++
// Get parent's child value
pc := a.e.child
if a.e.child > 0 {
a.e.buf.WriteByte(charComma)
}
// Set child value to 0, since this is a new object
a.e.child = 0
a.e.buf.WriteByte(charOpenBracket)
if err = value.MarshalJsoon(a); err != nil {
return
}
a.e.buf.WriteByte(charCloseBracket)
if _, err = a.e.w.Write(a.e.buf.Bytes()); err != nil {
return
}
a.e.buf.Reset()
// Set child value to parent's child value
a.e.child = pc
a.e.child++
// Reduce depth to the parent's level
a.e.depth--
return
}
// String will marshal a string
func (a *ArrayEncoder) String(value string) {
if a.e.child > 0 {
a.e.buf.WriteByte(charComma)
}
a.e.buf.WriteByte(charDoubleQuote)
a.e.buf.WriteString(value)
a.e.buf.WriteByte(charDoubleQuote)
a.e.child++
}
// Number will marshal a number
func (a *ArrayEncoder) Number(value float64) {
if a.e.child > 0 {
a.e.buf.WriteByte(charComma)
}
a.e.buf.WriteFloat64(value)
a.e.child++
}
// Bool will marshal a boolean
func (a *ArrayEncoder) Bool(value bool) {
if a.e.child > 0 {
a.e.buf.WriteByte(charComma)
}
a.e.buf.WriteBool(value)
a.e.child++
}