forked from golang/protobuf
-
Notifications
You must be signed in to change notification settings - Fork 1
/
properties.go
1655 lines (1508 loc) · 57.9 KB
/
properties.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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2016 Mist Systems. All rights reserved.
//
// This code is derived from earlier code which was itself:
//
// Copyright 2010 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package protobuf3
/*
* Routines for encoding data into the wire format for protocol buffers.
*/
import (
"fmt"
"os"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
"unsafe"
)
// compile with true to get some debug msgs when working on this file
const debug bool = false
// XXXHack enables a backwards compatibility hack to match the canonical golang.go/protobuf error behavior for fields whose names start with XXX_
// This isn't needed unless you are dealing with old protobuf v2 generated types like some unit tests do
var XXXHack = false
// MakeFieldName is a pointer to a function which returns what should be the name of field f in the protobuf definition of type t.
// You can replace this with your own function before calling AsProtobuf[Full]() to control the field names yourself.
var MakeFieldName func(f string, t reflect.Type) string = MakeLowercaseFieldName
// MakeTypeName is a pointer to a function which returns what should be the name of the protobuf message of type t, which is the type
// of a field named f.
var MakeTypeName func(t reflect.Type, f string) string = MakeUppercaseTypeName
// MakePackageName is a pointer to a function which returns what should be the name of the protobuf package given the go package path.
// By default it simply returns the last component of the pkgpath.
var MakePackageName func(pkgpath string) string = MakeSamePackageName
// AsProtobuf3er is the interface which returns the protobuf v3 type equivalent to what the MarshalProtobuf3() method
// encodes. This is optional, but useful when using AsProtobufFull() against types implementing Marshaler.
// `definition` can be "" if the datatype doesn't need a custom definition.
// `imports` is the list of files to import when using this type. The order of imports in the slice is not important, and is not respected.
type AsProtobuf3er interface {
AsProtobuf3() (name string, definition string, imports []string)
}
// legacy AsProtobuf3() which didn't support imports
type AsV1Protobuf3er interface {
AsProtobuf3() (name string, definition string)
}
// maxLen is the maximum length possible for a byte array. On a 64-bit target this is (1<<50)-1. On a 32-bit target it is (1<<31)-1
// The tricky part is figuring out in a constant what flavor of target we are on. I could sure use a ?: here. It would be more
// clear than using &^uint(0) to truncate (or not) the upper 32 bits of a constant.
const maxLen = int((1 << (31 + (((50-31)<<32)&uint64(^uint(0)))>>32)) - 1) // experiments with go1.7 on amd64 show any larger size causes the compiler to error
// Constants that identify the encoding of a value on the wire.
const (
WireVarint = WireType(0)
WireFixed64 = WireType(1)
WireBytes = WireType(2)
WireStartGroup = WireType(3) // legacy from protobuf v2. Groups are not used in protobuf v3
WireEndGroup = WireType(4) // legacy...
WireFixed32 = WireType(5)
)
type WireType byte
// mapping from WireType to string
var wireTypeNames = []string{WireVarint: "varint", WireFixed64: "fixed64", WireBytes: "bytes", WireStartGroup: "start-group", WireEndGroup: "end-group", WireFixed32: "fixed32"}
func (wt WireType) String() string {
if int(wt) < len(wireTypeNames) {
return wireTypeNames[wt]
}
return fmt.Sprintf("WireType(%d)", byte(wt))
}
// Encoders are defined in encode.go
// An encoder outputs the full representation of a field, including its
// tag and encoder type.
type encoder func(p *Buffer, prop *Properties, base unsafe.Pointer)
// A valueEncoder encodes a single integer in a particular encoding.
type valueEncoder func(o *Buffer, x uint64)
// Decoders are defined in decode.go
// A decoder creates a value from its wire representation.
// Unrecognized subelements are saved in unrec.
type decoder func(p *Buffer, prop *Properties, base unsafe.Pointer) error
// A valueDecoder decodes a single integer in a particular encoding.
type valueDecoder func(o *Buffer) (x uint64, err error)
// StructProperties represents properties for all the fields of a struct.
type StructProperties struct {
props []Properties // properties for each field encoded in protobuf, ordered by tag id
reserved []uint32 // all the reserved tags
}
// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec.
// See encode.go, (*Buffer).enc_struct.
func (sp *StructProperties) Len() int { return len(sp.props) }
func (sp *StructProperties) Less(i, j int) bool {
return sp.props[i].Tag < sp.props[j].Tag
}
func (sp *StructProperties) Swap(i, j int) { sp.props[i], sp.props[j] = sp.props[j], sp.props[i] }
// returns the properties into protobuf v3 format, suitable for feeding back into the protobuf compiler.
func (sp *StructProperties) asProtobuf(t reflect.Type, tname string) string {
lines := []string{fmt.Sprintf("message %s {", tname)}
for i := range sp.props {
pp := &sp.props[i]
if pp.Wire != "-" {
lines = append(lines, fmt.Sprintf(" %s%s %s = %d;", pp.optional(), pp.asProtobuf, pp.protobufFieldName(t), pp.Tag))
}
}
if len(sp.reserved) != 0 {
var b strings.Builder
b.WriteString(" reserved ")
sep := ""
for _, r := range sp.reserved {
fmt.Fprintf(&b, "%s%d", sep, r)
sep = ", "
}
b.WriteByte(';')
lines = append(lines, b.String())
}
lines = append(lines, "}")
return strings.Join(lines, "\n")
}
// Reserved is a special type used to indicate reserved protobuf IDs. Instead of the usual protobuf tag, the tag
// consists of a comma separated list of reserved protobuf IDs. Using these IDs elsewhere causes an error, and
// they are listed in the `reserved` section by asProtobuf.
// At the moment we only support reserveing IDs. If you need to reserve field names then you'll have to implement it.
type Reserved [0]byte
var reservedType = reflect.TypeOf((*Reserved)(nil)).Elem()
// parse the protobuf tag of a Reserved field
func (sp *StructProperties) parseReserved(tag string) error {
for _, s := range strings.Split(tag, ",") {
tag, err := strconv.Atoi(s)
if err != nil {
return fmt.Errorf("protobuf3: invalid reserved tag id %q: %v", s, err)
}
if tag <= 0 { // catch any negative or 0 values
return fmt.Errorf("protobuf3: reserved tag id %q out of range", s)
}
sp.reserved = append(sp.reserved, uint32(tag))
}
return nil
}
// return the name of this field in protobuf
func (p *Properties) protobufFieldName(struct_type reflect.Type) string {
// the "name=" tag overrides any computed field name. That lets us automate any manual fixup of names we might need.
for _, t := range strings.Split(p.Wire, ",") {
if strings.HasPrefix(t, "name=") {
return t[5:]
}
}
return MakeFieldName(p.Name, struct_type)
}
// return the protobuf "optional" field value (with a whitespace suffix for convenience)
func (p *Properties) optional() string {
// NOTE: we allow "optional" to be applied to all field types, even those for which, in the Go struct definition, there is no good way to tell the difference
// between the default value and absence of the value. (an int32 for example, or pretty much nothing but pointers and maps (which are pointers underneath))
// What isOptional does is apply
if p.isOptional {
return "optional "
}
return ""
}
// MakeLowercaseFieldName returns a reasonable lowercase field name
func MakeLowercaseFieldName(f string, t reflect.Type) string {
// To make people who use other languages happy it would be nice if our field names were like most and were lowercase.
// (In addition, since we use the name of fields with anonymous types as the name of the anonmymous types, we need to
// alter those fields (or the type's name) so there isn't a collision.)
// Converting "XxxYYzz" to "xxx_yyy_zz" seems to be reasonable for most fields names.
// If the name already has any '_' it then I just lowercase it without inserting any more.
if strings.ContainsRune(f, '_') {
return strings.ToLower(f)
}
buf := make([]byte, 2*len(f)+4) // 2x is enough for every 2nd rune to be a '_'. +4 is enough room for anything EncodeRune() might emit
j := 0
prev_was_upper := true // initial condition happens to prevent the 1st rune (which is almost certainly uppercase) from getting prefixed with _
for _, r := range f {
if unicode.IsUpper(r) {
// lowercase r, and prepend a '_' if this is a good place to break up the name
if !prev_was_upper {
buf[j] = '_'
j++
}
r = unicode.ToLower(r)
prev_was_upper = true
} else if unicode.IsLower(r) {
prev_was_upper = false
} // else leave prev_was_upper alone. This rule handles some edge condition names better ("L2TP" for instance, which otherwise would be named "l2_tp")
j += utf8.EncodeRune(buf[j:], r)
}
return string(buf[:j])
// PS I tried doing things like lowercasing and inserting a '_' before each group of uppercase chars.
// It didn't do well with field names our software was using. Yet
}
// returns the type expressed in protobuf v3 format, suitable for feeding back into the protobuf compiler.
func AsProtobuf(t reflect.Type) (string, error) {
// dig down through any pointer types
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
prop, err := GetProperties(t)
if err != nil {
return "# Error: " + err.Error(), err // cause an error in the protobuf compiler if the input is used
}
return prop.asProtobuf(t, t.Name()), nil
}
// given the full path of the package of the 1st type passed to AsProtobufFull(), return
// the last component of the package path to be used as the package name.
func MakeSamePackageName(pkgpath string) string {
slash := strings.LastIndexByte(pkgpath, '/')
pkg := pkgpath
if slash >= 0 {
pkg = pkgpath[slash+1:]
}
return pkg
}
// returns the type expressed in protobuf v3 format, including all dependent types and imports
func AsProtobufFull(t reflect.Type, more ...reflect.Type) (string, error) {
return AsProtobufFull2(t, nil, more...)
}
// returns the type expressed in protobuf v3 format, including all dependent types and imports
// extra_headers allow the caller to specify headers they want inserted after the `package` line.
func AsProtobufFull2(t reflect.Type, extra_package_headers []string, more ...reflect.Type) (string, error) {
// dig down through any pointer types on the first type, since we'll use that one to determine the package
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
todo := make(map[reflect.Type]struct{})
discovered := make(map[reflect.Type]struct{})
pkgpath := t.PkgPath()
headers := []string{
fmt.Sprintf("// protobuf definitions generated by protobuf3.AsProtobufFull(%s.%s)", pkgpath, t.Name()),
"",
`syntax = "proto3";`,
"",
}
imported := make(map[string]struct{}) // the set of all imported files
var body []string
if pkgpath != "" {
headers = append(headers, fmt.Sprintf("package %s;", MakePackageName(pkgpath)))
} // else the type is synthesized and lacks a path; humans need to deal with the output (after all they caused this)
headers = append(headers, extra_package_headers...)
// place all the arguments in the todo table to start things off
todo[t] = struct{}{}
for _, t := range more {
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
todo[t] = struct{}{}
}
// and lather/rinse/repeat until we've discovered all the types
var first_err error
for len(todo) != 0 {
for t := range todo {
// move t from todo to discovered
delete(todo, t)
discovered[t] = struct{}{}
// add to todo any new, non-anonymous types used by struct t's fields
p, err := GetProperties(t)
if err != nil {
if first_err == nil {
first_err = err
}
body = append(body, "# Error: "+err.Error()) // cause an error in the protobuf compiler
continue
}
for i := range p.props {
pp := &p.props[i]
tt := pp.Subtype()
if tt != nil {
if _, ok := discovered[tt]; !ok {
// it's a new type of field
switch {
case pp.isMarshaler:
// we can't recurse further into a custom type
discovered[tt] = struct{}{}
case isAsProtobuf3er(reflect.PtrTo(tt)) || isAsV1Protobuf3er(reflect.PtrTo(tt)):
// this type has a custom protobuf definition. it presumably encodes its own types
discovered[tt] = struct{}{}
case tt.Kind() == reflect.Struct:
switch tt {
case time_Time_type:
// the timestamp type get defined by an import of timestamp.proto
discovered[tt] = struct{}{}
default:
// put this new type in the todo table if it isn't already there
// (the duplicate insert when it is already present is a no-op)
todo[tt] = struct{}{}
}
case tt == time_Duration_type:
// the duration type get defined by an import of duration.proto
discovered[tt] = struct{}{}
}
}
}
}
// and we must break since todo has possibly been altered
break
}
}
// now that the types we need have all been discovered, sort their names and generate the .proto source
// the reason we do this in 2 passes is so that the output is consistent from run to run, and diff'able
// across runs with incremental differences.
ordered := make(Types, 0, len(discovered))
for t := range discovered {
if t.Name() != "" { // skip anonymous types
ordered = append(ordered, t)
}
}
sort.Sort(ordered)
for _, t := range ordered {
// generate type t's protobuf definition
ptr_t := reflect.PtrTo(t)
var definition string
var imports []string
var external bool
switch {
case t == time_Time_type:
// the timestamp type gets defined by an import
imports = []string{"google/protobuf/timestamp.proto"}
external = true
case t == time_Duration_type:
// the duration type gets defined by an import
imports = []string{"google/protobuf/duration.proto"}
external = true
case isMarshaler(ptr_t):
// we can't define a custom type automatically. see if it can tell us, and otherwise remind the human to do it.
switch {
case isAsProtobuf3er(ptr_t):
_, definition, imports = reflect.NewAt(t, nil).Interface().(AsProtobuf3er).AsProtobuf3()
case isAsV1Protobuf3er(ptr_t):
_, definition = reflect.NewAt(t, nil).Interface().(AsV1Protobuf3er).AsProtobuf3()
default:
headers = append(headers, fmt.Sprintf("// TODO supply the definition of message %s", t.Name()))
}
if definition == "" {
// the type doesn't need any additional definition (its name was sufficient)
external = true
}
case isAsProtobuf3er(ptr_t):
_, definition, imports = reflect.NewAt(t, nil).Interface().(AsProtobuf3er).AsProtobuf3()
case isAsV1Protobuf3er(ptr_t):
_, definition = reflect.NewAt(t, nil).Interface().(AsV1Protobuf3er).AsProtobuf3()
}
for _, imp := range imports {
imported[imp] = struct{}{}
}
if !external {
if definition == "" {
var err error
definition, err = AsProtobuf(t)
if err != nil {
if first_err == nil {
first_err = err
}
// and definition already contains the error
}
}
if definition != "" {
body = append(body, "") // put a blank line between each message definition
body = append(body, definition)
}
} // else the type doesn't need any additional definition (its name and imports are sufficient)
}
// generate the import header lines. to make the output reproducible, sort them
// (if someone the order of import headers becomes important we'll have to do something fancier, but for now they are well written and independant)
if len(imported) != 0 {
import_headers := make([]string, 0, len(imported))
for imp := range imported {
import_headers = append(import_headers, fmt.Sprintf("import %q;", imp))
}
sort.Strings(import_headers)
headers = append(headers, "")
headers = append(headers, import_headers...)
}
return strings.Join(append(headers, body...), "\n"), first_err
}
type Types []reflect.Type
func (ts Types) Len() int { return len(ts) }
func (ts Types) Swap(i, j int) { ts[i], ts[j] = ts[j], ts[i] }
func (ts Types) Less(i, j int) bool { return ts[i].Name() < ts[j].Name() } // sort types by their names
// Properties represents the protocol-specific behavior of a single struct field.
type Properties struct {
Name string // name of the field, for error messages
Wire string
asProtobuf string // protobuf v3 type for this field (or something equivalent, since we can't figure it out perfectly from the Go field type and tags)
Tag uint32
WireType WireType
enc encoder
valEnc valueEncoder // set for bool and numeric types only
offset uintptr // byte offset of this field within the struct
tagcode string // encoding of EncodeVarint((Tag<<3)|WireType), stored in a string for efficiency
stype reflect.Type // set for struct types and time.Duration only
sprop *StructProperties // set for struct types only
isMarshaler bool // true if the type implements Marshaler and marshals/unmarshals itself
isOptional bool // true if the "optional" attribute was specified in the protobuf: tag. This code (for the obvious reason that it doesn't generate the structs we unmarshal into) largely ignores "optional", but it is copied into the generated .proto, and protoc or some other protobuf code generator will obey it
mtype reflect.Type // set for map types only
mkeyprop *Properties // set for map types only
mvalprop *Properties // set for map types only
length uint // set for array types only
dec decoder
valDec valueDecoder // set for bool and numeric types only
}
// String formats the properties in the protobuf struct field tag style.
func (p *Properties) String() string {
if p.stype != nil {
return fmt.Sprintf("%s %s (%s)", p.Wire, p.Name, p.stype.Name())
}
if p.mtype != nil {
return fmt.Sprintf("%s %s (%s)", p.Wire, p.Name, p.mtype.Name())
}
return fmt.Sprintf("%s %s", p.Wire, p.Name)
}
// returns the inner type, or nil
func (p *Properties) Subtype() reflect.Type {
return p.stype
}
// IntEncoder enumerates the different ways of encoding integers in Protobuf v3
type IntEncoder int
const (
UnknownEncoder IntEncoder = iota // make the zero-value be different from any valid value so I can tell it is not set
VarintEncoder
Fixed32Encoder
Fixed64Encoder
Zigzag32Encoder
Zigzag64Encoder
)
// Parse populates p by parsing a string in the protobuf struct field tag style.
func (p *Properties) Parse(s string) (IntEncoder, bool, error) {
p.Wire = s
// "bytes,49,rep,..."
fields := strings.Split(s, ",")
if len(fields) < 2 {
if len(fields) > 0 && fields[0] == "-" {
// `protobuf="-"` is used to mark fields which should be skipped by the protobuf encoder (this is same mark as is used by the std encoding/json package)
return 0, true, nil
}
return 0, true, fmt.Errorf("protobuf3: tag of %q has too few fields: %q", p.Name, s)
}
var enc IntEncoder
switch fields[0] {
case "varint":
p.valEnc = (*Buffer).EncodeVarint
p.valDec = (*Buffer).DecodeVarint
p.WireType = WireVarint
enc = VarintEncoder
case "fixed32":
p.valEnc = (*Buffer).EncodeFixed32
p.valDec = (*Buffer).DecodeFixed32
p.WireType = WireFixed32
enc = Fixed32Encoder
case "fixed64":
p.valEnc = (*Buffer).EncodeFixed64
p.valDec = (*Buffer).DecodeFixed64
p.WireType = WireFixed64
enc = Fixed64Encoder
case "zigzag32":
p.valEnc = (*Buffer).EncodeZigzag32
p.valDec = (*Buffer).DecodeZigzag32
p.WireType = WireVarint
enc = Zigzag32Encoder
case "zigzag64":
p.valEnc = (*Buffer).EncodeZigzag64
p.valDec = (*Buffer).DecodeZigzag64
p.WireType = WireVarint
enc = Zigzag64Encoder
case "bytes":
// no numeric converter for non-numeric types
p.WireType = WireBytes
default:
return 0, false, fmt.Errorf("protobuf3: tag of %q has unknown wire type: %q", p.Name, s)
}
tag, err := strconv.Atoi(fields[1])
if err != nil {
return 0, false, fmt.Errorf("protobuf3: tag id of %q invalid: %s: %s", p.Name, s, err.Error())
}
if tag <= 0 { // catch any negative or 0 values
return 0, false, fmt.Errorf("protobuf3: tag id of %q out of range: %s", p.Name, s)
}
p.Tag = uint32(tag)
for _, field := range fields[2:] {
switch field {
case "optional":
p.isOptional = true
// and we don't care about any other fields
// (if you don't mark slices/arrays/maps with ",rep" that's your own problem; this encoder always repeats those types)
}
}
return enc, false, nil
}
// Initialize the fields for encoding and decoding.
func (p *Properties) setEncAndDec(t1 reflect.Type, f *reflect.StructField, name string, int_encoder IntEncoder) error {
var err error
p.enc = nil
p.dec = nil
wire := p.WireType
// since so many cases need it, decode int_encoder into a string now
var int32_encoder_txt, uint32_encoder_txt,
int64_encoder_txt, uint64_encoder_txt string
switch int_encoder {
case VarintEncoder:
uint32_encoder_txt = "uint32"
int32_encoder_txt = uint32_encoder_txt[1:] // strip the 'u' off
uint64_encoder_txt = "uint64"
int64_encoder_txt = uint64_encoder_txt[1:] // strip the 'u' off
case Fixed32Encoder:
int32_encoder_txt = "sfixed32"
uint32_encoder_txt = int32_encoder_txt[1:] // strip the 's' off
case Fixed64Encoder:
int64_encoder_txt = "sfixed64"
uint64_encoder_txt = int64_encoder_txt[1:] // strip the 's' off
case Zigzag32Encoder:
int32_encoder_txt = "sint32"
case Zigzag64Encoder:
int64_encoder_txt = "sint64"
}
// can t1 marshal itself?
ptr_t1 := reflect.PtrTo(t1)
if isMarshaler(ptr_t1) {
p.isMarshaler = true
p.stype = t1
p.enc = (*Buffer).enc_marshaler
p.dec = (*Buffer).dec_marshaler
p.asProtobuf = p.stypeAsProtobuf()
} else {
switch t1.Kind() {
default:
return fmt.Errorf("protobuf3: no encoder/decoder for type %s", t1.Name())
// proto3 scalar types
case reflect.Bool:
p.enc = (*Buffer).enc_bool
p.dec = (*Buffer).dec_bool
p.asProtobuf = "bool"
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Int:
p.enc = (*Buffer).enc_int
p.dec = (*Buffer).dec_int
p.asProtobuf = int32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Uint:
p.enc = (*Buffer).enc_uint
p.dec = (*Buffer).dec_int // signness doesn't matter when decoding. either the top bit is set or it isn't
p.asProtobuf = uint32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Int8:
p.enc = (*Buffer).enc_int8
p.dec = (*Buffer).dec_int8
p.asProtobuf = int32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Uint8:
p.enc = (*Buffer).enc_uint8
p.dec = (*Buffer).dec_int8
p.asProtobuf = uint32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Int16:
p.enc = (*Buffer).enc_int16
p.dec = (*Buffer).dec_int16
p.asProtobuf = int32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Uint16:
p.enc = (*Buffer).enc_uint16
p.dec = (*Buffer).dec_int16
p.asProtobuf = uint32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Int32:
p.enc = (*Buffer).enc_int32
p.dec = (*Buffer).dec_int32
p.asProtobuf = int32_encoder_txt
if p.valEnc == nil { // note it is safe, though peculiar, for an int32 to have a wiretype of fixed64
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Uint32:
p.enc = (*Buffer).enc_uint32
p.dec = (*Buffer).dec_int32
p.asProtobuf = uint32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Int64:
// this might be a time.Duration, or it might be an ordinary int64
// if the caller wants a time.Duration to be encoded as a protobuf Duration then the
// wiretype must be WireBytes. Otherwise they'll get the int64 encoding they've selected.
if p.WireType == WireBytes && t1 == time_Duration_type {
p.stype = time_Duration_type
p.enc = (*Buffer).enc_time_Duration
p.dec = (*Buffer).dec_time_Duration
p.asProtobuf = "google.protobuf.Duration"
} else {
p.enc = (*Buffer).enc_int64
p.dec = (*Buffer).dec_int64
p.asProtobuf = int64_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
}
case reflect.Uint64:
p.enc = (*Buffer).enc_int64
p.dec = (*Buffer).dec_int64
p.asProtobuf = uint64_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Float32:
p.enc = (*Buffer).enc_uint32 // can just treat them as bits
p.dec = (*Buffer).dec_int32
p.asProtobuf = "float"
if p.valEnc == nil || wire != WireFixed32 { // the way we encode and decode float32 at the moment means we can only support fixed32
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Float64:
p.enc = (*Buffer).enc_int64 // can just treat them as bits
p.dec = (*Buffer).dec_int64
p.asProtobuf = "double"
if p.valEnc == nil || wire != WireFixed64 { // the way we encode and decode float32 at the moment means we can only support fixed64
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.String:
p.enc = (*Buffer).enc_string
p.dec = (*Buffer).dec_string
p.asProtobuf = "string"
if wire != WireBytes {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Struct:
p.stype = t1
p.sprop, err = getPropertiesLocked(t1)
if err != nil {
return err
}
p.asProtobuf = p.stypeAsProtobuf()
switch t1 {
case time_Time_type:
p.enc = (*Buffer).enc_struct_message // time.Time encodes as a struct with 1 (made up) field
p.dec = (*Buffer).dec_time_Time // but it decodes with a custom function
default:
p.enc = (*Buffer).enc_struct_message
p.dec = (*Buffer).dec_struct_message
}
if wire != WireBytes {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Ptr:
t2 := t1.Elem()
// can the target of the pointer marshal itself?
if isMarshaler(t1) {
p.stype = t2
p.isMarshaler = true
p.enc = (*Buffer).enc_ptr_marshaler
p.dec = (*Buffer).dec_ptr_marshaler
p.asProtobuf = p.stypeAsProtobuf()
break
}
if isAsProtobuf3er(t1) || isAsV1Protobuf3er(t1) {
p.stype = t2
}
switch t2.Kind() {
default:
return fmt.Errorf("protobuf3: no encoder function for %s -> %s", t1, t2.Name())
case reflect.Bool:
p.enc = (*Buffer).enc_ptr_bool
p.dec = (*Buffer).dec_ptr_bool
p.asProtobuf = "bool"
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Int:
p.enc = (*Buffer).enc_ptr_int
p.dec = (*Buffer).dec_ptr_int
p.asProtobuf = int32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Uint:
p.enc = (*Buffer).enc_ptr_uint
p.dec = (*Buffer).dec_ptr_int // signness doesn't matter when decoding. either the top bit is set or it isn't
p.asProtobuf = uint32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Int8:
p.enc = (*Buffer).enc_ptr_int8
p.dec = (*Buffer).dec_ptr_int8
p.asProtobuf = int32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Uint8:
p.enc = (*Buffer).enc_ptr_uint8
p.dec = (*Buffer).dec_ptr_int8
p.asProtobuf = uint32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Int16:
p.enc = (*Buffer).enc_ptr_int16
p.dec = (*Buffer).dec_ptr_int16
p.asProtobuf = int32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Uint16:
p.enc = (*Buffer).enc_ptr_uint16
p.dec = (*Buffer).dec_ptr_int16
p.asProtobuf = uint32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Int32:
p.enc = (*Buffer).enc_ptr_int32
p.dec = (*Buffer).dec_ptr_int32
p.asProtobuf = int32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Uint32:
p.enc = (*Buffer).enc_ptr_uint32
p.dec = (*Buffer).dec_ptr_int32
p.asProtobuf = uint32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Int64:
if p.WireType == WireBytes && t2 == time_Duration_type {
p.stype = time_Duration_type
p.enc = (*Buffer).enc_ptr_time_Duration
p.dec = (*Buffer).dec_ptr_time_Duration
p.asProtobuf = "google.protobuf.Duration"
} else {
p.enc = (*Buffer).enc_ptr_int64
p.dec = (*Buffer).dec_ptr_int64
p.asProtobuf = int64_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
}
case reflect.Uint64:
p.enc = (*Buffer).enc_ptr_int64
p.dec = (*Buffer).dec_ptr_int64
p.asProtobuf = uint64_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Float32:
p.enc = (*Buffer).enc_ptr_uint32 // can just treat them as bits
p.dec = (*Buffer).dec_ptr_int32
p.asProtobuf = "float"
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Float64:
p.enc = (*Buffer).enc_ptr_int64 // can just treat them as bits
p.dec = (*Buffer).dec_ptr_int64
p.asProtobuf = "double"
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.String:
p.enc = (*Buffer).enc_ptr_string
p.dec = (*Buffer).dec_ptr_string
p.asProtobuf = "string"
if wire != WireBytes {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Struct:
p.stype = t2
p.sprop, err = getPropertiesLocked(t2)
if err != nil {
return err
}
p.asProtobuf = p.stypeAsProtobuf()
p.enc = (*Buffer).enc_ptr_struct_message
switch {
case t2 == time_Time_type:
p.dec = (*Buffer).dec_ptr_time_Time
default:
p.dec = (*Buffer).dec_ptr_struct_message
}
if wire != WireBytes {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
// what about *Slice and *Array types? Fill them in when we need them.
}
case reflect.Slice:
// can elements of the slice marshal themselves?
t2 := t1.Elem()
if isMarshaler(reflect.PtrTo(t2)) {
p.isMarshaler = true
p.stype = t2
p.enc = (*Buffer).enc_slice_marshaler
p.dec = (*Buffer).dec_slice_marshaler
p.asProtobuf = "repeated " + p.stypeAsProtobuf()
break
}
switch t2.Kind() {
default:
return fmt.Errorf("protobuf3: no slice encoder for %s = []%s", t1.Name(), t2.Name())
case reflect.Bool:
p.enc = (*Buffer).enc_slice_packed_bool
p.dec = (*Buffer).dec_slice_packed_bool
wire = WireBytes // packed=true is implied in protobuf v3
p.asProtobuf = "repeated bool"
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Int:
p.enc = (*Buffer).enc_slice_packed_int
p.dec = (*Buffer).dec_slice_packed_int
wire = WireBytes // packed=true...
p.asProtobuf = "repeated " + int32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Uint:
p.enc = (*Buffer).enc_slice_packed_uint
p.dec = (*Buffer).dec_slice_packed_int
wire = WireBytes // packed=true...
p.asProtobuf = "repeated " + uint32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Int8:
p.enc = (*Buffer).enc_slice_packed_int8
p.dec = (*Buffer).dec_slice_packed_int8
wire = WireBytes // packed=true...
p.asProtobuf = "repeated " + int32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Uint8:
p.enc = (*Buffer).enc_slice_byte
p.dec = (*Buffer).dec_slice_byte
wire = WireBytes // packed=true... even for integers
p.asProtobuf = "bytes"
case reflect.Int16:
p.enc = (*Buffer).enc_slice_packed_int16
p.dec = (*Buffer).dec_slice_packed_int16
wire = WireBytes // packed=true...
p.asProtobuf = "repeated " + int32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Uint16:
p.enc = (*Buffer).enc_slice_packed_uint16
p.dec = (*Buffer).dec_slice_packed_int16
wire = WireBytes // packed=true...
p.asProtobuf = "repeated " + uint32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Int32:
p.enc = (*Buffer).enc_slice_packed_int32
p.dec = (*Buffer).dec_slice_packed_int32
wire = WireBytes // packed=true...
p.asProtobuf = "repeated " + int32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Uint32:
p.enc = (*Buffer).enc_slice_packed_uint32
p.dec = (*Buffer).dec_slice_packed_int32
wire = WireBytes // packed=true...
p.asProtobuf = "repeated " + uint32_encoder_txt
if p.valEnc == nil {
return fmt.Errorf("protobuf3: %q %s cannot have wiretype %s", name, t1, wire)
}
case reflect.Int64:
if p.WireType == WireBytes && t2 == time_Duration_type {
p.stype = time_Duration_type
p.enc = (*Buffer).enc_slice_time_Duration
p.dec = (*Buffer).dec_slice_time_Duration
p.asProtobuf = "repeated google.protobuf.Duration"
} else {
p.enc = (*Buffer).enc_slice_packed_int64
p.dec = (*Buffer).dec_slice_packed_int64
wire = WireBytes // packed=true...
p.asProtobuf = "repeated " + int64_encoder_txt