...

Source file src/google.golang.org/protobuf/types/dynamicpb/dynamic.go

Documentation: google.golang.org/protobuf/types/dynamicpb

     1  // Copyright 2019 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package dynamicpb creates protocol buffer messages using runtime type information.
     6  package dynamicpb
     7  
     8  import (
     9  	"math"
    10  
    11  	"google.golang.org/protobuf/internal/errors"
    12  	"google.golang.org/protobuf/reflect/protoreflect"
    13  	"google.golang.org/protobuf/runtime/protoiface"
    14  	"google.golang.org/protobuf/runtime/protoimpl"
    15  )
    16  
    17  // enum is a dynamic protoreflect.Enum.
    18  type enum struct {
    19  	num protoreflect.EnumNumber
    20  	typ protoreflect.EnumType
    21  }
    22  
    23  func (e enum) Descriptor() protoreflect.EnumDescriptor { return e.typ.Descriptor() }
    24  func (e enum) Type() protoreflect.EnumType             { return e.typ }
    25  func (e enum) Number() protoreflect.EnumNumber         { return e.num }
    26  
    27  // enumType is a dynamic protoreflect.EnumType.
    28  type enumType struct {
    29  	desc protoreflect.EnumDescriptor
    30  }
    31  
    32  // NewEnumType creates a new EnumType with the provided descriptor.
    33  //
    34  // EnumTypes created by this package are equal if their descriptors are equal.
    35  // That is, if ed1 == ed2, then NewEnumType(ed1) == NewEnumType(ed2).
    36  //
    37  // Enum values created by the EnumType are equal if their numbers are equal.
    38  func NewEnumType(desc protoreflect.EnumDescriptor) protoreflect.EnumType {
    39  	return enumType{desc}
    40  }
    41  
    42  func (et enumType) New(n protoreflect.EnumNumber) protoreflect.Enum { return enum{n, et} }
    43  func (et enumType) Descriptor() protoreflect.EnumDescriptor         { return et.desc }
    44  
    45  // extensionType is a dynamic protoreflect.ExtensionType.
    46  type extensionType struct {
    47  	desc extensionTypeDescriptor
    48  }
    49  
    50  // A Message is a dynamically constructed protocol buffer message.
    51  //
    52  // Message implements the [google.golang.org/protobuf/proto.Message] interface,
    53  // and may be used with all  standard proto package functions
    54  // such as Marshal, Unmarshal, and so forth.
    55  //
    56  // Message also implements the [protoreflect.Message] interface.
    57  // See the [protoreflect] package documentation for that interface for how to
    58  // get and set fields and otherwise interact with the contents of a Message.
    59  //
    60  // Reflection API functions which construct messages, such as NewField,
    61  // return new dynamic messages of the appropriate type. Functions which take
    62  // messages, such as Set for a message-value field, will accept any message
    63  // with a compatible type.
    64  //
    65  // Operations which modify a Message are not safe for concurrent use.
    66  type Message struct {
    67  	typ     messageType
    68  	known   map[protoreflect.FieldNumber]protoreflect.Value
    69  	ext     map[protoreflect.FieldNumber]protoreflect.FieldDescriptor
    70  	unknown protoreflect.RawFields
    71  }
    72  
    73  var (
    74  	_ protoreflect.Message      = (*Message)(nil)
    75  	_ protoreflect.ProtoMessage = (*Message)(nil)
    76  	_ protoiface.MessageV1      = (*Message)(nil)
    77  )
    78  
    79  // NewMessage creates a new message with the provided descriptor.
    80  func NewMessage(desc protoreflect.MessageDescriptor) *Message {
    81  	return &Message{
    82  		typ:   messageType{desc},
    83  		known: make(map[protoreflect.FieldNumber]protoreflect.Value),
    84  		ext:   make(map[protoreflect.FieldNumber]protoreflect.FieldDescriptor),
    85  	}
    86  }
    87  
    88  // ProtoMessage implements the legacy message interface.
    89  func (m *Message) ProtoMessage() {}
    90  
    91  // ProtoReflect implements the [protoreflect.ProtoMessage] interface.
    92  func (m *Message) ProtoReflect() protoreflect.Message {
    93  	return m
    94  }
    95  
    96  // String returns a string representation of a message.
    97  func (m *Message) String() string {
    98  	return protoimpl.X.MessageStringOf(m)
    99  }
   100  
   101  // Reset clears the message to be empty, but preserves the dynamic message type.
   102  func (m *Message) Reset() {
   103  	m.known = make(map[protoreflect.FieldNumber]protoreflect.Value)
   104  	m.ext = make(map[protoreflect.FieldNumber]protoreflect.FieldDescriptor)
   105  	m.unknown = nil
   106  }
   107  
   108  // Descriptor returns the message descriptor.
   109  func (m *Message) Descriptor() protoreflect.MessageDescriptor {
   110  	return m.typ.desc
   111  }
   112  
   113  // Type returns the message type.
   114  func (m *Message) Type() protoreflect.MessageType {
   115  	return m.typ
   116  }
   117  
   118  // New returns a newly allocated empty message with the same descriptor.
   119  // See [protoreflect.Message] for details.
   120  func (m *Message) New() protoreflect.Message {
   121  	return m.Type().New()
   122  }
   123  
   124  // Interface returns the message.
   125  // See [protoreflect.Message] for details.
   126  func (m *Message) Interface() protoreflect.ProtoMessage {
   127  	return m
   128  }
   129  
   130  // ProtoMethods is an internal detail of the [protoreflect.Message] interface.
   131  // Users should never call this directly.
   132  func (m *Message) ProtoMethods() *protoiface.Methods {
   133  	return nil
   134  }
   135  
   136  // Range visits every populated field in undefined order.
   137  // See [protoreflect.Message] for details.
   138  func (m *Message) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {
   139  	for num, v := range m.known {
   140  		fd := m.ext[num]
   141  		if fd == nil {
   142  			fd = m.Descriptor().Fields().ByNumber(num)
   143  		}
   144  		if !isSet(fd, v) {
   145  			continue
   146  		}
   147  		if !f(fd, v) {
   148  			return
   149  		}
   150  	}
   151  }
   152  
   153  // Has reports whether a field is populated.
   154  // See [protoreflect.Message] for details.
   155  func (m *Message) Has(fd protoreflect.FieldDescriptor) bool {
   156  	m.checkField(fd)
   157  	if fd.IsExtension() && m.ext[fd.Number()] != fd {
   158  		return false
   159  	}
   160  	v, ok := m.known[fd.Number()]
   161  	if !ok {
   162  		return false
   163  	}
   164  	return isSet(fd, v)
   165  }
   166  
   167  // Clear clears a field.
   168  // See [protoreflect.Message] for details.
   169  func (m *Message) Clear(fd protoreflect.FieldDescriptor) {
   170  	m.checkField(fd)
   171  	num := fd.Number()
   172  	delete(m.known, num)
   173  	delete(m.ext, num)
   174  }
   175  
   176  // Get returns the value of a field.
   177  // See [protoreflect.Message] for details.
   178  func (m *Message) Get(fd protoreflect.FieldDescriptor) protoreflect.Value {
   179  	m.checkField(fd)
   180  	num := fd.Number()
   181  	if fd.IsExtension() {
   182  		if fd != m.ext[num] {
   183  			return fd.(protoreflect.ExtensionTypeDescriptor).Type().Zero()
   184  		}
   185  		return m.known[num]
   186  	}
   187  	if v, ok := m.known[num]; ok {
   188  		switch {
   189  		case fd.IsMap():
   190  			if v.Map().Len() > 0 {
   191  				return v
   192  			}
   193  		case fd.IsList():
   194  			if v.List().Len() > 0 {
   195  				return v
   196  			}
   197  		default:
   198  			return v
   199  		}
   200  	}
   201  	switch {
   202  	case fd.IsMap():
   203  		return protoreflect.ValueOfMap(&dynamicMap{desc: fd})
   204  	case fd.IsList():
   205  		return protoreflect.ValueOfList(emptyList{desc: fd})
   206  	case fd.Message() != nil:
   207  		return protoreflect.ValueOfMessage(&Message{typ: messageType{fd.Message()}})
   208  	case fd.Kind() == protoreflect.BytesKind:
   209  		return protoreflect.ValueOfBytes(append([]byte(nil), fd.Default().Bytes()...))
   210  	default:
   211  		return fd.Default()
   212  	}
   213  }
   214  
   215  // Mutable returns a mutable reference to a repeated, map, or message field.
   216  // See [protoreflect.Message] for details.
   217  func (m *Message) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value {
   218  	m.checkField(fd)
   219  	if !fd.IsMap() && !fd.IsList() && fd.Message() == nil {
   220  		panic(errors.New("%v: getting mutable reference to non-composite type", fd.FullName()))
   221  	}
   222  	if m.known == nil {
   223  		panic(errors.New("%v: modification of read-only message", fd.FullName()))
   224  	}
   225  	num := fd.Number()
   226  	if fd.IsExtension() {
   227  		if fd != m.ext[num] {
   228  			m.ext[num] = fd
   229  			m.known[num] = fd.(protoreflect.ExtensionTypeDescriptor).Type().New()
   230  		}
   231  		return m.known[num]
   232  	}
   233  	if v, ok := m.known[num]; ok {
   234  		return v
   235  	}
   236  	m.clearOtherOneofFields(fd)
   237  	m.known[num] = m.NewField(fd)
   238  	if fd.IsExtension() {
   239  		m.ext[num] = fd
   240  	}
   241  	return m.known[num]
   242  }
   243  
   244  // Set stores a value in a field.
   245  // See [protoreflect.Message] for details.
   246  func (m *Message) Set(fd protoreflect.FieldDescriptor, v protoreflect.Value) {
   247  	m.checkField(fd)
   248  	if m.known == nil {
   249  		panic(errors.New("%v: modification of read-only message", fd.FullName()))
   250  	}
   251  	if fd.IsExtension() {
   252  		isValid := true
   253  		switch {
   254  		case !fd.(protoreflect.ExtensionTypeDescriptor).Type().IsValidValue(v):
   255  			isValid = false
   256  		case fd.IsList():
   257  			isValid = v.List().IsValid()
   258  		case fd.IsMap():
   259  			isValid = v.Map().IsValid()
   260  		case fd.Message() != nil:
   261  			isValid = v.Message().IsValid()
   262  		}
   263  		if !isValid {
   264  			panic(errors.New("%v: assigning invalid type %T", fd.FullName(), v.Interface()))
   265  		}
   266  		m.ext[fd.Number()] = fd
   267  	} else {
   268  		typecheck(fd, v)
   269  	}
   270  	m.clearOtherOneofFields(fd)
   271  	m.known[fd.Number()] = v
   272  }
   273  
   274  func (m *Message) clearOtherOneofFields(fd protoreflect.FieldDescriptor) {
   275  	od := fd.ContainingOneof()
   276  	if od == nil {
   277  		return
   278  	}
   279  	num := fd.Number()
   280  	for i := 0; i < od.Fields().Len(); i++ {
   281  		if n := od.Fields().Get(i).Number(); n != num {
   282  			delete(m.known, n)
   283  		}
   284  	}
   285  }
   286  
   287  // NewField returns a new value for assignable to the field of a given descriptor.
   288  // See [protoreflect.Message] for details.
   289  func (m *Message) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value {
   290  	m.checkField(fd)
   291  	switch {
   292  	case fd.IsExtension():
   293  		return fd.(protoreflect.ExtensionTypeDescriptor).Type().New()
   294  	case fd.IsMap():
   295  		return protoreflect.ValueOfMap(&dynamicMap{
   296  			desc: fd,
   297  			mapv: make(map[interface{}]protoreflect.Value),
   298  		})
   299  	case fd.IsList():
   300  		return protoreflect.ValueOfList(&dynamicList{desc: fd})
   301  	case fd.Message() != nil:
   302  		return protoreflect.ValueOfMessage(NewMessage(fd.Message()).ProtoReflect())
   303  	default:
   304  		return fd.Default()
   305  	}
   306  }
   307  
   308  // WhichOneof reports which field in a oneof is populated, returning nil if none are populated.
   309  // See [protoreflect.Message] for details.
   310  func (m *Message) WhichOneof(od protoreflect.OneofDescriptor) protoreflect.FieldDescriptor {
   311  	for i := 0; i < od.Fields().Len(); i++ {
   312  		fd := od.Fields().Get(i)
   313  		if m.Has(fd) {
   314  			return fd
   315  		}
   316  	}
   317  	return nil
   318  }
   319  
   320  // GetUnknown returns the raw unknown fields.
   321  // See [protoreflect.Message] for details.
   322  func (m *Message) GetUnknown() protoreflect.RawFields {
   323  	return m.unknown
   324  }
   325  
   326  // SetUnknown sets the raw unknown fields.
   327  // See [protoreflect.Message] for details.
   328  func (m *Message) SetUnknown(r protoreflect.RawFields) {
   329  	if m.known == nil {
   330  		panic(errors.New("%v: modification of read-only message", m.typ.desc.FullName()))
   331  	}
   332  	m.unknown = r
   333  }
   334  
   335  // IsValid reports whether the message is valid.
   336  // See [protoreflect.Message] for details.
   337  func (m *Message) IsValid() bool {
   338  	return m.known != nil
   339  }
   340  
   341  func (m *Message) checkField(fd protoreflect.FieldDescriptor) {
   342  	if fd.IsExtension() && fd.ContainingMessage().FullName() == m.Descriptor().FullName() {
   343  		if _, ok := fd.(protoreflect.ExtensionTypeDescriptor); !ok {
   344  			panic(errors.New("%v: extension field descriptor does not implement ExtensionTypeDescriptor", fd.FullName()))
   345  		}
   346  		return
   347  	}
   348  	if fd.Parent() == m.Descriptor() {
   349  		return
   350  	}
   351  	fields := m.Descriptor().Fields()
   352  	index := fd.Index()
   353  	if index >= fields.Len() || fields.Get(index) != fd {
   354  		panic(errors.New("%v: field descriptor does not belong to this message", fd.FullName()))
   355  	}
   356  }
   357  
   358  type messageType struct {
   359  	desc protoreflect.MessageDescriptor
   360  }
   361  
   362  // NewMessageType creates a new MessageType with the provided descriptor.
   363  //
   364  // MessageTypes created by this package are equal if their descriptors are equal.
   365  // That is, if md1 == md2, then NewMessageType(md1) == NewMessageType(md2).
   366  func NewMessageType(desc protoreflect.MessageDescriptor) protoreflect.MessageType {
   367  	return messageType{desc}
   368  }
   369  
   370  func (mt messageType) New() protoreflect.Message                  { return NewMessage(mt.desc) }
   371  func (mt messageType) Zero() protoreflect.Message                 { return &Message{typ: messageType{mt.desc}} }
   372  func (mt messageType) Descriptor() protoreflect.MessageDescriptor { return mt.desc }
   373  func (mt messageType) Enum(i int) protoreflect.EnumType {
   374  	if ed := mt.desc.Fields().Get(i).Enum(); ed != nil {
   375  		return NewEnumType(ed)
   376  	}
   377  	return nil
   378  }
   379  func (mt messageType) Message(i int) protoreflect.MessageType {
   380  	if md := mt.desc.Fields().Get(i).Message(); md != nil {
   381  		return NewMessageType(md)
   382  	}
   383  	return nil
   384  }
   385  
   386  type emptyList struct {
   387  	desc protoreflect.FieldDescriptor
   388  }
   389  
   390  func (x emptyList) Len() int                     { return 0 }
   391  func (x emptyList) Get(n int) protoreflect.Value { panic(errors.New("out of range")) }
   392  func (x emptyList) Set(n int, v protoreflect.Value) {
   393  	panic(errors.New("modification of immutable list"))
   394  }
   395  func (x emptyList) Append(v protoreflect.Value) { panic(errors.New("modification of immutable list")) }
   396  func (x emptyList) AppendMutable() protoreflect.Value {
   397  	panic(errors.New("modification of immutable list"))
   398  }
   399  func (x emptyList) Truncate(n int)                 { panic(errors.New("modification of immutable list")) }
   400  func (x emptyList) NewElement() protoreflect.Value { return newListEntry(x.desc) }
   401  func (x emptyList) IsValid() bool                  { return false }
   402  
   403  type dynamicList struct {
   404  	desc protoreflect.FieldDescriptor
   405  	list []protoreflect.Value
   406  }
   407  
   408  func (x *dynamicList) Len() int {
   409  	return len(x.list)
   410  }
   411  
   412  func (x *dynamicList) Get(n int) protoreflect.Value {
   413  	return x.list[n]
   414  }
   415  
   416  func (x *dynamicList) Set(n int, v protoreflect.Value) {
   417  	typecheckSingular(x.desc, v)
   418  	x.list[n] = v
   419  }
   420  
   421  func (x *dynamicList) Append(v protoreflect.Value) {
   422  	typecheckSingular(x.desc, v)
   423  	x.list = append(x.list, v)
   424  }
   425  
   426  func (x *dynamicList) AppendMutable() protoreflect.Value {
   427  	if x.desc.Message() == nil {
   428  		panic(errors.New("%v: invalid AppendMutable on list with non-message type", x.desc.FullName()))
   429  	}
   430  	v := x.NewElement()
   431  	x.Append(v)
   432  	return v
   433  }
   434  
   435  func (x *dynamicList) Truncate(n int) {
   436  	// Zero truncated elements to avoid keeping data live.
   437  	for i := n; i < len(x.list); i++ {
   438  		x.list[i] = protoreflect.Value{}
   439  	}
   440  	x.list = x.list[:n]
   441  }
   442  
   443  func (x *dynamicList) NewElement() protoreflect.Value {
   444  	return newListEntry(x.desc)
   445  }
   446  
   447  func (x *dynamicList) IsValid() bool {
   448  	return true
   449  }
   450  
   451  type dynamicMap struct {
   452  	desc protoreflect.FieldDescriptor
   453  	mapv map[interface{}]protoreflect.Value
   454  }
   455  
   456  func (x *dynamicMap) Get(k protoreflect.MapKey) protoreflect.Value { return x.mapv[k.Interface()] }
   457  func (x *dynamicMap) Set(k protoreflect.MapKey, v protoreflect.Value) {
   458  	typecheckSingular(x.desc.MapKey(), k.Value())
   459  	typecheckSingular(x.desc.MapValue(), v)
   460  	x.mapv[k.Interface()] = v
   461  }
   462  func (x *dynamicMap) Has(k protoreflect.MapKey) bool { return x.Get(k).IsValid() }
   463  func (x *dynamicMap) Clear(k protoreflect.MapKey)    { delete(x.mapv, k.Interface()) }
   464  func (x *dynamicMap) Mutable(k protoreflect.MapKey) protoreflect.Value {
   465  	if x.desc.MapValue().Message() == nil {
   466  		panic(errors.New("%v: invalid Mutable on map with non-message value type", x.desc.FullName()))
   467  	}
   468  	v := x.Get(k)
   469  	if !v.IsValid() {
   470  		v = x.NewValue()
   471  		x.Set(k, v)
   472  	}
   473  	return v
   474  }
   475  func (x *dynamicMap) Len() int { return len(x.mapv) }
   476  func (x *dynamicMap) NewValue() protoreflect.Value {
   477  	if md := x.desc.MapValue().Message(); md != nil {
   478  		return protoreflect.ValueOfMessage(NewMessage(md).ProtoReflect())
   479  	}
   480  	return x.desc.MapValue().Default()
   481  }
   482  func (x *dynamicMap) IsValid() bool {
   483  	return x.mapv != nil
   484  }
   485  
   486  func (x *dynamicMap) Range(f func(protoreflect.MapKey, protoreflect.Value) bool) {
   487  	for k, v := range x.mapv {
   488  		if !f(protoreflect.ValueOf(k).MapKey(), v) {
   489  			return
   490  		}
   491  	}
   492  }
   493  
   494  func isSet(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
   495  	switch {
   496  	case fd.IsMap():
   497  		return v.Map().Len() > 0
   498  	case fd.IsList():
   499  		return v.List().Len() > 0
   500  	case fd.ContainingOneof() != nil:
   501  		return true
   502  	case fd.Syntax() == protoreflect.Proto3 && !fd.IsExtension():
   503  		switch fd.Kind() {
   504  		case protoreflect.BoolKind:
   505  			return v.Bool()
   506  		case protoreflect.EnumKind:
   507  			return v.Enum() != 0
   508  		case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed32Kind, protoreflect.Sfixed64Kind:
   509  			return v.Int() != 0
   510  		case protoreflect.Uint32Kind, protoreflect.Uint64Kind, protoreflect.Fixed32Kind, protoreflect.Fixed64Kind:
   511  			return v.Uint() != 0
   512  		case protoreflect.FloatKind, protoreflect.DoubleKind:
   513  			return v.Float() != 0 || math.Signbit(v.Float())
   514  		case protoreflect.StringKind:
   515  			return v.String() != ""
   516  		case protoreflect.BytesKind:
   517  			return len(v.Bytes()) > 0
   518  		}
   519  	}
   520  	return true
   521  }
   522  
   523  func typecheck(fd protoreflect.FieldDescriptor, v protoreflect.Value) {
   524  	if err := typeIsValid(fd, v); err != nil {
   525  		panic(err)
   526  	}
   527  }
   528  
   529  func typeIsValid(fd protoreflect.FieldDescriptor, v protoreflect.Value) error {
   530  	switch {
   531  	case !v.IsValid():
   532  		return errors.New("%v: assigning invalid value", fd.FullName())
   533  	case fd.IsMap():
   534  		if mapv, ok := v.Interface().(*dynamicMap); !ok || mapv.desc != fd || !mapv.IsValid() {
   535  			return errors.New("%v: assigning invalid type %T", fd.FullName(), v.Interface())
   536  		}
   537  		return nil
   538  	case fd.IsList():
   539  		switch list := v.Interface().(type) {
   540  		case *dynamicList:
   541  			if list.desc == fd && list.IsValid() {
   542  				return nil
   543  			}
   544  		case emptyList:
   545  			if list.desc == fd && list.IsValid() {
   546  				return nil
   547  			}
   548  		}
   549  		return errors.New("%v: assigning invalid type %T", fd.FullName(), v.Interface())
   550  	default:
   551  		return singularTypeIsValid(fd, v)
   552  	}
   553  }
   554  
   555  func typecheckSingular(fd protoreflect.FieldDescriptor, v protoreflect.Value) {
   556  	if err := singularTypeIsValid(fd, v); err != nil {
   557  		panic(err)
   558  	}
   559  }
   560  
   561  func singularTypeIsValid(fd protoreflect.FieldDescriptor, v protoreflect.Value) error {
   562  	vi := v.Interface()
   563  	var ok bool
   564  	switch fd.Kind() {
   565  	case protoreflect.BoolKind:
   566  		_, ok = vi.(bool)
   567  	case protoreflect.EnumKind:
   568  		// We could check against the valid set of enum values, but do not.
   569  		_, ok = vi.(protoreflect.EnumNumber)
   570  	case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
   571  		_, ok = vi.(int32)
   572  	case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
   573  		_, ok = vi.(uint32)
   574  	case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
   575  		_, ok = vi.(int64)
   576  	case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
   577  		_, ok = vi.(uint64)
   578  	case protoreflect.FloatKind:
   579  		_, ok = vi.(float32)
   580  	case protoreflect.DoubleKind:
   581  		_, ok = vi.(float64)
   582  	case protoreflect.StringKind:
   583  		_, ok = vi.(string)
   584  	case protoreflect.BytesKind:
   585  		_, ok = vi.([]byte)
   586  	case protoreflect.MessageKind, protoreflect.GroupKind:
   587  		var m protoreflect.Message
   588  		m, ok = vi.(protoreflect.Message)
   589  		if ok && m.Descriptor().FullName() != fd.Message().FullName() {
   590  			return errors.New("%v: assigning invalid message type %v", fd.FullName(), m.Descriptor().FullName())
   591  		}
   592  		if dm, ok := vi.(*Message); ok && dm.known == nil {
   593  			return errors.New("%v: assigning invalid zero-value message", fd.FullName())
   594  		}
   595  	}
   596  	if !ok {
   597  		return errors.New("%v: assigning invalid type %T", fd.FullName(), v.Interface())
   598  	}
   599  	return nil
   600  }
   601  
   602  func newListEntry(fd protoreflect.FieldDescriptor) protoreflect.Value {
   603  	switch fd.Kind() {
   604  	case protoreflect.BoolKind:
   605  		return protoreflect.ValueOfBool(false)
   606  	case protoreflect.EnumKind:
   607  		return protoreflect.ValueOfEnum(fd.Enum().Values().Get(0).Number())
   608  	case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
   609  		return protoreflect.ValueOfInt32(0)
   610  	case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
   611  		return protoreflect.ValueOfUint32(0)
   612  	case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
   613  		return protoreflect.ValueOfInt64(0)
   614  	case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
   615  		return protoreflect.ValueOfUint64(0)
   616  	case protoreflect.FloatKind:
   617  		return protoreflect.ValueOfFloat32(0)
   618  	case protoreflect.DoubleKind:
   619  		return protoreflect.ValueOfFloat64(0)
   620  	case protoreflect.StringKind:
   621  		return protoreflect.ValueOfString("")
   622  	case protoreflect.BytesKind:
   623  		return protoreflect.ValueOfBytes(nil)
   624  	case protoreflect.MessageKind, protoreflect.GroupKind:
   625  		return protoreflect.ValueOfMessage(NewMessage(fd.Message()).ProtoReflect())
   626  	}
   627  	panic(errors.New("%v: unknown kind %v", fd.FullName(), fd.Kind()))
   628  }
   629  
   630  // NewExtensionType creates a new ExtensionType with the provided descriptor.
   631  //
   632  // Dynamic ExtensionTypes with the same descriptor compare as equal. That is,
   633  // if xd1 == xd2, then NewExtensionType(xd1) == NewExtensionType(xd2).
   634  //
   635  // The InterfaceOf and ValueOf methods of the extension type are defined as:
   636  //
   637  //	func (xt extensionType) ValueOf(iv interface{}) protoreflect.Value {
   638  //		return protoreflect.ValueOf(iv)
   639  //	}
   640  //
   641  //	func (xt extensionType) InterfaceOf(v protoreflect.Value) interface{} {
   642  //		return v.Interface()
   643  //	}
   644  //
   645  // The Go type used by the proto.GetExtension and proto.SetExtension functions
   646  // is determined by these methods, and is therefore equivalent to the Go type
   647  // used to represent a protoreflect.Value. See the protoreflect.Value
   648  // documentation for more details.
   649  func NewExtensionType(desc protoreflect.ExtensionDescriptor) protoreflect.ExtensionType {
   650  	if xt, ok := desc.(protoreflect.ExtensionTypeDescriptor); ok {
   651  		desc = xt.Descriptor()
   652  	}
   653  	return extensionType{extensionTypeDescriptor{desc}}
   654  }
   655  
   656  func (xt extensionType) New() protoreflect.Value {
   657  	switch {
   658  	case xt.desc.IsMap():
   659  		return protoreflect.ValueOfMap(&dynamicMap{
   660  			desc: xt.desc,
   661  			mapv: make(map[interface{}]protoreflect.Value),
   662  		})
   663  	case xt.desc.IsList():
   664  		return protoreflect.ValueOfList(&dynamicList{desc: xt.desc})
   665  	case xt.desc.Message() != nil:
   666  		return protoreflect.ValueOfMessage(NewMessage(xt.desc.Message()))
   667  	default:
   668  		return xt.desc.Default()
   669  	}
   670  }
   671  
   672  func (xt extensionType) Zero() protoreflect.Value {
   673  	switch {
   674  	case xt.desc.IsMap():
   675  		return protoreflect.ValueOfMap(&dynamicMap{desc: xt.desc})
   676  	case xt.desc.Cardinality() == protoreflect.Repeated:
   677  		return protoreflect.ValueOfList(emptyList{desc: xt.desc})
   678  	case xt.desc.Message() != nil:
   679  		return protoreflect.ValueOfMessage(&Message{typ: messageType{xt.desc.Message()}})
   680  	default:
   681  		return xt.desc.Default()
   682  	}
   683  }
   684  
   685  func (xt extensionType) TypeDescriptor() protoreflect.ExtensionTypeDescriptor {
   686  	return xt.desc
   687  }
   688  
   689  func (xt extensionType) ValueOf(iv interface{}) protoreflect.Value {
   690  	v := protoreflect.ValueOf(iv)
   691  	typecheck(xt.desc, v)
   692  	return v
   693  }
   694  
   695  func (xt extensionType) InterfaceOf(v protoreflect.Value) interface{} {
   696  	typecheck(xt.desc, v)
   697  	return v.Interface()
   698  }
   699  
   700  func (xt extensionType) IsValidInterface(iv interface{}) bool {
   701  	return typeIsValid(xt.desc, protoreflect.ValueOf(iv)) == nil
   702  }
   703  
   704  func (xt extensionType) IsValidValue(v protoreflect.Value) bool {
   705  	return typeIsValid(xt.desc, v) == nil
   706  }
   707  
   708  type extensionTypeDescriptor struct {
   709  	protoreflect.ExtensionDescriptor
   710  }
   711  
   712  func (xt extensionTypeDescriptor) Type() protoreflect.ExtensionType {
   713  	return extensionType{xt}
   714  }
   715  
   716  func (xt extensionTypeDescriptor) Descriptor() protoreflect.ExtensionDescriptor {
   717  	return xt.ExtensionDescriptor
   718  }
   719  

View as plain text