blob: b2271d0b7b86e0f63968bdced8a1c87283301799 [file] [log] [blame]
khenaidooac637102019-01-14 15:44:34 -05001// Go support for Protocol Buffers - Google's data interchange format
2//
3// Copyright 2010 The Go Authors. All rights reserved.
4// https://github.com/golang/protobuf
5//
6// Redistribution and use in source and binary forms, with or without
7// modification, are permitted provided that the following conditions are
8// met:
9//
10// * Redistributions of source code must retain the above copyright
11// notice, this list of conditions and the following disclaimer.
12// * Redistributions in binary form must reproduce the above
13// copyright notice, this list of conditions and the following disclaimer
14// in the documentation and/or other materials provided with the
15// distribution.
16// * Neither the name of Google Inc. nor the names of its
17// contributors may be used to endorse or promote products derived from
18// this software without specific prior written permission.
19//
20// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32/*
33Package proto converts data structures to and from the wire format of
34protocol buffers. It works in concert with the Go source code generated
35for .proto files by the protocol compiler.
36
37A summary of the properties of the protocol buffer interface
38for a protocol buffer variable v:
39
40 - Names are turned from camel_case to CamelCase for export.
41 - There are no methods on v to set fields; just treat
42 them as structure fields.
43 - There are getters that return a field's value if set,
44 and return the field's default value if unset.
45 The getters work even if the receiver is a nil message.
46 - The zero value for a struct is its correct initialization state.
47 All desired fields must be set before marshaling.
48 - A Reset() method will restore a protobuf struct to its zero state.
49 - Non-repeated fields are pointers to the values; nil means unset.
50 That is, optional or required field int32 f becomes F *int32.
51 - Repeated fields are slices.
52 - Helper functions are available to aid the setting of fields.
53 msg.Foo = proto.String("hello") // set field
54 - Constants are defined to hold the default values of all fields that
55 have them. They have the form Default_StructName_FieldName.
56 Because the getter methods handle defaulted values,
57 direct use of these constants should be rare.
58 - Enums are given type names and maps from names to values.
59 Enum values are prefixed by the enclosing message's name, or by the
60 enum's type name if it is a top-level enum. Enum types have a String
61 method, and a Enum method to assist in message construction.
62 - Nested messages, groups and enums have type names prefixed with the name of
63 the surrounding message type.
64 - Extensions are given descriptor names that start with E_,
65 followed by an underscore-delimited list of the nested messages
66 that contain it (if any) followed by the CamelCased name of the
67 extension field itself. HasExtension, ClearExtension, GetExtension
68 and SetExtension are functions for manipulating extensions.
69 - Oneof field sets are given a single field in their message,
70 with distinguished wrapper types for each possible field value.
71 - Marshal and Unmarshal are functions to encode and decode the wire format.
72
73When the .proto file specifies `syntax="proto3"`, there are some differences:
74
75 - Non-repeated fields of non-message type are values instead of pointers.
76 - Enum types do not get an Enum method.
77
78The simplest way to describe this is to see an example.
79Given file test.proto, containing
80
81 package example;
82
83 enum FOO { X = 17; }
84
85 message Test {
86 required string label = 1;
87 optional int32 type = 2 [default=77];
88 repeated int64 reps = 3;
89 optional group OptionalGroup = 4 {
90 required string RequiredField = 5;
91 }
92 oneof union {
93 int32 number = 6;
94 string name = 7;
95 }
96 }
97
98The resulting file, test.pb.go, is:
99
100 package example
101
102 import proto "github.com/gogo/protobuf/proto"
103 import math "math"
104
105 type FOO int32
106 const (
107 FOO_X FOO = 17
108 )
109 var FOO_name = map[int32]string{
110 17: "X",
111 }
112 var FOO_value = map[string]int32{
113 "X": 17,
114 }
115
116 func (x FOO) Enum() *FOO {
117 p := new(FOO)
118 *p = x
119 return p
120 }
121 func (x FOO) String() string {
122 return proto.EnumName(FOO_name, int32(x))
123 }
124 func (x *FOO) UnmarshalJSON(data []byte) error {
125 value, err := proto.UnmarshalJSONEnum(FOO_value, data)
126 if err != nil {
127 return err
128 }
129 *x = FOO(value)
130 return nil
131 }
132
133 type Test struct {
134 Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
135 Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
136 Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
137 Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
138 // Types that are valid to be assigned to Union:
139 // *Test_Number
140 // *Test_Name
141 Union isTest_Union `protobuf_oneof:"union"`
142 XXX_unrecognized []byte `json:"-"`
143 }
144 func (m *Test) Reset() { *m = Test{} }
145 func (m *Test) String() string { return proto.CompactTextString(m) }
146 func (*Test) ProtoMessage() {}
147
148 type isTest_Union interface {
149 isTest_Union()
150 }
151
152 type Test_Number struct {
153 Number int32 `protobuf:"varint,6,opt,name=number"`
154 }
155 type Test_Name struct {
156 Name string `protobuf:"bytes,7,opt,name=name"`
157 }
158
159 func (*Test_Number) isTest_Union() {}
160 func (*Test_Name) isTest_Union() {}
161
162 func (m *Test) GetUnion() isTest_Union {
163 if m != nil {
164 return m.Union
165 }
166 return nil
167 }
168 const Default_Test_Type int32 = 77
169
170 func (m *Test) GetLabel() string {
171 if m != nil && m.Label != nil {
172 return *m.Label
173 }
174 return ""
175 }
176
177 func (m *Test) GetType() int32 {
178 if m != nil && m.Type != nil {
179 return *m.Type
180 }
181 return Default_Test_Type
182 }
183
184 func (m *Test) GetOptionalgroup() *Test_OptionalGroup {
185 if m != nil {
186 return m.Optionalgroup
187 }
188 return nil
189 }
190
191 type Test_OptionalGroup struct {
192 RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
193 }
194 func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} }
195 func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }
196
197 func (m *Test_OptionalGroup) GetRequiredField() string {
198 if m != nil && m.RequiredField != nil {
199 return *m.RequiredField
200 }
201 return ""
202 }
203
204 func (m *Test) GetNumber() int32 {
205 if x, ok := m.GetUnion().(*Test_Number); ok {
206 return x.Number
207 }
208 return 0
209 }
210
211 func (m *Test) GetName() string {
212 if x, ok := m.GetUnion().(*Test_Name); ok {
213 return x.Name
214 }
215 return ""
216 }
217
218 func init() {
219 proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
220 }
221
222To create and play with a Test object:
223
224 package main
225
226 import (
227 "log"
228
229 "github.com/gogo/protobuf/proto"
230 pb "./example.pb"
231 )
232
233 func main() {
234 test := &pb.Test{
235 Label: proto.String("hello"),
236 Type: proto.Int32(17),
237 Reps: []int64{1, 2, 3},
238 Optionalgroup: &pb.Test_OptionalGroup{
239 RequiredField: proto.String("good bye"),
240 },
241 Union: &pb.Test_Name{"fred"},
242 }
243 data, err := proto.Marshal(test)
244 if err != nil {
245 log.Fatal("marshaling error: ", err)
246 }
247 newTest := &pb.Test{}
248 err = proto.Unmarshal(data, newTest)
249 if err != nil {
250 log.Fatal("unmarshaling error: ", err)
251 }
252 // Now test and newTest contain the same data.
253 if test.GetLabel() != newTest.GetLabel() {
254 log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
255 }
256 // Use a type switch to determine which oneof was set.
257 switch u := test.Union.(type) {
258 case *pb.Test_Number: // u.Number contains the number.
259 case *pb.Test_Name: // u.Name contains the string.
260 }
261 // etc.
262 }
263*/
264package proto
265
266import (
267 "encoding/json"
268 "fmt"
269 "log"
270 "reflect"
271 "sort"
272 "strconv"
273 "sync"
274)
275
276// RequiredNotSetError is an error type returned by either Marshal or Unmarshal.
277// Marshal reports this when a required field is not initialized.
278// Unmarshal reports this when a required field is missing from the wire data.
279type RequiredNotSetError struct{ field string }
280
281func (e *RequiredNotSetError) Error() string {
282 if e.field == "" {
283 return fmt.Sprintf("proto: required field not set")
284 }
285 return fmt.Sprintf("proto: required field %q not set", e.field)
286}
287func (e *RequiredNotSetError) RequiredNotSet() bool {
288 return true
289}
290
291type invalidUTF8Error struct{ field string }
292
293func (e *invalidUTF8Error) Error() string {
294 if e.field == "" {
295 return "proto: invalid UTF-8 detected"
296 }
297 return fmt.Sprintf("proto: field %q contains invalid UTF-8", e.field)
298}
299func (e *invalidUTF8Error) InvalidUTF8() bool {
300 return true
301}
302
303// errInvalidUTF8 is a sentinel error to identify fields with invalid UTF-8.
304// This error should not be exposed to the external API as such errors should
305// be recreated with the field information.
306var errInvalidUTF8 = &invalidUTF8Error{}
307
308// isNonFatal reports whether the error is either a RequiredNotSet error
309// or a InvalidUTF8 error.
310func isNonFatal(err error) bool {
311 if re, ok := err.(interface{ RequiredNotSet() bool }); ok && re.RequiredNotSet() {
312 return true
313 }
314 if re, ok := err.(interface{ InvalidUTF8() bool }); ok && re.InvalidUTF8() {
315 return true
316 }
317 return false
318}
319
320type nonFatal struct{ E error }
321
322// Merge merges err into nf and reports whether it was successful.
323// Otherwise it returns false for any fatal non-nil errors.
324func (nf *nonFatal) Merge(err error) (ok bool) {
325 if err == nil {
326 return true // not an error
327 }
328 if !isNonFatal(err) {
329 return false // fatal error
330 }
331 if nf.E == nil {
332 nf.E = err // store first instance of non-fatal error
333 }
334 return true
335}
336
337// Message is implemented by generated protocol buffer messages.
338type Message interface {
339 Reset()
340 String() string
341 ProtoMessage()
342}
343
344// Stats records allocation details about the protocol buffer encoders
345// and decoders. Useful for tuning the library itself.
346type Stats struct {
347 Emalloc uint64 // mallocs in encode
348 Dmalloc uint64 // mallocs in decode
349 Encode uint64 // number of encodes
350 Decode uint64 // number of decodes
351 Chit uint64 // number of cache hits
352 Cmiss uint64 // number of cache misses
353 Size uint64 // number of sizes
354}
355
356// Set to true to enable stats collection.
357const collectStats = false
358
359var stats Stats
360
361// GetStats returns a copy of the global Stats structure.
362func GetStats() Stats { return stats }
363
364// A Buffer is a buffer manager for marshaling and unmarshaling
365// protocol buffers. It may be reused between invocations to
366// reduce memory usage. It is not necessary to use a Buffer;
367// the global functions Marshal and Unmarshal create a
368// temporary Buffer and are fine for most applications.
369type Buffer struct {
370 buf []byte // encode/decode byte stream
371 index int // read point
372
373 deterministic bool
374}
375
376// NewBuffer allocates a new Buffer and initializes its internal data to
377// the contents of the argument slice.
378func NewBuffer(e []byte) *Buffer {
379 return &Buffer{buf: e}
380}
381
382// Reset resets the Buffer, ready for marshaling a new protocol buffer.
383func (p *Buffer) Reset() {
384 p.buf = p.buf[0:0] // for reading/writing
385 p.index = 0 // for reading
386}
387
388// SetBuf replaces the internal buffer with the slice,
389// ready for unmarshaling the contents of the slice.
390func (p *Buffer) SetBuf(s []byte) {
391 p.buf = s
392 p.index = 0
393}
394
395// Bytes returns the contents of the Buffer.
396func (p *Buffer) Bytes() []byte { return p.buf }
397
398// SetDeterministic sets whether to use deterministic serialization.
399//
400// Deterministic serialization guarantees that for a given binary, equal
401// messages will always be serialized to the same bytes. This implies:
402//
403// - Repeated serialization of a message will return the same bytes.
404// - Different processes of the same binary (which may be executing on
405// different machines) will serialize equal messages to the same bytes.
406//
407// Note that the deterministic serialization is NOT canonical across
408// languages. It is not guaranteed to remain stable over time. It is unstable
409// across different builds with schema changes due to unknown fields.
410// Users who need canonical serialization (e.g., persistent storage in a
411// canonical form, fingerprinting, etc.) should define their own
412// canonicalization specification and implement their own serializer rather
413// than relying on this API.
414//
415// If deterministic serialization is requested, map entries will be sorted
416// by keys in lexographical order. This is an implementation detail and
417// subject to change.
418func (p *Buffer) SetDeterministic(deterministic bool) {
419 p.deterministic = deterministic
420}
421
422/*
423 * Helper routines for simplifying the creation of optional fields of basic type.
424 */
425
426// Bool is a helper routine that allocates a new bool value
427// to store v and returns a pointer to it.
428func Bool(v bool) *bool {
429 return &v
430}
431
432// Int32 is a helper routine that allocates a new int32 value
433// to store v and returns a pointer to it.
434func Int32(v int32) *int32 {
435 return &v
436}
437
438// Int is a helper routine that allocates a new int32 value
439// to store v and returns a pointer to it, but unlike Int32
440// its argument value is an int.
441func Int(v int) *int32 {
442 p := new(int32)
443 *p = int32(v)
444 return p
445}
446
447// Int64 is a helper routine that allocates a new int64 value
448// to store v and returns a pointer to it.
449func Int64(v int64) *int64 {
450 return &v
451}
452
453// Float32 is a helper routine that allocates a new float32 value
454// to store v and returns a pointer to it.
455func Float32(v float32) *float32 {
456 return &v
457}
458
459// Float64 is a helper routine that allocates a new float64 value
460// to store v and returns a pointer to it.
461func Float64(v float64) *float64 {
462 return &v
463}
464
465// Uint32 is a helper routine that allocates a new uint32 value
466// to store v and returns a pointer to it.
467func Uint32(v uint32) *uint32 {
468 return &v
469}
470
471// Uint64 is a helper routine that allocates a new uint64 value
472// to store v and returns a pointer to it.
473func Uint64(v uint64) *uint64 {
474 return &v
475}
476
477// String is a helper routine that allocates a new string value
478// to store v and returns a pointer to it.
479func String(v string) *string {
480 return &v
481}
482
483// EnumName is a helper function to simplify printing protocol buffer enums
484// by name. Given an enum map and a value, it returns a useful string.
485func EnumName(m map[int32]string, v int32) string {
486 s, ok := m[v]
487 if ok {
488 return s
489 }
490 return strconv.Itoa(int(v))
491}
492
493// UnmarshalJSONEnum is a helper function to simplify recovering enum int values
494// from their JSON-encoded representation. Given a map from the enum's symbolic
495// names to its int values, and a byte buffer containing the JSON-encoded
496// value, it returns an int32 that can be cast to the enum type by the caller.
497//
498// The function can deal with both JSON representations, numeric and symbolic.
499func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
500 if data[0] == '"' {
501 // New style: enums are strings.
502 var repr string
503 if err := json.Unmarshal(data, &repr); err != nil {
504 return -1, err
505 }
506 val, ok := m[repr]
507 if !ok {
508 return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
509 }
510 return val, nil
511 }
512 // Old style: enums are ints.
513 var val int32
514 if err := json.Unmarshal(data, &val); err != nil {
515 return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
516 }
517 return val, nil
518}
519
520// DebugPrint dumps the encoded data in b in a debugging format with a header
521// including the string s. Used in testing but made available for general debugging.
522func (p *Buffer) DebugPrint(s string, b []byte) {
523 var u uint64
524
525 obuf := p.buf
526 sindex := p.index
527 p.buf = b
528 p.index = 0
529 depth := 0
530
531 fmt.Printf("\n--- %s ---\n", s)
532
533out:
534 for {
535 for i := 0; i < depth; i++ {
536 fmt.Print(" ")
537 }
538
539 index := p.index
540 if index == len(p.buf) {
541 break
542 }
543
544 op, err := p.DecodeVarint()
545 if err != nil {
546 fmt.Printf("%3d: fetching op err %v\n", index, err)
547 break out
548 }
549 tag := op >> 3
550 wire := op & 7
551
552 switch wire {
553 default:
554 fmt.Printf("%3d: t=%3d unknown wire=%d\n",
555 index, tag, wire)
556 break out
557
558 case WireBytes:
559 var r []byte
560
561 r, err = p.DecodeRawBytes(false)
562 if err != nil {
563 break out
564 }
565 fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
566 if len(r) <= 6 {
567 for i := 0; i < len(r); i++ {
568 fmt.Printf(" %.2x", r[i])
569 }
570 } else {
571 for i := 0; i < 3; i++ {
572 fmt.Printf(" %.2x", r[i])
573 }
574 fmt.Printf(" ..")
575 for i := len(r) - 3; i < len(r); i++ {
576 fmt.Printf(" %.2x", r[i])
577 }
578 }
579 fmt.Printf("\n")
580
581 case WireFixed32:
582 u, err = p.DecodeFixed32()
583 if err != nil {
584 fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
585 break out
586 }
587 fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
588
589 case WireFixed64:
590 u, err = p.DecodeFixed64()
591 if err != nil {
592 fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
593 break out
594 }
595 fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
596
597 case WireVarint:
598 u, err = p.DecodeVarint()
599 if err != nil {
600 fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
601 break out
602 }
603 fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
604
605 case WireStartGroup:
606 fmt.Printf("%3d: t=%3d start\n", index, tag)
607 depth++
608
609 case WireEndGroup:
610 depth--
611 fmt.Printf("%3d: t=%3d end\n", index, tag)
612 }
613 }
614
615 if depth != 0 {
616 fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth)
617 }
618 fmt.Printf("\n")
619
620 p.buf = obuf
621 p.index = sindex
622}
623
624// SetDefaults sets unset protocol buffer fields to their default values.
625// It only modifies fields that are both unset and have defined defaults.
626// It recursively sets default values in any non-nil sub-messages.
627func SetDefaults(pb Message) {
628 setDefaults(reflect.ValueOf(pb), true, false)
629}
630
631// v is a struct.
632func setDefaults(v reflect.Value, recur, zeros bool) {
633 if v.Kind() == reflect.Ptr {
634 v = v.Elem()
635 }
636
637 defaultMu.RLock()
638 dm, ok := defaults[v.Type()]
639 defaultMu.RUnlock()
640 if !ok {
641 dm = buildDefaultMessage(v.Type())
642 defaultMu.Lock()
643 defaults[v.Type()] = dm
644 defaultMu.Unlock()
645 }
646
647 for _, sf := range dm.scalars {
648 f := v.Field(sf.index)
649 if !f.IsNil() {
650 // field already set
651 continue
652 }
653 dv := sf.value
654 if dv == nil && !zeros {
655 // no explicit default, and don't want to set zeros
656 continue
657 }
658 fptr := f.Addr().Interface() // **T
659 // TODO: Consider batching the allocations we do here.
660 switch sf.kind {
661 case reflect.Bool:
662 b := new(bool)
663 if dv != nil {
664 *b = dv.(bool)
665 }
666 *(fptr.(**bool)) = b
667 case reflect.Float32:
668 f := new(float32)
669 if dv != nil {
670 *f = dv.(float32)
671 }
672 *(fptr.(**float32)) = f
673 case reflect.Float64:
674 f := new(float64)
675 if dv != nil {
676 *f = dv.(float64)
677 }
678 *(fptr.(**float64)) = f
679 case reflect.Int32:
680 // might be an enum
681 if ft := f.Type(); ft != int32PtrType {
682 // enum
683 f.Set(reflect.New(ft.Elem()))
684 if dv != nil {
685 f.Elem().SetInt(int64(dv.(int32)))
686 }
687 } else {
688 // int32 field
689 i := new(int32)
690 if dv != nil {
691 *i = dv.(int32)
692 }
693 *(fptr.(**int32)) = i
694 }
695 case reflect.Int64:
696 i := new(int64)
697 if dv != nil {
698 *i = dv.(int64)
699 }
700 *(fptr.(**int64)) = i
701 case reflect.String:
702 s := new(string)
703 if dv != nil {
704 *s = dv.(string)
705 }
706 *(fptr.(**string)) = s
707 case reflect.Uint8:
708 // exceptional case: []byte
709 var b []byte
710 if dv != nil {
711 db := dv.([]byte)
712 b = make([]byte, len(db))
713 copy(b, db)
714 } else {
715 b = []byte{}
716 }
717 *(fptr.(*[]byte)) = b
718 case reflect.Uint32:
719 u := new(uint32)
720 if dv != nil {
721 *u = dv.(uint32)
722 }
723 *(fptr.(**uint32)) = u
724 case reflect.Uint64:
725 u := new(uint64)
726 if dv != nil {
727 *u = dv.(uint64)
728 }
729 *(fptr.(**uint64)) = u
730 default:
731 log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
732 }
733 }
734
735 for _, ni := range dm.nested {
736 f := v.Field(ni)
737 // f is *T or T or []*T or []T
738 switch f.Kind() {
739 case reflect.Struct:
740 setDefaults(f, recur, zeros)
741
742 case reflect.Ptr:
743 if f.IsNil() {
744 continue
745 }
746 setDefaults(f, recur, zeros)
747
748 case reflect.Slice:
749 for i := 0; i < f.Len(); i++ {
750 e := f.Index(i)
751 if e.Kind() == reflect.Ptr && e.IsNil() {
752 continue
753 }
754 setDefaults(e, recur, zeros)
755 }
756
757 case reflect.Map:
758 for _, k := range f.MapKeys() {
759 e := f.MapIndex(k)
760 if e.IsNil() {
761 continue
762 }
763 setDefaults(e, recur, zeros)
764 }
765 }
766 }
767}
768
769var (
770 // defaults maps a protocol buffer struct type to a slice of the fields,
771 // with its scalar fields set to their proto-declared non-zero default values.
772 defaultMu sync.RWMutex
773 defaults = make(map[reflect.Type]defaultMessage)
774
775 int32PtrType = reflect.TypeOf((*int32)(nil))
776)
777
778// defaultMessage represents information about the default values of a message.
779type defaultMessage struct {
780 scalars []scalarField
781 nested []int // struct field index of nested messages
782}
783
784type scalarField struct {
785 index int // struct field index
786 kind reflect.Kind // element type (the T in *T or []T)
787 value interface{} // the proto-declared default value, or nil
788}
789
790// t is a struct type.
791func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
792 sprop := GetProperties(t)
793 for _, prop := range sprop.Prop {
794 fi, ok := sprop.decoderTags.get(prop.Tag)
795 if !ok {
796 // XXX_unrecognized
797 continue
798 }
799 ft := t.Field(fi).Type
800
801 sf, nested, err := fieldDefault(ft, prop)
802 switch {
803 case err != nil:
804 log.Print(err)
805 case nested:
806 dm.nested = append(dm.nested, fi)
807 case sf != nil:
808 sf.index = fi
809 dm.scalars = append(dm.scalars, *sf)
810 }
811 }
812
813 return dm
814}
815
816// fieldDefault returns the scalarField for field type ft.
817// sf will be nil if the field can not have a default.
818// nestedMessage will be true if this is a nested message.
819// Note that sf.index is not set on return.
820func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) {
821 var canHaveDefault bool
822 switch ft.Kind() {
823 case reflect.Struct:
824 nestedMessage = true // non-nullable
825
826 case reflect.Ptr:
827 if ft.Elem().Kind() == reflect.Struct {
828 nestedMessage = true
829 } else {
830 canHaveDefault = true // proto2 scalar field
831 }
832
833 case reflect.Slice:
834 switch ft.Elem().Kind() {
835 case reflect.Ptr, reflect.Struct:
836 nestedMessage = true // repeated message
837 case reflect.Uint8:
838 canHaveDefault = true // bytes field
839 }
840
841 case reflect.Map:
842 if ft.Elem().Kind() == reflect.Ptr {
843 nestedMessage = true // map with message values
844 }
845 }
846
847 if !canHaveDefault {
848 if nestedMessage {
849 return nil, true, nil
850 }
851 return nil, false, nil
852 }
853
854 // We now know that ft is a pointer or slice.
855 sf = &scalarField{kind: ft.Elem().Kind()}
856
857 // scalar fields without defaults
858 if !prop.HasDefault {
859 return sf, false, nil
860 }
861
862 // a scalar field: either *T or []byte
863 switch ft.Elem().Kind() {
864 case reflect.Bool:
865 x, err := strconv.ParseBool(prop.Default)
866 if err != nil {
867 return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err)
868 }
869 sf.value = x
870 case reflect.Float32:
871 x, err := strconv.ParseFloat(prop.Default, 32)
872 if err != nil {
873 return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err)
874 }
875 sf.value = float32(x)
876 case reflect.Float64:
877 x, err := strconv.ParseFloat(prop.Default, 64)
878 if err != nil {
879 return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err)
880 }
881 sf.value = x
882 case reflect.Int32:
883 x, err := strconv.ParseInt(prop.Default, 10, 32)
884 if err != nil {
885 return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err)
886 }
887 sf.value = int32(x)
888 case reflect.Int64:
889 x, err := strconv.ParseInt(prop.Default, 10, 64)
890 if err != nil {
891 return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err)
892 }
893 sf.value = x
894 case reflect.String:
895 sf.value = prop.Default
896 case reflect.Uint8:
897 // []byte (not *uint8)
898 sf.value = []byte(prop.Default)
899 case reflect.Uint32:
900 x, err := strconv.ParseUint(prop.Default, 10, 32)
901 if err != nil {
902 return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err)
903 }
904 sf.value = uint32(x)
905 case reflect.Uint64:
906 x, err := strconv.ParseUint(prop.Default, 10, 64)
907 if err != nil {
908 return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err)
909 }
910 sf.value = x
911 default:
912 return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind())
913 }
914
915 return sf, false, nil
916}
917
918// mapKeys returns a sort.Interface to be used for sorting the map keys.
919// Map fields may have key types of non-float scalars, strings and enums.
920func mapKeys(vs []reflect.Value) sort.Interface {
921 s := mapKeySorter{vs: vs}
922
923 // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps.
924 if len(vs) == 0 {
925 return s
926 }
927 switch vs[0].Kind() {
928 case reflect.Int32, reflect.Int64:
929 s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
930 case reflect.Uint32, reflect.Uint64:
931 s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
932 case reflect.Bool:
933 s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true
934 case reflect.String:
935 s.less = func(a, b reflect.Value) bool { return a.String() < b.String() }
936 default:
937 panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind()))
938 }
939
940 return s
941}
942
943type mapKeySorter struct {
944 vs []reflect.Value
945 less func(a, b reflect.Value) bool
946}
947
948func (s mapKeySorter) Len() int { return len(s.vs) }
949func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
950func (s mapKeySorter) Less(i, j int) bool {
951 return s.less(s.vs[i], s.vs[j])
952}
953
954// isProto3Zero reports whether v is a zero proto3 value.
955func isProto3Zero(v reflect.Value) bool {
956 switch v.Kind() {
957 case reflect.Bool:
958 return !v.Bool()
959 case reflect.Int32, reflect.Int64:
960 return v.Int() == 0
961 case reflect.Uint32, reflect.Uint64:
962 return v.Uint() == 0
963 case reflect.Float32, reflect.Float64:
964 return v.Float() == 0
965 case reflect.String:
966 return v.String() == ""
967 }
968 return false
969}
970
971// ProtoPackageIsVersion2 is referenced from generated protocol buffer files
972// to assert that that code is compatible with this version of the proto package.
973const GoGoProtoPackageIsVersion2 = true
974
975// ProtoPackageIsVersion1 is referenced from generated protocol buffer files
976// to assert that that code is compatible with this version of the proto package.
977const GoGoProtoPackageIsVersion1 = true
978
979// InternalMessageInfo is a type used internally by generated .pb.go files.
980// This type is not intended to be used by non-generated code.
981// This type is not subject to any compatibility guarantee.
982type InternalMessageInfo struct {
983 marshal *marshalInfo
984 unmarshal *unmarshalInfo
985 merge *mergeInfo
986 discard *discardInfo
987}