-
Notifications
You must be signed in to change notification settings - Fork 0
/
converters_xml.go
413 lines (345 loc) · 10.8 KB
/
converters_xml.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
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
package main
import (
"encoding/xml"
"fmt"
"io"
"math/big"
"strings"
"github.com/kstenerud/go-concise-encoding/cbe"
"github.com/kstenerud/go-concise-encoding/ce/events"
"github.com/kstenerud/go-concise-encoding/configuration"
"github.com/kstenerud/go-concise-encoding/cte"
"github.com/kstenerud/go-concise-encoding/rules"
"github.com/kstenerud/go-concise-encoding/version"
"github.com/cockroachdb/apd/v2"
compact_float "github.com/kstenerud/go-compact-float"
compact_time "github.com/kstenerud/go-compact-time"
)
func XMLToCBE(in io.Reader, out io.Writer, config *encoderConfig) error {
opts := configuration.New()
encoder := cbe.NewEncoder(opts)
rules := rules.NewRules(encoder, opts)
encoder.PrepareToEncode(out)
return XMLToCE(in, rules)
}
func XMLToCTE(in io.Reader, out io.Writer, config *encoderConfig) error {
opts := configuration.New()
encoder := cte.NewEncoder(opts)
rules := rules.NewRules(encoder, opts)
encoder.PrepareToEncode(out)
return XMLToCE(in, rules)
}
func CBEToXML(in io.Reader, out io.Writer, config *encoderConfig) error {
eventReceiver := NewXMLEventReceiver(out, config.indentSpaces)
decoder := cbe.NewDecoder(nil)
return decoder.Decode(in, eventReceiver)
}
func CTEToXML(in io.Reader, out io.Writer, config *encoderConfig) error {
eventReceiver := NewXMLEventReceiver(out, config.indentSpaces)
decoder := cte.NewDecoder(nil)
return decoder.Decode(in, eventReceiver)
}
func XMLToCE(in io.Reader, encoder events.DataEventReceiver) error {
var token xml.Token
var err error
encoder.OnBeginDocument()
encoder.OnVersion(version.ConciseEncodingVersion)
decoder := xml.NewDecoder(in)
for {
token, err = decoder.Token()
if err != nil {
if err == io.EOF {
encoder.OnEndDocument()
return nil
}
return err
}
if _, ok := token.(xml.StartElement); ok {
break
}
}
for {
switch elem := token.(type) {
case xml.StartElement:
encoder.OnNode()
encoder.OnMap()
encoder.OnStringlikeArray(events.ArrayTypeString, "t")
tag := getMarkupNameBytes(elem.Name)
encoder.OnArray(events.ArrayTypeString, uint64(len(tag)), tag)
if len(elem.Attr) > 0 {
encoder.OnStringlikeArray(events.ArrayTypeString, "a")
encoder.OnMap()
for _, v := range elem.Attr {
b := getMarkupNameBytes(v.Name)
encoder.OnArray(events.ArrayTypeString, uint64(len(b)), b)
encoder.OnStringlikeArray(events.ArrayTypeString, v.Value)
}
encoder.OnEndContainer()
}
encoder.OnEndContainer()
case xml.EndElement:
encoder.OnEndContainer()
case xml.CharData:
str := strings.TrimSpace(string(elem))
if len(str) > 0 {
encoder.OnStringlikeArray(events.ArrayTypeString, str)
}
case xml.Comment:
encoder.OnComment(true, elem)
case xml.ProcInst:
// TODO: Anything?
case xml.Directive:
// TODO: Anything?
}
token, err = decoder.Token()
if err != nil {
if err == io.EOF {
encoder.OnEndDocument()
return nil
}
return err
}
}
}
type XMLEventReceiver struct {
encoder *xml.Encoder
stack []string
attributes []xml.Attr
key xml.Name
stage MarkupStage
stringBuffer []byte
arrayBytesRemaining uint64
moreChunksComing bool
}
func NewXMLEventReceiver(out io.Writer, indentSpaces int) *XMLEventReceiver {
rcv := &XMLEventReceiver{
encoder: xml.NewEncoder(out),
}
rcv.encoder.Indent("", generateIndentSpaces(indentSpaces))
return rcv
}
func (_this *XMLEventReceiver) OnComment(isMultiline bool, contents []byte) {
_this.encoder.EncodeToken(xml.Comment(string(contents)))
}
func (_this *XMLEventReceiver) OnStringlikeArray(arrayType events.ArrayType, str string) {
if arrayType != events.ArrayTypeResourceID && arrayType != events.ArrayTypeString {
panic(fmt.Errorf("cannot convert array type %v to XML", arrayType))
}
switch _this.stage {
case MarkupStageAttributeKey:
_this.key = toXMLName(str)
_this.stage = MarkupStageAttributeValue
case MarkupStageAttributeValue:
_this.attributes = append(_this.attributes, xml.Attr{
Name: _this.key,
Value: str,
})
_this.stage = MarkupStageAttributeKey
case MarkupStageContents:
_this.encoder.EncodeToken(xml.CharData(str))
_this.clearStringBuffer()
default:
panic(fmt.Errorf("non-markup content detected"))
}
}
func (_this *XMLEventReceiver) OnEndContainer() {
switch _this.stage {
case MarkupStageAttributeKey:
name := _this.getCurrentMarkupName()
_this.encoder.EncodeToken(xml.StartElement{
Name: toXMLName(name),
Attr: _this.attributes,
})
_this.stage = MarkupStageContents
case MarkupStageContents:
name := _this.getCurrentMarkupName()
_this.encoder.EncodeToken(xml.EndElement{
Name: toXMLName(name),
})
_this.unstackMarkup()
default:
panic(fmt.Errorf("BUG: Unhandled stage: %v", _this.stage))
}
}
func (_this *XMLEventReceiver) getCurrentMarkupName() string {
return _this.stack[len(_this.stack)-1]
}
func (_this *XMLEventReceiver) unstackMarkup() {
_this.stack = _this.stack[:len(_this.stack)-1]
}
func (_this *XMLEventReceiver) clearStringBuffer() {
_this.stringBuffer = _this.stringBuffer[:0]
}
func (_this *XMLEventReceiver) appendStringBuffer(data []byte) {
_this.stringBuffer = append(_this.stringBuffer, data...)
}
func (_this *XMLEventReceiver) OnBeginDocument() {}
func (_this *XMLEventReceiver) OnVersion(uint64) {
_this.stage = MarkupStageNonMarkup
}
func (_this *XMLEventReceiver) OnPadding() {}
func (_this *XMLEventReceiver) OnNull() {
_this.OnStringlikeArray(events.ArrayTypeString, "null")
}
func (_this *XMLEventReceiver) OnBoolean(v bool) {
if v {
_this.OnTrue()
} else {
_this.OnFalse()
}
}
func (_this *XMLEventReceiver) OnTrue() {
_this.OnStringlikeArray(events.ArrayTypeString, "true")
}
func (_this *XMLEventReceiver) OnFalse() {
_this.OnStringlikeArray(events.ArrayTypeString, "false")
}
func (_this *XMLEventReceiver) OnPositiveInt(v uint64) {
_this.OnStringlikeArray(events.ArrayTypeString, fmt.Sprintf("%v", v))
}
func (_this *XMLEventReceiver) OnNegativeInt(v uint64) {
_this.OnStringlikeArray(events.ArrayTypeString, fmt.Sprintf("-%v", v))
}
func (_this *XMLEventReceiver) OnInt(v int64) {
if v < 0 {
_this.OnNegativeInt(uint64(-v))
} else {
_this.OnPositiveInt(uint64(v))
}
}
func (_this *XMLEventReceiver) OnBigInt(v *big.Int) {
_this.OnStringlikeArray(events.ArrayTypeString, fmt.Sprintf("%v", v))
}
func (_this *XMLEventReceiver) OnFloat(v float64) {
_this.OnStringlikeArray(events.ArrayTypeString, fmt.Sprintf("%v", v))
}
func (_this *XMLEventReceiver) OnBigFloat(v *big.Float) {
_this.OnStringlikeArray(events.ArrayTypeString, fmt.Sprintf("%v", v))
}
func (_this *XMLEventReceiver) OnDecimalFloat(v compact_float.DFloat) {
_this.OnStringlikeArray(events.ArrayTypeString, fmt.Sprintf("%v", v))
}
func (_this *XMLEventReceiver) OnBigDecimalFloat(v *apd.Decimal) {
_this.OnStringlikeArray(events.ArrayTypeString, fmt.Sprintf("%v", v))
}
func (_this *XMLEventReceiver) OnNan(isSignaling bool) {
if isSignaling {
_this.OnStringlikeArray(events.ArrayTypeString, "snan")
} else {
_this.OnStringlikeArray(events.ArrayTypeString, "nan")
}
}
func (_this *XMLEventReceiver) OnUID(v []byte) {
_this.OnStringlikeArray(events.ArrayTypeString,
fmt.Sprintf("%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12], v[13], v[14], v[15]))
}
func (_this *XMLEventReceiver) OnTime(v compact_time.Time) {
_this.OnStringlikeArray(events.ArrayTypeString, fmt.Sprintf("%v", v))
}
func (_this *XMLEventReceiver) OnArray(arrayType events.ArrayType, elemCount uint64, elems []byte) {
switch arrayType {
case events.ArrayTypeResourceID, events.ArrayTypeString:
_this.OnStringlikeArray(arrayType, string(elems))
default:
panic(fmt.Errorf("cannot convert array type %v to XML", arrayType))
}
}
func (_this *XMLEventReceiver) OnMedia(mediaType string, data []byte) {
panic(fmt.Errorf("cannot convert media to XML"))
}
func (_this *XMLEventReceiver) OnCustomBinary(customType uint64, data []byte) {
panic(fmt.Errorf("cannot convert custom types to XML"))
}
func (_this *XMLEventReceiver) OnCustomText(customType uint64, data string) {
panic(fmt.Errorf("cannot convert custom types to XML"))
}
func (_this *XMLEventReceiver) OnArrayBegin(arrayType events.ArrayType) {
if arrayType != events.ArrayTypeResourceID && arrayType != events.ArrayTypeString {
panic(fmt.Errorf("cannot convert array type %v to XML", arrayType))
}
_this.clearStringBuffer()
}
func (_this *XMLEventReceiver) OnMediaBegin(mediaType string) {
panic(fmt.Errorf("cannot convert media to XML"))
}
func (_this *XMLEventReceiver) OnCustomBegin(arrayType events.ArrayType, customType uint64) {
panic(fmt.Errorf("cannot convert custom types to XML"))
}
func (_this *XMLEventReceiver) OnArrayChunk(chunkSize uint64, moreChunksComing bool) {
_this.arrayBytesRemaining = chunkSize
_this.moreChunksComing = moreChunksComing
}
func (_this *XMLEventReceiver) OnArrayData(data []byte) {
_this.appendStringBuffer(data)
_this.arrayBytesRemaining -= uint64(len(data))
if _this.arrayBytesRemaining == 0 && !_this.moreChunksComing {
_this.OnStringlikeArray(events.ArrayTypeString, string(_this.stringBuffer))
}
}
func (_this *XMLEventReceiver) OnList() {
panic(fmt.Errorf("cannot convert list to XML"))
}
func (_this *XMLEventReceiver) OnMap() {
panic(fmt.Errorf("cannot convert map to XML"))
}
func (_this *XMLEventReceiver) OnNode() {
panic("TODO: Convert node to XML")
}
func (_this *XMLEventReceiver) OnEdge() {
panic(fmt.Errorf("cannot convert edge to XML"))
}
func (_this *XMLEventReceiver) OnRecordType(id []byte) {
panic("TODO: Convert record type to XML")
}
func (_this *XMLEventReceiver) OnRecord(id []byte) {
panic("TODO: Convert record to XML")
}
func (_this *XMLEventReceiver) OnMarker([]byte) {
panic(fmt.Errorf("cannot convert marker to XML"))
}
func (_this *XMLEventReceiver) OnReferenceLocal([]byte) {
panic(fmt.Errorf("cannot convert local reference to XML"))
}
func (_this *XMLEventReceiver) OnReferenceRemote() {
panic(fmt.Errorf("cannot convert remote reference to XML"))
}
func (_this *XMLEventReceiver) OnConstant(_ []byte) {
panic(fmt.Errorf("cannot convert constant to XML"))
}
func (_this *XMLEventReceiver) OnEndDocument() {}
func generateIndentSpaces(count int) string {
var buff []byte
for i := 0; i < count; i++ {
buff = append(buff, ' ')
}
return string(buff)
}
func toXMLName(name string) xml.Name {
split := strings.SplitN(name, ":", 2)
if len(split) == 2 {
return xml.Name{
Space: split[0],
Local: split[1],
}
}
return xml.Name{
Local: name,
}
}
func getMarkupNameBytes(name xml.Name) (nameBytes []byte) {
if len(name.Space) > 0 {
nameBytes = []byte(name.Space)
}
if len(name.Local) > 0 {
nameBytes = append(nameBytes, []byte(name.Local)...)
}
return
}
type MarkupStage int
const (
MarkupStageNonMarkup MarkupStage = iota
MarkupStageAttributeKey
MarkupStageAttributeValue
MarkupStageContents
)