forked from Azure/go-amqp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encode.go
546 lines (480 loc) · 10.8 KB
/
encode.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
package amqp
import (
"bytes"
"encoding/binary"
"io"
"math"
"sync"
"time"
"unicode/utf8"
)
const intSize = 32 << (^uint(0) >> 63)
var (
errInvalidLength = errorNew("length field is larger than frame")
errNull = errorNew("error is null")
)
// writer is the required interface for marshaling AMQP encoded data.
type writer interface {
io.Writer
io.ByteWriter
}
// bufPool is used to reduce allocations when encoding.
var bufPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
// writesFrame encodes fr into buf.
func writeFrame(buf *bytes.Buffer, fr frame) error {
header := frameHeader{
Size: 0, // overwrite later
DataOffset: 2, // see frameHeader.DataOffset comment
FrameType: fr.typ,
Channel: fr.channel,
}
// write header
err := binary.Write(buf, binary.BigEndian, header)
if err != nil {
return err
}
// write AMQP frame body
err = marshal(buf, fr.body)
if err != nil {
return err
}
// validate size
if buf.Len() > math.MaxUint32 {
return errorNew("frame too large")
}
// retrieve raw bytes
bufBytes := buf.Bytes()
// write correct size
binary.BigEndian.PutUint32(bufBytes, uint32(len(bufBytes)))
return nil
}
type marshaler interface {
marshal(writer) error
}
func marshal(wr writer, i interface{}) error {
var err error
switch t := i.(type) {
case marshaler:
return t.marshal(wr)
case bool:
if t {
err = wr.WriteByte(byte(typeCodeBoolTrue))
} else {
err = wr.WriteByte(byte(typeCodeBoolFalse))
}
case uint:
if intSize == 64 {
return writeUint64(wr, uint64(t))
}
return writeUint32(wr, uint32(t))
case uint64:
return writeUint64(wr, t)
case uint32:
return writeUint32(wr, t)
case *uint32:
if t == nil {
err = wr.WriteByte(byte(typeCodeNull))
break
}
return writeUint32(wr, *t)
case uint16:
err = wr.WriteByte(byte(typeCodeUshort))
if err != nil {
return err
}
err = binary.Write(wr, binary.BigEndian, t)
case uint8:
_, err = wr.Write([]byte{byte(typeCodeUbyte), t})
case *uint8:
_, err = wr.Write([]byte{byte(typeCodeUbyte), *t})
case int:
if intSize == 64 {
return writeInt64(wr, int64(t))
}
return writeInt32(wr, int32(t))
case int8:
err = wr.WriteByte(byte(typeCodeByte))
if err != nil {
return err
}
binary.Write(wr, binary.BigEndian, t)
case int16:
err = wr.WriteByte(byte(typeCodeShort))
if err != nil {
return err
}
binary.Write(wr, binary.BigEndian, t)
case int64:
return writeInt64(wr, t)
case int32:
return writeInt32(wr, t)
case []symbol:
err = writeSymbolArray(wr, t)
case string:
err = writeString(wr, t)
case []byte:
err = writeBinary(wr, t)
case map[interface{}]interface{}:
err = writeMap(wr, t)
case map[string]interface{}:
err = writeMap(wr, t)
case map[symbol]interface{}:
err = writeMap(wr, t)
case unsettled:
err = writeMap(wr, t)
case time.Time:
err = writeTimestamp(wr, t)
default:
return errorErrorf("marshal not implemented for %T", i)
}
return err
}
func writeInt32(wr writer, n int32) error {
if n < 128 && n >= -128 {
_, err := wr.Write([]byte{byte(typeCodeSmallint), byte(n)})
return err
}
err := wr.WriteByte(byte(typeCodeInt))
if err != nil {
return err
}
return binary.Write(wr, binary.BigEndian, n)
}
func writeInt64(wr writer, n int64) error {
if n < 128 && n >= -128 {
_, err := wr.Write([]byte{byte(typeCodeSmalllong), byte(n)})
return err
}
err := wr.WriteByte(byte(typeCodeLong))
if err != nil {
return err
}
return binary.Write(wr, binary.BigEndian, n)
}
func writeUint32(wr writer, n uint32) error {
if n == 0 {
return wr.WriteByte(byte(typeCodeUint0))
}
if n < 256 {
_, err := wr.Write([]byte{byte(typeCodeSmallUint), byte(n)})
return err
}
err := wr.WriteByte(byte(typeCodeUint))
if err != nil {
return err
}
return binary.Write(wr, binary.BigEndian, n)
}
func writeUint64(wr writer, n uint64) error {
if n == 0 {
return wr.WriteByte(byte(typeCodeUlong0))
}
if n < 256 {
_, err := wr.Write([]byte{byte(typeCodeSmallUlong), byte(n)})
return err
}
err := wr.WriteByte(byte(typeCodeUlong))
if err != nil {
return err
}
return binary.Write(wr, binary.BigEndian, n)
}
func writeTimestamp(wr writer, t time.Time) error {
err := wr.WriteByte(byte(typeCodeTimestamp))
if err != nil {
return err
}
ms := t.UnixNano() / int64(time.Millisecond)
return binary.Write(wr, binary.BigEndian, ms)
}
// marshalField is a field to be marshaled
type marshalField struct {
value interface{}
omit bool // indicates that this field should be omitted (set to null)
}
// marshalComposite is a helper for us in a composite's marshal() function.
//
// The returned bytes include the composite header and fields. Fields with
// omit set to true will be encoded as null or omitted altogether if there are
// no non-null fields after them.
func marshalComposite(wr writer, code amqpType, fields ...marshalField) error {
// lastSetIdx is the last index to have a non-omitted field.
// start at -1 as it's possible to have no fields in a composite
lastSetIdx := -1
// marshal each field into it's index in rawFields,
// null fields are skipped, leaving the index nil.
for i, f := range fields {
if f.omit {
continue
}
lastSetIdx = i
}
// write header only
if lastSetIdx == -1 {
_, err := wr.Write([]byte{0x0, byte(typeCodeSmallUlong), byte(code), byte(typeCodeList0)})
return err
}
buf := bufPool.Get().(*bytes.Buffer)
defer bufPool.Put(buf)
buf.Reset()
// write null to each index up to lastSetIdx
for _, f := range fields[:lastSetIdx+1] {
if f.omit {
buf.WriteByte(byte(typeCodeNull))
continue
}
err := marshal(buf, f.value)
if err != nil {
return err
}
}
// write header
err := writeDescriptor(wr, code)
if err != nil {
return err
}
// write fields
err = writeList(wr, lastSetIdx+1, buf.Len())
if err != nil {
return err
}
_, err = buf.WriteTo(wr)
return err
}
func writeDescriptor(wr writer, code amqpType) error {
_, err := wr.Write([]byte{0x0, byte(typeCodeSmallUlong), uint8(code)})
return err
}
func writeSymbolArray(wr writer, symbols []symbol) error {
ofType := typeCodeSym8
for _, symbol := range symbols {
if len(symbol) > math.MaxUint8 {
ofType = typeCodeSym32
break
}
}
buf := bufPool.Get().(*bytes.Buffer)
defer bufPool.Put(buf)
for _, symbol := range symbols {
err := writeSymbol(buf, symbol, ofType)
if err != nil {
return err
}
}
err := writeArray(wr, ofType, len(symbols), buf.Len())
if err != nil {
return err
}
_, err = buf.WriteTo(wr)
return err
}
func writeSymbol(wr writer, sym symbol, typ amqpType) error {
if !utf8.ValidString(string(sym)) {
return errorNew("not a valid UTF-8 string")
}
l := len(sym)
switch typ {
case typeCodeSym8:
err := wr.WriteByte(uint8(l))
if err != nil {
return err
}
case typeCodeSym32:
err := binary.Write(wr, binary.BigEndian, uint32(l))
if err != nil {
return err
}
default:
return errorNew("invalid symbol type")
}
_, err := wr.Write([]byte(sym))
return err
}
func writeString(wr writer, str string) error {
if !utf8.ValidString(str) {
return errorNew("not a valid UTF-8 string")
}
l := len(str)
switch {
// Str8
case l < 256:
_, err := wr.Write(append([]byte{byte(typeCodeStr8), uint8(l)}, []byte(str)...))
return err
// Str32
case l < math.MaxUint32:
err := wr.WriteByte(byte(typeCodeStr32))
if err != nil {
return err
}
err = binary.Write(wr, binary.BigEndian, uint32(l))
if err != nil {
return err
}
_, err = wr.Write([]byte(str))
return err
default:
return errorNew("too long")
}
}
func writeBinary(wr writer, bin []byte) error {
l := len(bin)
switch {
// List8
case l < 256:
_, err := wr.Write(append([]byte{byte(typeCodeVbin8), uint8(l)}, bin...))
return err
// List32
case l < math.MaxUint32:
err := wr.WriteByte(byte(typeCodeVbin32))
if err != nil {
return err
}
err = binary.Write(wr, binary.BigEndian, uint32(l))
if err != nil {
return err
}
_, err = wr.Write(bin)
return err
default:
return errorNew("too long")
}
}
func writeArray(wr writer, of amqpType, numFields int, size int) error {
const isArray = true
return writeSlice(wr, isArray, of, numFields, size)
}
func writeList(wr writer, numFields int, size int) error {
const isArray = false
return writeSlice(wr, isArray, 0, numFields, size)
}
func writeSlice(wr writer, isArray bool, of amqpType, numFields int, size int) error {
size8 := typeCodeList8
size32 := typeCodeList32
if isArray {
size8 = typeCodeArray8
size32 = typeCodeArray32
}
switch {
// list0
case numFields == 0 && isArray:
return wr.WriteByte(byte(typeCodeList0))
// list8
case numFields < 256 && size < 256:
_, err := wr.Write([]byte{byte(size8), uint8(size + 1), uint8(numFields)})
if err != nil {
return err
}
// list32
case numFields < math.MaxUint32 && size < math.MaxUint32:
err := wr.WriteByte(byte(size32))
if err != nil {
return err
}
err = binary.Write(wr, binary.BigEndian, uint32(size+4))
if err != nil {
return err
}
err = binary.Write(wr, binary.BigEndian, uint32(numFields))
if err != nil {
return err
}
default:
return errorNew("too many fields")
}
if isArray {
err := wr.WriteByte(byte(of))
if err != nil {
return err
}
}
return nil
}
func writeMap(wr writer, m interface{}) error {
var length int
buf := new(bytes.Buffer)
switch m := m.(type) {
case map[interface{}]interface{}:
length = len(m)
for key, val := range m {
err := marshal(buf, key)
if err != nil {
return err
}
err = marshal(buf, val)
if err != nil {
return err
}
}
case map[string]interface{}:
length = len(m)
for key, val := range m {
err := marshal(buf, key)
if err != nil {
return err
}
err = marshal(buf, val)
if err != nil {
return err
}
}
case map[symbol]interface{}:
length = len(m)
for key, val := range m {
err := marshal(buf, key)
if err != nil {
return err
}
err = marshal(buf, val)
if err != nil {
return err
}
}
case unsettled:
length = len(m)
for key, val := range m {
err := marshal(buf, key)
if err != nil {
return err
}
err = marshal(buf, val)
if err != nil {
return err
}
}
default:
return errorErrorf("unsupported type or map type %T", m)
}
pairs := length * 2
if pairs > 255 {
return errorNew("map contains too many elements")
}
l := buf.Len() + 1 // +1 for pairs byte
switch {
case l < 256:
_, err := wr.Write([]byte{byte(typeCodeMap8), byte(l)})
if err != nil {
return err
}
case l < math.MaxUint32:
err := wr.WriteByte(byte(typeCodeMap32))
if err != nil {
return err
}
err = binary.Write(wr, binary.BigEndian, uint32(l))
if err != nil {
return err
}
default:
return errorNew("map too large")
}
err := wr.WriteByte(uint8(pairs))
if err != nil {
return err
}
_, err = buf.WriteTo(wr)
return err
}