-
Notifications
You must be signed in to change notification settings - Fork 1
/
marshal.go
500 lines (390 loc) · 10.9 KB
/
marshal.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// Package protoenc provides a way to marshal and unmarshal Go structs tp protocol buffers.
package protoenc
import (
"encoding"
"errors"
"fmt"
"math"
"reflect"
"time"
"google.golang.org/protobuf/encoding/protowire"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/structpb"
"google.golang.org/protobuf/types/known/timestamppb"
)
// Marshal a Go struct into protocol buffer format.
// The caller must pass a pointer to the struct to encode.
func Marshal(structPtr interface{}) (result []byte, err error) {
defer func() {
if recovered := recover(); recovered != nil {
e, ok := recovered.(error)
if !ok {
err = fmt.Errorf("%v", recovered)
} else {
err = e
}
result = nil
}
}()
if structPtr == nil {
return nil, nil
}
if hasCustomEncoders(reflect.TypeOf(structPtr)) {
return nil, errors.New("custom encoders are not supported for top-level structs, use BinaryMarshaler instead")
}
if bu, ok := structPtr.(encoding.BinaryMarshaler); ok {
return bu.MarshalBinary()
}
m := marshaller{
buf: make([]byte, 0, 32),
}
val := reflect.ValueOf(structPtr)
if val.Kind() != reflect.Pointer || val.Type().Elem().Kind() != reflect.Struct {
return nil, errors.New("marshal takes a pointer to struct")
}
m.encodeStruct(val.Elem())
return m.Bytes(), nil
}
type marshaller struct {
buf []byte
}
func (m *marshaller) Bytes() []byte {
if len(m.buf) == 0 {
return nil
}
return m.buf
}
func (m *marshaller) encodeStruct(val reflect.Value) {
structFields, err := StructFields(val.Type())
if err != nil {
panic(err)
}
if len(structFields) == 0 {
return
}
m.encodeFields(val, structFields)
}
func (m *marshaller) encodeFields(val reflect.Value, fieldsData []FieldData) {
var fieldData FieldData
defer func() {
if r := recover(); r != nil {
if !fieldData.IsZero() {
panic(fmt.Errorf("%s (field %s)", r, fieldData.Field.Name))
}
panic(r)
}
}()
noneEncoded := true
for _, fieldData = range fieldsData {
field := fieldByIndex(val, fieldData)
if field.IsValid() {
m.encodeValue(fieldData.Num, field)
noneEncoded = false
}
}
if noneEncoded {
panic(fmt.Errorf("struct '%s' has no marshallable fields", val.Type().Name()))
}
}
// fieldByIndex returns the field of the struct by its index if the field is exported.
// Otherwise, it returns empty reflect.Value.
func fieldByIndex(structVal reflect.Value, data FieldData) reflect.Value {
if !structVal.IsValid() || !data.Field.IsExported() || len(data.FieldIndex) == 0 {
return reflect.Value{}
}
var result reflect.Value
for i := 0; i < len(data.FieldIndex); i++ {
index := data.FieldIndex[:i+1]
result = structVal.FieldByIndex(index)
if len(data.FieldIndex) > 1 && result.Kind() == reflect.Pointer && result.IsNil() {
// Embedded field is nil, return empty reflect.Value. Avo
return reflect.Value{}
}
}
return result
}
//nolint:cyclop,gocyclo
func (m *marshaller) encodeValue(num protowire.Number, val reflect.Value) {
if m.tryEncodePredefined(num, val) {
return
}
switch val.Kind() { //nolint:exhaustive
case reflect.Bool:
putTag(m, num, protowire.VarintType)
putBool(m, val.Bool())
case reflect.Int8, reflect.Int16:
putTag(m, num, protowire.VarintType)
putUVarint(m, val.Int())
case reflect.Uint8, reflect.Uint16:
putTag(m, num, protowire.VarintType)
putUVarint(m, val.Uint())
case reflect.Int, reflect.Int32, reflect.Int64:
putTag(m, num, protowire.VarintType)
putUVarint(m, val.Int())
case reflect.Uint, reflect.Uint32, reflect.Uint64:
putTag(m, num, protowire.VarintType)
putUVarint(m, val.Uint())
case reflect.Float32:
putTag(m, num, protowire.Fixed32Type)
putInt32(m, math.Float32bits(float32(val.Float())))
case reflect.Float64:
putTag(m, num, protowire.Fixed64Type)
putInt64(m, math.Float64bits(val.Float()))
case reflect.String:
putTag(m, num, protowire.BytesType)
putString(m, val.String())
case reflect.Struct:
var b []byte
if result, ok := tryEncodeFunc(val); ok {
b = result
} else if bmarshaler, ok := asBinaryMarshaler(val); ok {
result, err := bmarshaler.MarshalBinary()
if err != nil {
panic(err)
}
b = result
} else {
inner := marshaller{}
inner.encodeStruct(val)
b = inner.Bytes()
}
putTag(m, num, protowire.BytesType)
putBytes(m, b)
case reflect.Slice, reflect.Array:
if val.Len() == 0 {
return
}
m.encodeSlice(num, val)
return
case reflect.Pointer:
if val.IsNil() {
return
}
// If the pointer is to a struct
if indirect(val.Type()).Kind() == reflect.Struct {
b, ok := tryEncodeFunc(val)
if ok {
putTag(m, num, protowire.BytesType)
putBytes(m, b)
return
}
}
m.encodeValue(num, val.Elem())
case reflect.Map:
m.encodeMap(num, val)
return
default:
panic(fmt.Sprintf("unsupported field Kind %d", val.Kind()))
}
}
func (m *marshaller) tryEncodePredefined(num protowire.Number, val reflect.Value) bool {
switch val.Type() {
case typeMapInterface:
v := val.Interface().(map[string]interface{}) //nolint:errcheck,forcetypeassert
val, err := structpb.NewStruct(v)
if err != nil {
panic(fmt.Errorf("failed to create structpb.Struct: %w", err))
}
encoded, err := proto.Marshal(val)
if err != nil {
panic(err)
}
putTag(m, num, protowire.BytesType)
putBytes(m, encoded)
case typeDuration:
d := val.Interface().(time.Duration) //nolint:errcheck,forcetypeassert
duration := durationpb.New(d)
encoded, err := proto.Marshal(duration)
if err != nil {
panic(err)
}
putTag(m, num, protowire.BytesType)
putBytes(m, encoded)
case typeTime:
t := val.Interface().(time.Time) //nolint:errcheck,forcetypeassert
timestamp := timestamppb.New(t)
encoded, err := proto.Marshal(timestamp)
if err != nil {
panic(err)
}
putTag(m, num, protowire.BytesType)
putBytes(m, encoded)
case typeFixedS32:
putTag(m, num, protowire.Fixed32Type)
putInt32(m, int32(val.Int()))
case typeFixedS64:
putTag(m, num, protowire.Fixed64Type)
putInt64(m, val.Int())
case typeFixedU32:
putTag(m, num, protowire.Fixed32Type)
putInt32(m, uint32(val.Uint()))
case typeFixedU64:
putTag(m, num, protowire.Fixed64Type)
putInt64(m, val.Uint())
default:
return false
}
return true
}
func tryEncodeFunc(val reflect.Value) ([]byte, bool) {
typ := val.Type()
enc, ok := encoders.Get(typ)
if !ok {
return nil, false
}
b, err := enc(val.Interface())
if err != nil {
panic(err)
}
return b, true
}
func asBinaryMarshaler(val reflect.Value) (encoding.BinaryMarshaler, bool) {
if enc, ok := val.Interface().(encoding.BinaryMarshaler); ok {
return enc, true
}
if val.CanAddr() {
if enc, ok := val.Addr().Interface().(encoding.BinaryMarshaler); ok {
return enc, true
}
}
return nil, false
}
func (m *marshaller) encodeSlice(key protowire.Number, val reflect.Value) {
sliceLen := val.Len()
result := marshaller{}
typ := val.Type()
if typ.Elem() == typeByte {
// Special case for byte arrays and slices.
putTag(m, key, protowire.BytesType)
putBytes(m, val.Bytes())
return
}
switch typ {
case typeDurations:
// Special case for []time.Duration.
slice := val.Interface().([]time.Duration) //nolint:errcheck,forcetypeassert
for _, d := range slice {
duration := durationpb.New(d)
encoded, err := proto.Marshal(duration)
if err != nil {
panic(err)
}
putTag(m, key, protowire.BytesType)
putBytes(m, encoded)
}
return
case typeFixedS64s:
slice := val.Interface().([]FixedS64) //nolint:errcheck,forcetypeassert
for i := 0; i < sliceLen; i++ {
putInt64(&result, slice[i])
}
case typeFixedS32s:
slice := val.Interface().([]FixedS32) //nolint:errcheck,forcetypeassert
for i := 0; i < sliceLen; i++ {
putInt32(&result, slice[i])
}
case typeFixedU64s:
slice := val.Interface().([]FixedU64) //nolint:errcheck,forcetypeassert
for i := 0; i < sliceLen; i++ {
putInt64(&result, slice[i])
}
case typeFixedU32s:
slice := val.Interface().([]FixedU32) //nolint:errcheck,forcetypeassert
for i := 0; i < sliceLen; i++ {
putInt32(&result, slice[i])
}
default:
// None of predefined types worked, so we need to do it manually.
m.sliceReflect(key, val)
return
}
putTag(m, key, protowire.BytesType)
putBytes(m, result.Bytes())
}
func (m *marshaller) sliceReflect(key protowire.Number, val reflect.Value) {
sliceLen := val.Len()
elem := val.Type().Elem()
result := marshaller{}
switch elem.Kind() { //nolint:exhaustive
case reflect.Int8, reflect.Int16:
for i := 0; i < sliceLen; i++ {
putUVarint(&result, val.Index(i).Int())
}
case reflect.Uint8, reflect.Uint16:
for i := 0; i < sliceLen; i++ {
putUVarint(&result, val.Index(i).Uint())
}
case reflect.Bool:
for i := 0; i < sliceLen; i++ {
putBool(&result, val.Index(i).Bool())
}
case reflect.Int, reflect.Int32, reflect.Int64:
for i := 0; i < sliceLen; i++ {
putUVarint(&result, val.Index(i).Int())
}
case reflect.Uint, reflect.Uint32, reflect.Uint64:
for i := 0; i < sliceLen; i++ {
putUVarint(&result, val.Index(i).Uint())
}
case reflect.Float32:
for i := 0; i < sliceLen; i++ {
putInt32(&result, math.Float32bits(float32(val.Index(i).Float())))
}
case reflect.Float64:
for i := 0; i < sliceLen; i++ {
putInt64(&result, math.Float64bits(val.Index(i).Float()))
}
case reflect.Pointer:
for i := 0; i < sliceLen; i++ {
m.encodeValue(key, val.Index(i))
}
return
case reflect.Map:
panic(fmt.Errorf("unsupported type %s", val.Type().String()))
default: // Write each element as a separate key,value pair
for i := 0; i < sliceLen; i++ {
m.encodeValue(key, val.Index(i))
}
return
}
putTag(m, key, protowire.BytesType)
putBytes(m, result.buf)
}
func (m *marshaller) encodeMap(key protowire.Number, mpval reflect.Value) {
for _, mkey := range mpval.MapKeys() {
mval := mpval.MapIndex(mkey)
if kind := mval.Kind(); kind == reflect.Pointer && mval.IsNil() {
panic("error: map has nil element")
}
inner := marshaller{}
inner.encodeValue(1, mkey)
inner.encodeValue(2, mval)
putTag(m, key, protowire.BytesType)
putBytes(m, inner.buf)
}
}
func putTag(m *marshaller, num protowire.Number, typ protowire.Type) {
m.buf = protowire.AppendTag(m.buf, num, typ)
}
func putInt32[T ~int32 | ~uint32](m *marshaller, val T) {
m.buf = protowire.AppendFixed32(m.buf, uint32(val))
}
func putInt64[T ~int64 | ~uint64](m *marshaller, val T) {
m.buf = protowire.AppendFixed64(m.buf, uint64(val))
}
func putUVarint[T ~int64 | ~uint64](m *marshaller, val T) {
m.buf = protowire.AppendVarint(m.buf, uint64(val))
}
func putBool(m *marshaller, b bool) {
putUVarint(m, protowire.EncodeBool(b))
}
func putString(m *marshaller, s string) {
m.buf = protowire.AppendString(m.buf, s)
}
func putBytes(m *marshaller, b []byte) {
m.buf = protowire.AppendBytes(m.buf, b)
}