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