-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoder.go
330 lines (300 loc) · 7.14 KB
/
encoder.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
package gosaxml
import (
"errors"
"io"
)
// pre-allocate all constant byte slices that we write
var (
// all characters used to build new namespace aliases
namespaceAliases = []byte("abcdefghijklmnopqrstuvwxyz")
// constant strings needed here and there
slashAngleClose = []byte("/>")
angleOpenSlash = []byte("</")
angleOpenQuest = []byte("<?")
questAngleClose = []byte("?>")
)
// EncoderMiddleware allows to pre-process a Token before
// it is finally encoded/written.
type EncoderMiddleware interface {
// EncodeToken will be called by the Encoder before the provided Token
// is finally byte-encoded into the io.Writer.
// The Encoder will ensure that the pointed-to Token and all its contained
// field values will remain unmodified for the lexical scope of the
// XML-element represented by the Token.
// If, for example, the Token represents a TokenTypeStartElement, then
// the Token and all of its contained fields/byte-slices will contain
// their values until after its corresponding TokenTypeEndElement is processed
// by the EncoderMiddleware.
EncodeToken(token *Token) error
// Reset resets the state of an EncoderMiddleware.
// This can be used to e.g. reset all pre-allocated data structures
// and reinitialize the EncoderMiddleware to the state before the
// any first call to EncodeToken.
Reset()
}
// Encoder encodes Token values to an io.Writer.
type Encoder struct {
// buffers writes to the underlying io.Writer
buf []byte
// middlewares can modify encoded tokens before encoding.
middlewares []EncoderMiddleware
// The io.Writer we encode/write into.
wr io.Writer
// Whether the last token was of type TokenTypeStartElement.
// This is used to delay encoding the ending ">" or "/>" string
// based on whether the element is immediately closed afterwards.
lastStartElement bool
}
// NewEncoder creates a new Encoder with the given middlewares and returns a pointer to it.
func NewEncoder(w io.Writer, middlewares ...EncoderMiddleware) *Encoder {
return &Encoder{
buf: make([]byte, 0, 2048),
wr: w,
middlewares: middlewares,
}
}
// Flush writes all buffered output into the io.Writer.
// It must be called after token encoding is done in order
// to write all remaining bytes into the io.Writer.
func (thiz *Encoder) Flush() error {
_, err := thiz.wr.Write(thiz.buf)
thiz.buf = thiz.buf[:0]
return err
}
func (thiz *Encoder) write(b byte) error {
if len(thiz.buf)+1 >= cap(thiz.buf) {
err := thiz.Flush()
if err != nil {
return err
}
}
thiz.buf = append(thiz.buf, b)
return nil
}
func (thiz *Encoder) writeBytes(bs []byte) error {
l := len(bs)
if len(thiz.buf)+l >= cap(thiz.buf) {
err := thiz.Flush()
if err != nil {
return err
}
}
thiz.buf = append(thiz.buf, bs...)
return nil
}
// Reset resets this Encoder to write into the provided io.Writer
// and resets all middlewares.
func (thiz *Encoder) Reset(w io.Writer) {
thiz.wr = w
thiz.buf = thiz.buf[:0]
thiz.lastStartElement = false
for _, middleware := range thiz.middlewares {
middleware.Reset()
}
}
// EncodeToken first calls any EncoderMiddleware and then
// writes the byte-representation of that Token to the io.Writer
// of this Encoder.
func (thiz *Encoder) EncodeToken(t *Token) error {
switch t.Kind {
case TokenTypeInvalid:
return errors.New("trying to encode invalid/zerovalue token")
case TokenTypeStartElement:
err := thiz.encodeStartElement(t)
if err != nil {
return err
}
thiz.lastStartElement = true
case TokenTypeEndElement:
err := thiz.encodeEndElement(t)
if err != nil {
return err
}
thiz.lastStartElement = false
case TokenTypeTextElement:
err := thiz.encodeTextElement(t)
if err != nil {
return err
}
thiz.lastStartElement = false
case TokenTypeDirective:
err := thiz.encodeDirective(t)
if err != nil {
return err
}
thiz.lastStartElement = false
case TokenTypeProcInst:
err := thiz.encodeProcInst(t)
if err != nil {
return err
}
thiz.lastStartElement = false
default:
thiz.lastStartElement = false
return errors.New("NYI")
}
return nil
}
func (thiz *Encoder) encodeStartElement(t *Token) error {
err := thiz.endLastStartElement()
if err != nil {
return err
}
err = thiz.write('<')
if err != nil {
return err
}
err = thiz.callMiddlewares(t)
if err != nil {
return err
}
// write element name
err = thiz.writeName(t.Name)
if err != nil {
return err
}
// write attributes
for i := 0; i < len(t.Attr); i++ {
attr := &t.Attr[i]
err = thiz.write(' ')
if err != nil {
return err
}
err = thiz.writeName(attr.Name)
if err != nil {
return err
}
err = thiz.write('=')
if err != nil {
return err
}
err = thiz.writeString(attr.Value, attr.SingleQuote)
if err != nil {
return err
}
}
// DO NOT write the ending ">" character, because the element
// could get closed right away with the next EndElement token.
return nil
}
func (thiz *Encoder) encodeEndElement(t *Token) error {
if thiz.lastStartElement {
// the last seen token was a StartElement, so this
// token can only be its accompanying EndElement.
err := thiz.writeBytes(slashAngleClose)
if err != nil {
return err
}
return thiz.callMiddlewares(t)
}
err := thiz.callMiddlewares(t)
if err != nil {
return err
}
err = thiz.writeBytes(angleOpenSlash)
if err != nil {
return err
}
err = thiz.writeName(t.Name)
if err != nil {
return err
}
err = thiz.write('>')
if err != nil {
return err
}
return nil
}
func (thiz *Encoder) callMiddlewares(t *Token) error {
var err error
for _, middleware := range thiz.middlewares {
err = middleware.EncodeToken(t)
if err != nil {
return err
}
}
return nil
}
func (thiz *Encoder) writeName(n Name) error {
var err error
if n.Prefix != nil {
err = thiz.writeBytes(n.Prefix)
if err != nil {
return err
}
err = thiz.write(':')
if err != nil {
return err
}
}
return thiz.writeBytes(n.Local)
}
func (thiz *Encoder) writeString(s []byte, useSingleQuote bool) error {
var err error
if useSingleQuote {
err = thiz.write('\'')
} else {
err = thiz.write('"')
}
if err != nil {
return err
}
err = thiz.writeBytes(s)
if err != nil {
return err
}
if useSingleQuote {
err = thiz.write('\'')
} else {
err = thiz.write('"')
}
return err
}
func (thiz *Encoder) encodeTextElement(t *Token) error {
err := thiz.endLastStartElement()
if err != nil {
return err
}
return thiz.writeBytes(t.ByteData)
}
func (thiz *Encoder) endLastStartElement() error {
if thiz.lastStartElement {
// end the last StartElement with its ">"
err := thiz.write('>')
if err != nil {
return err
}
}
return nil
}
func (thiz *Encoder) encodeDirective(t *Token) error {
err := thiz.endLastStartElement()
if err != nil {
return err
}
return thiz.writeBytes(t.ByteData)
}
func (thiz *Encoder) encodeProcInst(t *Token) error {
err := thiz.endLastStartElement()
if err != nil {
return err
}
err = thiz.writeBytes(angleOpenQuest)
if err != nil {
return err
}
err = thiz.writeName(t.Name)
if err != nil {
return err
}
err = thiz.write(' ')
if err != nil {
return err
}
err = thiz.writeBytes(t.ByteData)
if err != nil {
return err
}
err = thiz.writeBytes(questAngleClose)
return err
}