podman
1// 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
42them as structure fields.
43- There are getters that return a field's value if set,
44and return the field's default value if unset.
45The getters work even if the receiver is a nil message.
46- The zero value for a struct is its correct initialization state.
47All 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.
50That 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.
53msg.Foo = proto.String("hello") // set field
54- Constants are defined to hold the default values of all fields that
55have them. They have the form Default_StructName_FieldName.
56Because the getter methods handle defaulted values,
57direct use of these constants should be rare.
58- Enums are given type names and maps from names to values.
59Enum values are prefixed by the enclosing message's name, or by the
60enum's type name if it is a top-level enum. Enum types have a String
61method, and a Enum method to assist in message construction.
62- Nested messages, groups and enums have type names prefixed with the name of
63the surrounding message type.
64- Extensions are given descriptor names that start with E_,
65followed by an underscore-delimited list of the nested messages
66that contain it (if any) followed by the CamelCased name of the
67extension field itself. HasExtension, ClearExtension, GetExtension
68and SetExtension are functions for manipulating extensions.
69- Oneof field sets are given a single field in their message,
70with 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
81package example;
82
83enum FOO { X = 17; }
84
85message Test {
86required string label = 1;
87optional int32 type = 2 [default=77];
88repeated int64 reps = 3;
89optional group OptionalGroup = 4 {
90required string RequiredField = 5;
91}
92oneof union {
93int32 number = 6;
94string name = 7;
95}
96}
97
98The resulting file, test.pb.go, is:
99
100package example
101
102import proto "github.com/gogo/protobuf/proto"
103import math "math"
104
105type FOO int32
106const (
107FOO_X FOO = 17
108)
109var FOO_name = map[int32]string{
11017: "X",
111}
112var FOO_value = map[string]int32{
113"X": 17,
114}
115
116func (x FOO) Enum() *FOO {
117p := new(FOO)
118*p = x
119return p
120}
121func (x FOO) String() string {
122return proto.EnumName(FOO_name, int32(x))
123}
124func (x *FOO) UnmarshalJSON(data []byte) error {
125value, err := proto.UnmarshalJSONEnum(FOO_value, data)
126if err != nil {
127return err
128}
129*x = FOO(value)
130return nil
131}
132
133type Test struct {
134Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
135Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
136Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
137Optionalgroup *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
141Union isTest_Union `protobuf_oneof:"union"`
142XXX_unrecognized []byte `json:"-"`
143}
144func (m *Test) Reset() { *m = Test{} }
145func (m *Test) String() string { return proto.CompactTextString(m) }
146func (*Test) ProtoMessage() {}
147
148type isTest_Union interface {
149isTest_Union()
150}
151
152type Test_Number struct {
153Number int32 `protobuf:"varint,6,opt,name=number"`
154}
155type Test_Name struct {
156Name string `protobuf:"bytes,7,opt,name=name"`
157}
158
159func (*Test_Number) isTest_Union() {}
160func (*Test_Name) isTest_Union() {}
161
162func (m *Test) GetUnion() isTest_Union {
163if m != nil {
164return m.Union
165}
166return nil
167}
168const Default_Test_Type int32 = 77
169
170func (m *Test) GetLabel() string {
171if m != nil && m.Label != nil {
172return *m.Label
173}
174return ""
175}
176
177func (m *Test) GetType() int32 {
178if m != nil && m.Type != nil {
179return *m.Type
180}
181return Default_Test_Type
182}
183
184func (m *Test) GetOptionalgroup() *Test_OptionalGroup {
185if m != nil {
186return m.Optionalgroup
187}
188return nil
189}
190
191type Test_OptionalGroup struct {
192RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
193}
194func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} }
195func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }
196
197func (m *Test_OptionalGroup) GetRequiredField() string {
198if m != nil && m.RequiredField != nil {
199return *m.RequiredField
200}
201return ""
202}
203
204func (m *Test) GetNumber() int32 {
205if x, ok := m.GetUnion().(*Test_Number); ok {
206return x.Number
207}
208return 0
209}
210
211func (m *Test) GetName() string {
212if x, ok := m.GetUnion().(*Test_Name); ok {
213return x.Name
214}
215return ""
216}
217
218func init() {
219proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
220}
221
222To create and play with a Test object:
223
224package main
225
226import (
227"log"
228
229"github.com/gogo/protobuf/proto"
230pb "./example.pb"
231)
232
233func main() {
234test := &pb.Test{
235Label: proto.String("hello"),
236Type: proto.Int32(17),
237Reps: []int64{1, 2, 3},
238Optionalgroup: &pb.Test_OptionalGroup{
239RequiredField: proto.String("good bye"),
240},
241Union: &pb.Test_Name{"fred"},
242}
243data, err := proto.Marshal(test)
244if err != nil {
245log.Fatal("marshaling error: ", err)
246}
247newTest := &pb.Test{}
248err = proto.Unmarshal(data, newTest)
249if err != nil {
250log.Fatal("unmarshaling error: ", err)
251}
252// Now test and newTest contain the same data.
253if test.GetLabel() != newTest.GetLabel() {
254log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
255}
256// Use a type switch to determine which oneof was set.
257switch u := test.Union.(type) {
258case *pb.Test_Number: // u.Number contains the number.
259case *pb.Test_Name: // u.Name contains the string.
260}
261// etc.
262}
263*/
264package proto265
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 {282if e.field == "" {283return fmt.Sprintf("proto: required field not set")284}285return fmt.Sprintf("proto: required field %q not set", e.field)286}
287func (e *RequiredNotSetError) RequiredNotSet() bool {288return true289}
290
291type invalidUTF8Error struct{ field string }292
293func (e *invalidUTF8Error) Error() string {294if e.field == "" {295return "proto: invalid UTF-8 detected"296}297return fmt.Sprintf("proto: field %q contains invalid UTF-8", e.field)298}
299func (e *invalidUTF8Error) InvalidUTF8() bool {300return true301}
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 {311if re, ok := err.(interface{ RequiredNotSet() bool }); ok && re.RequiredNotSet() {312return true313}314if re, ok := err.(interface{ InvalidUTF8() bool }); ok && re.InvalidUTF8() {315return true316}317return false318}
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) {325if err == nil {326return true // not an error327}328if !isNonFatal(err) {329return false // fatal error330}331if nf.E == nil {332nf.E = err // store first instance of non-fatal error333}334return true335}
336
337// Message is implemented by generated protocol buffer messages.
338type Message interface {339Reset()340String() string341ProtoMessage()342}
343
344// A Buffer is a buffer manager for marshaling and unmarshaling
345// protocol buffers. It may be reused between invocations to
346// reduce memory usage. It is not necessary to use a Buffer;
347// the global functions Marshal and Unmarshal create a
348// temporary Buffer and are fine for most applications.
349type Buffer struct {350buf []byte // encode/decode byte stream351index int // read point352
353deterministic bool354}
355
356// NewBuffer allocates a new Buffer and initializes its internal data to
357// the contents of the argument slice.
358func NewBuffer(e []byte) *Buffer {359return &Buffer{buf: e}360}
361
362// Reset resets the Buffer, ready for marshaling a new protocol buffer.
363func (p *Buffer) Reset() {364p.buf = p.buf[0:0] // for reading/writing365p.index = 0 // for reading366}
367
368// SetBuf replaces the internal buffer with the slice,
369// ready for unmarshaling the contents of the slice.
370func (p *Buffer) SetBuf(s []byte) {371p.buf = s372p.index = 0373}
374
375// Bytes returns the contents of the Buffer.
376func (p *Buffer) Bytes() []byte { return p.buf }377
378// SetDeterministic sets whether to use deterministic serialization.
379//
380// Deterministic serialization guarantees that for a given binary, equal
381// messages will always be serialized to the same bytes. This implies:
382//
383// - Repeated serialization of a message will return the same bytes.
384// - Different processes of the same binary (which may be executing on
385// different machines) will serialize equal messages to the same bytes.
386//
387// Note that the deterministic serialization is NOT canonical across
388// languages. It is not guaranteed to remain stable over time. It is unstable
389// across different builds with schema changes due to unknown fields.
390// Users who need canonical serialization (e.g., persistent storage in a
391// canonical form, fingerprinting, etc.) should define their own
392// canonicalization specification and implement their own serializer rather
393// than relying on this API.
394//
395// If deterministic serialization is requested, map entries will be sorted
396// by keys in lexographical order. This is an implementation detail and
397// subject to change.
398func (p *Buffer) SetDeterministic(deterministic bool) {399p.deterministic = deterministic400}
401
402/*
403* Helper routines for simplifying the creation of optional fields of basic type.
404*/
405
406// Bool is a helper routine that allocates a new bool value
407// to store v and returns a pointer to it.
408func Bool(v bool) *bool {409return &v410}
411
412// Int32 is a helper routine that allocates a new int32 value
413// to store v and returns a pointer to it.
414func Int32(v int32) *int32 {415return &v416}
417
418// Int is a helper routine that allocates a new int32 value
419// to store v and returns a pointer to it, but unlike Int32
420// its argument value is an int.
421func Int(v int) *int32 {422p := new(int32)423*p = int32(v)424return p425}
426
427// Int64 is a helper routine that allocates a new int64 value
428// to store v and returns a pointer to it.
429func Int64(v int64) *int64 {430return &v431}
432
433// Float32 is a helper routine that allocates a new float32 value
434// to store v and returns a pointer to it.
435func Float32(v float32) *float32 {436return &v437}
438
439// Float64 is a helper routine that allocates a new float64 value
440// to store v and returns a pointer to it.
441func Float64(v float64) *float64 {442return &v443}
444
445// Uint32 is a helper routine that allocates a new uint32 value
446// to store v and returns a pointer to it.
447func Uint32(v uint32) *uint32 {448return &v449}
450
451// Uint64 is a helper routine that allocates a new uint64 value
452// to store v and returns a pointer to it.
453func Uint64(v uint64) *uint64 {454return &v455}
456
457// String is a helper routine that allocates a new string value
458// to store v and returns a pointer to it.
459func String(v string) *string {460return &v461}
462
463// EnumName is a helper function to simplify printing protocol buffer enums
464// by name. Given an enum map and a value, it returns a useful string.
465func EnumName(m map[int32]string, v int32) string {466s, ok := m[v]467if ok {468return s469}470return strconv.Itoa(int(v))471}
472
473// UnmarshalJSONEnum is a helper function to simplify recovering enum int values
474// from their JSON-encoded representation. Given a map from the enum's symbolic
475// names to its int values, and a byte buffer containing the JSON-encoded
476// value, it returns an int32 that can be cast to the enum type by the caller.
477//
478// The function can deal with both JSON representations, numeric and symbolic.
479func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {480if data[0] == '"' {481// New style: enums are strings.482var repr string483if err := json.Unmarshal(data, &repr); err != nil {484return -1, err485}486val, ok := m[repr]487if !ok {488return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)489}490return val, nil491}492// Old style: enums are ints.493var val int32494if err := json.Unmarshal(data, &val); err != nil {495return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)496}497return val, nil498}
499
500// DebugPrint dumps the encoded data in b in a debugging format with a header
501// including the string s. Used in testing but made available for general debugging.
502func (p *Buffer) DebugPrint(s string, b []byte) {503var u uint64504
505obuf := p.buf506sindex := p.index507p.buf = b508p.index = 0509depth := 0510
511fmt.Printf("\n--- %s ---\n", s)512
513out:514for {515for i := 0; i < depth; i++ {516fmt.Print(" ")517}518
519index := p.index520if index == len(p.buf) {521break522}523
524op, err := p.DecodeVarint()525if err != nil {526fmt.Printf("%3d: fetching op err %v\n", index, err)527break out528}529tag := op >> 3530wire := op & 7531
532switch wire {533default:534fmt.Printf("%3d: t=%3d unknown wire=%d\n",535index, tag, wire)536break out537
538case WireBytes:539var r []byte540
541r, err = p.DecodeRawBytes(false)542if err != nil {543break out544}545fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))546if len(r) <= 6 {547for i := 0; i < len(r); i++ {548fmt.Printf(" %.2x", r[i])549}550} else {551for i := 0; i < 3; i++ {552fmt.Printf(" %.2x", r[i])553}554fmt.Printf(" ..")555for i := len(r) - 3; i < len(r); i++ {556fmt.Printf(" %.2x", r[i])557}558}559fmt.Printf("\n")560
561case WireFixed32:562u, err = p.DecodeFixed32()563if err != nil {564fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)565break out566}567fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)568
569case WireFixed64:570u, err = p.DecodeFixed64()571if err != nil {572fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)573break out574}575fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)576
577case WireVarint:578u, err = p.DecodeVarint()579if err != nil {580fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)581break out582}583fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)584
585case WireStartGroup:586fmt.Printf("%3d: t=%3d start\n", index, tag)587depth++588
589case WireEndGroup:590depth--591fmt.Printf("%3d: t=%3d end\n", index, tag)592}593}594
595if depth != 0 {596fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth)597}598fmt.Printf("\n")599
600p.buf = obuf601p.index = sindex602}
603
604// SetDefaults sets unset protocol buffer fields to their default values.
605// It only modifies fields that are both unset and have defined defaults.
606// It recursively sets default values in any non-nil sub-messages.
607func SetDefaults(pb Message) {608setDefaults(reflect.ValueOf(pb), true, false)609}
610
611// v is a struct.
612func setDefaults(v reflect.Value, recur, zeros bool) {613if v.Kind() == reflect.Ptr {614v = v.Elem()615}616
617defaultMu.RLock()618dm, ok := defaults[v.Type()]619defaultMu.RUnlock()620if !ok {621dm = buildDefaultMessage(v.Type())622defaultMu.Lock()623defaults[v.Type()] = dm624defaultMu.Unlock()625}626
627for _, sf := range dm.scalars {628f := v.Field(sf.index)629if !f.IsNil() {630// field already set631continue632}633dv := sf.value634if dv == nil && !zeros {635// no explicit default, and don't want to set zeros636continue637}638fptr := f.Addr().Interface() // **T639// TODO: Consider batching the allocations we do here.640switch sf.kind {641case reflect.Bool:642b := new(bool)643if dv != nil {644*b = dv.(bool)645}646*(fptr.(**bool)) = b647case reflect.Float32:648f := new(float32)649if dv != nil {650*f = dv.(float32)651}652*(fptr.(**float32)) = f653case reflect.Float64:654f := new(float64)655if dv != nil {656*f = dv.(float64)657}658*(fptr.(**float64)) = f659case reflect.Int32:660// might be an enum661if ft := f.Type(); ft != int32PtrType {662// enum663f.Set(reflect.New(ft.Elem()))664if dv != nil {665f.Elem().SetInt(int64(dv.(int32)))666}667} else {668// int32 field669i := new(int32)670if dv != nil {671*i = dv.(int32)672}673*(fptr.(**int32)) = i674}675case reflect.Int64:676i := new(int64)677if dv != nil {678*i = dv.(int64)679}680*(fptr.(**int64)) = i681case reflect.String:682s := new(string)683if dv != nil {684*s = dv.(string)685}686*(fptr.(**string)) = s687case reflect.Uint8:688// exceptional case: []byte689var b []byte690if dv != nil {691db := dv.([]byte)692b = make([]byte, len(db))693copy(b, db)694} else {695b = []byte{}696}697*(fptr.(*[]byte)) = b698case reflect.Uint32:699u := new(uint32)700if dv != nil {701*u = dv.(uint32)702}703*(fptr.(**uint32)) = u704case reflect.Uint64:705u := new(uint64)706if dv != nil {707*u = dv.(uint64)708}709*(fptr.(**uint64)) = u710default:711log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)712}713}714
715for _, ni := range dm.nested {716f := v.Field(ni)717// f is *T or T or []*T or []T718switch f.Kind() {719case reflect.Struct:720setDefaults(f, recur, zeros)721
722case reflect.Ptr:723if f.IsNil() {724continue725}726setDefaults(f, recur, zeros)727
728case reflect.Slice:729for i := 0; i < f.Len(); i++ {730e := f.Index(i)731if e.Kind() == reflect.Ptr && e.IsNil() {732continue733}734setDefaults(e, recur, zeros)735}736
737case reflect.Map:738for _, k := range f.MapKeys() {739e := f.MapIndex(k)740if e.IsNil() {741continue742}743setDefaults(e, recur, zeros)744}745}746}747}
748
749var (750// defaults maps a protocol buffer struct type to a slice of the fields,751// with its scalar fields set to their proto-declared non-zero default values.752defaultMu sync.RWMutex753defaults = make(map[reflect.Type]defaultMessage)754
755int32PtrType = reflect.TypeOf((*int32)(nil))756)
757
758// defaultMessage represents information about the default values of a message.
759type defaultMessage struct {760scalars []scalarField761nested []int // struct field index of nested messages762}
763
764type scalarField struct {765index int // struct field index766kind reflect.Kind // element type (the T in *T or []T)767value interface{} // the proto-declared default value, or nil768}
769
770// t is a struct type.
771func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {772sprop := GetProperties(t)773for _, prop := range sprop.Prop {774fi, ok := sprop.decoderTags.get(prop.Tag)775if !ok {776// XXX_unrecognized777continue778}779ft := t.Field(fi).Type780
781sf, nested, err := fieldDefault(ft, prop)782switch {783case err != nil:784log.Print(err)785case nested:786dm.nested = append(dm.nested, fi)787case sf != nil:788sf.index = fi789dm.scalars = append(dm.scalars, *sf)790}791}792
793return dm794}
795
796// fieldDefault returns the scalarField for field type ft.
797// sf will be nil if the field can not have a default.
798// nestedMessage will be true if this is a nested message.
799// Note that sf.index is not set on return.
800func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) {801var canHaveDefault bool802switch ft.Kind() {803case reflect.Struct:804nestedMessage = true // non-nullable805
806case reflect.Ptr:807if ft.Elem().Kind() == reflect.Struct {808nestedMessage = true809} else {810canHaveDefault = true // proto2 scalar field811}812
813case reflect.Slice:814switch ft.Elem().Kind() {815case reflect.Ptr, reflect.Struct:816nestedMessage = true // repeated message817case reflect.Uint8:818canHaveDefault = true // bytes field819}820
821case reflect.Map:822if ft.Elem().Kind() == reflect.Ptr {823nestedMessage = true // map with message values824}825}826
827if !canHaveDefault {828if nestedMessage {829return nil, true, nil830}831return nil, false, nil832}833
834// We now know that ft is a pointer or slice.835sf = &scalarField{kind: ft.Elem().Kind()}836
837// scalar fields without defaults838if !prop.HasDefault {839return sf, false, nil840}841
842// a scalar field: either *T or []byte843switch ft.Elem().Kind() {844case reflect.Bool:845x, err := strconv.ParseBool(prop.Default)846if err != nil {847return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err)848}849sf.value = x850case reflect.Float32:851x, err := strconv.ParseFloat(prop.Default, 32)852if err != nil {853return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err)854}855sf.value = float32(x)856case reflect.Float64:857x, err := strconv.ParseFloat(prop.Default, 64)858if err != nil {859return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err)860}861sf.value = x862case reflect.Int32:863x, err := strconv.ParseInt(prop.Default, 10, 32)864if err != nil {865return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err)866}867sf.value = int32(x)868case reflect.Int64:869x, err := strconv.ParseInt(prop.Default, 10, 64)870if err != nil {871return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err)872}873sf.value = x874case reflect.String:875sf.value = prop.Default876case reflect.Uint8:877// []byte (not *uint8)878sf.value = []byte(prop.Default)879case reflect.Uint32:880x, err := strconv.ParseUint(prop.Default, 10, 32)881if err != nil {882return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err)883}884sf.value = uint32(x)885case reflect.Uint64:886x, err := strconv.ParseUint(prop.Default, 10, 64)887if err != nil {888return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err)889}890sf.value = x891default:892return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind())893}894
895return sf, false, nil896}
897
898// mapKeys returns a sort.Interface to be used for sorting the map keys.
899// Map fields may have key types of non-float scalars, strings and enums.
900func mapKeys(vs []reflect.Value) sort.Interface {901s := mapKeySorter{vs: vs}902
903// Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps.904if len(vs) == 0 {905return s906}907switch vs[0].Kind() {908case reflect.Int32, reflect.Int64:909s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }910case reflect.Uint32, reflect.Uint64:911s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }912case reflect.Bool:913s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true914case reflect.String:915s.less = func(a, b reflect.Value) bool { return a.String() < b.String() }916default:917panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind()))918}919
920return s921}
922
923type mapKeySorter struct {924vs []reflect.Value925less func(a, b reflect.Value) bool926}
927
928func (s mapKeySorter) Len() int { return len(s.vs) }929func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }930func (s mapKeySorter) Less(i, j int) bool {931return s.less(s.vs[i], s.vs[j])932}
933
934// isProto3Zero reports whether v is a zero proto3 value.
935func isProto3Zero(v reflect.Value) bool {936switch v.Kind() {937case reflect.Bool:938return !v.Bool()939case reflect.Int32, reflect.Int64:940return v.Int() == 0941case reflect.Uint32, reflect.Uint64:942return v.Uint() == 0943case reflect.Float32, reflect.Float64:944return v.Float() == 0945case reflect.String:946return v.String() == ""947}948return false949}
950
951const (952// ProtoPackageIsVersion3 is referenced from generated protocol buffer files953// to assert that that code is compatible with this version of the proto package.954GoGoProtoPackageIsVersion3 = true955
956// ProtoPackageIsVersion2 is referenced from generated protocol buffer files957// to assert that that code is compatible with this version of the proto package.958GoGoProtoPackageIsVersion2 = true959
960// ProtoPackageIsVersion1 is referenced from generated protocol buffer files961// to assert that that code is compatible with this version of the proto package.962GoGoProtoPackageIsVersion1 = true963)
964
965// InternalMessageInfo is a type used internally by generated .pb.go files.
966// This type is not intended to be used by non-generated code.
967// This type is not subject to any compatibility guarantee.
968type InternalMessageInfo struct {969marshal *marshalInfo970unmarshal *unmarshalInfo971merge *mergeInfo972discard *discardInfo973}
974