-
Notifications
You must be signed in to change notification settings - Fork 170
/
dynamic_message.go
2830 lines (2610 loc) · 93.4 KB
/
dynamic_message.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package dynamic
import (
"bytes"
"compress/gzip"
"errors"
"fmt"
"reflect"
"sort"
"strings"
"github.com/golang/protobuf/proto"
protov2 "google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/descriptorpb"
"github.com/jhump/protoreflect/codec"
"github.com/jhump/protoreflect/desc"
"github.com/jhump/protoreflect/internal"
)
// ErrUnknownTagNumber is an error that is returned when an operation refers
// to an unknown tag number.
var ErrUnknownTagNumber = errors.New("unknown tag number")
// UnknownTagNumberError is the same as ErrUnknownTagNumber.
// Deprecated: use ErrUnknownTagNumber
var UnknownTagNumberError = ErrUnknownTagNumber
// ErrUnknownFieldName is an error that is returned when an operation refers
// to an unknown field name.
var ErrUnknownFieldName = errors.New("unknown field name")
// UnknownFieldNameError is the same as ErrUnknownFieldName.
// Deprecated: use ErrUnknownFieldName
var UnknownFieldNameError = ErrUnknownFieldName
// ErrFieldIsNotMap is an error that is returned when map-related operations
// are attempted with fields that are not maps.
var ErrFieldIsNotMap = errors.New("field is not a map type")
// FieldIsNotMapError is the same as ErrFieldIsNotMap.
// Deprecated: use ErrFieldIsNotMap
var FieldIsNotMapError = ErrFieldIsNotMap
// ErrFieldIsNotRepeated is an error that is returned when repeated field
// operations are attempted with fields that are not repeated.
var ErrFieldIsNotRepeated = errors.New("field is not repeated")
// FieldIsNotRepeatedError is the same as ErrFieldIsNotRepeated.
// Deprecated: use ErrFieldIsNotRepeated
var FieldIsNotRepeatedError = ErrFieldIsNotRepeated
// ErrIndexOutOfRange is an error that is returned when an invalid index is
// provided when access a single element of a repeated field.
var ErrIndexOutOfRange = errors.New("index is out of range")
// IndexOutOfRangeError is the same as ErrIndexOutOfRange.
// Deprecated: use ErrIndexOutOfRange
var IndexOutOfRangeError = ErrIndexOutOfRange
// ErrNumericOverflow is an error returned by operations that encounter a
// numeric value that is too large, for example de-serializing a value into an
// int32 field when the value is larger that can fit into a 32-bit value.
var ErrNumericOverflow = errors.New("numeric value is out of range")
// NumericOverflowError is the same as ErrNumericOverflow.
// Deprecated: use ErrNumericOverflow
var NumericOverflowError = ErrNumericOverflow
var typeOfProtoMessage = reflect.TypeOf((*proto.Message)(nil)).Elem()
var typeOfDynamicMessage = reflect.TypeOf((*Message)(nil))
var typeOfBytes = reflect.TypeOf(([]byte)(nil))
// Message is a dynamic protobuf message. Instead of a generated struct,
// like most protobuf messages, this is a map of field number to values and
// a message descriptor, which is used to validate the field values and
// also to de-serialize messages (from the standard binary format, as well
// as from the text format and from JSON).
type Message struct {
md *desc.MessageDescriptor
er *ExtensionRegistry
mf *MessageFactory
extraFields map[int32]*desc.FieldDescriptor
values map[int32]interface{}
unknownFields map[int32][]UnknownField
}
// UnknownField represents a field that was parsed from the binary wire
// format for a message, but was not a recognized field number. Enough
// information is preserved so that re-serializing the message won't lose
// any of the unrecognized data.
type UnknownField struct {
// Encoding indicates how the unknown field was encoded on the wire. If it
// is proto.WireBytes or proto.WireGroupStart then Contents will be set to
// the raw bytes. If it is proto.WireTypeFixed32 then the data is in the least
// significant 32 bits of Value. Otherwise, the data is in all 64 bits of
// Value.
Encoding int8
Contents []byte
Value uint64
}
// NewMessage creates a new dynamic message for the type represented by the given
// message descriptor. During de-serialization, a default MessageFactory is used to
// instantiate any nested message fields and no extension fields will be parsed. To
// use a custom MessageFactory or ExtensionRegistry, use MessageFactory.NewMessage.
func NewMessage(md *desc.MessageDescriptor) *Message {
return NewMessageWithMessageFactory(md, nil)
}
// NewMessageWithExtensionRegistry creates a new dynamic message for the type
// represented by the given message descriptor. During de-serialization, the given
// ExtensionRegistry is used to parse extension fields and nested messages will be
// instantiated using dynamic.NewMessageFactoryWithExtensionRegistry(er).
func NewMessageWithExtensionRegistry(md *desc.MessageDescriptor, er *ExtensionRegistry) *Message {
mf := NewMessageFactoryWithExtensionRegistry(er)
return NewMessageWithMessageFactory(md, mf)
}
// NewMessageWithMessageFactory creates a new dynamic message for the type
// represented by the given message descriptor. During de-serialization, the given
// MessageFactory is used to instantiate nested messages.
func NewMessageWithMessageFactory(md *desc.MessageDescriptor, mf *MessageFactory) *Message {
var er *ExtensionRegistry
if mf != nil {
er = mf.er
}
return &Message{
md: md,
mf: mf,
er: er,
}
}
// AsDynamicMessage converts the given message to a dynamic message. If the
// given message is dynamic, it is returned. Otherwise, a dynamic message is
// created using NewMessage.
func AsDynamicMessage(msg proto.Message) (*Message, error) {
return AsDynamicMessageWithMessageFactory(msg, nil)
}
// AsDynamicMessageWithExtensionRegistry converts the given message to a dynamic
// message. If the given message is dynamic, it is returned. Otherwise, a
// dynamic message is created using NewMessageWithExtensionRegistry.
func AsDynamicMessageWithExtensionRegistry(msg proto.Message, er *ExtensionRegistry) (*Message, error) {
mf := NewMessageFactoryWithExtensionRegistry(er)
return AsDynamicMessageWithMessageFactory(msg, mf)
}
// AsDynamicMessageWithMessageFactory converts the given message to a dynamic
// message. If the given message is dynamic, it is returned. Otherwise, a
// dynamic message is created using NewMessageWithMessageFactory.
func AsDynamicMessageWithMessageFactory(msg proto.Message, mf *MessageFactory) (*Message, error) {
if dm, ok := msg.(*Message); ok {
return dm, nil
}
md, err := desc.LoadMessageDescriptorForMessage(msg)
if err != nil {
return nil, err
}
dm := NewMessageWithMessageFactory(md, mf)
err = dm.mergeFrom(msg)
if err != nil {
return nil, err
}
return dm, nil
}
// GetMessageDescriptor returns a descriptor for this message's type.
func (m *Message) GetMessageDescriptor() *desc.MessageDescriptor {
return m.md
}
// GetKnownFields returns a slice of descriptors for all known fields. The
// fields will not be in any defined order.
func (m *Message) GetKnownFields() []*desc.FieldDescriptor {
if len(m.extraFields) == 0 {
return m.md.GetFields()
}
flds := make([]*desc.FieldDescriptor, len(m.md.GetFields()), len(m.md.GetFields())+len(m.extraFields))
copy(flds, m.md.GetFields())
for _, fld := range m.extraFields {
if !fld.IsExtension() {
flds = append(flds, fld)
}
}
return flds
}
// GetKnownExtensions returns a slice of descriptors for all extensions known by
// the message's extension registry. The fields will not be in any defined order.
func (m *Message) GetKnownExtensions() []*desc.FieldDescriptor {
if !m.md.IsExtendable() {
return nil
}
exts := m.er.AllExtensionsForType(m.md.GetFullyQualifiedName())
for _, fld := range m.extraFields {
if fld.IsExtension() {
exts = append(exts, fld)
}
}
return exts
}
// GetUnknownFields returns a slice of tag numbers for all unknown fields that
// this message contains. The tags will not be in any defined order.
func (m *Message) GetUnknownFields() []int32 {
flds := make([]int32, 0, len(m.unknownFields))
for tag := range m.unknownFields {
flds = append(flds, tag)
}
return flds
}
// Descriptor returns the serialized form of the file descriptor in which the
// message was defined and a path to the message type therein. This mimics the
// method of the same name on message types generated by protoc.
func (m *Message) Descriptor() ([]byte, []int) {
// get encoded file descriptor
b, err := proto.Marshal(m.md.GetFile().AsProto())
if err != nil {
panic(fmt.Sprintf("failed to get encoded descriptor for %s: %v", m.md.GetFile().GetName(), err))
}
var zippedBytes bytes.Buffer
w := gzip.NewWriter(&zippedBytes)
if _, err := w.Write(b); err != nil {
panic(fmt.Sprintf("failed to get encoded descriptor for %s: %v", m.md.GetFile().GetName(), err))
}
if err := w.Close(); err != nil {
panic(fmt.Sprintf("failed to get an encoded descriptor for %s: %v", m.md.GetFile().GetName(), err))
}
// and path to message
path := []int{}
var d desc.Descriptor
name := m.md.GetFullyQualifiedName()
for d = m.md.GetParent(); d != nil; name, d = d.GetFullyQualifiedName(), d.GetParent() {
found := false
switch d := d.(type) {
case (*desc.FileDescriptor):
for i, md := range d.GetMessageTypes() {
if md.GetFullyQualifiedName() == name {
found = true
path = append(path, i)
}
}
case (*desc.MessageDescriptor):
for i, md := range d.GetNestedMessageTypes() {
if md.GetFullyQualifiedName() == name {
found = true
path = append(path, i)
}
}
}
if !found {
panic(fmt.Sprintf("failed to compute descriptor path for %s", m.md.GetFullyQualifiedName()))
}
}
// reverse the path
i := 0
j := len(path) - 1
for i < j {
path[i], path[j] = path[j], path[i]
i++
j--
}
return zippedBytes.Bytes(), path
}
// XXX_MessageName returns the fully qualified name of this message's type. This
// allows dynamic messages to be used with proto.MessageName.
func (m *Message) XXX_MessageName() string {
return m.md.GetFullyQualifiedName()
}
// FindFieldDescriptor returns a field descriptor for the given tag number. This
// searches known fields in the descriptor, known fields discovered during calls
// to GetField or SetField, and extension fields known by the message's extension
// registry. It returns nil if the tag is unknown.
func (m *Message) FindFieldDescriptor(tagNumber int32) *desc.FieldDescriptor {
fd := m.md.FindFieldByNumber(tagNumber)
if fd != nil {
return fd
}
fd = m.er.FindExtension(m.md.GetFullyQualifiedName(), tagNumber)
if fd != nil {
return fd
}
return m.extraFields[tagNumber]
}
// FindFieldDescriptorByName returns a field descriptor for the given field
// name. This searches known fields in the descriptor, known fields discovered
// during calls to GetField or SetField, and extension fields known by the
// message's extension registry. It returns nil if the name is unknown. If the
// given name refers to an extension, it should be fully qualified and may be
// optionally enclosed in parentheses or brackets.
func (m *Message) FindFieldDescriptorByName(name string) *desc.FieldDescriptor {
if name == "" {
return nil
}
fd := m.md.FindFieldByName(name)
if fd != nil {
return fd
}
mustBeExt := false
if name[0] == '(' {
if name[len(name)-1] != ')' {
// malformed name
return nil
}
mustBeExt = true
name = name[1 : len(name)-1]
} else if name[0] == '[' {
if name[len(name)-1] != ']' {
// malformed name
return nil
}
mustBeExt = true
name = name[1 : len(name)-1]
}
fd = m.er.FindExtensionByName(m.md.GetFullyQualifiedName(), name)
if fd != nil {
return fd
}
for _, fd := range m.extraFields {
if fd.IsExtension() && name == fd.GetFullyQualifiedName() {
return fd
} else if !mustBeExt && !fd.IsExtension() && name == fd.GetName() {
return fd
}
}
return nil
}
// FindFieldDescriptorByJSONName returns a field descriptor for the given JSON
// name. This searches known fields in the descriptor, known fields discovered
// during calls to GetField or SetField, and extension fields known by the
// message's extension registry. If no field matches the given JSON name, it
// will fall back to searching field names (e.g. FindFieldDescriptorByName). If
// this also yields no match, nil is returned.
func (m *Message) FindFieldDescriptorByJSONName(name string) *desc.FieldDescriptor {
if name == "" {
return nil
}
fd := m.md.FindFieldByJSONName(name)
if fd != nil {
return fd
}
mustBeExt := false
if name[0] == '(' {
if name[len(name)-1] != ')' {
// malformed name
return nil
}
mustBeExt = true
name = name[1 : len(name)-1]
} else if name[0] == '[' {
if name[len(name)-1] != ']' {
// malformed name
return nil
}
mustBeExt = true
name = name[1 : len(name)-1]
}
fd = m.er.FindExtensionByJSONName(m.md.GetFullyQualifiedName(), name)
if fd != nil {
return fd
}
for _, fd := range m.extraFields {
if fd.IsExtension() && name == fd.GetFullyQualifiedJSONName() {
return fd
} else if !mustBeExt && !fd.IsExtension() && name == fd.GetJSONName() {
return fd
}
}
// try non-JSON names
return m.FindFieldDescriptorByName(name)
}
func (m *Message) checkField(fd *desc.FieldDescriptor) error {
return checkField(fd, m.md)
}
func checkField(fd *desc.FieldDescriptor, md *desc.MessageDescriptor) error {
if fd.GetOwner().GetFullyQualifiedName() != md.GetFullyQualifiedName() {
return fmt.Errorf("given field, %s, is for wrong message type: %s; expecting %s", fd.GetName(), fd.GetOwner().GetFullyQualifiedName(), md.GetFullyQualifiedName())
}
if fd.IsExtension() && !md.IsExtension(fd.GetNumber()) {
return fmt.Errorf("given field, %s, is an extension but is not in message extension range: %v", fd.GetFullyQualifiedName(), md.GetExtensionRanges())
}
return nil
}
// GetField returns the value for the given field descriptor. It panics if an
// error is encountered. See TryGetField.
func (m *Message) GetField(fd *desc.FieldDescriptor) interface{} {
if v, err := m.TryGetField(fd); err != nil {
panic(err.Error())
} else {
return v
}
}
// TryGetField returns the value for the given field descriptor. An error is
// returned if the given field descriptor does not belong to the right message
// type.
//
// The Go type of the returned value, for scalar fields, is the same as protoc
// would generate for the field (in a non-dynamic message). The table below
// lists the scalar types and the corresponding Go types.
//
// +-------------------------+-----------+
// | Declared Type | Go Type |
// +-------------------------+-----------+
// | int32, sint32, sfixed32 | int32 |
// | int64, sint64, sfixed64 | int64 |
// | uint32, fixed32 | uint32 |
// | uint64, fixed64 | uint64 |
// | float | float32 |
// | double | double32 |
// | bool | bool |
// | string | string |
// | bytes | []byte |
// +-------------------------+-----------+
//
// Values for enum fields will always be int32 values. You can use the enum
// descriptor associated with the field to lookup value names with those values.
// Values for message type fields may be an instance of the generated type *or*
// may be another *dynamic.Message that represents the type.
//
// If the given field is a map field, the returned type will be
// map[interface{}]interface{}. The actual concrete types of keys and values is
// as described above. If the given field is a (non-map) repeated field, the
// returned type is always []interface{}; the type of the actual elements is as
// described above.
//
// If this message has no value for the given field, its default value is
// returned. If the message is defined in a file with "proto3" syntax, the
// default is always the zero value for the field. The default value for map and
// repeated fields is a nil map or slice (respectively). For field's whose types
// is a message, the default value is an empty message for "proto2" syntax or a
// nil message for "proto3" syntax. Note that the in the latter case, a non-nil
// interface with a nil pointer is returned, not a nil interface. Also note that
// whether the returned value is an empty message or nil depends on if *this*
// message was defined as "proto3" syntax, not the message type referred to by
// the field's type.
//
// If the given field descriptor is not known (e.g. not present in the message
// descriptor) but corresponds to an unknown field, the unknown value will be
// parsed and become known. The parsed value will be returned, or an error will
// be returned if the unknown value cannot be parsed according to the field
// descriptor's type information.
func (m *Message) TryGetField(fd *desc.FieldDescriptor) (interface{}, error) {
if err := m.checkField(fd); err != nil {
return nil, err
}
return m.getField(fd)
}
// GetFieldByName returns the value for the field with the given name. It panics
// if an error is encountered. See TryGetFieldByName.
func (m *Message) GetFieldByName(name string) interface{} {
if v, err := m.TryGetFieldByName(name); err != nil {
panic(err.Error())
} else {
return v
}
}
// TryGetFieldByName returns the value for the field with the given name. An
// error is returned if the given name is unknown. If the given name refers to
// an extension field, it should be fully qualified and optionally enclosed in
// parenthesis or brackets.
//
// If this message has no value for the given field, its default value is
// returned. (See TryGetField for more info on types and default field values.)
func (m *Message) TryGetFieldByName(name string) (interface{}, error) {
fd := m.FindFieldDescriptorByName(name)
if fd == nil {
return nil, UnknownFieldNameError
}
return m.getField(fd)
}
// GetFieldByNumber returns the value for the field with the given tag number.
// It panics if an error is encountered. See TryGetFieldByNumber.
func (m *Message) GetFieldByNumber(tagNumber int) interface{} {
if v, err := m.TryGetFieldByNumber(tagNumber); err != nil {
panic(err.Error())
} else {
return v
}
}
// TryGetFieldByNumber returns the value for the field with the given tag
// number. An error is returned if the given tag is unknown.
//
// If this message has no value for the given field, its default value is
// returned. (See TryGetField for more info on types and default field values.)
func (m *Message) TryGetFieldByNumber(tagNumber int) (interface{}, error) {
fd := m.FindFieldDescriptor(int32(tagNumber))
if fd == nil {
return nil, UnknownTagNumberError
}
return m.getField(fd)
}
func (m *Message) getField(fd *desc.FieldDescriptor) (interface{}, error) {
return m.doGetField(fd, false)
}
func (m *Message) doGetField(fd *desc.FieldDescriptor, nilIfAbsent bool) (interface{}, error) {
res := m.values[fd.GetNumber()]
if res == nil {
var err error
if res, err = m.parseUnknownField(fd); err != nil {
return nil, err
}
if res == nil {
if nilIfAbsent {
return nil, nil
} else {
def := fd.GetDefaultValue()
if def != nil {
return def, nil
}
// GetDefaultValue only returns nil for message types
md := fd.GetMessageType()
if m.md.IsProto3() {
return nilMessage(md), nil
} else {
// for proto2, return default instance of message
return m.mf.NewMessage(md), nil
}
}
}
}
rt := reflect.TypeOf(res)
if rt.Kind() == reflect.Map {
// make defensive copies to prevent caller from storing illegal keys and values
m := res.(map[interface{}]interface{})
res := map[interface{}]interface{}{}
for k, v := range m {
res[k] = v
}
return res, nil
} else if rt.Kind() == reflect.Slice && rt != typeOfBytes {
// make defensive copies to prevent caller from storing illegal elements
sl := res.([]interface{})
res := make([]interface{}, len(sl))
copy(res, sl)
return res, nil
}
return res, nil
}
func nilMessage(md *desc.MessageDescriptor) interface{} {
// try to return a proper nil pointer
msgType := proto.MessageType(md.GetFullyQualifiedName())
if msgType != nil && msgType.Implements(typeOfProtoMessage) {
return reflect.Zero(msgType).Interface().(proto.Message)
}
// fallback to nil dynamic message pointer
return (*Message)(nil)
}
// HasField returns true if this message has a value for the given field. If the
// given field is not valid (e.g. belongs to a different message type), false is
// returned. If this message is defined in a file with "proto3" syntax, this
// will return false even if a field was explicitly assigned its zero value (the
// zero values for a field are intentionally indistinguishable from absent).
func (m *Message) HasField(fd *desc.FieldDescriptor) bool {
if err := m.checkField(fd); err != nil {
return false
}
return m.HasFieldNumber(int(fd.GetNumber()))
}
// HasFieldName returns true if this message has a value for a field with the
// given name. If the given name is unknown, this returns false.
func (m *Message) HasFieldName(name string) bool {
fd := m.FindFieldDescriptorByName(name)
if fd == nil {
return false
}
return m.HasFieldNumber(int(fd.GetNumber()))
}
// HasFieldNumber returns true if this message has a value for a field with the
// given tag number. If the given tag is unknown, this returns false.
func (m *Message) HasFieldNumber(tagNumber int) bool {
if _, ok := m.values[int32(tagNumber)]; ok {
return true
}
_, ok := m.unknownFields[int32(tagNumber)]
return ok
}
// SetField sets the value for the given field descriptor to the given value. It
// panics if an error is encountered. See TrySetField.
func (m *Message) SetField(fd *desc.FieldDescriptor, val interface{}) {
if err := m.TrySetField(fd, val); err != nil {
panic(err.Error())
}
}
// TrySetField sets the value for the given field descriptor to the given value.
// An error is returned if the given field descriptor does not belong to the
// right message type or if the given value is not a correct/compatible type for
// the given field.
//
// The Go type expected for a field is the same as TryGetField would return for
// the field. So message values can be supplied as either the correct generated
// message type or as a *dynamic.Message.
//
// Since it is cumbersome to work with dynamic messages, some concessions are
// made to simplify usage regarding types:
//
// 1. If a numeric type is provided that can be converted *without loss or
// overflow*, it is accepted. This allows for setting int64 fields using int
// or int32 values. Similarly for uint64 with uint and uint32 values and for
// float64 fields with float32 values.
// 2. The value can be a named type, as long as its underlying type is correct.
// 3. Map and repeated fields can be set using any kind of concrete map or
// slice type, as long as the values within are all of the correct type. So
// a field defined as a 'map<string, int32>` can be set using a
// map[string]int32, a map[string]interface{}, or even a
// map[interface{}]interface{}.
// 4. Finally, dynamic code that chooses to not treat maps as a special-case
// find that they can set map fields using a slice where each element is a
// message that matches the implicit map-entry field message type.
//
// If the given field descriptor is not known (e.g. not present in the message
// descriptor) it will become known. Subsequent operations using tag numbers or
// names will be able to resolve the newly-known type. If the message has a
// value for the unknown value, it is cleared, replaced by the given known
// value.
func (m *Message) TrySetField(fd *desc.FieldDescriptor, val interface{}) error {
if err := m.checkField(fd); err != nil {
return err
}
return m.setField(fd, val)
}
// SetFieldByName sets the value for the field with the given name to the given
// value. It panics if an error is encountered. See TrySetFieldByName.
func (m *Message) SetFieldByName(name string, val interface{}) {
if err := m.TrySetFieldByName(name, val); err != nil {
panic(err.Error())
}
}
// TrySetFieldByName sets the value for the field with the given name to the
// given value. An error is returned if the given name is unknown or if the
// given value has an incorrect type. If the given name refers to an extension
// field, it should be fully qualified and optionally enclosed in parenthesis or
// brackets.
//
// (See TrySetField for more info on types.)
func (m *Message) TrySetFieldByName(name string, val interface{}) error {
fd := m.FindFieldDescriptorByName(name)
if fd == nil {
return UnknownFieldNameError
}
return m.setField(fd, val)
}
// SetFieldByNumber sets the value for the field with the given tag number to
// the given value. It panics if an error is encountered. See
// TrySetFieldByNumber.
func (m *Message) SetFieldByNumber(tagNumber int, val interface{}) {
if err := m.TrySetFieldByNumber(tagNumber, val); err != nil {
panic(err.Error())
}
}
// TrySetFieldByNumber sets the value for the field with the given tag number to
// the given value. An error is returned if the given tag is unknown or if the
// given value has an incorrect type.
//
// (See TrySetField for more info on types.)
func (m *Message) TrySetFieldByNumber(tagNumber int, val interface{}) error {
fd := m.FindFieldDescriptor(int32(tagNumber))
if fd == nil {
return UnknownTagNumberError
}
return m.setField(fd, val)
}
func (m *Message) setField(fd *desc.FieldDescriptor, val interface{}) error {
var err error
if val, err = validFieldValue(fd, val); err != nil {
return err
}
m.internalSetField(fd, val)
return nil
}
func (m *Message) internalSetField(fd *desc.FieldDescriptor, val interface{}) {
if fd.IsRepeated() {
// Unset fields and zero-length fields are indistinguishable, in both
// proto2 and proto3 syntax
if reflect.ValueOf(val).Len() == 0 {
if m.values != nil {
delete(m.values, fd.GetNumber())
}
return
}
} else if m.md.IsProto3() && fd.GetOneOf() == nil {
// proto3 considers fields that are set to their zero value as unset
// (we already handled repeated fields above)
var equal bool
if b, ok := val.([]byte); ok {
// can't compare slices, so we have to special-case []byte values
equal = ok && bytes.Equal(b, fd.GetDefaultValue().([]byte))
} else {
defVal := fd.GetDefaultValue()
equal = defVal == val
if !equal && defVal == nil {
// above just checks if value is the nil interface,
// but we should also test if the given value is a
// nil pointer
rv := reflect.ValueOf(val)
if rv.Kind() == reflect.Ptr && rv.IsNil() {
equal = true
}
}
}
if equal {
if m.values != nil {
delete(m.values, fd.GetNumber())
}
return
}
}
if m.values == nil {
m.values = map[int32]interface{}{}
}
m.values[fd.GetNumber()] = val
// if this field is part of a one-of, make sure all other one-of choices are cleared
od := fd.GetOneOf()
if od != nil {
for _, other := range od.GetChoices() {
if other.GetNumber() != fd.GetNumber() {
delete(m.values, other.GetNumber())
}
}
}
// also clear any unknown fields
if m.unknownFields != nil {
delete(m.unknownFields, fd.GetNumber())
}
// and add this field if it was previously unknown
if existing := m.FindFieldDescriptor(fd.GetNumber()); existing == nil {
m.addField(fd)
}
}
func (m *Message) addField(fd *desc.FieldDescriptor) {
if m.extraFields == nil {
m.extraFields = map[int32]*desc.FieldDescriptor{}
}
m.extraFields[fd.GetNumber()] = fd
}
// ClearField removes any value for the given field. It panics if an error is
// encountered. See TryClearField.
func (m *Message) ClearField(fd *desc.FieldDescriptor) {
if err := m.TryClearField(fd); err != nil {
panic(err.Error())
}
}
// TryClearField removes any value for the given field. An error is returned if
// the given field descriptor does not belong to the right message type.
func (m *Message) TryClearField(fd *desc.FieldDescriptor) error {
if err := m.checkField(fd); err != nil {
return err
}
m.clearField(fd)
return nil
}
// ClearFieldByName removes any value for the field with the given name. It
// panics if an error is encountered. See TryClearFieldByName.
func (m *Message) ClearFieldByName(name string) {
if err := m.TryClearFieldByName(name); err != nil {
panic(err.Error())
}
}
// TryClearFieldByName removes any value for the field with the given name. An
// error is returned if the given name is unknown. If the given name refers to
// an extension field, it should be fully qualified and optionally enclosed in
// parenthesis or brackets.
func (m *Message) TryClearFieldByName(name string) error {
fd := m.FindFieldDescriptorByName(name)
if fd == nil {
return UnknownFieldNameError
}
m.clearField(fd)
return nil
}
// ClearFieldByNumber removes any value for the field with the given tag number.
// It panics if an error is encountered. See TryClearFieldByNumber.
func (m *Message) ClearFieldByNumber(tagNumber int) {
if err := m.TryClearFieldByNumber(tagNumber); err != nil {
panic(err.Error())
}
}
// TryClearFieldByNumber removes any value for the field with the given tag
// number. An error is returned if the given tag is unknown.
func (m *Message) TryClearFieldByNumber(tagNumber int) error {
fd := m.FindFieldDescriptor(int32(tagNumber))
if fd == nil {
return UnknownTagNumberError
}
m.clearField(fd)
return nil
}
func (m *Message) clearField(fd *desc.FieldDescriptor) {
// clear value
if m.values != nil {
delete(m.values, fd.GetNumber())
}
// also clear any unknown fields
if m.unknownFields != nil {
delete(m.unknownFields, fd.GetNumber())
}
// and add this field if it was previously unknown
if existing := m.FindFieldDescriptor(fd.GetNumber()); existing == nil {
m.addField(fd)
}
}
// GetOneOfField returns which of the given one-of's fields is set and the
// corresponding value. It panics if an error is encountered. See
// TryGetOneOfField.
func (m *Message) GetOneOfField(od *desc.OneOfDescriptor) (*desc.FieldDescriptor, interface{}) {
if fd, val, err := m.TryGetOneOfField(od); err != nil {
panic(err.Error())
} else {
return fd, val
}
}
// TryGetOneOfField returns which of the given one-of's fields is set and the
// corresponding value. An error is returned if the given one-of belongs to the
// wrong message type. If the given one-of has no field set, this method will
// return nil, nil.
//
// The type of the value, if one is set, is the same as would be returned by
// TryGetField using the returned field descriptor.
//
// Like with TryGetField, if the given one-of contains any fields that are not
// known (e.g. not present in this message's descriptor), they will become known
// and any unknown value will be parsed (and become a known value on success).
func (m *Message) TryGetOneOfField(od *desc.OneOfDescriptor) (*desc.FieldDescriptor, interface{}, error) {
if od.GetOwner().GetFullyQualifiedName() != m.md.GetFullyQualifiedName() {
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())
}
for _, fd := range od.GetChoices() {
val, err := m.doGetField(fd, true)
if err != nil {
return nil, nil, err
}
if val != nil {
return fd, val, nil
}
}
return nil, nil, nil
}
// ClearOneOfField removes any value for any of the given one-of's fields. It
// panics if an error is encountered. See TryClearOneOfField.
func (m *Message) ClearOneOfField(od *desc.OneOfDescriptor) {
if err := m.TryClearOneOfField(od); err != nil {
panic(err.Error())
}
}
// TryClearOneOfField removes any value for any of the given one-of's fields. An
// error is returned if the given one-of descriptor does not belong to the right
// message type.
func (m *Message) TryClearOneOfField(od *desc.OneOfDescriptor) error {
if od.GetOwner().GetFullyQualifiedName() != m.md.GetFullyQualifiedName() {
return fmt.Errorf("given one-of, %s, is for wrong message type: %s; expecting %s", od.GetName(), od.GetOwner().GetFullyQualifiedName(), m.md.GetFullyQualifiedName())
}
for _, fd := range od.GetChoices() {
m.clearField(fd)
}
return nil
}
// GetMapField returns the value for the given map field descriptor and given
// key. It panics if an error is encountered. See TryGetMapField.
func (m *Message) GetMapField(fd *desc.FieldDescriptor, key interface{}) interface{} {
if v, err := m.TryGetMapField(fd, key); err != nil {
panic(err.Error())
} else {
return v
}
}
// TryGetMapField returns the value for the given map field descriptor and given
// key. An error is returned if the given field descriptor does not belong to
// the right message type or if it is not a map field.
//
// If the map field does not contain the requested key, this method returns
// nil, nil. The Go type of the value returned mirrors the type that protoc
// would generate for the field. (See TryGetField for more details on types).
//
// If the given field descriptor is not known (e.g. not present in the message
// descriptor) but corresponds to an unknown field, the unknown value will be
// parsed and become known. The parsed value will be searched for the requested
// key and any value returned. An error will be returned if the unknown value
// cannot be parsed according to the field descriptor's type information.
func (m *Message) TryGetMapField(fd *desc.FieldDescriptor, key interface{}) (interface{}, error) {
if err := m.checkField(fd); err != nil {
return nil, err
}
return m.getMapField(fd, key)
}
// GetMapFieldByName returns the value for the map field with the given name and
// given key. It panics if an error is encountered. See TryGetMapFieldByName.
func (m *Message) GetMapFieldByName(name string, key interface{}) interface{} {
if v, err := m.TryGetMapFieldByName(name, key); err != nil {
panic(err.Error())
} else {
return v
}
}
// TryGetMapFieldByName returns the value for the map field with the given name
// and given key. An error is returned if the given name is unknown or if it
// names a field that is not a map field.
//
// If this message has no value for the given field or the value has no value
// for the requested key, then this method returns nil, nil.
//
// (See TryGetField for more info on types.)
func (m *Message) TryGetMapFieldByName(name string, key interface{}) (interface{}, error) {
fd := m.FindFieldDescriptorByName(name)
if fd == nil {
return nil, UnknownFieldNameError
}
return m.getMapField(fd, key)
}
// GetMapFieldByNumber returns the value for the map field with the given tag
// number and given key. It panics if an error is encountered. See
// TryGetMapFieldByNumber.
func (m *Message) GetMapFieldByNumber(tagNumber int, key interface{}) interface{} {
if v, err := m.TryGetMapFieldByNumber(tagNumber, key); err != nil {
panic(err.Error())
} else {
return v
}
}
// TryGetMapFieldByNumber returns the value for the map field with the given tag
// number and given key. An error is returned if the given tag is unknown or if
// it indicates a field that is not a map field.
//
// If this message has no value for the given field or the value has no value
// for the requested key, then this method returns nil, nil.
//
// (See TryGetField for more info on types.)
func (m *Message) TryGetMapFieldByNumber(tagNumber int, key interface{}) (interface{}, error) {
fd := m.FindFieldDescriptor(int32(tagNumber))
if fd == nil {
return nil, UnknownTagNumberError
}
return m.getMapField(fd, key)
}
func (m *Message) getMapField(fd *desc.FieldDescriptor, key interface{}) (interface{}, error) {
if !fd.IsMap() {
return nil, FieldIsNotMapError
}
kfd := fd.GetMessageType().GetFields()[0]
ki, err := validElementFieldValue(kfd, key, false)
if err != nil {
return nil, err
}
mp := m.values[fd.GetNumber()]
if mp == nil {
if mp, err = m.parseUnknownField(fd); err != nil {
return nil, err
} else if mp == nil {
return nil, nil