blob: ac7e52f0fcb62b3de72e6730f16d4dcb5882635e [file] [log] [blame]
Zack Williamse940c7a2019-08-21 14:25:39 -07001package dynamic
2
3import (
4 "bytes"
5 "compress/gzip"
6 "errors"
7 "fmt"
8 "reflect"
9 "sort"
10 "strings"
11
12 "github.com/golang/protobuf/proto"
13 "github.com/golang/protobuf/protoc-gen-go/descriptor"
14
15 "github.com/jhump/protoreflect/desc"
16)
17
18// ErrUnknownTagNumber is an error that is returned when an operation refers
19// to an unknown tag number.
20var ErrUnknownTagNumber = errors.New("unknown tag number")
21
22// UnknownTagNumberError is the same as ErrUnknownTagNumber.
23// Deprecated: use ErrUnknownTagNumber
24var UnknownTagNumberError = ErrUnknownTagNumber
25
26// ErrUnknownFieldName is an error that is returned when an operation refers
27// to an unknown field name.
28var ErrUnknownFieldName = errors.New("unknown field name")
29
30// UnknownFieldNameError is the same as ErrUnknownFieldName.
31// Deprecated: use ErrUnknownFieldName
32var UnknownFieldNameError = ErrUnknownFieldName
33
34// ErrFieldIsNotMap is an error that is returned when map-related operations
35// are attempted with fields that are not maps.
36var ErrFieldIsNotMap = errors.New("field is not a map type")
37
38// FieldIsNotMapError is the same as ErrFieldIsNotMap.
39// Deprecated: use ErrFieldIsNotMap
40var FieldIsNotMapError = ErrFieldIsNotMap
41
42// ErrFieldIsNotRepeated is an error that is returned when repeated field
43// operations are attempted with fields that are not repeated.
44var ErrFieldIsNotRepeated = errors.New("field is not repeated")
45
46// FieldIsNotRepeatedError is the same as ErrFieldIsNotRepeated.
47// Deprecated: use ErrFieldIsNotRepeated
48var FieldIsNotRepeatedError = ErrFieldIsNotRepeated
49
50// ErrIndexOutOfRange is an error that is returned when an invalid index is
51// provided when access a single element of a repeated field.
52var ErrIndexOutOfRange = errors.New("index is out of range")
53
54// IndexOutOfRangeError is the same as ErrIndexOutOfRange.
55// Deprecated: use ErrIndexOutOfRange
56var IndexOutOfRangeError = ErrIndexOutOfRange
57
58// ErrNumericOverflow is an error returned by operations that encounter a
59// numeric value that is too large, for example de-serializing a value into an
60// int32 field when the value is larger that can fit into a 32-bit value.
61var ErrNumericOverflow = errors.New("numeric value is out of range")
62
63// NumericOverflowError is the same as ErrNumericOverflow.
64// Deprecated: use ErrNumericOverflow
65var NumericOverflowError = ErrNumericOverflow
66
67var typeOfProtoMessage = reflect.TypeOf((*proto.Message)(nil)).Elem()
68var typeOfDynamicMessage = reflect.TypeOf((*Message)(nil))
69var typeOfBytes = reflect.TypeOf(([]byte)(nil))
70
71var varintTypes = map[descriptor.FieldDescriptorProto_Type]bool{}
72var fixed32Types = map[descriptor.FieldDescriptorProto_Type]bool{}
73var fixed64Types = map[descriptor.FieldDescriptorProto_Type]bool{}
74
75func init() {
76 varintTypes[descriptor.FieldDescriptorProto_TYPE_BOOL] = true
77 varintTypes[descriptor.FieldDescriptorProto_TYPE_INT32] = true
78 varintTypes[descriptor.FieldDescriptorProto_TYPE_INT64] = true
79 varintTypes[descriptor.FieldDescriptorProto_TYPE_UINT32] = true
80 varintTypes[descriptor.FieldDescriptorProto_TYPE_UINT64] = true
81 varintTypes[descriptor.FieldDescriptorProto_TYPE_SINT32] = true
82 varintTypes[descriptor.FieldDescriptorProto_TYPE_SINT64] = true
83 varintTypes[descriptor.FieldDescriptorProto_TYPE_ENUM] = true
84
85 fixed32Types[descriptor.FieldDescriptorProto_TYPE_FIXED32] = true
86 fixed32Types[descriptor.FieldDescriptorProto_TYPE_SFIXED32] = true
87 fixed32Types[descriptor.FieldDescriptorProto_TYPE_FLOAT] = true
88
89 fixed64Types[descriptor.FieldDescriptorProto_TYPE_FIXED64] = true
90 fixed64Types[descriptor.FieldDescriptorProto_TYPE_SFIXED64] = true
91 fixed64Types[descriptor.FieldDescriptorProto_TYPE_DOUBLE] = true
92}
93
94// Message is a dynamic protobuf message. Instead of a generated struct,
95// like most protobuf messages, this is a map of field number to values and
96// a message descriptor, which is used to validate the field values and
97// also to de-serialize messages (from the standard binary format, as well
98// as from the text format and from JSON).
99type Message struct {
100 md *desc.MessageDescriptor
101 er *ExtensionRegistry
102 mf *MessageFactory
103 extraFields map[int32]*desc.FieldDescriptor
104 values map[int32]interface{}
105 unknownFields map[int32][]UnknownField
106}
107
108// UnknownField represents a field that was parsed from the binary wire
109// format for a message, but was not a recognized field number. Enough
110// information is preserved so that re-serializing the message won't lose
111// any of the unrecognized data.
112type UnknownField struct {
113 // Encoding indicates how the unknown field was encoded on the wire. If it
114 // is proto.WireBytes or proto.WireGroupStart then Contents will be set to
115 // the raw bytes. If it is proto.WireTypeFixed32 then the data is in the least
116 // significant 32 bits of Value. Otherwise, the data is in all 64 bits of
117 // Value.
118 Encoding int8
119 Contents []byte
120 Value uint64
121}
122
123// NewMessage creates a new dynamic message for the type represented by the given
124// message descriptor. During de-serialization, a default MessageFactory is used to
125// instantiate any nested message fields and no extension fields will be parsed. To
126// use a custom MessageFactory or ExtensionRegistry, use MessageFactory.NewMessage.
127func NewMessage(md *desc.MessageDescriptor) *Message {
128 return NewMessageWithMessageFactory(md, nil)
129}
130
131// NewMessageWithExtensionRegistry creates a new dynamic message for the type
132// represented by the given message descriptor. During de-serialization, the given
133// ExtensionRegistry is used to parse extension fields and nested messages will be
134// instantiated using dynamic.NewMessageFactoryWithExtensionRegistry(er).
135func NewMessageWithExtensionRegistry(md *desc.MessageDescriptor, er *ExtensionRegistry) *Message {
136 mf := NewMessageFactoryWithExtensionRegistry(er)
137 return NewMessageWithMessageFactory(md, mf)
138}
139
140// NewMessageWithMessageFactory creates a new dynamic message for the type
141// represented by the given message descriptor. During de-serialization, the given
142// MessageFactory is used to instantiate nested messages.
143func NewMessageWithMessageFactory(md *desc.MessageDescriptor, mf *MessageFactory) *Message {
144 var er *ExtensionRegistry
145 if mf != nil {
146 er = mf.er
147 }
148 return &Message{
149 md: md,
150 mf: mf,
151 er: er,
152 }
153}
154
155// AsDynamicMessage converts the given message to a dynamic message. If the
156// given message is dynamic, it is returned. Otherwise, a dynamic message is
157// created using NewMessage.
158func AsDynamicMessage(msg proto.Message) (*Message, error) {
159 return AsDynamicMessageWithMessageFactory(msg, nil)
160}
161
162// AsDynamicMessageWithExtensionRegistry converts the given message to a dynamic
163// message. If the given message is dynamic, it is returned. Otherwise, a
164// dynamic message is created using NewMessageWithExtensionRegistry.
165func AsDynamicMessageWithExtensionRegistry(msg proto.Message, er *ExtensionRegistry) (*Message, error) {
166 mf := NewMessageFactoryWithExtensionRegistry(er)
167 return AsDynamicMessageWithMessageFactory(msg, mf)
168}
169
170// AsDynamicMessageWithMessageFactory converts the given message to a dynamic
171// message. If the given message is dynamic, it is returned. Otherwise, a
172// dynamic message is created using NewMessageWithMessageFactory.
173func AsDynamicMessageWithMessageFactory(msg proto.Message, mf *MessageFactory) (*Message, error) {
174 if dm, ok := msg.(*Message); ok {
175 return dm, nil
176 }
177 md, err := desc.LoadMessageDescriptorForMessage(msg)
178 if err != nil {
179 return nil, err
180 }
181 dm := NewMessageWithMessageFactory(md, mf)
182 err = dm.mergeFrom(msg)
183 if err != nil {
184 return nil, err
185 }
186 return dm, nil
187}
188
189// GetMessageDescriptor returns a descriptor for this message's type.
190func (m *Message) GetMessageDescriptor() *desc.MessageDescriptor {
191 return m.md
192}
193
194// GetKnownFields returns a slice of descriptors for all known fields. The
195// fields will not be in any defined order.
196func (m *Message) GetKnownFields() []*desc.FieldDescriptor {
197 if len(m.extraFields) == 0 {
198 return m.md.GetFields()
199 }
200 flds := make([]*desc.FieldDescriptor, len(m.md.GetFields()), len(m.md.GetFields())+len(m.extraFields))
201 copy(flds, m.md.GetFields())
202 for _, fld := range m.extraFields {
203 if !fld.IsExtension() {
204 flds = append(flds, fld)
205 }
206 }
207 return flds
208}
209
210// GetKnownExtensions returns a slice of descriptors for all extensions known by
211// the message's extension registry. The fields will not be in any defined order.
212func (m *Message) GetKnownExtensions() []*desc.FieldDescriptor {
213 if !m.md.IsExtendable() {
214 return nil
215 }
216 exts := m.er.AllExtensionsForType(m.md.GetFullyQualifiedName())
217 for _, fld := range m.extraFields {
218 if fld.IsExtension() {
219 exts = append(exts, fld)
220 }
221 }
222 return exts
223}
224
225// GetUnknownFields returns a slice of tag numbers for all unknown fields that
226// this message contains. The tags will not be in any defined order.
227func (m *Message) GetUnknownFields() []int32 {
228 flds := make([]int32, 0, len(m.unknownFields))
229 for tag := range m.unknownFields {
230 flds = append(flds, tag)
231 }
232 return flds
233}
234
235// Descriptor returns the serialized form of the file descriptor in which the
236// message was defined and a path to the message type therein. This mimics the
237// method of the same name on message types generated by protoc.
238func (m *Message) Descriptor() ([]byte, []int) {
239 // get encoded file descriptor
240 b, err := proto.Marshal(m.md.GetFile().AsProto())
241 if err != nil {
242 panic(fmt.Sprintf("failed to get encoded descriptor for %s: %v", m.md.GetFile().GetName(), err))
243 }
244 var zippedBytes bytes.Buffer
245 w := gzip.NewWriter(&zippedBytes)
246 if _, err := w.Write(b); err != nil {
247 panic(fmt.Sprintf("failed to get encoded descriptor for %s: %v", m.md.GetFile().GetName(), err))
248 }
249 if err := w.Close(); err != nil {
250 panic(fmt.Sprintf("failed to get an encoded descriptor for %s: %v", m.md.GetFile().GetName(), err))
251 }
252
253 // and path to message
254 path := []int{}
255 var d desc.Descriptor
256 name := m.md.GetFullyQualifiedName()
257 for d = m.md.GetParent(); d != nil; name, d = d.GetFullyQualifiedName(), d.GetParent() {
258 found := false
259 switch d := d.(type) {
260 case (*desc.FileDescriptor):
261 for i, md := range d.GetMessageTypes() {
262 if md.GetFullyQualifiedName() == name {
263 found = true
264 path = append(path, i)
265 }
266 }
267 case (*desc.MessageDescriptor):
268 for i, md := range d.GetNestedMessageTypes() {
269 if md.GetFullyQualifiedName() == name {
270 found = true
271 path = append(path, i)
272 }
273 }
274 }
275 if !found {
276 panic(fmt.Sprintf("failed to compute descriptor path for %s", m.md.GetFullyQualifiedName()))
277 }
278 }
279 // reverse the path
280 i := 0
281 j := len(path) - 1
282 for i < j {
283 path[i], path[j] = path[j], path[i]
284 i++
285 j--
286 }
287
288 return zippedBytes.Bytes(), path
289}
290
291// XXX_MessageName returns the fully qualified name of this message's type. This
292// allows dynamic messages to be used with proto.MessageName.
293func (m *Message) XXX_MessageName() string {
294 return m.md.GetFullyQualifiedName()
295}
296
297// FindFieldDescriptor returns a field descriptor for the given tag number. This
298// searches known fields in the descriptor, known fields discovered during calls
299// to GetField or SetField, and extension fields known by the message's extension
300// registry. It returns nil if the tag is unknown.
301func (m *Message) FindFieldDescriptor(tagNumber int32) *desc.FieldDescriptor {
302 fd := m.md.FindFieldByNumber(tagNumber)
303 if fd != nil {
304 return fd
305 }
306 fd = m.er.FindExtension(m.md.GetFullyQualifiedName(), tagNumber)
307 if fd != nil {
308 return fd
309 }
310 return m.extraFields[tagNumber]
311}
312
313// FindFieldDescriptorByName returns a field descriptor for the given field
314// name. This searches known fields in the descriptor, known fields discovered
315// during calls to GetField or SetField, and extension fields known by the
316// message's extension registry. It returns nil if the name is unknown. If the
317// given name refers to an extension, it should be fully qualified and may be
318// optionally enclosed in parentheses or brackets.
319func (m *Message) FindFieldDescriptorByName(name string) *desc.FieldDescriptor {
320 if name == "" {
321 return nil
322 }
323 fd := m.md.FindFieldByName(name)
324 if fd != nil {
325 return fd
326 }
327 mustBeExt := false
328 if name[0] == '(' {
329 if name[len(name)-1] != ')' {
330 // malformed name
331 return nil
332 }
333 mustBeExt = true
334 name = name[1 : len(name)-1]
335 } else if name[0] == '[' {
336 if name[len(name)-1] != ']' {
337 // malformed name
338 return nil
339 }
340 mustBeExt = true
341 name = name[1 : len(name)-1]
342 }
343 fd = m.er.FindExtensionByName(m.md.GetFullyQualifiedName(), name)
344 if fd != nil {
345 return fd
346 }
347 for _, fd := range m.extraFields {
348 if fd.IsExtension() && name == fd.GetFullyQualifiedName() {
349 return fd
350 } else if !mustBeExt && !fd.IsExtension() && name == fd.GetName() {
351 return fd
352 }
353 }
354
355 return nil
356}
357
358// FindFieldDescriptorByJSONName returns a field descriptor for the given JSON
359// name. This searches known fields in the descriptor, known fields discovered
360// during calls to GetField or SetField, and extension fields known by the
361// message's extension registry. If no field matches the given JSON name, it
362// will fall back to searching field names (e.g. FindFieldDescriptorByName). If
363// this also yields no match, nil is returned.
364func (m *Message) FindFieldDescriptorByJSONName(name string) *desc.FieldDescriptor {
365 if name == "" {
366 return nil
367 }
368 fd := m.md.FindFieldByJSONName(name)
369 if fd != nil {
370 return fd
371 }
372 mustBeExt := false
373 if name[0] == '(' {
374 if name[len(name)-1] != ')' {
375 // malformed name
376 return nil
377 }
378 mustBeExt = true
379 name = name[1 : len(name)-1]
380 } else if name[0] == '[' {
381 if name[len(name)-1] != ']' {
382 // malformed name
383 return nil
384 }
385 mustBeExt = true
386 name = name[1 : len(name)-1]
387 }
388 fd = m.er.FindExtensionByJSONName(m.md.GetFullyQualifiedName(), name)
389 if fd != nil {
390 return fd
391 }
392 for _, fd := range m.extraFields {
393 if fd.IsExtension() && name == fd.GetFullyQualifiedJSONName() {
394 return fd
395 } else if !mustBeExt && !fd.IsExtension() && name == fd.GetJSONName() {
396 return fd
397 }
398 }
399
400 // try non-JSON names
401 return m.FindFieldDescriptorByName(name)
402}
403
404func (m *Message) checkField(fd *desc.FieldDescriptor) error {
405 return checkField(fd, m.md)
406}
407
408func checkField(fd *desc.FieldDescriptor, md *desc.MessageDescriptor) error {
409 if fd.GetOwner().GetFullyQualifiedName() != md.GetFullyQualifiedName() {
410 return fmt.Errorf("given field, %s, is for wrong message type: %s; expecting %s", fd.GetName(), fd.GetOwner().GetFullyQualifiedName(), md.GetFullyQualifiedName())
411 }
412 if fd.IsExtension() && !md.IsExtension(fd.GetNumber()) {
413 return fmt.Errorf("given field, %s, is an extension but is not in message extension range: %v", fd.GetFullyQualifiedName(), md.GetExtensionRanges())
414 }
415 return nil
416}
417
418// GetField returns the value for the given field descriptor. It panics if an
419// error is encountered. See TryGetField.
420func (m *Message) GetField(fd *desc.FieldDescriptor) interface{} {
421 if v, err := m.TryGetField(fd); err != nil {
422 panic(err.Error())
423 } else {
424 return v
425 }
426}
427
428// TryGetField returns the value for the given field descriptor. An error is
429// returned if the given field descriptor does not belong to the right message
430// type.
431//
432// The Go type of the returned value, for scalar fields, is the same as protoc
433// would generate for the field (in a non-dynamic message). The table below
434// lists the scalar types and the corresponding Go types.
435// +-------------------------+-----------+
436// | Declared Type | Go Type |
437// +-------------------------+-----------+
438// | int32, sint32, sfixed32 | int32 |
439// | int64, sint64, sfixed64 | int64 |
440// | uint32, fixed32 | uint32 |
441// | uint64, fixed64 | uint64 |
442// | float | float32 |
443// | double | double32 |
444// | bool | bool |
445// | string | string |
446// | bytes | []byte |
447// +-------------------------+-----------+
448//
449// Values for enum fields will always be int32 values. You can use the enum
450// descriptor associated with the field to lookup value names with those values.
451// Values for message type fields may be an instance of the generated type *or*
452// may be another *dynamic.Message that represents the type.
453//
454// If the given field is a map field, the returned type will be
455// map[interface{}]interface{}. The actual concrete types of keys and values is
456// as described above. If the given field is a (non-map) repeated field, the
457// returned type is always []interface{}; the type of the actual elements is as
458// described above.
459//
460// If this message has no value for the given field, its default value is
461// returned. If the message is defined in a file with "proto3" syntax, the
462// default is always the zero value for the field. The default value for map and
463// repeated fields is a nil map or slice (respectively). For field's whose types
464// is a message, the default value is an empty message for "proto2" syntax or a
465// nil message for "proto3" syntax. Note that the in the latter case, a non-nil
466// interface with a nil pointer is returned, not a nil interface. Also note that
467// whether the returned value is an empty message or nil depends on if *this*
468// message was defined as "proto3" syntax, not the message type referred to by
469// the field's type.
470//
471// If the given field descriptor is not known (e.g. not present in the message
472// descriptor) but corresponds to an unknown field, the unknown value will be
473// parsed and become known. The parsed value will be returned, or an error will
474// be returned if the unknown value cannot be parsed according to the field
475// descriptor's type information.
476func (m *Message) TryGetField(fd *desc.FieldDescriptor) (interface{}, error) {
477 if err := m.checkField(fd); err != nil {
478 return nil, err
479 }
480 return m.getField(fd)
481}
482
483// GetFieldByName returns the value for the field with the given name. It panics
484// if an error is encountered. See TryGetFieldByName.
485func (m *Message) GetFieldByName(name string) interface{} {
486 if v, err := m.TryGetFieldByName(name); err != nil {
487 panic(err.Error())
488 } else {
489 return v
490 }
491}
492
493// TryGetFieldByName returns the value for the field with the given name. An
494// error is returned if the given name is unknown. If the given name refers to
495// an extension field, it should be fully qualified and optionally enclosed in
496// parenthesis or brackets.
497//
498// If this message has no value for the given field, its default value is
499// returned. (See TryGetField for more info on types and default field values.)
500func (m *Message) TryGetFieldByName(name string) (interface{}, error) {
501 fd := m.FindFieldDescriptorByName(name)
502 if fd == nil {
503 return nil, UnknownFieldNameError
504 }
505 return m.getField(fd)
506}
507
508// GetFieldByNumber returns the value for the field with the given tag number.
509// It panics if an error is encountered. See TryGetFieldByNumber.
510func (m *Message) GetFieldByNumber(tagNumber int) interface{} {
511 if v, err := m.TryGetFieldByNumber(tagNumber); err != nil {
512 panic(err.Error())
513 } else {
514 return v
515 }
516}
517
518// TryGetFieldByNumber returns the value for the field with the given tag
519// number. An error is returned if the given tag is unknown.
520//
521// If this message has no value for the given field, its default value is
522// returned. (See TryGetField for more info on types and default field values.)
523func (m *Message) TryGetFieldByNumber(tagNumber int) (interface{}, error) {
524 fd := m.FindFieldDescriptor(int32(tagNumber))
525 if fd == nil {
526 return nil, UnknownTagNumberError
527 }
528 return m.getField(fd)
529}
530
531func (m *Message) getField(fd *desc.FieldDescriptor) (interface{}, error) {
532 return m.doGetField(fd, false)
533}
534
535func (m *Message) doGetField(fd *desc.FieldDescriptor, nilIfAbsent bool) (interface{}, error) {
536 res := m.values[fd.GetNumber()]
537 if res == nil {
538 var err error
539 if res, err = m.parseUnknownField(fd); err != nil {
540 return nil, err
541 }
542 if res == nil {
543 if nilIfAbsent {
544 return nil, nil
545 } else {
546 def := fd.GetDefaultValue()
547 if def != nil {
548 return def, nil
549 }
550 // GetDefaultValue only returns nil for message types
551 md := fd.GetMessageType()
552 if md.IsProto3() {
553 // try to return a proper nil pointer
554 msgType := proto.MessageType(md.GetFullyQualifiedName())
555 if msgType != nil && msgType.Implements(typeOfProtoMessage) {
556 return reflect.Zero(msgType).Interface().(proto.Message), nil
557 }
558 // fallback to nil dynamic message pointer
559 return (*Message)(nil), nil
560 } else {
561 // for proto2, return default instance of message
562 return m.mf.NewMessage(md), nil
563 }
564 }
565 }
566 }
567 rt := reflect.TypeOf(res)
568 if rt.Kind() == reflect.Map {
569 // make defensive copies to prevent caller from storing illegal keys and values
570 m := res.(map[interface{}]interface{})
571 res := map[interface{}]interface{}{}
572 for k, v := range m {
573 res[k] = v
574 }
575 return res, nil
576 } else if rt.Kind() == reflect.Slice && rt != typeOfBytes {
577 // make defensive copies to prevent caller from storing illegal elements
578 sl := res.([]interface{})
579 res := make([]interface{}, len(sl))
580 copy(res, sl)
581 return res, nil
582 }
583 return res, nil
584}
585
586// HasField returns true if this message has a value for the given field. If the
587// given field is not valid (e.g. belongs to a different message type), false is
588// returned. If this message is defined in a file with "proto3" syntax, this
589// will return false even if a field was explicitly assigned its zero value (the
590// zero values for a field are intentionally indistinguishable from absent).
591func (m *Message) HasField(fd *desc.FieldDescriptor) bool {
592 if err := m.checkField(fd); err != nil {
593 return false
594 }
595 return m.HasFieldNumber(int(fd.GetNumber()))
596}
597
598// HasFieldName returns true if this message has a value for a field with the
599// given name. If the given name is unknown, this returns false.
600func (m *Message) HasFieldName(name string) bool {
601 fd := m.FindFieldDescriptorByName(name)
602 if fd == nil {
603 return false
604 }
605 return m.HasFieldNumber(int(fd.GetNumber()))
606}
607
608// HasFieldNumber returns true if this message has a value for a field with the
609// given tag number. If the given tag is unknown, this returns false.
610func (m *Message) HasFieldNumber(tagNumber int) bool {
611 if _, ok := m.values[int32(tagNumber)]; ok {
612 return true
613 }
614 _, ok := m.unknownFields[int32(tagNumber)]
615 return ok
616}
617
618// SetField sets the value for the given field descriptor to the given value. It
619// panics if an error is encountered. See TrySetField.
620func (m *Message) SetField(fd *desc.FieldDescriptor, val interface{}) {
621 if err := m.TrySetField(fd, val); err != nil {
622 panic(err.Error())
623 }
624}
625
626// TrySetField sets the value for the given field descriptor to the given value.
627// An error is returned if the given field descriptor does not belong to the
628// right message type or if the given value is not a correct/compatible type for
629// the given field.
630//
631// The Go type expected for a field is the same as TryGetField would return for
632// the field. So message values can be supplied as either the correct generated
633// message type or as a *dynamic.Message.
634//
635// Since it is cumbersome to work with dynamic messages, some concessions are
636// made to simplify usage regarding types:
637//
638// 1. If a numeric type is provided that can be converted *without loss or
639// overflow*, it is accepted. This allows for setting int64 fields using int
640// or int32 values. Similarly for uint64 with uint and uint32 values and for
641// float64 fields with float32 values.
642// 2. The value can be a named type, as long as its underlying type is correct.
643// 3. Map and repeated fields can be set using any kind of concrete map or
644// slice type, as long as the values within are all of the correct type. So
645// a field defined as a 'map<string, int32>` can be set using a
646// map[string]int32, a map[string]interface{}, or even a
647// map[interface{}]interface{}.
648// 4. Finally, dynamic code that chooses to not treat maps as a special-case
649// find that they can set map fields using a slice where each element is a
650// message that matches the implicit map-entry field message type.
651//
652// If the given field descriptor is not known (e.g. not present in the message
653// descriptor) it will become known. Subsequent operations using tag numbers or
654// names will be able to resolve the newly-known type. If the message has a
655// value for the unknown value, it is cleared, replaced by the given known
656// value.
657func (m *Message) TrySetField(fd *desc.FieldDescriptor, val interface{}) error {
658 if err := m.checkField(fd); err != nil {
659 return err
660 }
661 return m.setField(fd, val)
662}
663
664// SetFieldByName sets the value for the field with the given name to the given
665// value. It panics if an error is encountered. See TrySetFieldByName.
666func (m *Message) SetFieldByName(name string, val interface{}) {
667 if err := m.TrySetFieldByName(name, val); err != nil {
668 panic(err.Error())
669 }
670}
671
672// TrySetFieldByName sets the value for the field with the given name to the
673// given value. An error is returned if the given name is unknown or if the
674// given value has an incorrect type. If the given name refers to an extension
675// field, it should be fully qualified and optionally enclosed in parenthesis or
676// brackets.
677//
678// (See TrySetField for more info on types.)
679func (m *Message) TrySetFieldByName(name string, val interface{}) error {
680 fd := m.FindFieldDescriptorByName(name)
681 if fd == nil {
682 return UnknownFieldNameError
683 }
684 return m.setField(fd, val)
685}
686
687// SetFieldByNumber sets the value for the field with the given tag number to
688// the given value. It panics if an error is encountered. See
689// TrySetFieldByNumber.
690func (m *Message) SetFieldByNumber(tagNumber int, val interface{}) {
691 if err := m.TrySetFieldByNumber(tagNumber, val); err != nil {
692 panic(err.Error())
693 }
694}
695
696// TrySetFieldByNumber sets the value for the field with the given tag number to
697// the given value. An error is returned if the given tag is unknown or if the
698// given value has an incorrect type.
699//
700// (See TrySetField for more info on types.)
701func (m *Message) TrySetFieldByNumber(tagNumber int, val interface{}) error {
702 fd := m.FindFieldDescriptor(int32(tagNumber))
703 if fd == nil {
704 return UnknownTagNumberError
705 }
706 return m.setField(fd, val)
707}
708
709func (m *Message) setField(fd *desc.FieldDescriptor, val interface{}) error {
710 var err error
711 if val, err = validFieldValue(fd, val); err != nil {
712 return err
713 }
714 m.internalSetField(fd, val)
715 return nil
716}
717
718func (m *Message) internalSetField(fd *desc.FieldDescriptor, val interface{}) {
719 if fd.IsRepeated() {
720 // Unset fields and zero-length fields are indistinguishable, in both
721 // proto2 and proto3 syntax
722 if reflect.ValueOf(val).Len() == 0 {
723 if m.values != nil {
724 delete(m.values, fd.GetNumber())
725 }
726 return
727 }
728 } else if m.md.IsProto3() && fd.GetOneOf() == nil {
729 // proto3 considers fields that are set to their zero value as unset
730 // (we already handled repeated fields above)
731 var equal bool
732 if b, ok := val.([]byte); ok {
733 // can't compare slices, so we have to special-case []byte values
734 equal = ok && bytes.Equal(b, fd.GetDefaultValue().([]byte))
735 } else {
736 defVal := fd.GetDefaultValue()
737 equal = defVal == val
738 if !equal && defVal == nil {
739 // above just checks if value is the nil interface,
740 // but we should also test if the given value is a
741 // nil pointer
742 rv := reflect.ValueOf(val)
743 if rv.Kind() == reflect.Ptr && rv.IsNil() {
744 equal = true
745 }
746 }
747 }
748 if equal {
749 if m.values != nil {
750 delete(m.values, fd.GetNumber())
751 }
752 return
753 }
754 }
755 if m.values == nil {
756 m.values = map[int32]interface{}{}
757 }
758 m.values[fd.GetNumber()] = val
759 // if this field is part of a one-of, make sure all other one-of choices are cleared
760 od := fd.GetOneOf()
761 if od != nil {
762 for _, other := range od.GetChoices() {
763 if other.GetNumber() != fd.GetNumber() {
764 delete(m.values, other.GetNumber())
765 }
766 }
767 }
768 // also clear any unknown fields
769 if m.unknownFields != nil {
770 delete(m.unknownFields, fd.GetNumber())
771 }
772 // and add this field if it was previously unknown
773 if existing := m.FindFieldDescriptor(fd.GetNumber()); existing == nil {
774 m.addField(fd)
775 }
776}
777
778func (m *Message) addField(fd *desc.FieldDescriptor) {
779 if m.extraFields == nil {
780 m.extraFields = map[int32]*desc.FieldDescriptor{}
781 }
782 m.extraFields[fd.GetNumber()] = fd
783}
784
785// ClearField removes any value for the given field. It panics if an error is
786// encountered. See TryClearField.
787func (m *Message) ClearField(fd *desc.FieldDescriptor) {
788 if err := m.TryClearField(fd); err != nil {
789 panic(err.Error())
790 }
791}
792
793// TryClearField removes any value for the given field. An error is returned if
794// the given field descriptor does not belong to the right message type.
795func (m *Message) TryClearField(fd *desc.FieldDescriptor) error {
796 if err := m.checkField(fd); err != nil {
797 return err
798 }
799 m.clearField(fd)
800 return nil
801}
802
803// ClearFieldByName removes any value for the field with the given name. It
804// panics if an error is encountered. See TryClearFieldByName.
805func (m *Message) ClearFieldByName(name string) {
806 if err := m.TryClearFieldByName(name); err != nil {
807 panic(err.Error())
808 }
809}
810
811// TryClearFieldByName removes any value for the field with the given name. An
812// error is returned if the given name is unknown. If the given name refers to
813// an extension field, it should be fully qualified and optionally enclosed in
814// parenthesis or brackets.
815func (m *Message) TryClearFieldByName(name string) error {
816 fd := m.FindFieldDescriptorByName(name)
817 if fd == nil {
818 return UnknownFieldNameError
819 }
820 m.clearField(fd)
821 return nil
822}
823
824// ClearFieldByNumber removes any value for the field with the given tag number.
825// It panics if an error is encountered. See TryClearFieldByNumber.
826func (m *Message) ClearFieldByNumber(tagNumber int) {
827 if err := m.TryClearFieldByNumber(tagNumber); err != nil {
828 panic(err.Error())
829 }
830}
831
832// TryClearFieldByNumber removes any value for the field with the given tag
833// number. An error is returned if the given tag is unknown.
834func (m *Message) TryClearFieldByNumber(tagNumber int) error {
835 fd := m.FindFieldDescriptor(int32(tagNumber))
836 if fd == nil {
837 return UnknownTagNumberError
838 }
839 m.clearField(fd)
840 return nil
841}
842
843func (m *Message) clearField(fd *desc.FieldDescriptor) {
844 // clear value
845 if m.values != nil {
846 delete(m.values, fd.GetNumber())
847 }
848 // also clear any unknown fields
849 if m.unknownFields != nil {
850 delete(m.unknownFields, fd.GetNumber())
851 }
852 // and add this field if it was previously unknown
853 if existing := m.FindFieldDescriptor(fd.GetNumber()); existing == nil {
854 m.addField(fd)
855 }
856}
857
858// GetOneOfField returns which of the given one-of's fields is set and the
859// corresponding value. It panics if an error is encountered. See
860// TryGetOneOfField.
861func (m *Message) GetOneOfField(od *desc.OneOfDescriptor) (*desc.FieldDescriptor, interface{}) {
862 if fd, val, err := m.TryGetOneOfField(od); err != nil {
863 panic(err.Error())
864 } else {
865 return fd, val
866 }
867}
868
869// TryGetOneOfField returns which of the given one-of's fields is set and the
870// corresponding value. An error is returned if the given one-of belongs to the
871// wrong message type. If the given one-of has no field set, this method will
872// return nil, nil.
873//
874// The type of the value, if one is set, is the same as would be returned by
875// TryGetField using the returned field descriptor.
876//
877// Like with TryGetField, if the given one-of contains any fields that are not
878// known (e.g. not present in this message's descriptor), they will become known
879// and any unknown value will be parsed (and become a known value on success).
880func (m *Message) TryGetOneOfField(od *desc.OneOfDescriptor) (*desc.FieldDescriptor, interface{}, error) {
881 if od.GetOwner().GetFullyQualifiedName() != m.md.GetFullyQualifiedName() {
882 return nil, nil, fmt.Errorf("given one-of, %s, is for wrong message type: %s; expecting %s", od.GetName(), od.GetOwner().GetFullyQualifiedName(), m.md.GetFullyQualifiedName())
883 }
884 for _, fd := range od.GetChoices() {
885 val, err := m.doGetField(fd, true)
886 if err != nil {
887 return nil, nil, err
888 }
889 if val != nil {
890 return fd, val, nil
891 }
892 }
893 return nil, nil, nil
894}
895
896// ClearOneOfField removes any value for any of the given one-of's fields. It
897// panics if an error is encountered. See TryClearOneOfField.
898func (m *Message) ClearOneOfField(od *desc.OneOfDescriptor) {
899 if err := m.TryClearOneOfField(od); err != nil {
900 panic(err.Error())
901 }
902}
903
904// TryClearOneOfField removes any value for any of the given one-of's fields. An
905// error is returned if the given one-of descriptor does not belong to the right
906// message type.
907func (m *Message) TryClearOneOfField(od *desc.OneOfDescriptor) error {
908 if od.GetOwner().GetFullyQualifiedName() != m.md.GetFullyQualifiedName() {
909 return fmt.Errorf("given one-of, %s, is for wrong message type: %s; expecting %s", od.GetName(), od.GetOwner().GetFullyQualifiedName(), m.md.GetFullyQualifiedName())
910 }
911 for _, fd := range od.GetChoices() {
912 m.clearField(fd)
913 }
914 return nil
915}
916
917// GetMapField returns the value for the given map field descriptor and given
918// key. It panics if an error is encountered. See TryGetMapField.
919func (m *Message) GetMapField(fd *desc.FieldDescriptor, key interface{}) interface{} {
920 if v, err := m.TryGetMapField(fd, key); err != nil {
921 panic(err.Error())
922 } else {
923 return v
924 }
925}
926
927// TryGetMapField returns the value for the given map field descriptor and given
928// key. An error is returned if the given field descriptor does not belong to
929// the right message type or if it is not a map field.
930//
931// If the map field does not contain the requested key, this method returns
932// nil, nil. The Go type of the value returned mirrors the type that protoc
933// would generate for the field. (See TryGetField for more details on types).
934//
935// If the given field descriptor is not known (e.g. not present in the message
936// descriptor) but corresponds to an unknown field, the unknown value will be
937// parsed and become known. The parsed value will be searched for the requested
938// key and any value returned. An error will be returned if the unknown value
939// cannot be parsed according to the field descriptor's type information.
940func (m *Message) TryGetMapField(fd *desc.FieldDescriptor, key interface{}) (interface{}, error) {
941 if err := m.checkField(fd); err != nil {
942 return nil, err
943 }
944 return m.getMapField(fd, key)
945}
946
947// GetMapFieldByName returns the value for the map field with the given name and
948// given key. It panics if an error is encountered. See TryGetMapFieldByName.
949func (m *Message) GetMapFieldByName(name string, key interface{}) interface{} {
950 if v, err := m.TryGetMapFieldByName(name, key); err != nil {
951 panic(err.Error())
952 } else {
953 return v
954 }
955}
956
957// TryGetMapFieldByName returns the value for the map field with the given name
958// and given key. An error is returned if the given name is unknown or if it
959// names a field that is not a map field.
960//
961// If this message has no value for the given field or the value has no value
962// for the requested key, then this method returns nil, nil.
963//
964// (See TryGetField for more info on types.)
965func (m *Message) TryGetMapFieldByName(name string, key interface{}) (interface{}, error) {
966 fd := m.FindFieldDescriptorByName(name)
967 if fd == nil {
968 return nil, UnknownFieldNameError
969 }
970 return m.getMapField(fd, key)
971}
972
973// GetMapFieldByNumber returns the value for the map field with the given tag
974// number and given key. It panics if an error is encountered. See
975// TryGetMapFieldByNumber.
976func (m *Message) GetMapFieldByNumber(tagNumber int, key interface{}) interface{} {
977 if v, err := m.TryGetMapFieldByNumber(tagNumber, key); err != nil {
978 panic(err.Error())
979 } else {
980 return v
981 }
982}
983
984// TryGetMapFieldByNumber returns the value for the map field with the given tag
985// number and given key. An error is returned if the given tag is unknown or if
986// it indicates a field that is not a map field.
987//
988// If this message has no value for the given field or the value has no value
989// for the requested key, then this method returns nil, nil.
990//
991// (See TryGetField for more info on types.)
992func (m *Message) TryGetMapFieldByNumber(tagNumber int, key interface{}) (interface{}, error) {
993 fd := m.FindFieldDescriptor(int32(tagNumber))
994 if fd == nil {
995 return nil, UnknownTagNumberError
996 }
997 return m.getMapField(fd, key)
998}
999
1000func (m *Message) getMapField(fd *desc.FieldDescriptor, key interface{}) (interface{}, error) {
1001 if !fd.IsMap() {
1002 return nil, FieldIsNotMapError
1003 }
1004 kfd := fd.GetMessageType().GetFields()[0]
1005 ki, err := validElementFieldValue(kfd, key)
1006 if err != nil {
1007 return nil, err
1008 }
1009 mp := m.values[fd.GetNumber()]
1010 if mp == nil {
1011 if mp, err = m.parseUnknownField(fd); err != nil {
1012 return nil, err
1013 } else if mp == nil {
1014 return nil, nil
1015 }
1016 }
1017 return mp.(map[interface{}]interface{})[ki], nil
1018}
1019
1020// ForEachMapFieldEntry executes the given function for each entry in the map
1021// value for the given field descriptor. It stops iteration if the function
1022// returns false. It panics if an error is encountered. See
1023// TryForEachMapFieldEntry.
1024func (m *Message) ForEachMapFieldEntry(fd *desc.FieldDescriptor, fn func(key, val interface{}) bool) {
1025 if err := m.TryForEachMapFieldEntry(fd, fn); err != nil {
1026 panic(err.Error())
1027 }
1028}
1029
1030// TryForEachMapFieldEntry executes the given function for each entry in the map
1031// value for the given field descriptor. An error is returned if the given field
1032// descriptor does not belong to the right message type or if it is not a map
1033// field.
1034//
1035// Iteration ends either when all entries have been examined or when the given
1036// function returns false. So the function is expected to return true for normal
1037// iteration and false to break out. If this message has no value for the given
1038// field, it returns without invoking the given function.
1039//
1040// The Go type of the key and value supplied to the function mirrors the type
1041// that protoc would generate for the field. (See TryGetField for more details
1042// on types).
1043//
1044// If the given field descriptor is not known (e.g. not present in the message
1045// descriptor) but corresponds to an unknown field, the unknown value will be
1046// parsed and become known. The parsed value will be searched for the requested
1047// key and any value returned. An error will be returned if the unknown value
1048// cannot be parsed according to the field descriptor's type information.
1049func (m *Message) TryForEachMapFieldEntry(fd *desc.FieldDescriptor, fn func(key, val interface{}) bool) error {
1050 if err := m.checkField(fd); err != nil {
1051 return err
1052 }
1053 return m.forEachMapFieldEntry(fd, fn)
1054}
1055
1056// ForEachMapFieldEntryByName executes the given function for each entry in the
1057// map value for the field with the given name. It stops iteration if the
1058// function returns false. It panics if an error is encountered. See
1059// TryForEachMapFieldEntryByName.
1060func (m *Message) ForEachMapFieldEntryByName(name string, fn func(key, val interface{}) bool) {
1061 if err := m.TryForEachMapFieldEntryByName(name, fn); err != nil {
1062 panic(err.Error())
1063 }
1064}
1065
1066// TryForEachMapFieldEntryByName executes the given function for each entry in
1067// the map value for the field with the given name. It stops iteration if the
1068// function returns false. An error is returned if the given name is unknown or
1069// if it names a field that is not a map field.
1070//
1071// If this message has no value for the given field, it returns without ever
1072// invoking the given function.
1073//
1074// (See TryGetField for more info on types supplied to the function.)
1075func (m *Message) TryForEachMapFieldEntryByName(name string, fn func(key, val interface{}) bool) error {
1076 fd := m.FindFieldDescriptorByName(name)
1077 if fd == nil {
1078 return UnknownFieldNameError
1079 }
1080 return m.forEachMapFieldEntry(fd, fn)
1081}
1082
1083// ForEachMapFieldEntryByNumber executes the given function for each entry in
1084// the map value for the field with the given tag number. It stops iteration if
1085// the function returns false. It panics if an error is encountered. See
1086// TryForEachMapFieldEntryByNumber.
1087func (m *Message) ForEachMapFieldEntryByNumber(tagNumber int, fn func(key, val interface{}) bool) {
1088 if err := m.TryForEachMapFieldEntryByNumber(tagNumber, fn); err != nil {
1089 panic(err.Error())
1090 }
1091}
1092
1093// TryForEachMapFieldEntryByNumber executes the given function for each entry in
1094// the map value for the field with the given tag number. It stops iteration if
1095// the function returns false. An error is returned if the given tag is unknown
1096// or if it indicates a field that is not a map field.
1097//
1098// If this message has no value for the given field, it returns without ever
1099// invoking the given function.
1100//
1101// (See TryGetField for more info on types supplied to the function.)
1102func (m *Message) TryForEachMapFieldEntryByNumber(tagNumber int, fn func(key, val interface{}) bool) error {
1103 fd := m.FindFieldDescriptor(int32(tagNumber))
1104 if fd == nil {
1105 return UnknownTagNumberError
1106 }
1107 return m.forEachMapFieldEntry(fd, fn)
1108}
1109
1110func (m *Message) forEachMapFieldEntry(fd *desc.FieldDescriptor, fn func(key, val interface{}) bool) error {
1111 if !fd.IsMap() {
1112 return FieldIsNotMapError
1113 }
1114 mp := m.values[fd.GetNumber()]
1115 if mp == nil {
1116 if mp, err := m.parseUnknownField(fd); err != nil {
1117 return err
1118 } else if mp == nil {
1119 return nil
1120 }
1121 }
1122 for k, v := range mp.(map[interface{}]interface{}) {
1123 if !fn(k, v) {
1124 break
1125 }
1126 }
1127 return nil
1128}
1129
1130// PutMapField sets the value for the given map field descriptor and given key
1131// to the given value. It panics if an error is encountered. See TryPutMapField.
1132func (m *Message) PutMapField(fd *desc.FieldDescriptor, key interface{}, val interface{}) {
1133 if err := m.TryPutMapField(fd, key, val); err != nil {
1134 panic(err.Error())
1135 }
1136}
1137
1138// TryPutMapField sets the value for the given map field descriptor and given
1139// key to the given value. An error is returned if the given field descriptor
1140// does not belong to the right message type, if the given field is not a map
1141// field, or if the given value is not a correct/compatible type for the given
1142// field.
1143//
1144// The Go type expected for a field is the same as required by TrySetField for
1145// a field with the same type as the map's value type.
1146//
1147// If the given field descriptor is not known (e.g. not present in the message
1148// descriptor) it will become known. Subsequent operations using tag numbers or
1149// names will be able to resolve the newly-known type. If the message has a
1150// value for the unknown value, it is cleared, replaced by the given known
1151// value.
1152func (m *Message) TryPutMapField(fd *desc.FieldDescriptor, key interface{}, val interface{}) error {
1153 if err := m.checkField(fd); err != nil {
1154 return err
1155 }
1156 return m.putMapField(fd, key, val)
1157}
1158
1159// PutMapFieldByName sets the value for the map field with the given name and
1160// given key to the given value. It panics if an error is encountered. See
1161// TryPutMapFieldByName.
1162func (m *Message) PutMapFieldByName(name string, key interface{}, val interface{}) {
1163 if err := m.TryPutMapFieldByName(name, key, val); err != nil {
1164 panic(err.Error())
1165 }
1166}
1167
1168// TryPutMapFieldByName sets the value for the map field with the given name and
1169// the given key to the given value. An error is returned if the given name is
1170// unknown, if it names a field that is not a map, or if the given value has an
1171// incorrect type.
1172//
1173// (See TrySetField for more info on types.)
1174func (m *Message) TryPutMapFieldByName(name string, key interface{}, val interface{}) error {
1175 fd := m.FindFieldDescriptorByName(name)
1176 if fd == nil {
1177 return UnknownFieldNameError
1178 }
1179 return m.putMapField(fd, key, val)
1180}
1181
1182// PutMapFieldByNumber sets the value for the map field with the given tag
1183// number and given key to the given value. It panics if an error is
1184// encountered. See TryPutMapFieldByNumber.
1185func (m *Message) PutMapFieldByNumber(tagNumber int, key interface{}, val interface{}) {
1186 if err := m.TryPutMapFieldByNumber(tagNumber, key, val); err != nil {
1187 panic(err.Error())
1188 }
1189}
1190
1191// TryPutMapFieldByNumber sets the value for the map field with the given tag
1192// number and the given key to the given value. An error is returned if the
1193// given tag is unknown, if it indicates a field that is not a map, or if the
1194// given value has an incorrect type.
1195//
1196// (See TrySetField for more info on types.)
1197func (m *Message) TryPutMapFieldByNumber(tagNumber int, key interface{}, val interface{}) error {
1198 fd := m.FindFieldDescriptor(int32(tagNumber))
1199 if fd == nil {
1200 return UnknownTagNumberError
1201 }
1202 return m.putMapField(fd, key, val)
1203}
1204
1205func (m *Message) putMapField(fd *desc.FieldDescriptor, key interface{}, val interface{}) error {
1206 if !fd.IsMap() {
1207 return FieldIsNotMapError
1208 }
1209 kfd := fd.GetMessageType().GetFields()[0]
1210 ki, err := validElementFieldValue(kfd, key)
1211 if err != nil {
1212 return err
1213 }
1214 vfd := fd.GetMessageType().GetFields()[1]
1215 vi, err := validElementFieldValue(vfd, val)
1216 if err != nil {
1217 return err
1218 }
1219 mp := m.values[fd.GetNumber()]
1220 if mp == nil {
1221 if mp, err = m.parseUnknownField(fd); err != nil {
1222 return err
1223 } else if mp == nil {
1224 mp = map[interface{}]interface{}{}
1225 m.internalSetField(fd, map[interface{}]interface{}{ki: vi})
1226 return nil
1227 }
1228 }
1229 mp.(map[interface{}]interface{})[ki] = vi
1230 return nil
1231}
1232
1233// RemoveMapField changes the value for the given field descriptor by removing
1234// any value associated with the given key. It panics if an error is
1235// encountered. See TryRemoveMapField.
1236func (m *Message) RemoveMapField(fd *desc.FieldDescriptor, key interface{}) {
1237 if err := m.TryRemoveMapField(fd, key); err != nil {
1238 panic(err.Error())
1239 }
1240}
1241
1242// TryRemoveMapField changes the value for the given field descriptor by
1243// removing any value associated with the given key. An error is returned if the
1244// given field descriptor does not belong to the right message type or if the
1245// given field is not a map field.
1246//
1247// If the given field descriptor is not known (e.g. not present in the message
1248// descriptor) it will become known. Subsequent operations using tag numbers or
1249// names will be able to resolve the newly-known type. If the message has a
1250// value for the unknown value, it is parsed and any value for the given key
1251// removed.
1252func (m *Message) TryRemoveMapField(fd *desc.FieldDescriptor, key interface{}) error {
1253 if err := m.checkField(fd); err != nil {
1254 return err
1255 }
1256 return m.removeMapField(fd, key)
1257}
1258
1259// RemoveMapFieldByName changes the value for the field with the given name by
1260// removing any value associated with the given key. It panics if an error is
1261// encountered. See TryRemoveMapFieldByName.
1262func (m *Message) RemoveMapFieldByName(name string, key interface{}) {
1263 if err := m.TryRemoveMapFieldByName(name, key); err != nil {
1264 panic(err.Error())
1265 }
1266}
1267
1268// TryRemoveMapFieldByName changes the value for the field with the given name
1269// by removing any value associated with the given key. An error is returned if
1270// the given name is unknown or if it names a field that is not a map.
1271func (m *Message) TryRemoveMapFieldByName(name string, key interface{}) error {
1272 fd := m.FindFieldDescriptorByName(name)
1273 if fd == nil {
1274 return UnknownFieldNameError
1275 }
1276 return m.removeMapField(fd, key)
1277}
1278
1279// RemoveMapFieldByNumber changes the value for the field with the given tag
1280// number by removing any value associated with the given key. It panics if an
1281// error is encountered. See TryRemoveMapFieldByNumber.
1282func (m *Message) RemoveMapFieldByNumber(tagNumber int, key interface{}) {
1283 if err := m.TryRemoveMapFieldByNumber(tagNumber, key); err != nil {
1284 panic(err.Error())
1285 }
1286}
1287
1288// TryRemoveMapFieldByNumber changes the value for the field with the given tag
1289// number by removing any value associated with the given key. An error is
1290// returned if the given tag is unknown or if it indicates a field that is not
1291// a map.
1292func (m *Message) TryRemoveMapFieldByNumber(tagNumber int, key interface{}) error {
1293 fd := m.FindFieldDescriptor(int32(tagNumber))
1294 if fd == nil {
1295 return UnknownTagNumberError
1296 }
1297 return m.removeMapField(fd, key)
1298}
1299
1300func (m *Message) removeMapField(fd *desc.FieldDescriptor, key interface{}) error {
1301 if !fd.IsMap() {
1302 return FieldIsNotMapError
1303 }
1304 kfd := fd.GetMessageType().GetFields()[0]
1305 ki, err := validElementFieldValue(kfd, key)
1306 if err != nil {
1307 return err
1308 }
1309 mp := m.values[fd.GetNumber()]
1310 if mp == nil {
1311 if mp, err = m.parseUnknownField(fd); err != nil {
1312 return err
1313 } else if mp == nil {
1314 return nil
1315 }
1316 }
1317 res := mp.(map[interface{}]interface{})
1318 delete(res, ki)
1319 if len(res) == 0 {
1320 delete(m.values, fd.GetNumber())
1321 }
1322 return nil
1323}
1324
1325// FieldLength returns the number of elements in this message for the given
1326// field descriptor. It panics if an error is encountered. See TryFieldLength.
1327func (m *Message) FieldLength(fd *desc.FieldDescriptor) int {
1328 l, err := m.TryFieldLength(fd)
1329 if err != nil {
1330 panic(err.Error())
1331 }
1332 return l
1333}
1334
1335// TryFieldLength returns the number of elements in this message for the given
1336// field descriptor. An error is returned if the given field descriptor does not
1337// belong to the right message type or if it is neither a map field nor a
1338// repeated field.
1339func (m *Message) TryFieldLength(fd *desc.FieldDescriptor) (int, error) {
1340 if err := m.checkField(fd); err != nil {
1341 return 0, err
1342 }
1343 return m.fieldLength(fd)
1344}
1345
1346// FieldLengthByName returns the number of elements in this message for the
1347// field with the given name. It panics if an error is encountered. See
1348// TryFieldLengthByName.
1349func (m *Message) FieldLengthByName(name string) int {
1350 l, err := m.TryFieldLengthByName(name)
1351 if err != nil {
1352 panic(err.Error())
1353 }
1354 return l
1355}
1356
1357// TryFieldLengthByName returns the number of elements in this message for the
1358// field with the given name. An error is returned if the given name is unknown
1359// or if the named field is neither a map field nor a repeated field.
1360func (m *Message) TryFieldLengthByName(name string) (int, error) {
1361 fd := m.FindFieldDescriptorByName(name)
1362 if fd == nil {
1363 return 0, UnknownFieldNameError
1364 }
1365 return m.fieldLength(fd)
1366}
1367
1368// FieldLengthByNumber returns the number of elements in this message for the
1369// field with the given tag number. It panics if an error is encountered. See
1370// TryFieldLengthByNumber.
1371func (m *Message) FieldLengthByNumber(tagNumber int32) int {
1372 l, err := m.TryFieldLengthByNumber(tagNumber)
1373 if err != nil {
1374 panic(err.Error())
1375 }
1376 return l
1377}
1378
1379// TryFieldLengthByNumber returns the number of elements in this message for the
1380// field with the given tag number. An error is returned if the given tag is
1381// unknown or if the named field is neither a map field nor a repeated field.
1382func (m *Message) TryFieldLengthByNumber(tagNumber int32) (int, error) {
1383 fd := m.FindFieldDescriptor(int32(tagNumber))
1384 if fd == nil {
1385 return 0, UnknownTagNumberError
1386 }
1387 return m.fieldLength(fd)
1388}
1389
1390func (m *Message) fieldLength(fd *desc.FieldDescriptor) (int, error) {
1391 if !fd.IsRepeated() {
1392 return 0, FieldIsNotRepeatedError
1393 }
1394 val := m.values[fd.GetNumber()]
1395 if val == nil {
1396 var err error
1397 if val, err = m.parseUnknownField(fd); err != nil {
1398 return 0, err
1399 } else if val == nil {
1400 return 0, nil
1401 }
1402 }
1403 if sl, ok := val.([]interface{}); ok {
1404 return len(sl), nil
1405 } else if mp, ok := val.(map[interface{}]interface{}); ok {
1406 return len(mp), nil
1407 }
1408 return 0, nil
1409}
1410
1411// GetRepeatedField returns the value for the given repeated field descriptor at
1412// the given index. It panics if an error is encountered. See
1413// TryGetRepeatedField.
1414func (m *Message) GetRepeatedField(fd *desc.FieldDescriptor, index int) interface{} {
1415 if v, err := m.TryGetRepeatedField(fd, index); err != nil {
1416 panic(err.Error())
1417 } else {
1418 return v
1419 }
1420}
1421
1422// TryGetRepeatedField returns the value for the given repeated field descriptor
1423// at the given index. An error is returned if the given field descriptor does
1424// not belong to the right message type, if it is not a repeated field, or if
1425// the given index is out of range (less than zero or greater than or equal to
1426// the length of the repeated field). Also, even though map fields technically
1427// are repeated fields, if the given field is a map field an error will result:
1428// map representation does not lend itself to random access by index.
1429//
1430// The Go type of the value returned mirrors the type that protoc would generate
1431// for the field's element type. (See TryGetField for more details on types).
1432//
1433// If the given field descriptor is not known (e.g. not present in the message
1434// descriptor) but corresponds to an unknown field, the unknown value will be
1435// parsed and become known. The value at the given index in the parsed value
1436// will be returned. An error will be returned if the unknown value cannot be
1437// parsed according to the field descriptor's type information.
1438func (m *Message) TryGetRepeatedField(fd *desc.FieldDescriptor, index int) (interface{}, error) {
1439 if index < 0 {
1440 return nil, IndexOutOfRangeError
1441 }
1442 if err := m.checkField(fd); err != nil {
1443 return nil, err
1444 }
1445 return m.getRepeatedField(fd, index)
1446}
1447
1448// GetRepeatedFieldByName returns the value for the repeated field with the
1449// given name at the given index. It panics if an error is encountered. See
1450// TryGetRepeatedFieldByName.
1451func (m *Message) GetRepeatedFieldByName(name string, index int) interface{} {
1452 if v, err := m.TryGetRepeatedFieldByName(name, index); err != nil {
1453 panic(err.Error())
1454 } else {
1455 return v
1456 }
1457}
1458
1459// TryGetRepeatedFieldByName returns the value for the repeated field with the
1460// given name at the given index. An error is returned if the given name is
1461// unknown, if it names a field that is not a repeated field (or is a map
1462// field), or if the given index is out of range (less than zero or greater
1463// than or equal to the length of the repeated field).
1464//
1465// (See TryGetField for more info on types.)
1466func (m *Message) TryGetRepeatedFieldByName(name string, index int) (interface{}, error) {
1467 if index < 0 {
1468 return nil, IndexOutOfRangeError
1469 }
1470 fd := m.FindFieldDescriptorByName(name)
1471 if fd == nil {
1472 return nil, UnknownFieldNameError
1473 }
1474 return m.getRepeatedField(fd, index)
1475}
1476
1477// GetRepeatedFieldByNumber returns the value for the repeated field with the
1478// given tag number at the given index. It panics if an error is encountered.
1479// See TryGetRepeatedFieldByNumber.
1480func (m *Message) GetRepeatedFieldByNumber(tagNumber int, index int) interface{} {
1481 if v, err := m.TryGetRepeatedFieldByNumber(tagNumber, index); err != nil {
1482 panic(err.Error())
1483 } else {
1484 return v
1485 }
1486}
1487
1488// TryGetRepeatedFieldByNumber returns the value for the repeated field with the
1489// given tag number at the given index. An error is returned if the given tag is
1490// unknown, if it indicates a field that is not a repeated field (or is a map
1491// field), or if the given index is out of range (less than zero or greater than
1492// or equal to the length of the repeated field).
1493//
1494// (See TryGetField for more info on types.)
1495func (m *Message) TryGetRepeatedFieldByNumber(tagNumber int, index int) (interface{}, error) {
1496 if index < 0 {
1497 return nil, IndexOutOfRangeError
1498 }
1499 fd := m.FindFieldDescriptor(int32(tagNumber))
1500 if fd == nil {
1501 return nil, UnknownTagNumberError
1502 }
1503 return m.getRepeatedField(fd, index)
1504}
1505
1506func (m *Message) getRepeatedField(fd *desc.FieldDescriptor, index int) (interface{}, error) {
1507 if fd.IsMap() || !fd.IsRepeated() {
1508 return nil, FieldIsNotRepeatedError
1509 }
1510 sl := m.values[fd.GetNumber()]
1511 if sl == nil {
1512 var err error
1513 if sl, err = m.parseUnknownField(fd); err != nil {
1514 return nil, err
1515 } else if sl == nil {
1516 return nil, IndexOutOfRangeError
1517 }
1518 }
1519 res := sl.([]interface{})
1520 if index >= len(res) {
1521 return nil, IndexOutOfRangeError
1522 }
1523 return res[index], nil
1524}
1525
1526// AddRepeatedField appends the given value to the given repeated field. It
1527// panics if an error is encountered. See TryAddRepeatedField.
1528func (m *Message) AddRepeatedField(fd *desc.FieldDescriptor, val interface{}) {
1529 if err := m.TryAddRepeatedField(fd, val); err != nil {
1530 panic(err.Error())
1531 }
1532}
1533
1534// TryAddRepeatedField appends the given value to the given repeated field. An
1535// error is returned if the given field descriptor does not belong to the right
1536// message type, if the given field is not repeated, or if the given value is
1537// not a correct/compatible type for the given field. If the given field is a
1538// map field, the call will succeed if the given value is an instance of the
1539// map's entry message type.
1540//
1541// The Go type expected for a field is the same as required by TrySetField for
1542// a non-repeated field of the same type.
1543//
1544// If the given field descriptor is not known (e.g. not present in the message
1545// descriptor) it will become known. Subsequent operations using tag numbers or
1546// names will be able to resolve the newly-known type. If the message has a
1547// value for the unknown value, it is parsed and the given value is appended to
1548// it.
1549func (m *Message) TryAddRepeatedField(fd *desc.FieldDescriptor, val interface{}) error {
1550 if err := m.checkField(fd); err != nil {
1551 return err
1552 }
1553 return m.addRepeatedField(fd, val)
1554}
1555
1556// AddRepeatedFieldByName appends the given value to the repeated field with the
1557// given name. It panics if an error is encountered. See
1558// TryAddRepeatedFieldByName.
1559func (m *Message) AddRepeatedFieldByName(name string, val interface{}) {
1560 if err := m.TryAddRepeatedFieldByName(name, val); err != nil {
1561 panic(err.Error())
1562 }
1563}
1564
1565// TryAddRepeatedFieldByName appends the given value to the repeated field with
1566// the given name. An error is returned if the given name is unknown, if it
1567// names a field that is not repeated, or if the given value has an incorrect
1568// type.
1569//
1570// (See TrySetField for more info on types.)
1571func (m *Message) TryAddRepeatedFieldByName(name string, val interface{}) error {
1572 fd := m.FindFieldDescriptorByName(name)
1573 if fd == nil {
1574 return UnknownFieldNameError
1575 }
1576 return m.addRepeatedField(fd, val)
1577}
1578
1579// AddRepeatedFieldByNumber appends the given value to the repeated field with
1580// the given tag number. It panics if an error is encountered. See
1581// TryAddRepeatedFieldByNumber.
1582func (m *Message) AddRepeatedFieldByNumber(tagNumber int, val interface{}) {
1583 if err := m.TryAddRepeatedFieldByNumber(tagNumber, val); err != nil {
1584 panic(err.Error())
1585 }
1586}
1587
1588// TryAddRepeatedFieldByNumber appends the given value to the repeated field
1589// with the given tag number. An error is returned if the given tag is unknown,
1590// if it indicates a field that is not repeated, or if the given value has an
1591// incorrect type.
1592//
1593// (See TrySetField for more info on types.)
1594func (m *Message) TryAddRepeatedFieldByNumber(tagNumber int, val interface{}) error {
1595 fd := m.FindFieldDescriptor(int32(tagNumber))
1596 if fd == nil {
1597 return UnknownTagNumberError
1598 }
1599 return m.addRepeatedField(fd, val)
1600}
1601
1602func (m *Message) addRepeatedField(fd *desc.FieldDescriptor, val interface{}) error {
1603 if !fd.IsRepeated() {
1604 return FieldIsNotRepeatedError
1605 }
1606 val, err := validElementFieldValue(fd, val)
1607 if err != nil {
1608 return err
1609 }
1610
1611 if fd.IsMap() {
1612 // We're lenient. Just as we allow setting a map field to a slice of entry messages, we also allow
1613 // adding entries one at a time (as if the field were a normal repeated field).
1614 msg := val.(proto.Message)
1615 dm, err := asDynamicMessage(msg, fd.GetMessageType(), m.mf)
1616 if err != nil {
1617 return err
1618 }
1619 k, err := dm.TryGetFieldByNumber(1)
1620 if err != nil {
1621 return err
1622 }
1623 v, err := dm.TryGetFieldByNumber(2)
1624 if err != nil {
1625 return err
1626 }
1627 return m.putMapField(fd, k, v)
1628 }
1629
1630 sl := m.values[fd.GetNumber()]
1631 if sl == nil {
1632 if sl, err = m.parseUnknownField(fd); err != nil {
1633 return err
1634 } else if sl == nil {
1635 sl = []interface{}{}
1636 }
1637 }
1638 res := sl.([]interface{})
1639 res = append(res, val)
1640 m.internalSetField(fd, res)
1641 return nil
1642}
1643
1644// SetRepeatedField sets the value for the given repeated field descriptor and
1645// given index to the given value. It panics if an error is encountered. See
1646// SetRepeatedField.
1647func (m *Message) SetRepeatedField(fd *desc.FieldDescriptor, index int, val interface{}) {
1648 if err := m.TrySetRepeatedField(fd, index, val); err != nil {
1649 panic(err.Error())
1650 }
1651}
1652
1653// TrySetRepeatedField sets the value for the given repeated field descriptor
1654// and given index to the given value. An error is returned if the given field
1655// descriptor does not belong to the right message type, if the given field is
1656// not repeated, or if the given value is not a correct/compatible type for the
1657// given field. Also, even though map fields technically are repeated fields, if
1658// the given field is a map field an error will result: map representation does
1659// not lend itself to random access by index.
1660//
1661// The Go type expected for a field is the same as required by TrySetField for
1662// a non-repeated field of the same type.
1663//
1664// If the given field descriptor is not known (e.g. not present in the message
1665// descriptor) it will become known. Subsequent operations using tag numbers or
1666// names will be able to resolve the newly-known type. If the message has a
1667// value for the unknown value, it is parsed and the element at the given index
1668// is replaced with the given value.
1669func (m *Message) TrySetRepeatedField(fd *desc.FieldDescriptor, index int, val interface{}) error {
1670 if index < 0 {
1671 return IndexOutOfRangeError
1672 }
1673 if err := m.checkField(fd); err != nil {
1674 return err
1675 }
1676 return m.setRepeatedField(fd, index, val)
1677}
1678
1679// SetRepeatedFieldByName sets the value for the repeated field with the given
1680// name and given index to the given value. It panics if an error is
1681// encountered. See TrySetRepeatedFieldByName.
1682func (m *Message) SetRepeatedFieldByName(name string, index int, val interface{}) {
1683 if err := m.TrySetRepeatedFieldByName(name, index, val); err != nil {
1684 panic(err.Error())
1685 }
1686}
1687
1688// TrySetRepeatedFieldByName sets the value for the repeated field with the
1689// given name and the given index to the given value. An error is returned if
1690// the given name is unknown, if it names a field that is not repeated (or is a
1691// map field), or if the given value has an incorrect type.
1692//
1693// (See TrySetField for more info on types.)
1694func (m *Message) TrySetRepeatedFieldByName(name string, index int, val interface{}) error {
1695 if index < 0 {
1696 return IndexOutOfRangeError
1697 }
1698 fd := m.FindFieldDescriptorByName(name)
1699 if fd == nil {
1700 return UnknownFieldNameError
1701 }
1702 return m.setRepeatedField(fd, index, val)
1703}
1704
1705// SetRepeatedFieldByNumber sets the value for the repeated field with the given
1706// tag number and given index to the given value. It panics if an error is
1707// encountered. See TrySetRepeatedFieldByNumber.
1708func (m *Message) SetRepeatedFieldByNumber(tagNumber int, index int, val interface{}) {
1709 if err := m.TrySetRepeatedFieldByNumber(tagNumber, index, val); err != nil {
1710 panic(err.Error())
1711 }
1712}
1713
1714// TrySetRepeatedFieldByNumber sets the value for the repeated field with the
1715// given tag number and the given index to the given value. An error is returned
1716// if the given tag is unknown, if it indicates a field that is not repeated (or
1717// is a map field), or if the given value has an incorrect type.
1718//
1719// (See TrySetField for more info on types.)
1720func (m *Message) TrySetRepeatedFieldByNumber(tagNumber int, index int, val interface{}) error {
1721 if index < 0 {
1722 return IndexOutOfRangeError
1723 }
1724 fd := m.FindFieldDescriptor(int32(tagNumber))
1725 if fd == nil {
1726 return UnknownTagNumberError
1727 }
1728 return m.setRepeatedField(fd, index, val)
1729}
1730
1731func (m *Message) setRepeatedField(fd *desc.FieldDescriptor, index int, val interface{}) error {
1732 if fd.IsMap() || !fd.IsRepeated() {
1733 return FieldIsNotRepeatedError
1734 }
1735 val, err := validElementFieldValue(fd, val)
1736 if err != nil {
1737 return err
1738 }
1739 sl := m.values[fd.GetNumber()]
1740 if sl == nil {
1741 if sl, err = m.parseUnknownField(fd); err != nil {
1742 return err
1743 } else if sl == nil {
1744 return IndexOutOfRangeError
1745 }
1746 }
1747 res := sl.([]interface{})
1748 if index >= len(res) {
1749 return IndexOutOfRangeError
1750 }
1751 res[index] = val
1752 return nil
1753}
1754
1755// GetUnknownField gets the value(s) for the given unknown tag number. If this
1756// message has no unknown fields with the given tag, nil is returned.
1757func (m *Message) GetUnknownField(tagNumber int32) []UnknownField {
1758 if u, ok := m.unknownFields[tagNumber]; ok {
1759 return u
1760 } else {
1761 return nil
1762 }
1763}
1764
1765func (m *Message) parseUnknownField(fd *desc.FieldDescriptor) (interface{}, error) {
1766 unks, ok := m.unknownFields[fd.GetNumber()]
1767 if !ok {
1768 return nil, nil
1769 }
1770 var v interface{}
1771 var sl []interface{}
1772 var mp map[interface{}]interface{}
1773 if fd.IsMap() {
1774 mp = map[interface{}]interface{}{}
1775 }
1776 var err error
1777 for _, unk := range unks {
1778 var val interface{}
1779 if unk.Encoding == proto.WireBytes || unk.Encoding == proto.WireStartGroup {
1780 val, err = unmarshalLengthDelimitedField(fd, unk.Contents, m.mf)
1781 } else {
1782 val, err = unmarshalSimpleField(fd, unk.Value)
1783 }
1784 if err != nil {
1785 return nil, err
1786 }
1787 if fd.IsMap() {
1788 newEntry := val.(*Message)
1789 kk, err := newEntry.TryGetFieldByNumber(1)
1790 if err != nil {
1791 return nil, err
1792 }
1793 vv, err := newEntry.TryGetFieldByNumber(2)
1794 if err != nil {
1795 return nil, err
1796 }
1797 mp[kk] = vv
1798 v = mp
1799 } else if fd.IsRepeated() {
1800 t := reflect.TypeOf(val)
1801 if t.Kind() == reflect.Slice && t != typeOfBytes {
1802 // append slices if we unmarshalled a packed repeated field
1803 newVals := val.([]interface{})
1804 sl = append(sl, newVals...)
1805 } else {
1806 sl = append(sl, val)
1807 }
1808 v = sl
1809 } else {
1810 v = val
1811 }
1812 }
1813 m.internalSetField(fd, v)
1814 return v, nil
1815}
1816
1817func validFieldValue(fd *desc.FieldDescriptor, val interface{}) (interface{}, error) {
1818 return validFieldValueForRv(fd, reflect.ValueOf(val))
1819}
1820
1821func validFieldValueForRv(fd *desc.FieldDescriptor, val reflect.Value) (interface{}, error) {
1822 if fd.IsMap() && val.Kind() == reflect.Map {
1823 return validFieldValueForMapField(fd, val)
1824 }
1825
1826 if fd.IsRepeated() { // this will also catch map fields where given value was not a map
1827 if val.Kind() != reflect.Array && val.Kind() != reflect.Slice {
1828 if fd.IsMap() {
1829 return nil, fmt.Errorf("value for map field must be a map; instead was %v", val.Type())
1830 } else {
1831 return nil, fmt.Errorf("value for repeated field must be a slice; instead was %v", val.Type())
1832 }
1833 }
1834
1835 if fd.IsMap() {
1836 // value should be a slice of entry messages that we need convert into a map[interface{}]interface{}
1837 m := map[interface{}]interface{}{}
1838 for i := 0; i < val.Len(); i++ {
1839 e, err := validElementFieldValue(fd, val.Index(i).Interface())
1840 if err != nil {
1841 return nil, err
1842 }
1843 msg := e.(proto.Message)
1844 dm, err := asDynamicMessage(msg, fd.GetMessageType(), nil)
1845 if err != nil {
1846 return nil, err
1847 }
1848 k, err := dm.TryGetFieldByNumber(1)
1849 if err != nil {
1850 return nil, err
1851 }
1852 v, err := dm.TryGetFieldByNumber(2)
1853 if err != nil {
1854 return nil, err
1855 }
1856 m[k] = v
1857 }
1858 return m, nil
1859 }
1860
1861 // make a defensive copy while checking contents (also converts to []interface{})
1862 s := make([]interface{}, val.Len())
1863 for i := 0; i < val.Len(); i++ {
1864 ev := val.Index(i)
1865 if ev.Kind() == reflect.Interface {
1866 // unwrap it
1867 ev = reflect.ValueOf(ev.Interface())
1868 }
1869 e, err := validElementFieldValueForRv(fd, ev)
1870 if err != nil {
1871 return nil, err
1872 }
1873 s[i] = e
1874 }
1875
1876 return s, nil
1877 }
1878
1879 return validElementFieldValueForRv(fd, val)
1880}
1881
1882func asDynamicMessage(m proto.Message, md *desc.MessageDescriptor, mf *MessageFactory) (*Message, error) {
1883 if dm, ok := m.(*Message); ok {
1884 return dm, nil
1885 }
1886 dm := NewMessageWithMessageFactory(md, mf)
1887 if err := dm.mergeFrom(m); err != nil {
1888 return nil, err
1889 }
1890 return dm, nil
1891}
1892
1893func validElementFieldValue(fd *desc.FieldDescriptor, val interface{}) (interface{}, error) {
1894 return validElementFieldValueForRv(fd, reflect.ValueOf(val))
1895}
1896
1897func validElementFieldValueForRv(fd *desc.FieldDescriptor, val reflect.Value) (interface{}, error) {
1898 t := fd.GetType()
1899 if !val.IsValid() {
1900 return nil, typeError(fd, nil)
1901 }
1902
1903 switch t {
1904 case descriptor.FieldDescriptorProto_TYPE_SFIXED32,
1905 descriptor.FieldDescriptorProto_TYPE_INT32,
1906 descriptor.FieldDescriptorProto_TYPE_SINT32,
1907 descriptor.FieldDescriptorProto_TYPE_ENUM:
1908 return toInt32(reflect.Indirect(val), fd)
1909
1910 case descriptor.FieldDescriptorProto_TYPE_SFIXED64,
1911 descriptor.FieldDescriptorProto_TYPE_INT64,
1912 descriptor.FieldDescriptorProto_TYPE_SINT64:
1913 return toInt64(reflect.Indirect(val), fd)
1914
1915 case descriptor.FieldDescriptorProto_TYPE_FIXED32,
1916 descriptor.FieldDescriptorProto_TYPE_UINT32:
1917 return toUint32(reflect.Indirect(val), fd)
1918
1919 case descriptor.FieldDescriptorProto_TYPE_FIXED64,
1920 descriptor.FieldDescriptorProto_TYPE_UINT64:
1921 return toUint64(reflect.Indirect(val), fd)
1922
1923 case descriptor.FieldDescriptorProto_TYPE_FLOAT:
1924 return toFloat32(reflect.Indirect(val), fd)
1925
1926 case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
1927 return toFloat64(reflect.Indirect(val), fd)
1928
1929 case descriptor.FieldDescriptorProto_TYPE_BOOL:
1930 return toBool(reflect.Indirect(val), fd)
1931
1932 case descriptor.FieldDescriptorProto_TYPE_BYTES:
1933 return toBytes(reflect.Indirect(val), fd)
1934
1935 case descriptor.FieldDescriptorProto_TYPE_STRING:
1936 return toString(reflect.Indirect(val), fd)
1937
1938 case descriptor.FieldDescriptorProto_TYPE_MESSAGE,
1939 descriptor.FieldDescriptorProto_TYPE_GROUP:
1940 m, err := asMessage(val, fd.GetFullyQualifiedName())
1941 // check that message is correct type
1942 if err != nil {
1943 return nil, err
1944 }
1945 var msgType string
1946 if dm, ok := m.(*Message); ok {
1947 msgType = dm.GetMessageDescriptor().GetFullyQualifiedName()
1948 } else {
1949 msgType = proto.MessageName(m)
1950 }
1951 if msgType != fd.GetMessageType().GetFullyQualifiedName() {
1952 return nil, fmt.Errorf("message field %s requires value of type %s; received %s", fd.GetFullyQualifiedName(), fd.GetMessageType().GetFullyQualifiedName(), msgType)
1953 }
1954 return m, nil
1955
1956 default:
1957 return nil, fmt.Errorf("unable to handle unrecognized field type: %v", fd.GetType())
1958 }
1959}
1960
1961func toInt32(v reflect.Value, fd *desc.FieldDescriptor) (int32, error) {
1962 if v.Kind() == reflect.Int32 {
1963 return int32(v.Int()), nil
1964 }
1965 return 0, typeError(fd, v.Type())
1966}
1967
1968func toUint32(v reflect.Value, fd *desc.FieldDescriptor) (uint32, error) {
1969 if v.Kind() == reflect.Uint32 {
1970 return uint32(v.Uint()), nil
1971 }
1972 return 0, typeError(fd, v.Type())
1973}
1974
1975func toFloat32(v reflect.Value, fd *desc.FieldDescriptor) (float32, error) {
1976 if v.Kind() == reflect.Float32 {
1977 return float32(v.Float()), nil
1978 }
1979 return 0, typeError(fd, v.Type())
1980}
1981
1982func toInt64(v reflect.Value, fd *desc.FieldDescriptor) (int64, error) {
1983 if v.Kind() == reflect.Int64 || v.Kind() == reflect.Int || v.Kind() == reflect.Int32 {
1984 return v.Int(), nil
1985 }
1986 return 0, typeError(fd, v.Type())
1987}
1988
1989func toUint64(v reflect.Value, fd *desc.FieldDescriptor) (uint64, error) {
1990 if v.Kind() == reflect.Uint64 || v.Kind() == reflect.Uint || v.Kind() == reflect.Uint32 {
1991 return v.Uint(), nil
1992 }
1993 return 0, typeError(fd, v.Type())
1994}
1995
1996func toFloat64(v reflect.Value, fd *desc.FieldDescriptor) (float64, error) {
1997 if v.Kind() == reflect.Float64 || v.Kind() == reflect.Float32 {
1998 return v.Float(), nil
1999 }
2000 return 0, typeError(fd, v.Type())
2001}
2002
2003func toBool(v reflect.Value, fd *desc.FieldDescriptor) (bool, error) {
2004 if v.Kind() == reflect.Bool {
2005 return v.Bool(), nil
2006 }
2007 return false, typeError(fd, v.Type())
2008}
2009
2010func toBytes(v reflect.Value, fd *desc.FieldDescriptor) ([]byte, error) {
2011 if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 {
2012 return v.Bytes(), nil
2013 }
2014 return nil, typeError(fd, v.Type())
2015}
2016
2017func toString(v reflect.Value, fd *desc.FieldDescriptor) (string, error) {
2018 if v.Kind() == reflect.String {
2019 return v.String(), nil
2020 }
2021 return "", typeError(fd, v.Type())
2022}
2023
2024func typeError(fd *desc.FieldDescriptor, t reflect.Type) error {
2025 return fmt.Errorf(
2026 "%s field %s is not compatible with value of type %v",
2027 getTypeString(fd), fd.GetFullyQualifiedName(), t)
2028}
2029
2030func getTypeString(fd *desc.FieldDescriptor) string {
2031 return strings.ToLower(fd.GetType().String())
2032}
2033
2034func asMessage(v reflect.Value, fieldName string) (proto.Message, error) {
2035 t := v.Type()
2036 // we need a pointer to a struct that implements proto.Message
2037 if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct || !t.Implements(typeOfProtoMessage) {
2038 return nil, fmt.Errorf("message field %s requires is not compatible with value of type %v", fieldName, v.Type())
2039 }
2040 return v.Interface().(proto.Message), nil
2041}
2042
2043// Reset resets this message to an empty message. It removes all values set in
2044// the message.
2045func (m *Message) Reset() {
2046 for k := range m.values {
2047 delete(m.values, k)
2048 }
2049 for k := range m.unknownFields {
2050 delete(m.unknownFields, k)
2051 }
2052}
2053
2054// String returns this message rendered in compact text format.
2055func (m *Message) String() string {
2056 b, err := m.MarshalText()
2057 if err != nil {
2058 panic(fmt.Sprintf("Failed to create string representation of message: %s", err.Error()))
2059 }
2060 return string(b)
2061}
2062
2063// ProtoMessage is present to satisfy the proto.Message interface.
2064func (m *Message) ProtoMessage() {
2065}
2066
2067// ConvertTo converts this dynamic message into the given message. This is
2068// shorthand for resetting then merging:
2069// target.Reset()
2070// m.MergeInto(target)
2071func (m *Message) ConvertTo(target proto.Message) error {
2072 if err := m.checkType(target); err != nil {
2073 return err
2074 }
2075
2076 target.Reset()
2077 return m.mergeInto(target)
2078}
2079
2080// ConvertFrom converts the given message into this dynamic message. This is
2081// shorthand for resetting then merging:
2082// m.Reset()
2083// m.MergeFrom(target)
2084func (m *Message) ConvertFrom(target proto.Message) error {
2085 if err := m.checkType(target); err != nil {
2086 return err
2087 }
2088
2089 m.Reset()
2090 return m.mergeFrom(target)
2091}
2092
2093// MergeInto merges this dynamic message into the given message. All field
2094// values in this message will be set on the given message. For map fields,
2095// entries are added to the given message (if the given message has existing
2096// values for like keys, they are overwritten). For slice fields, elements are
2097// added.
2098//
2099// If the given message has a different set of known fields, it is possible for
2100// some known fields in this message to be represented as unknown fields in the
2101// given message after merging, and vice versa.
2102func (m *Message) MergeInto(target proto.Message) error {
2103 if err := m.checkType(target); err != nil {
2104 return err
2105 }
2106 return m.mergeInto(target)
2107}
2108
2109// MergeFrom merges the given message into this dynamic message. All field
2110// values in the given message will be set on this message. For map fields,
2111// entries are added to this message (if this message has existing values for
2112// like keys, they are overwritten). For slice fields, elements are added.
2113//
2114// If the given message has a different set of known fields, it is possible for
2115// some known fields in that message to be represented as unknown fields in this
2116// message after merging, and vice versa.
2117func (m *Message) MergeFrom(source proto.Message) error {
2118 if err := m.checkType(source); err != nil {
2119 return err
2120 }
2121 return m.mergeFrom(source)
2122}
2123
2124// Merge implements the proto.Merger interface so that dynamic messages are
2125// compatible with the proto.Merge function. It delegates to MergeFrom but will
2126// panic on error as the proto.Merger interface doesn't allow for returning an
2127// error.
2128//
2129// Unlike nearly all other methods, this method can work if this message's type
2130// is not defined (such as instantiating the message without using NewMessage).
2131// This is strictly so that dynamic message's are compatible with the
2132// proto.Clone function, which instantiates a new message via reflection (thus
2133// its message descriptor will not be set) and than calls Merge.
2134func (m *Message) Merge(source proto.Message) {
2135 if m.md == nil {
2136 // To support proto.Clone, initialize the descriptor from the source.
2137 if dm, ok := source.(*Message); ok {
2138 m.md = dm.md
2139 // also make sure the clone uses the same message factory and
2140 // extensions and also knows about the same extra fields (if any)
2141 m.mf = dm.mf
2142 m.er = dm.er
2143 m.extraFields = dm.extraFields
2144 } else if md, err := desc.LoadMessageDescriptorForMessage(source); err != nil {
2145 panic(err.Error())
2146 } else {
2147 m.md = md
2148 }
2149 }
2150
2151 if err := m.MergeFrom(source); err != nil {
2152 panic(err.Error())
2153 }
2154}
2155
2156func (m *Message) checkType(target proto.Message) error {
2157 if dm, ok := target.(*Message); ok {
2158 if dm.md.GetFullyQualifiedName() != m.md.GetFullyQualifiedName() {
2159 return fmt.Errorf("given message has wrong type: %q; expecting %q", dm.md.GetFullyQualifiedName(), m.md.GetFullyQualifiedName())
2160 }
2161 return nil
2162 }
2163
2164 msgName := proto.MessageName(target)
2165 if msgName != m.md.GetFullyQualifiedName() {
2166 return fmt.Errorf("given message has wrong type: %q; expecting %q", msgName, m.md.GetFullyQualifiedName())
2167 }
2168 return nil
2169}
2170
2171func (m *Message) mergeInto(pm proto.Message) error {
2172 if dm, ok := pm.(*Message); ok {
2173 return dm.mergeFrom(m)
2174 }
2175
2176 target := reflect.ValueOf(pm)
2177 if target.Kind() == reflect.Ptr {
2178 target = target.Elem()
2179 }
2180
2181 // track tags for which the dynamic message has data but the given
2182 // message doesn't know about it
2183 u := target.FieldByName("XXX_unrecognized")
2184 var unknownTags map[int32]struct{}
2185 if u.IsValid() && u.Type() == typeOfBytes {
2186 unknownTags = map[int32]struct{}{}
2187 for tag := range m.values {
2188 unknownTags[tag] = struct{}{}
2189 }
2190 }
2191
2192 // check that we can successfully do the merge
2193 structProps := proto.GetProperties(reflect.TypeOf(pm).Elem())
2194 for _, prop := range structProps.Prop {
2195 if prop.Tag == 0 {
2196 continue // one-of or special field (such as XXX_unrecognized, etc.)
2197 }
2198 tag := int32(prop.Tag)
2199 v, ok := m.values[tag]
2200 if !ok {
2201 continue
2202 }
2203 if unknownTags != nil {
2204 delete(unknownTags, tag)
2205 }
2206 f := target.FieldByName(prop.Name)
2207 ft := f.Type()
2208 val := reflect.ValueOf(v)
2209 if !canConvert(val, ft) {
2210 return fmt.Errorf("cannot convert %v to %v", val.Type(), ft)
2211 }
2212 }
2213 // check one-of fields
2214 for _, oop := range structProps.OneofTypes {
2215 prop := oop.Prop
2216 tag := int32(prop.Tag)
2217 v, ok := m.values[tag]
2218 if !ok {
2219 continue
2220 }
2221 if unknownTags != nil {
2222 delete(unknownTags, tag)
2223 }
2224 stf, ok := oop.Type.Elem().FieldByName(prop.Name)
2225 if !ok {
2226 return fmt.Errorf("one-of field indicates struct field name %s, but type %v has no such field", prop.Name, oop.Type.Elem())
2227 }
2228 ft := stf.Type
2229 val := reflect.ValueOf(v)
2230 if !canConvert(val, ft) {
2231 return fmt.Errorf("cannot convert %v to %v", val.Type(), ft)
2232 }
2233 }
2234 // and check extensions, too
2235 for tag, ext := range proto.RegisteredExtensions(pm) {
2236 v, ok := m.values[tag]
2237 if !ok {
2238 continue
2239 }
2240 if unknownTags != nil {
2241 delete(unknownTags, tag)
2242 }
2243 ft := reflect.TypeOf(ext.ExtensionType)
2244 val := reflect.ValueOf(v)
2245 if !canConvert(val, ft) {
2246 return fmt.Errorf("cannot convert %v to %v", val.Type(), ft)
2247 }
2248 }
2249
2250 // now actually perform the merge
2251 for _, prop := range structProps.Prop {
2252 v, ok := m.values[int32(prop.Tag)]
2253 if !ok {
2254 continue
2255 }
2256 f := target.FieldByName(prop.Name)
2257 if err := mergeVal(reflect.ValueOf(v), f); err != nil {
2258 return err
2259 }
2260 }
2261 // merge one-ofs
2262 for _, oop := range structProps.OneofTypes {
2263 prop := oop.Prop
2264 tag := int32(prop.Tag)
2265 v, ok := m.values[tag]
2266 if !ok {
2267 continue
2268 }
2269 oov := reflect.New(oop.Type.Elem())
2270 f := oov.Elem().FieldByName(prop.Name)
2271 if err := mergeVal(reflect.ValueOf(v), f); err != nil {
2272 return err
2273 }
2274 target.Field(oop.Field).Set(oov)
2275 }
2276 // merge extensions, too
2277 for tag, ext := range proto.RegisteredExtensions(pm) {
2278 v, ok := m.values[tag]
2279 if !ok {
2280 continue
2281 }
2282 e := reflect.New(reflect.TypeOf(ext.ExtensionType)).Elem()
2283 if err := mergeVal(reflect.ValueOf(v), e); err != nil {
2284 return err
2285 }
2286 if err := proto.SetExtension(pm, ext, e.Interface()); err != nil {
2287 // shouldn't happen since we already checked that the extension type was compatible above
2288 return err
2289 }
2290 }
2291
2292 // if we have fields that the given message doesn't know about, add to its unknown fields
2293 if len(unknownTags) > 0 {
2294 ub := u.Interface().([]byte)
2295 var b codedBuffer
2296 for tag := range unknownTags {
2297 fd := m.FindFieldDescriptor(tag)
2298 if err := marshalField(tag, fd, m.values[tag], &b, false); err != nil {
2299 return err
2300 }
2301 }
2302 ub = append(ub, b.buf...)
2303 u.Set(reflect.ValueOf(ub))
2304 }
2305
2306 // finally, convey unknown fields into the given message by letting it unmarshal them
2307 // (this will append to its unknown fields if not known; if somehow the given message recognizes
2308 // a field even though the dynamic message did not, it will get correctly unmarshalled)
2309 if unknownTags != nil && len(m.unknownFields) > 0 {
2310 var b codedBuffer
2311 m.marshalUnknownFields(&b)
2312 proto.UnmarshalMerge(b.buf, pm)
2313 }
2314
2315 return nil
2316}
2317
2318func canConvert(src reflect.Value, target reflect.Type) bool {
2319 if src.Kind() == reflect.Interface {
2320 src = reflect.ValueOf(src.Interface())
2321 }
2322 srcType := src.Type()
2323 // we allow convertible types instead of requiring exact types so that calling
2324 // code can, for example, assign an enum constant to an enum field. In that case,
2325 // one type is the enum type (a sub-type of int32) and the other may be the int32
2326 // type. So we automatically do the conversion in that case.
2327 if srcType.ConvertibleTo(target) {
2328 return true
2329 } else if target.Kind() == reflect.Ptr && srcType.ConvertibleTo(target.Elem()) {
2330 return true
2331 } else if target.Kind() == reflect.Slice {
2332 if srcType.Kind() != reflect.Slice {
2333 return false
2334 }
2335 et := target.Elem()
2336 for i := 0; i < src.Len(); i++ {
2337 if !canConvert(src.Index(i), et) {
2338 return false
2339 }
2340 }
2341 return true
2342 } else if target.Kind() == reflect.Map {
2343 if srcType.Kind() != reflect.Map {
2344 return false
2345 }
2346 return canConvertMap(src, target)
2347 } else if srcType == typeOfDynamicMessage && target.Implements(typeOfProtoMessage) {
2348 z := reflect.Zero(target).Interface()
2349 msgType := proto.MessageName(z.(proto.Message))
2350 return msgType == src.Interface().(*Message).GetMessageDescriptor().GetFullyQualifiedName()
2351 } else {
2352 return false
2353 }
2354}
2355
2356func mergeVal(src, target reflect.Value) error {
2357 if src.Kind() == reflect.Interface && !src.IsNil() {
2358 src = src.Elem()
2359 }
2360 srcType := src.Type()
2361 targetType := target.Type()
2362 if srcType.ConvertibleTo(targetType) {
2363 if targetType.Implements(typeOfProtoMessage) && !target.IsNil() {
2364 Merge(target.Interface().(proto.Message), src.Convert(targetType).Interface().(proto.Message))
2365 } else {
2366 target.Set(src.Convert(targetType))
2367 }
2368 } else if targetType.Kind() == reflect.Ptr && srcType.ConvertibleTo(targetType.Elem()) {
2369 if !src.CanAddr() {
2370 target.Set(reflect.New(targetType.Elem()))
2371 target.Elem().Set(src.Convert(targetType.Elem()))
2372 } else {
2373 target.Set(src.Addr().Convert(targetType))
2374 }
2375 } else if targetType.Kind() == reflect.Slice {
2376 l := target.Len()
2377 newL := l + src.Len()
2378 if target.Cap() < newL {
2379 // expand capacity of the slice and copy
2380 newSl := reflect.MakeSlice(targetType, newL, newL)
2381 for i := 0; i < target.Len(); i++ {
2382 newSl.Index(i).Set(target.Index(i))
2383 }
2384 target.Set(newSl)
2385 } else {
2386 target.SetLen(newL)
2387 }
2388 for i := 0; i < src.Len(); i++ {
2389 dest := target.Index(l + i)
2390 if dest.Kind() == reflect.Ptr {
2391 dest.Set(reflect.New(dest.Type().Elem()))
2392 }
2393 if err := mergeVal(src.Index(i), dest); err != nil {
2394 return err
2395 }
2396 }
2397 } else if targetType.Kind() == reflect.Map {
2398 return mergeMapVal(src, target, targetType)
2399 } else if srcType == typeOfDynamicMessage && targetType.Implements(typeOfProtoMessage) {
2400 dm := src.Interface().(*Message)
2401 if target.IsNil() {
2402 target.Set(reflect.New(targetType.Elem()))
2403 }
2404 m := target.Interface().(proto.Message)
2405 if err := dm.mergeInto(m); err != nil {
2406 return err
2407 }
2408 } else {
2409 return fmt.Errorf("cannot convert %v to %v", srcType, targetType)
2410 }
2411 return nil
2412}
2413
2414func (m *Message) mergeFrom(pm proto.Message) error {
2415 if dm, ok := pm.(*Message); ok {
2416 // if given message is also a dynamic message, we merge differently
2417 for tag, v := range dm.values {
2418 fd := m.FindFieldDescriptor(tag)
2419 if fd == nil {
2420 fd = dm.FindFieldDescriptor(tag)
2421 }
2422 if err := mergeField(m, fd, v); err != nil {
2423 return err
2424 }
2425 }
2426 return nil
2427 }
2428
2429 pmrv := reflect.ValueOf(pm)
2430 if pmrv.IsNil() {
2431 // nil is an empty message, so nothing to do
2432 return nil
2433 }
2434
2435 // check that we can successfully do the merge
2436 src := pmrv.Elem()
2437 values := map[*desc.FieldDescriptor]interface{}{}
2438 props := proto.GetProperties(reflect.TypeOf(pm).Elem())
2439 if props == nil {
2440 return fmt.Errorf("could not determine message properties to merge for %v", reflect.TypeOf(pm).Elem())
2441 }
2442
2443 // regular fields
2444 for _, prop := range props.Prop {
2445 if prop.Tag == 0 {
2446 continue // one-of or special field (such as XXX_unrecognized, etc.)
2447 }
2448 fd := m.FindFieldDescriptor(int32(prop.Tag))
2449 if fd == nil {
2450 // Our descriptor has different fields than this message object. So
2451 // try to reflect on the message object's fields.
2452 md, err := desc.LoadMessageDescriptorForMessage(pm)
2453 if err != nil {
2454 return err
2455 }
2456 fd = md.FindFieldByNumber(int32(prop.Tag))
2457 if fd == nil {
2458 return fmt.Errorf("message descriptor %q did not contain field for tag %d (%q)", md.GetFullyQualifiedName(), prop.Tag, prop.Name)
2459 }
2460 }
2461 rv := src.FieldByName(prop.Name)
2462 if (rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Slice) && rv.IsNil() {
2463 continue
2464 }
2465 if v, err := validFieldValueForRv(fd, rv); err != nil {
2466 return err
2467 } else {
2468 values[fd] = v
2469 }
2470 }
2471
2472 // one-of fields
2473 for _, oop := range props.OneofTypes {
2474 oov := src.Field(oop.Field).Elem()
2475 if !oov.IsValid() || oov.Type() != oop.Type {
2476 // this field is unset (in other words, one-of message field is not currently set to this option)
2477 continue
2478 }
2479 prop := oop.Prop
2480 rv := oov.Elem().FieldByName(prop.Name)
2481 fd := m.FindFieldDescriptor(int32(prop.Tag))
2482 if fd == nil {
2483 // Our descriptor has different fields than this message object. So
2484 // try to reflect on the message object's fields.
2485 md, err := desc.LoadMessageDescriptorForMessage(pm)
2486 if err != nil {
2487 return err
2488 }
2489 fd = md.FindFieldByNumber(int32(prop.Tag))
2490 if fd == nil {
2491 return fmt.Errorf("message descriptor %q did not contain field for tag %d (%q in one-of %q)", md.GetFullyQualifiedName(), prop.Tag, prop.Name, src.Type().Field(oop.Field).Name)
2492 }
2493 }
2494 if v, err := validFieldValueForRv(fd, rv); err != nil {
2495 return err
2496 } else {
2497 values[fd] = v
2498 }
2499 }
2500
2501 // extension fields
2502 rexts, _ := proto.ExtensionDescs(pm)
2503 var unknownExtensions []byte
2504 for _, ed := range rexts {
2505 v, _ := proto.GetExtension(pm, ed)
2506 if v == nil {
2507 continue
2508 }
2509 if ed.ExtensionType == nil {
2510 extBytes, _ := v.([]byte)
2511 if len(extBytes) > 0 {
2512 unknownExtensions = append(unknownExtensions, extBytes...)
2513 }
2514 continue
2515 }
2516 fd := m.er.FindExtension(m.md.GetFullyQualifiedName(), ed.Field)
2517 if fd == nil {
2518 var err error
2519 if fd, err = desc.LoadFieldDescriptorForExtension(ed); err != nil {
2520 return err
2521 }
2522 }
2523 if v, err := validFieldValue(fd, v); err != nil {
2524 return err
2525 } else {
2526 values[fd] = v
2527 }
2528 }
2529
2530 // now actually perform the merge
2531 for fd, v := range values {
2532 mergeField(m, fd, v)
2533 }
2534
2535 u := src.FieldByName("XXX_unrecognized")
2536 if u.IsValid() && u.Type() == typeOfBytes {
2537 // ignore any error returned: pulling in unknown fields is best-effort
2538 m.UnmarshalMerge(u.Interface().([]byte))
2539 }
2540
2541 // lastly, also extract any unknown extensions the message may have (unknown extensions
2542 // are stored with other extensions, not in the XXX_unrecognized field, so we have to do
2543 // more than just the step above...)
2544 if len(unknownExtensions) > 0 {
2545 // pulling in unknown fields is best-effort, so we just ignore errors
2546 m.UnmarshalMerge(unknownExtensions)
2547 }
2548 return nil
2549}
2550
2551// Validate checks that all required fields are present. It returns an error if any are absent.
2552func (m *Message) Validate() error {
2553 missingFields := m.findMissingFields()
2554 if len(missingFields) == 0 {
2555 return nil
2556 }
2557 return fmt.Errorf("some required fields missing: %v", strings.Join(missingFields, ", "))
2558}
2559
2560func (m *Message) findMissingFields() []string {
2561 if m.md.IsProto3() {
2562 // proto3 does not allow required fields
2563 return nil
2564 }
2565 var missingFields []string
2566 for _, fd := range m.md.GetFields() {
2567 if fd.IsRequired() {
2568 if _, ok := m.values[fd.GetNumber()]; !ok {
2569 missingFields = append(missingFields, fd.GetName())
2570 }
2571 }
2572 }
2573 return missingFields
2574}
2575
2576// ValidateRecursive checks that all required fields are present and also
2577// recursively validates all fields who are also messages. It returns an error
2578// if any required fields, in this message or nested within, are absent.
2579func (m *Message) ValidateRecursive() error {
2580 return m.validateRecursive("")
2581}
2582
2583func (m *Message) validateRecursive(prefix string) error {
2584 if missingFields := m.findMissingFields(); len(missingFields) > 0 {
2585 for i := range missingFields {
2586 missingFields[i] = fmt.Sprintf("%s%s", prefix, missingFields[i])
2587 }
2588 return fmt.Errorf("some required fields missing: %v", strings.Join(missingFields, ", "))
2589 }
2590
2591 for tag, fld := range m.values {
2592 fd := m.FindFieldDescriptor(tag)
2593 var chprefix string
2594 var md *desc.MessageDescriptor
2595 checkMsg := func(pm proto.Message) error {
2596 var dm *Message
2597 if d, ok := pm.(*Message); ok {
2598 dm = d
2599 } else {
2600 dm = m.mf.NewDynamicMessage(md)
2601 if err := dm.ConvertFrom(pm); err != nil {
2602 return nil
2603 }
2604 }
2605 if err := dm.validateRecursive(chprefix); err != nil {
2606 return err
2607 }
2608 return nil
2609 }
2610 isMap := fd.IsMap()
2611 if isMap && fd.GetMapValueType().GetMessageType() != nil {
2612 md = fd.GetMapValueType().GetMessageType()
2613 mp := fld.(map[interface{}]interface{})
2614 for k, v := range mp {
2615 chprefix = fmt.Sprintf("%s%s[%v].", prefix, getName(fd), k)
2616 if err := checkMsg(v.(proto.Message)); err != nil {
2617 return err
2618 }
2619 }
2620 } else if !isMap && fd.GetMessageType() != nil {
2621 md = fd.GetMessageType()
2622 if fd.IsRepeated() {
2623 sl := fld.([]interface{})
2624 for i, v := range sl {
2625 chprefix = fmt.Sprintf("%s%s[%d].", prefix, getName(fd), i)
2626 if err := checkMsg(v.(proto.Message)); err != nil {
2627 return err
2628 }
2629 }
2630 } else {
2631 chprefix = fmt.Sprintf("%s%s.", prefix, getName(fd))
2632 if err := checkMsg(fld.(proto.Message)); err != nil {
2633 return err
2634 }
2635 }
2636 }
2637 }
2638
2639 return nil
2640}
2641
2642func getName(fd *desc.FieldDescriptor) string {
2643 if fd.IsExtension() {
2644 return fmt.Sprintf("(%s)", fd.GetFullyQualifiedName())
2645 } else {
2646 return fd.GetName()
2647 }
2648}
2649
2650// knownFieldTags return tags of present and recognized fields, in sorted order.
2651func (m *Message) knownFieldTags() []int {
2652 if len(m.values) == 0 {
2653 return []int(nil)
2654 }
2655
2656 keys := make([]int, len(m.values))
2657 i := 0
2658 for k := range m.values {
2659 keys[i] = int(k)
2660 i++
2661 }
2662
2663 sort.Ints(keys)
2664 return keys
2665}
2666
2667// allKnownFieldTags return tags of present and recognized fields, including
2668// those that are unset, in sorted order. This only includes extensions that are
2669// present. Known but not-present extensions are not included in the returned
2670// set of tags.
2671func (m *Message) allKnownFieldTags() []int {
2672 fds := m.md.GetFields()
2673 keys := make([]int, 0, len(fds)+len(m.extraFields))
2674
2675 for k := range m.values {
2676 keys = append(keys, int(k))
2677 }
2678
2679 // also include known fields that are not present
2680 for _, fd := range fds {
2681 if _, ok := m.values[fd.GetNumber()]; !ok {
2682 keys = append(keys, int(fd.GetNumber()))
2683 }
2684 }
2685 for _, fd := range m.extraFields {
2686 if !fd.IsExtension() { // skip extensions that are not present
2687 if _, ok := m.values[fd.GetNumber()]; !ok {
2688 keys = append(keys, int(fd.GetNumber()))
2689 }
2690 }
2691 }
2692
2693 sort.Ints(keys)
2694 return keys
2695}
2696
2697// unknownFieldTags return tags of present but unrecognized fields, in sorted order.
2698func (m *Message) unknownFieldTags() []int {
2699 if len(m.unknownFields) == 0 {
2700 return []int(nil)
2701 }
2702 keys := make([]int, len(m.unknownFields))
2703 i := 0
2704 for k := range m.unknownFields {
2705 keys[i] = int(k)
2706 i++
2707 }
2708 sort.Ints(keys)
2709 return keys
2710}