-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathencode.go
550 lines (474 loc) · 11.3 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
547
548
549
550
package protobuf
import (
"bytes"
"encoding"
"encoding/binary"
"errors"
"fmt"
"math"
"reflect"
"time"
)
// Message fields declared to have exactly this type
// will be transmitted as fixed-size 32-bit unsigned integers.
type Ufixed32 uint32
// Message fields declared to have exactly this type
// will be transmitted as fixed-size 64-bit unsigned integers.
type Ufixed64 uint64
// Message fields declared to have exactly this type
// will be transmitted as fixed-size 32-bit signed integers.
type Sfixed32 int32
// Message fields declared to have exactly this type
// will be transmitted as fixed-size 64-bit signed integers.
type Sfixed64 int64
// Protobufs enums are transmitted as unsigned varints;
// using this type alias is optional but recommended
// to ensure they get the correct type.
type Enum uint32
type encoder struct {
bytes.Buffer
}
// Encode a Go struct into protocol buffer format.
// The caller must pass a pointer to the struct to encode.
func Encode(structPtr interface{}) (bytes []byte, err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("%v", e)
bytes = nil
}
}()
if structPtr == nil {
return nil, nil
}
if bu, ok := structPtr.(encoding.BinaryMarshaler); ok {
return bu.MarshalBinary()
}
en := encoder{}
val := reflect.ValueOf(structPtr)
if val.Kind() != reflect.Ptr {
return nil, errors.New("encode takes a pointer to struct")
}
en.message(val.Elem())
return en.Bytes(), nil
}
func (en *encoder) message(sval reflect.Value) {
var index *ProtoField
defer func() {
if r := recover(); r != nil {
if index != nil {
panic(fmt.Sprintf("%s (field %s)", r, index.Field.Name))
} else {
panic(r)
}
}
}()
// Encode all fields in-order
protoFields := ProtoFields(sval.Type())
if len(protoFields) == 0 {
return
}
noPublicFields := true
for _, index = range protoFields {
field := sval.FieldByIndex(index.Index)
key := uint64(index.ID) << 3
if field.CanSet() { // Skip blank/padding fields
en.value(key, field, index.Prefix)
noPublicFields = false
}
}
if noPublicFields {
panic("struct has no serializable fields")
}
}
var timeType = reflect.TypeOf(time.Time{})
var durationType = reflect.TypeOf(time.Duration(0))
func (en *encoder) value(key uint64, val reflect.Value, prefix TagPrefix) {
// Non-reflectively handle some of the fixed types
switch v := val.Interface().(type) {
case bool:
en.uvarint(key | 0)
vi := uint64(0)
if v {
vi = 1
}
en.uvarint(vi)
return
case int:
en.uvarint(key | 0)
en.svarint(int64(v))
return
case int32:
en.uvarint(key | 0)
en.svarint(int64(v))
return
case time.Time: // Encode time.Time as sfixed64
t := v.UnixNano()
en.uvarint(key | 1)
en.u64(uint64(t))
return
case int64:
en.uvarint(key | 0)
en.svarint(v)
return
case uint32:
en.uvarint(key | 0)
en.uvarint(uint64(v))
return
case uint64:
en.uvarint(key | 0)
en.uvarint(v)
return
case Sfixed32:
en.uvarint(key | 5)
en.u32(uint32(v))
return
case Sfixed64:
en.uvarint(key | 1)
en.u64(uint64(v))
return
case Ufixed32:
en.uvarint(key | 5)
en.u32(uint32(v))
return
case Ufixed64:
en.uvarint(key | 1)
en.u64(uint64(v))
return
case float32:
en.uvarint(key | 5)
en.u32(math.Float32bits(v))
return
case float64:
en.uvarint(key | 1)
en.u64(math.Float64bits(v))
return
case string:
en.uvarint(key | 2)
b := []byte(v)
en.uvarint(uint64(len(b)))
en.Write(b)
return
}
// Handle pointer or interface values (possibly within slices).
// Note that this switch has to handle all the cases,
// because custom type aliases will fail the above typeswitch.
switch val.Kind() {
case reflect.Bool:
en.uvarint(key | 0)
v := uint64(0)
if val.Bool() {
v = 1
}
en.uvarint(v)
case reflect.Int, reflect.Int32, reflect.Int64:
// Varint-encoded 32-bit and 64-bit signed integers.
// Note that protobufs don't support 8- or 16-bit ints.
en.uvarint(key | 0)
en.svarint(val.Int())
case reflect.Uint32, reflect.Uint64:
// Varint-encoded 32-bit and 64-bit unsigned integers.
en.uvarint(key | 0)
en.uvarint(val.Uint())
case reflect.Float32:
// Fixed-length 32-bit floats.
en.uvarint(key | 5)
en.u32(math.Float32bits(float32(val.Float())))
case reflect.Float64:
// Fixed-length 64-bit floats.
en.uvarint(key | 1)
en.u64(math.Float64bits(val.Float()))
case reflect.String:
// Length-delimited string.
en.uvarint(key | 2)
b := []byte(val.String())
en.uvarint(uint64(len(b)))
en.Write(b)
case reflect.Struct:
var b []byte
if enc, ok := val.Interface().(encoding.BinaryMarshaler); ok {
en.uvarint(key | 2)
var err error
b, err = enc.MarshalBinary()
if err != nil {
panic(err.Error())
}
} else {
// Embedded messages.
en.uvarint(key | 2)
emb := encoder{}
emb.message(val)
b = emb.Bytes()
}
en.uvarint(uint64(len(b)))
en.Write(b)
case reflect.Slice, reflect.Array:
// Length-delimited slices or byte-vectors.
en.slice(key, val)
return
case reflect.Ptr:
// Optional field: encode only if pointer is non-nil.
if val.IsNil() {
if prefix == TagRequired {
panic("required field is nil")
}
return
}
en.value(key, val.Elem(), prefix)
case reflect.Interface:
// Abstract interface field.
if val.IsNil() {
return
}
// If the object support self-encoding, use that.
if enc, ok := val.Interface().(encoding.BinaryMarshaler); ok {
en.uvarint(key | 2)
bytes, err := enc.MarshalBinary()
if err != nil {
panic(err.Error())
}
size := len(bytes)
var id GeneratorID
im, ok := val.Interface().(InterfaceMarshaler)
if ok {
id = im.MarshalID()
g := generators.get(id)
ok = g != nil
if ok {
// add the length of the type tag
size += len(id)
}
}
en.uvarint(uint64(size))
if ok {
// Only write the tag if a generator exists
en.Write(id[:])
}
en.Write(bytes)
return
}
// Encode from the object the interface points to.
en.value(key, val.Elem(), prefix)
case reflect.Map:
en.handleMap(key, val, prefix)
return
default:
panic(fmt.Sprintf("unsupported field Kind %d", val.Kind()))
}
}
func (en *encoder) slice(key uint64, slval reflect.Value) {
// First handle common cases with a direct typeswitch
sllen := slval.Len()
packed := encoder{}
switch slt := slval.Interface().(type) {
case []bool:
for i := 0; i < sllen; i++ {
v := uint64(0)
if slt[i] {
v = 1
}
packed.uvarint(v)
}
case []int32:
for i := 0; i < sllen; i++ {
packed.svarint(int64(slt[i]))
}
case []int64:
for i := 0; i < sllen; i++ {
packed.svarint(slt[i])
}
case []uint32:
for i := 0; i < sllen; i++ {
packed.uvarint(uint64(slt[i]))
}
case []uint64:
for i := 0; i < sllen; i++ {
packed.uvarint(slt[i])
}
case []Sfixed32:
for i := 0; i < sllen; i++ {
packed.u32(uint32(slt[i]))
}
case []Sfixed64:
for i := 0; i < sllen; i++ {
packed.u64(uint64(slt[i]))
}
case []Ufixed32:
for i := 0; i < sllen; i++ {
packed.u32(uint32(slt[i]))
}
case []Ufixed64:
for i := 0; i < sllen; i++ {
packed.u64(uint64(slt[i]))
}
case []float32:
for i := 0; i < sllen; i++ {
packed.u32(math.Float32bits(slt[i]))
}
case []float64:
for i := 0; i < sllen; i++ {
packed.u64(math.Float64bits(slt[i]))
}
case []byte: // Write the whole byte-slice as one key,value pair
en.uvarint(key | 2)
en.uvarint(uint64(sllen))
en.Write(slt)
return
case []string:
for i := 0; i < sllen; i++ {
subVal := slval.Index(i)
subStr := subVal.Interface().(string)
subSlice := []byte(subStr)
en.uvarint(key | 2)
en.uvarint(uint64(len(subSlice)))
en.Write(subSlice)
}
return
default: // We'll need to use the reflective path
en.sliceReflect(key, slval)
return
}
// Encode packed representation key/value pair
en.uvarint(key | 2)
b := packed.Bytes()
en.uvarint(uint64(len(b)))
en.Write(b)
}
// Handle the encoding of an arbritary map[K]V
func (en *encoder) handleMap(key uint64, mpval reflect.Value, prefix TagPrefix) {
/*
A map defined as
map<key_type, value_type> map_field = N;
is encoded in the same way as
message MapFieldEntry {
key_type key = 1;
value_type value = 2;
}
repeated MapFieldEntry map_field = N;
*/
for _, mkey := range mpval.MapKeys() {
mval := mpval.MapIndex(mkey)
// illegal map entry values
// - nil message pointers.
switch kind := mval.Kind(); kind {
case reflect.Ptr:
if mval.IsNil() {
panic("proto: map has nil element")
}
case reflect.Slice, reflect.Array:
if mval.Type().Elem().Kind() != reflect.Uint8 {
panic("protobuf: map only support []byte or string as repeated value")
}
}
packed := encoder{}
packed.value(1<<3, mkey, prefix)
packed.value(2<<3, mval, prefix)
en.uvarint(key | 2)
b := packed.Bytes()
en.uvarint((uint64(len(b))))
en.Write(b)
}
}
var bytesType = reflect.TypeOf([]byte{})
func (en *encoder) sliceReflect(key uint64, slval reflect.Value) {
kind := slval.Kind()
if kind != reflect.Slice && kind != reflect.Array {
panic("no slice passed")
}
sllen := slval.Len()
slelt := slval.Type().Elem()
packed := encoder{}
switch slelt.Kind() {
case reflect.Bool:
for i := 0; i < sllen; i++ {
v := uint64(0)
if slval.Index(i).Bool() {
v = 1
}
packed.uvarint(v)
}
case reflect.Int, reflect.Int32, reflect.Int64:
for i := 0; i < sllen; i++ {
packed.svarint(slval.Index(i).Int())
}
case reflect.Uint32, reflect.Uint64:
for i := 0; i < sllen; i++ {
packed.uvarint(slval.Index(i).Uint())
}
case reflect.Float32:
for i := 0; i < sllen; i++ {
packed.u32(math.Float32bits(
float32(slval.Index(i).Float())))
}
case reflect.Float64:
for i := 0; i < sllen; i++ {
packed.u64(math.Float64bits(slval.Index(i).Float()))
}
case reflect.Uint8: // Write the byte-slice as one key,value pair
en.uvarint(key | 2)
en.uvarint(uint64(sllen))
var b []byte
if slval.Kind() == reflect.Array {
if slval.CanAddr() {
sliceVal := slval.Slice(0, sllen)
b = sliceVal.Convert(bytesType).Interface().([]byte)
} else {
sliceVal := reflect.MakeSlice(bytesType, sllen, sllen)
reflect.Copy(sliceVal, slval)
b = sliceVal.Interface().([]byte)
}
} else {
b = slval.Convert(bytesType).Interface().([]byte)
}
en.Write(b)
return
default: // Write each element as a separate key,value pair
t := slval.Type().Elem()
if t.Kind() == reflect.Slice || t.Kind() == reflect.Array {
subSlice := t.Elem()
if subSlice.Kind() != reflect.Uint8 {
panic("protobuf: no support for 2-dimensional array except for [][]byte")
}
}
for i := 0; i < sllen; i++ {
en.value(key, slval.Index(i), TagNone)
}
return
}
// Encode packed representation key/value pair
en.uvarint(key | 2)
b := packed.Bytes()
en.uvarint(uint64(len(b)))
en.Write(b)
}
func (en *encoder) uvarint(v uint64) {
var b [binary.MaxVarintLen64]byte
n := binary.PutUvarint(b[:], v)
en.Write(b[:n])
}
func (en *encoder) svarint(v int64) {
if v >= 0 {
en.uvarint(uint64(v) << 1)
} else {
en.uvarint(^uint64(v << 1))
}
}
func (en *encoder) u32(v uint32) {
var b [4]byte
b[0] = byte(v)
b[1] = byte(v >> 8)
b[2] = byte(v >> 16)
b[3] = byte(v >> 24)
en.Write(b[:])
}
func (en *encoder) u64(v uint64) {
var b [8]byte
b[0] = byte(v)
b[1] = byte(v >> 8)
b[2] = byte(v >> 16)
b[3] = byte(v >> 24)
b[4] = byte(v >> 32)
b[5] = byte(v >> 40)
b[6] = byte(v >> 48)
b[7] = byte(v >> 56)
en.Write(b[:])
}