1 // Go support for Protocol Buffers - Google's data interchange format
3 // Copyright 2010 The Go Authors. All rights reserved.
4 // https://github.com/golang/protobuf
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are
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
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.
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.
33 Package proto converts data structures to and from the wire format of
34 protocol buffers. It works in concert with the Go source code generated
35 for .proto files by the protocol compiler.
37 A summary of the properties of the protocol buffer interface
38 for a protocol buffer variable v:
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.
73 When the .proto file specifies `syntax="proto3"`, there are some differences:
75 - Non-repeated fields of non-message type are values instead of pointers.
76 - Enum types do not get an Enum method.
78 The simplest way to describe this is to see an example.
79 Given file test.proto, containing
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;
98 The resulting file, test.pb.go, is:
102 import proto "github.com/golang/protobuf/proto"
109 var FOO_name = map[int32]string{
112 var FOO_value = map[string]int32{
116 func (x FOO) Enum() *FOO {
121 func (x FOO) String() string {
122 return proto.EnumName(FOO_name, int32(x))
124 func (x *FOO) UnmarshalJSON(data []byte) error {
125 value, err := proto.UnmarshalJSONEnum(FOO_value, data)
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:
141 Union isTest_Union `protobuf_oneof:"union"`
142 XXX_unrecognized []byte `json:"-"`
144 func (m *Test) Reset() { *m = Test{} }
145 func (m *Test) String() string { return proto.CompactTextString(m) }
146 func (*Test) ProtoMessage() {}
148 type isTest_Union interface {
152 type Test_Number struct {
153 Number int32 `protobuf:"varint,6,opt,name=number"`
155 type Test_Name struct {
156 Name string `protobuf:"bytes,7,opt,name=name"`
159 func (*Test_Number) isTest_Union() {}
160 func (*Test_Name) isTest_Union() {}
162 func (m *Test) GetUnion() isTest_Union {
168 const Default_Test_Type int32 = 77
170 func (m *Test) GetLabel() string {
171 if m != nil && m.Label != nil {
177 func (m *Test) GetType() int32 {
178 if m != nil && m.Type != nil {
181 return Default_Test_Type
184 func (m *Test) GetOptionalgroup() *Test_OptionalGroup {
186 return m.Optionalgroup
191 type Test_OptionalGroup struct {
192 RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
194 func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} }
195 func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }
197 func (m *Test_OptionalGroup) GetRequiredField() string {
198 if m != nil && m.RequiredField != nil {
199 return *m.RequiredField
204 func (m *Test) GetNumber() int32 {
205 if x, ok := m.GetUnion().(*Test_Number); ok {
211 func (m *Test) GetName() string {
212 if x, ok := m.GetUnion().(*Test_Name); ok {
219 proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
222 To create and play with a Test object:
229 "github.com/golang/protobuf/proto"
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"),
241 Union: &pb.Test_Name{"fred"},
243 data, err := proto.Marshal(test)
245 log.Fatal("marshaling error: ", err)
247 newTest := &pb.Test{}
248 err = proto.Unmarshal(data, newTest)
250 log.Fatal("unmarshaling error: ", err)
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())
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.
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.
279 type RequiredNotSetError struct{ field string }
281 func (e *RequiredNotSetError) Error() string {
283 return fmt.Sprintf("proto: required field not set")
285 return fmt.Sprintf("proto: required field %q not set", e.field)
287 func (e *RequiredNotSetError) RequiredNotSet() bool {
291 type invalidUTF8Error struct{ field string }
293 func (e *invalidUTF8Error) Error() string {
295 return "proto: invalid UTF-8 detected"
297 return fmt.Sprintf("proto: field %q contains invalid UTF-8", e.field)
299 func (e *invalidUTF8Error) InvalidUTF8() bool {
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.
306 var errInvalidUTF8 = &invalidUTF8Error{}
308 // isNonFatal reports whether the error is either a RequiredNotSet error
309 // or a InvalidUTF8 error.
310 func isNonFatal(err error) bool {
311 if re, ok := err.(interface{ RequiredNotSet() bool }); ok && re.RequiredNotSet() {
314 if re, ok := err.(interface{ InvalidUTF8() bool }); ok && re.InvalidUTF8() {
320 type nonFatal struct{ E error }
322 // Merge merges err into nf and reports whether it was successful.
323 // Otherwise it returns false for any fatal non-nil errors.
324 func (nf *nonFatal) Merge(err error) (ok bool) {
326 return true // not an error
328 if !isNonFatal(err) {
329 return false // fatal error
332 nf.E = err // store first instance of non-fatal error
337 // Message is implemented by generated protocol buffer messages.
338 type Message interface {
344 // Stats records allocation details about the protocol buffer encoders
345 // and decoders. Useful for tuning the library itself.
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
356 // Set to true to enable stats collection.
357 const collectStats = false
361 // GetStats returns a copy of the global Stats structure.
362 func GetStats() Stats { return stats }
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.
370 buf []byte // encode/decode byte stream
371 index int // read point
376 // NewBuffer allocates a new Buffer and initializes its internal data to
377 // the contents of the argument slice.
378 func NewBuffer(e []byte) *Buffer {
379 return &Buffer{buf: e}
382 // Reset resets the Buffer, ready for marshaling a new protocol buffer.
383 func (p *Buffer) Reset() {
384 p.buf = p.buf[0:0] // for reading/writing
385 p.index = 0 // for reading
388 // SetBuf replaces the internal buffer with the slice,
389 // ready for unmarshaling the contents of the slice.
390 func (p *Buffer) SetBuf(s []byte) {
395 // Bytes returns the contents of the Buffer.
396 func (p *Buffer) Bytes() []byte { return p.buf }
398 // SetDeterministic sets whether to use deterministic serialization.
400 // Deterministic serialization guarantees that for a given binary, equal
401 // messages will always be serialized to the same bytes. This implies:
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.
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.
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.
418 func (p *Buffer) SetDeterministic(deterministic bool) {
419 p.deterministic = deterministic
423 * Helper routines for simplifying the creation of optional fields of basic type.
426 // Bool is a helper routine that allocates a new bool value
427 // to store v and returns a pointer to it.
428 func Bool(v bool) *bool {
432 // Int32 is a helper routine that allocates a new int32 value
433 // to store v and returns a pointer to it.
434 func Int32(v int32) *int32 {
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.
441 func Int(v int) *int32 {
447 // Int64 is a helper routine that allocates a new int64 value
448 // to store v and returns a pointer to it.
449 func Int64(v int64) *int64 {
453 // Float32 is a helper routine that allocates a new float32 value
454 // to store v and returns a pointer to it.
455 func Float32(v float32) *float32 {
459 // Float64 is a helper routine that allocates a new float64 value
460 // to store v and returns a pointer to it.
461 func Float64(v float64) *float64 {
465 // Uint32 is a helper routine that allocates a new uint32 value
466 // to store v and returns a pointer to it.
467 func Uint32(v uint32) *uint32 {
471 // Uint64 is a helper routine that allocates a new uint64 value
472 // to store v and returns a pointer to it.
473 func Uint64(v uint64) *uint64 {
477 // String is a helper routine that allocates a new string value
478 // to store v and returns a pointer to it.
479 func String(v string) *string {
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.
485 func EnumName(m map[int32]string, v int32) string {
490 return strconv.Itoa(int(v))
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.
498 // The function can deal with both JSON representations, numeric and symbolic.
499 func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
501 // New style: enums are strings.
503 if err := json.Unmarshal(data, &repr); err != nil {
508 return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
512 // Old style: enums are ints.
514 if err := json.Unmarshal(data, &val); err != nil {
515 return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
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.
522 func (p *Buffer) DebugPrint(s string, b []byte) {
531 fmt.Printf("\n--- %s ---\n", s)
535 for i := 0; i < depth; i++ {
540 if index == len(p.buf) {
544 op, err := p.DecodeVarint()
546 fmt.Printf("%3d: fetching op err %v\n", index, err)
554 fmt.Printf("%3d: t=%3d unknown wire=%d\n",
561 r, err = p.DecodeRawBytes(false)
565 fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
567 for i := 0; i < len(r); i++ {
568 fmt.Printf(" %.2x", r[i])
571 for i := 0; i < 3; i++ {
572 fmt.Printf(" %.2x", r[i])
575 for i := len(r) - 3; i < len(r); i++ {
576 fmt.Printf(" %.2x", r[i])
582 u, err = p.DecodeFixed32()
584 fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
587 fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
590 u, err = p.DecodeFixed64()
592 fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
595 fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
598 u, err = p.DecodeVarint()
600 fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
603 fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
606 fmt.Printf("%3d: t=%3d start\n", index, tag)
611 fmt.Printf("%3d: t=%3d end\n", index, tag)
616 fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth)
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.
627 func SetDefaults(pb Message) {
628 setDefaults(reflect.ValueOf(pb), true, false)
631 // v is a pointer to a struct.
632 func setDefaults(v reflect.Value, recur, zeros bool) {
636 dm, ok := defaults[v.Type()]
639 dm = buildDefaultMessage(v.Type())
641 defaults[v.Type()] = dm
645 for _, sf := range dm.scalars {
646 f := v.Field(sf.index)
652 if dv == nil && !zeros {
653 // no explicit default, and don't want to set zeros
656 fptr := f.Addr().Interface() // **T
657 // TODO: Consider batching the allocations we do here.
665 case reflect.Float32:
670 *(fptr.(**float32)) = f
671 case reflect.Float64:
676 *(fptr.(**float64)) = f
679 if ft := f.Type(); ft != int32PtrType {
681 f.Set(reflect.New(ft.Elem()))
683 f.Elem().SetInt(int64(dv.(int32)))
691 *(fptr.(**int32)) = i
698 *(fptr.(**int64)) = i
704 *(fptr.(**string)) = s
706 // exceptional case: []byte
710 b = make([]byte, len(db))
715 *(fptr.(*[]byte)) = b
721 *(fptr.(**uint32)) = u
727 *(fptr.(**uint64)) = u
729 log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
733 for _, ni := range dm.nested {
735 // f is *T or []*T or map[T]*T
741 setDefaults(f, recur, zeros)
744 for i := 0; i < f.Len(); i++ {
749 setDefaults(e, recur, zeros)
753 for _, k := range f.MapKeys() {
758 setDefaults(e, recur, zeros)
765 // defaults maps a protocol buffer struct type to a slice of the fields,
766 // with its scalar fields set to their proto-declared non-zero default values.
767 defaultMu sync.RWMutex
768 defaults = make(map[reflect.Type]defaultMessage)
770 int32PtrType = reflect.TypeOf((*int32)(nil))
773 // defaultMessage represents information about the default values of a message.
774 type defaultMessage struct {
775 scalars []scalarField
776 nested []int // struct field index of nested messages
779 type scalarField struct {
780 index int // struct field index
781 kind reflect.Kind // element type (the T in *T or []T)
782 value interface{} // the proto-declared default value, or nil
785 // t is a struct type.
786 func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
787 sprop := GetProperties(t)
788 for _, prop := range sprop.Prop {
789 fi, ok := sprop.decoderTags.get(prop.Tag)
794 ft := t.Field(fi).Type
796 sf, nested, err := fieldDefault(ft, prop)
801 dm.nested = append(dm.nested, fi)
804 dm.scalars = append(dm.scalars, *sf)
811 // fieldDefault returns the scalarField for field type ft.
812 // sf will be nil if the field can not have a default.
813 // nestedMessage will be true if this is a nested message.
814 // Note that sf.index is not set on return.
815 func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) {
816 var canHaveDefault bool
819 if ft.Elem().Kind() == reflect.Struct {
822 canHaveDefault = true // proto2 scalar field
826 switch ft.Elem().Kind() {
828 nestedMessage = true // repeated message
830 canHaveDefault = true // bytes field
834 if ft.Elem().Kind() == reflect.Ptr {
835 nestedMessage = true // map with message values
841 return nil, true, nil
843 return nil, false, nil
846 // We now know that ft is a pointer or slice.
847 sf = &scalarField{kind: ft.Elem().Kind()}
849 // scalar fields without defaults
850 if !prop.HasDefault {
851 return sf, false, nil
854 // a scalar field: either *T or []byte
855 switch ft.Elem().Kind() {
857 x, err := strconv.ParseBool(prop.Default)
859 return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err)
862 case reflect.Float32:
863 x, err := strconv.ParseFloat(prop.Default, 32)
865 return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err)
867 sf.value = float32(x)
868 case reflect.Float64:
869 x, err := strconv.ParseFloat(prop.Default, 64)
871 return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err)
875 x, err := strconv.ParseInt(prop.Default, 10, 32)
877 return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err)
881 x, err := strconv.ParseInt(prop.Default, 10, 64)
883 return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err)
887 sf.value = prop.Default
889 // []byte (not *uint8)
890 sf.value = []byte(prop.Default)
892 x, err := strconv.ParseUint(prop.Default, 10, 32)
894 return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err)
898 x, err := strconv.ParseUint(prop.Default, 10, 64)
900 return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err)
904 return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind())
907 return sf, false, nil
910 // mapKeys returns a sort.Interface to be used for sorting the map keys.
911 // Map fields may have key types of non-float scalars, strings and enums.
912 func mapKeys(vs []reflect.Value) sort.Interface {
913 s := mapKeySorter{vs: vs}
915 // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps.
919 switch vs[0].Kind() {
920 case reflect.Int32, reflect.Int64:
921 s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
922 case reflect.Uint32, reflect.Uint64:
923 s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
925 s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true
927 s.less = func(a, b reflect.Value) bool { return a.String() < b.String() }
929 panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind()))
935 type mapKeySorter struct {
937 less func(a, b reflect.Value) bool
940 func (s mapKeySorter) Len() int { return len(s.vs) }
941 func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
942 func (s mapKeySorter) Less(i, j int) bool {
943 return s.less(s.vs[i], s.vs[j])
946 // isProto3Zero reports whether v is a zero proto3 value.
947 func isProto3Zero(v reflect.Value) bool {
951 case reflect.Int32, reflect.Int64:
953 case reflect.Uint32, reflect.Uint64:
955 case reflect.Float32, reflect.Float64:
956 return v.Float() == 0
958 return v.String() == ""
963 // ProtoPackageIsVersion2 is referenced from generated protocol buffer files
964 // to assert that that code is compatible with this version of the proto package.
965 const ProtoPackageIsVersion2 = true
967 // ProtoPackageIsVersion1 is referenced from generated protocol buffer files
968 // to assert that that code is compatible with this version of the proto package.
969 const ProtoPackageIsVersion1 = true
971 // InternalMessageInfo is a type used internally by generated .pb.go files.
972 // This type is not intended to be used by non-generated code.
973 // This type is not subject to any compatibility guarantee.
974 type InternalMessageInfo struct {
976 unmarshal *unmarshalInfo