• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
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/golang/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/golang/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// Message is implemented by generated protocol buffer messages.
277type Message interface {
278	Reset()
279	String() string
280	ProtoMessage()
281}
282
283// Stats records allocation details about the protocol buffer encoders
284// and decoders.  Useful for tuning the library itself.
285type Stats struct {
286	Emalloc uint64 // mallocs in encode
287	Dmalloc uint64 // mallocs in decode
288	Encode  uint64 // number of encodes
289	Decode  uint64 // number of decodes
290	Chit    uint64 // number of cache hits
291	Cmiss   uint64 // number of cache misses
292	Size    uint64 // number of sizes
293}
294
295// Set to true to enable stats collection.
296const collectStats = false
297
298var stats Stats
299
300// GetStats returns a copy of the global Stats structure.
301func GetStats() Stats { return stats }
302
303// A Buffer is a buffer manager for marshaling and unmarshaling
304// protocol buffers.  It may be reused between invocations to
305// reduce memory usage.  It is not necessary to use a Buffer;
306// the global functions Marshal and Unmarshal create a
307// temporary Buffer and are fine for most applications.
308type Buffer struct {
309	buf   []byte // encode/decode byte stream
310	index int    // read point
311
312	// pools of basic types to amortize allocation.
313	bools   []bool
314	uint32s []uint32
315	uint64s []uint64
316
317	// extra pools, only used with pointer_reflect.go
318	int32s   []int32
319	int64s   []int64
320	float32s []float32
321	float64s []float64
322}
323
324// NewBuffer allocates a new Buffer and initializes its internal data to
325// the contents of the argument slice.
326func NewBuffer(e []byte) *Buffer {
327	return &Buffer{buf: e}
328}
329
330// Reset resets the Buffer, ready for marshaling a new protocol buffer.
331func (p *Buffer) Reset() {
332	p.buf = p.buf[0:0] // for reading/writing
333	p.index = 0        // for reading
334}
335
336// SetBuf replaces the internal buffer with the slice,
337// ready for unmarshaling the contents of the slice.
338func (p *Buffer) SetBuf(s []byte) {
339	p.buf = s
340	p.index = 0
341}
342
343// Bytes returns the contents of the Buffer.
344func (p *Buffer) Bytes() []byte { return p.buf }
345
346/*
347 * Helper routines for simplifying the creation of optional fields of basic type.
348 */
349
350// Bool is a helper routine that allocates a new bool value
351// to store v and returns a pointer to it.
352func Bool(v bool) *bool {
353	return &v
354}
355
356// Int32 is a helper routine that allocates a new int32 value
357// to store v and returns a pointer to it.
358func Int32(v int32) *int32 {
359	return &v
360}
361
362// Int is a helper routine that allocates a new int32 value
363// to store v and returns a pointer to it, but unlike Int32
364// its argument value is an int.
365func Int(v int) *int32 {
366	p := new(int32)
367	*p = int32(v)
368	return p
369}
370
371// Int64 is a helper routine that allocates a new int64 value
372// to store v and returns a pointer to it.
373func Int64(v int64) *int64 {
374	return &v
375}
376
377// Float32 is a helper routine that allocates a new float32 value
378// to store v and returns a pointer to it.
379func Float32(v float32) *float32 {
380	return &v
381}
382
383// Float64 is a helper routine that allocates a new float64 value
384// to store v and returns a pointer to it.
385func Float64(v float64) *float64 {
386	return &v
387}
388
389// Uint32 is a helper routine that allocates a new uint32 value
390// to store v and returns a pointer to it.
391func Uint32(v uint32) *uint32 {
392	return &v
393}
394
395// Uint64 is a helper routine that allocates a new uint64 value
396// to store v and returns a pointer to it.
397func Uint64(v uint64) *uint64 {
398	return &v
399}
400
401// String is a helper routine that allocates a new string value
402// to store v and returns a pointer to it.
403func String(v string) *string {
404	return &v
405}
406
407// EnumName is a helper function to simplify printing protocol buffer enums
408// by name.  Given an enum map and a value, it returns a useful string.
409func EnumName(m map[int32]string, v int32) string {
410	s, ok := m[v]
411	if ok {
412		return s
413	}
414	return strconv.Itoa(int(v))
415}
416
417// UnmarshalJSONEnum is a helper function to simplify recovering enum int values
418// from their JSON-encoded representation. Given a map from the enum's symbolic
419// names to its int values, and a byte buffer containing the JSON-encoded
420// value, it returns an int32 that can be cast to the enum type by the caller.
421//
422// The function can deal with both JSON representations, numeric and symbolic.
423func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
424	if data[0] == '"' {
425		// New style: enums are strings.
426		var repr string
427		if err := json.Unmarshal(data, &repr); err != nil {
428			return -1, err
429		}
430		val, ok := m[repr]
431		if !ok {
432			return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
433		}
434		return val, nil
435	}
436	// Old style: enums are ints.
437	var val int32
438	if err := json.Unmarshal(data, &val); err != nil {
439		return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
440	}
441	return val, nil
442}
443
444// DebugPrint dumps the encoded data in b in a debugging format with a header
445// including the string s. Used in testing but made available for general debugging.
446func (p *Buffer) DebugPrint(s string, b []byte) {
447	var u uint64
448
449	obuf := p.buf
450	index := p.index
451	p.buf = b
452	p.index = 0
453	depth := 0
454
455	fmt.Printf("\n--- %s ---\n", s)
456
457out:
458	for {
459		for i := 0; i < depth; i++ {
460			fmt.Print("  ")
461		}
462
463		index := p.index
464		if index == len(p.buf) {
465			break
466		}
467
468		op, err := p.DecodeVarint()
469		if err != nil {
470			fmt.Printf("%3d: fetching op err %v\n", index, err)
471			break out
472		}
473		tag := op >> 3
474		wire := op & 7
475
476		switch wire {
477		default:
478			fmt.Printf("%3d: t=%3d unknown wire=%d\n",
479				index, tag, wire)
480			break out
481
482		case WireBytes:
483			var r []byte
484
485			r, err = p.DecodeRawBytes(false)
486			if err != nil {
487				break out
488			}
489			fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
490			if len(r) <= 6 {
491				for i := 0; i < len(r); i++ {
492					fmt.Printf(" %.2x", r[i])
493				}
494			} else {
495				for i := 0; i < 3; i++ {
496					fmt.Printf(" %.2x", r[i])
497				}
498				fmt.Printf(" ..")
499				for i := len(r) - 3; i < len(r); i++ {
500					fmt.Printf(" %.2x", r[i])
501				}
502			}
503			fmt.Printf("\n")
504
505		case WireFixed32:
506			u, err = p.DecodeFixed32()
507			if err != nil {
508				fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
509				break out
510			}
511			fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
512
513		case WireFixed64:
514			u, err = p.DecodeFixed64()
515			if err != nil {
516				fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
517				break out
518			}
519			fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
520
521		case WireVarint:
522			u, err = p.DecodeVarint()
523			if err != nil {
524				fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
525				break out
526			}
527			fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
528
529		case WireStartGroup:
530			fmt.Printf("%3d: t=%3d start\n", index, tag)
531			depth++
532
533		case WireEndGroup:
534			depth--
535			fmt.Printf("%3d: t=%3d end\n", index, tag)
536		}
537	}
538
539	if depth != 0 {
540		fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth)
541	}
542	fmt.Printf("\n")
543
544	p.buf = obuf
545	p.index = index
546}
547
548// SetDefaults sets unset protocol buffer fields to their default values.
549// It only modifies fields that are both unset and have defined defaults.
550// It recursively sets default values in any non-nil sub-messages.
551func SetDefaults(pb Message) {
552	setDefaults(reflect.ValueOf(pb), true, false)
553}
554
555// v is a pointer to a struct.
556func setDefaults(v reflect.Value, recur, zeros bool) {
557	v = v.Elem()
558
559	defaultMu.RLock()
560	dm, ok := defaults[v.Type()]
561	defaultMu.RUnlock()
562	if !ok {
563		dm = buildDefaultMessage(v.Type())
564		defaultMu.Lock()
565		defaults[v.Type()] = dm
566		defaultMu.Unlock()
567	}
568
569	for _, sf := range dm.scalars {
570		f := v.Field(sf.index)
571		if !f.IsNil() {
572			// field already set
573			continue
574		}
575		dv := sf.value
576		if dv == nil && !zeros {
577			// no explicit default, and don't want to set zeros
578			continue
579		}
580		fptr := f.Addr().Interface() // **T
581		// TODO: Consider batching the allocations we do here.
582		switch sf.kind {
583		case reflect.Bool:
584			b := new(bool)
585			if dv != nil {
586				*b = dv.(bool)
587			}
588			*(fptr.(**bool)) = b
589		case reflect.Float32:
590			f := new(float32)
591			if dv != nil {
592				*f = dv.(float32)
593			}
594			*(fptr.(**float32)) = f
595		case reflect.Float64:
596			f := new(float64)
597			if dv != nil {
598				*f = dv.(float64)
599			}
600			*(fptr.(**float64)) = f
601		case reflect.Int32:
602			// might be an enum
603			if ft := f.Type(); ft != int32PtrType {
604				// enum
605				f.Set(reflect.New(ft.Elem()))
606				if dv != nil {
607					f.Elem().SetInt(int64(dv.(int32)))
608				}
609			} else {
610				// int32 field
611				i := new(int32)
612				if dv != nil {
613					*i = dv.(int32)
614				}
615				*(fptr.(**int32)) = i
616			}
617		case reflect.Int64:
618			i := new(int64)
619			if dv != nil {
620				*i = dv.(int64)
621			}
622			*(fptr.(**int64)) = i
623		case reflect.String:
624			s := new(string)
625			if dv != nil {
626				*s = dv.(string)
627			}
628			*(fptr.(**string)) = s
629		case reflect.Uint8:
630			// exceptional case: []byte
631			var b []byte
632			if dv != nil {
633				db := dv.([]byte)
634				b = make([]byte, len(db))
635				copy(b, db)
636			} else {
637				b = []byte{}
638			}
639			*(fptr.(*[]byte)) = b
640		case reflect.Uint32:
641			u := new(uint32)
642			if dv != nil {
643				*u = dv.(uint32)
644			}
645			*(fptr.(**uint32)) = u
646		case reflect.Uint64:
647			u := new(uint64)
648			if dv != nil {
649				*u = dv.(uint64)
650			}
651			*(fptr.(**uint64)) = u
652		default:
653			log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
654		}
655	}
656
657	for _, ni := range dm.nested {
658		f := v.Field(ni)
659		// f is *T or []*T or map[T]*T
660		switch f.Kind() {
661		case reflect.Ptr:
662			if f.IsNil() {
663				continue
664			}
665			setDefaults(f, recur, zeros)
666
667		case reflect.Slice:
668			for i := 0; i < f.Len(); i++ {
669				e := f.Index(i)
670				if e.IsNil() {
671					continue
672				}
673				setDefaults(e, recur, zeros)
674			}
675
676		case reflect.Map:
677			for _, k := range f.MapKeys() {
678				e := f.MapIndex(k)
679				if e.IsNil() {
680					continue
681				}
682				setDefaults(e, recur, zeros)
683			}
684		}
685	}
686}
687
688var (
689	// defaults maps a protocol buffer struct type to a slice of the fields,
690	// with its scalar fields set to their proto-declared non-zero default values.
691	defaultMu sync.RWMutex
692	defaults  = make(map[reflect.Type]defaultMessage)
693
694	int32PtrType = reflect.TypeOf((*int32)(nil))
695)
696
697// defaultMessage represents information about the default values of a message.
698type defaultMessage struct {
699	scalars []scalarField
700	nested  []int // struct field index of nested messages
701}
702
703type scalarField struct {
704	index int          // struct field index
705	kind  reflect.Kind // element type (the T in *T or []T)
706	value interface{}  // the proto-declared default value, or nil
707}
708
709// t is a struct type.
710func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
711	sprop := GetProperties(t)
712	for _, prop := range sprop.Prop {
713		fi, ok := sprop.decoderTags.get(prop.Tag)
714		if !ok {
715			// XXX_unrecognized
716			continue
717		}
718		ft := t.Field(fi).Type
719
720		sf, nested, err := fieldDefault(ft, prop)
721		switch {
722		case err != nil:
723			log.Print(err)
724		case nested:
725			dm.nested = append(dm.nested, fi)
726		case sf != nil:
727			sf.index = fi
728			dm.scalars = append(dm.scalars, *sf)
729		}
730	}
731
732	return dm
733}
734
735// fieldDefault returns the scalarField for field type ft.
736// sf will be nil if the field can not have a default.
737// nestedMessage will be true if this is a nested message.
738// Note that sf.index is not set on return.
739func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) {
740	var canHaveDefault bool
741	switch ft.Kind() {
742	case reflect.Ptr:
743		if ft.Elem().Kind() == reflect.Struct {
744			nestedMessage = true
745		} else {
746			canHaveDefault = true // proto2 scalar field
747		}
748
749	case reflect.Slice:
750		switch ft.Elem().Kind() {
751		case reflect.Ptr:
752			nestedMessage = true // repeated message
753		case reflect.Uint8:
754			canHaveDefault = true // bytes field
755		}
756
757	case reflect.Map:
758		if ft.Elem().Kind() == reflect.Ptr {
759			nestedMessage = true // map with message values
760		}
761	}
762
763	if !canHaveDefault {
764		if nestedMessage {
765			return nil, true, nil
766		}
767		return nil, false, nil
768	}
769
770	// We now know that ft is a pointer or slice.
771	sf = &scalarField{kind: ft.Elem().Kind()}
772
773	// scalar fields without defaults
774	if !prop.HasDefault {
775		return sf, false, nil
776	}
777
778	// a scalar field: either *T or []byte
779	switch ft.Elem().Kind() {
780	case reflect.Bool:
781		x, err := strconv.ParseBool(prop.Default)
782		if err != nil {
783			return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err)
784		}
785		sf.value = x
786	case reflect.Float32:
787		x, err := strconv.ParseFloat(prop.Default, 32)
788		if err != nil {
789			return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err)
790		}
791		sf.value = float32(x)
792	case reflect.Float64:
793		x, err := strconv.ParseFloat(prop.Default, 64)
794		if err != nil {
795			return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err)
796		}
797		sf.value = x
798	case reflect.Int32:
799		x, err := strconv.ParseInt(prop.Default, 10, 32)
800		if err != nil {
801			return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err)
802		}
803		sf.value = int32(x)
804	case reflect.Int64:
805		x, err := strconv.ParseInt(prop.Default, 10, 64)
806		if err != nil {
807			return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err)
808		}
809		sf.value = x
810	case reflect.String:
811		sf.value = prop.Default
812	case reflect.Uint8:
813		// []byte (not *uint8)
814		sf.value = []byte(prop.Default)
815	case reflect.Uint32:
816		x, err := strconv.ParseUint(prop.Default, 10, 32)
817		if err != nil {
818			return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err)
819		}
820		sf.value = uint32(x)
821	case reflect.Uint64:
822		x, err := strconv.ParseUint(prop.Default, 10, 64)
823		if err != nil {
824			return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err)
825		}
826		sf.value = x
827	default:
828		return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind())
829	}
830
831	return sf, false, nil
832}
833
834// Map fields may have key types of non-float scalars, strings and enums.
835// The easiest way to sort them in some deterministic order is to use fmt.
836// If this turns out to be inefficient we can always consider other options,
837// such as doing a Schwartzian transform.
838
839func mapKeys(vs []reflect.Value) sort.Interface {
840	s := mapKeySorter{
841		vs: vs,
842		// default Less function: textual comparison
843		less: func(a, b reflect.Value) bool {
844			return fmt.Sprint(a.Interface()) < fmt.Sprint(b.Interface())
845		},
846	}
847
848	// Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps;
849	// numeric keys are sorted numerically.
850	if len(vs) == 0 {
851		return s
852	}
853	switch vs[0].Kind() {
854	case reflect.Int32, reflect.Int64:
855		s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
856	case reflect.Uint32, reflect.Uint64:
857		s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
858	}
859
860	return s
861}
862
863type mapKeySorter struct {
864	vs   []reflect.Value
865	less func(a, b reflect.Value) bool
866}
867
868func (s mapKeySorter) Len() int      { return len(s.vs) }
869func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
870func (s mapKeySorter) Less(i, j int) bool {
871	return s.less(s.vs[i], s.vs[j])
872}
873
874// isProto3Zero reports whether v is a zero proto3 value.
875func isProto3Zero(v reflect.Value) bool {
876	switch v.Kind() {
877	case reflect.Bool:
878		return !v.Bool()
879	case reflect.Int32, reflect.Int64:
880		return v.Int() == 0
881	case reflect.Uint32, reflect.Uint64:
882		return v.Uint() == 0
883	case reflect.Float32, reflect.Float64:
884		return v.Float() == 0
885	case reflect.String:
886		return v.String() == ""
887	}
888	return false
889}
890
891// ProtoPackageIsVersion2 is referenced from generated protocol buffer files
892// to assert that that code is compatible with this version of the proto package.
893const ProtoPackageIsVersion2 = true
894
895// ProtoPackageIsVersion1 is referenced from generated protocol buffer files
896// to assert that that code is compatible with this version of the proto package.
897const ProtoPackageIsVersion1 = true
898