1 // Protocol Buffers for Go with Gadgets
3 // Copyright (c) 2013, The GoGo Authors. All rights reserved.
4 // http://github.com/gogo/protobuf
6 // Go support for Protocol Buffers - Google's data interchange format
8 // Copyright 2010 The Go Authors. All rights reserved.
9 // https://github.com/golang/protobuf
11 // Redistribution and use in source and binary forms, with or without
12 // modification, are permitted provided that the following conditions are
15 // * Redistributions of source code must retain the above copyright
16 // notice, this list of conditions and the following disclaimer.
17 // * Redistributions in binary form must reproduce the above
18 // copyright notice, this list of conditions and the following disclaimer
19 // in the documentation and/or other materials provided with the
21 // * Neither the name of Google Inc. nor the names of its
22 // contributors may be used to endorse or promote products derived from
23 // this software without specific prior written permission.
25 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 * Routines for encoding data into the wire format for protocol buffers.
54 const debug bool = false
56 // Constants that identify the encoding of a value on the wire.
66 // tagMap is an optimization over map[int]int for typical protocol buffer
67 // use-cases. Encoded protocol buffers are often in tag order with small tag
74 // tagMapFastLimit is the upper bound on the tag number that will be stored in
75 // the tagMap slice rather than its map.
76 const tagMapFastLimit = 1024
78 func (p *tagMap) get(t int) (int, bool) {
79 if t > 0 && t < tagMapFastLimit {
80 if t >= len(p.fastTags) {
86 fi, ok := p.slowTags[t]
90 func (p *tagMap) put(t int, fi int) {
91 if t > 0 && t < tagMapFastLimit {
92 for len(p.fastTags) < t+1 {
93 p.fastTags = append(p.fastTags, -1)
98 if p.slowTags == nil {
99 p.slowTags = make(map[int]int)
104 // StructProperties represents properties for all the fields of a struct.
105 // decoderTags and decoderOrigNames should only be used by the decoder.
106 type StructProperties struct {
107 Prop []*Properties // properties for each field
108 reqCount int // required count
109 decoderTags tagMap // map from proto tag to struct field number
110 decoderOrigNames map[string]int // map from original name to struct field number
111 order []int // list of struct field numbers in tag order
113 // OneofTypes contains information about the oneof fields in this message.
114 // It is keyed by the original name of a field.
115 OneofTypes map[string]*OneofProperties
118 // OneofProperties represents information about a specific field in a oneof.
119 type OneofProperties struct {
120 Type reflect.Type // pointer to generated struct type for this oneof field
121 Field int // struct field number of the containing oneof in the message
125 // Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec.
126 // See encode.go, (*Buffer).enc_struct.
128 func (sp *StructProperties) Len() int { return len(sp.order) }
129 func (sp *StructProperties) Less(i, j int) bool {
130 return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag
132 func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] }
134 // Properties represents the protocol-specific behavior of a single struct field.
135 type Properties struct {
136 Name string // name of the field, for error messages
137 OrigName string // original name before protocol compiler (always set)
138 JSONName string // name to use for JSON; determined by protoc
145 Packed bool // relevant for repeated primitives only
146 Enum string // set for enum types only
147 proto3 bool // whether this is known to be a proto3 field
148 oneof bool // whether this is a oneof field
150 Default string // default value
151 HasDefault bool // whether an explicit default was provided
158 stype reflect.Type // set for struct types only
159 ctype reflect.Type // set for custom types only
160 sprop *StructProperties // set for struct types only
162 mtype reflect.Type // set for map types only
163 MapKeyProp *Properties // set for map types only
164 MapValProp *Properties // set for map types only
167 // String formats the properties in the protobuf struct field tag style.
168 func (p *Properties) String() string {
171 s += strconv.Itoa(p.Tag)
184 s += ",name=" + p.OrigName
185 if p.JSONName != p.OrigName {
186 s += ",json=" + p.JSONName
195 s += ",enum=" + p.Enum
198 s += ",def=" + p.Default
203 // Parse populates p by parsing a string in the protobuf struct field tag style.
204 func (p *Properties) Parse(s string) {
205 // "bytes,49,opt,name=foo,def=hello!"
206 fields := strings.Split(s, ",") // breaks def=, but handled below.
208 fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s)
215 p.WireType = WireVarint
217 p.WireType = WireFixed32
219 p.WireType = WireFixed64
221 p.WireType = WireVarint
223 p.WireType = WireVarint
224 case "bytes", "group":
225 p.WireType = WireBytes
226 // no numeric converter for non-numeric types
228 fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s)
233 p.Tag, err = strconv.Atoi(fields[1])
239 for i := 2; i < len(fields); i++ {
250 case strings.HasPrefix(f, "name="):
252 case strings.HasPrefix(f, "json="):
254 case strings.HasPrefix(f, "enum="):
260 case strings.HasPrefix(f, "def="):
262 p.Default = f[4:] // rest of string
263 if i+1 < len(fields) {
264 // Commas aren't escaped, and def is always last.
265 p.Default += "," + strings.Join(fields[i+1:], ",")
268 case strings.HasPrefix(f, "embedded="):
269 p.OrigName = strings.Split(f, "=")[1]
270 case strings.HasPrefix(f, "customtype="):
271 p.CustomType = strings.Split(f, "=")[1]
272 case strings.HasPrefix(f, "casttype="):
273 p.CastType = strings.Split(f, "=")[1]
276 case f == "stdduration":
284 var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem()
286 // setFieldProps initializes the field properties for submessages and maps.
287 func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) {
288 isMap := typ.Kind() == reflect.Map
289 if len(p.CustomType) > 0 && !isMap {
291 p.setTag(lockGetProp)
294 if p.StdTime && !isMap {
295 p.setTag(lockGetProp)
298 if p.StdDuration && !isMap {
299 p.setTag(lockGetProp)
302 if p.WktPointer && !isMap {
303 p.setTag(lockGetProp)
306 switch t1 := typ; t1.Kind() {
310 if t1.Elem().Kind() == reflect.Struct {
314 switch t2 := t1.Elem(); t2.Kind() {
316 switch t3 := t2.Elem(); t3.Kind() {
327 p.MapKeyProp = &Properties{}
328 p.MapKeyProp.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp)
329 p.MapValProp = &Properties{}
330 vtype := p.mtype.Elem()
331 if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice {
332 // The value type is not a message (*T) or bytes ([]byte),
333 // so we need encoders for the pointer to this type.
334 vtype = reflect.PtrTo(vtype)
337 p.MapValProp.CustomType = p.CustomType
338 p.MapValProp.StdDuration = p.StdDuration
339 p.MapValProp.StdTime = p.StdTime
340 p.MapValProp.WktPointer = p.WktPointer
341 p.MapValProp.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp)
343 p.setTag(lockGetProp)
346 func (p *Properties) setTag(lockGetProp bool) {
349 p.sprop = GetProperties(p.stype)
351 p.sprop = getPropertiesLocked(p.stype)
357 marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
360 // Init populates the properties from a protocol buffer struct tag.
361 func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) {
362 p.init(typ, name, tag, f, true)
365 func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) {
366 // "bytes,49,opt,def=hello!"
373 p.setFieldProps(typ, f, lockGetProp)
377 propertiesMu sync.RWMutex
378 propertiesMap = make(map[reflect.Type]*StructProperties)
381 // GetProperties returns the list of properties for the type represented by t.
382 // t must represent a generated struct type of a protocol message.
383 func GetProperties(t reflect.Type) *StructProperties {
384 if t.Kind() != reflect.Struct {
385 panic("proto: type must have kind struct")
388 // Most calls to GetProperties in a long-running program will be
389 // retrieving details for types we have seen before.
391 sprop, ok := propertiesMap[t]
392 propertiesMu.RUnlock()
398 sprop = getPropertiesLocked(t)
399 propertiesMu.Unlock()
403 // getPropertiesLocked requires that propertiesMu is held.
404 func getPropertiesLocked(t reflect.Type) *StructProperties {
405 if prop, ok := propertiesMap[t]; ok {
409 prop := new(StructProperties)
410 // in case of recursive protos, fill this in now.
411 propertiesMap[t] = prop
414 prop.Prop = make([]*Properties, t.NumField())
415 prop.order = make([]int, t.NumField())
417 isOneofMessage := false
418 for i := 0; i < t.NumField(); i++ {
422 p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false)
424 oneof := f.Tag.Get("protobuf_oneof") // special case
426 isOneofMessage = true
427 // Oneof fields don't use the traditional protobuf tag.
433 print(i, " ", f.Name, " ", t.String(), " ")
441 // Re-order prop.order.
444 type oneofMessage interface {
445 XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
447 if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); isOneofMessage && ok {
448 var oots []interface{}
449 _, _, _, oots = om.XXX_OneofFuncs()
451 // Interpret oneof metadata.
452 prop.OneofTypes = make(map[string]*OneofProperties)
453 for _, oot := range oots {
454 oop := &OneofProperties{
455 Type: reflect.ValueOf(oot).Type(), // *T
456 Prop: new(Properties),
458 sft := oop.Type.Elem().Field(0)
459 oop.Prop.Name = sft.Name
460 oop.Prop.Parse(sft.Tag.Get("protobuf"))
461 // There will be exactly one interface field that
462 // this new value is assignable to.
463 for i := 0; i < t.NumField(); i++ {
465 if f.Type.Kind() != reflect.Interface {
468 if !oop.Type.AssignableTo(f.Type) {
474 prop.OneofTypes[oop.Prop.OrigName] = oop
478 // build required counts
481 prop.decoderOrigNames = make(map[string]int)
482 for i, p := range prop.Prop {
483 if strings.HasPrefix(p.Name, "XXX_") {
484 // Internal fields should not appear in tags/origNames maps.
485 // They are handled specially when encoding and decoding.
491 prop.decoderTags.put(p.Tag, i)
492 prop.decoderOrigNames[p.OrigName] = i
494 prop.reqCount = reqCount
499 // A global registry of enum types.
500 // The generated code will register the generated maps by calling RegisterEnum.
502 var enumValueMaps = make(map[string]map[string]int32)
503 var enumStringMaps = make(map[string]map[int32]string)
505 // RegisterEnum is called from the generated code to install the enum descriptor
506 // maps into the global table to aid parsing text format protocol buffers.
507 func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) {
508 if _, ok := enumValueMaps[typeName]; ok {
509 panic("proto: duplicate enum registered: " + typeName)
511 enumValueMaps[typeName] = valueMap
512 if _, ok := enumStringMaps[typeName]; ok {
513 panic("proto: duplicate enum registered: " + typeName)
515 enumStringMaps[typeName] = unusedNameMap
518 // EnumValueMap returns the mapping from names to integers of the
519 // enum type enumType, or a nil if not found.
520 func EnumValueMap(enumType string) map[string]int32 {
521 return enumValueMaps[enumType]
524 // A registry of all linked message types.
525 // The string is a fully-qualified proto name ("pkg.Message").
527 protoTypedNils = make(map[string]Message) // a map from proto names to typed nil pointers
528 protoMapTypes = make(map[string]reflect.Type) // a map from proto names to map types
529 revProtoTypes = make(map[reflect.Type]string)
532 // RegisterType is called from generated code and maps from the fully qualified
533 // proto name to the type (pointer to struct) of the protocol buffer.
534 func RegisterType(x Message, name string) {
535 if _, ok := protoTypedNils[name]; ok {
536 // TODO: Some day, make this a panic.
537 log.Printf("proto: duplicate proto type registered: %s", name)
540 t := reflect.TypeOf(x)
541 if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 {
542 // Generated code always calls RegisterType with nil x.
543 // This check is just for extra safety.
544 protoTypedNils[name] = x
546 protoTypedNils[name] = reflect.Zero(t).Interface().(Message)
548 revProtoTypes[t] = name
551 // RegisterMapType is called from generated code and maps from the fully qualified
552 // proto name to the native map type of the proto map definition.
553 func RegisterMapType(x interface{}, name string) {
554 if reflect.TypeOf(x).Kind() != reflect.Map {
555 panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name))
557 if _, ok := protoMapTypes[name]; ok {
558 log.Printf("proto: duplicate proto type registered: %s", name)
561 t := reflect.TypeOf(x)
562 protoMapTypes[name] = t
563 revProtoTypes[t] = name
566 // MessageName returns the fully-qualified proto name for the given message type.
567 func MessageName(x Message) string {
568 type xname interface {
569 XXX_MessageName() string
571 if m, ok := x.(xname); ok {
572 return m.XXX_MessageName()
574 return revProtoTypes[reflect.TypeOf(x)]
577 // MessageType returns the message type (pointer to struct) for a named message.
578 // The type is not guaranteed to implement proto.Message if the name refers to a
580 func MessageType(name string) reflect.Type {
581 if t, ok := protoTypedNils[name]; ok {
582 return reflect.TypeOf(t)
584 return protoMapTypes[name]
587 // A registry of all linked proto files.
589 protoFiles = make(map[string][]byte) // file name => fileDescriptor
592 // RegisterFile is called from generated code and maps from the
593 // full file name of a .proto file to its compressed FileDescriptorProto.
594 func RegisterFile(filename string, fileDescriptor []byte) {
595 protoFiles[filename] = fileDescriptor
598 // FileDescriptor returns the compressed FileDescriptorProto for a .proto file.
599 func FileDescriptor(filename string) []byte { return protoFiles[filename] }