blob: c416440114d31329beb3df810982c1c8fc4639a5 [file] [log] [blame]
Joe Tsaifa02f4e2018-09-12 16:20:37 -07001// Copyright 2018 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
5package impl
6
7import (
Joe Tsaic6b75612018-09-13 14:24:37 -07008 "fmt"
Joe Tsaifa02f4e2018-09-12 16:20:37 -07009 "reflect"
Damien Neilc37adef2019-04-01 13:49:56 -070010 "sort"
Joe Tsaifa02f4e2018-09-12 16:20:37 -070011 "strconv"
12 "strings"
Joe Tsaic6b75612018-09-13 14:24:37 -070013 "sync"
Damien Neilc37adef2019-04-01 13:49:56 -070014 "sync/atomic"
Joe Tsaifa02f4e2018-09-12 16:20:37 -070015
Damien Neile89e6242019-05-13 23:55:40 -070016 pvalue "google.golang.org/protobuf/internal/value"
17 pref "google.golang.org/protobuf/reflect/protoreflect"
18 piface "google.golang.org/protobuf/runtime/protoiface"
Joe Tsaifa02f4e2018-09-12 16:20:37 -070019)
20
Joe Tsai4fe96632019-05-22 05:12:36 -040021// MessageInfo provides protobuf related functionality for a given Go type
22// that represents a message. A given instance of MessageInfo is tied to
Joe Tsaic6b75612018-09-13 14:24:37 -070023// exactly one Go type, which must be a pointer to a struct type.
Joe Tsai4fe96632019-05-22 05:12:36 -040024type MessageInfo struct {
Damien Neil8012b442019-01-18 09:32:24 -080025 // GoType is the underlying message Go type and must be populated.
Joe Tsaic6b75612018-09-13 14:24:37 -070026 // Once set, this field must never be mutated.
Damien Neil8012b442019-01-18 09:32:24 -080027 GoType reflect.Type // pointer to struct
28
29 // PBType is the underlying message descriptor type and must be populated.
30 // Once set, this field must never be mutated.
31 PBType pref.MessageType
Joe Tsaic6b75612018-09-13 14:24:37 -070032
Damien Neilc37adef2019-04-01 13:49:56 -070033 initMu sync.Mutex // protects all unexported fields
34 initDone uint32
Joe Tsaic6b75612018-09-13 14:24:37 -070035
Damien Neilc37adef2019-04-01 13:49:56 -070036 // Keep a separate slice of fields for efficient field encoding in tag order
37 // and because iterating over a slice is substantially faster than a map.
38 fields map[pref.FieldNumber]*fieldInfo
39 fieldsOrdered []*fieldInfo
40
Joe Tsai4ec39c72019-04-03 13:40:53 -070041 oneofs map[pref.Name]*oneofInfo
Joe Tsaibe5348c2018-10-23 18:31:18 -070042
Joe Tsai378c1322019-04-25 23:48:08 -070043 getUnknown func(pointer) pref.RawFields
44 setUnknown func(pointer, pref.RawFields)
45
46 extensionMap func(pointer) *extensionMap
47
Joe Tsaibe5348c2018-10-23 18:31:18 -070048 unknownFields func(*messageDataType) pref.UnknownFields
49 extensionFields func(*messageDataType) pref.KnownFields
Damien Neilc37adef2019-04-01 13:49:56 -070050 methods piface.Methods
51
Damien Neilc37adef2019-04-01 13:49:56 -070052 sizecacheOffset offset
Joe Tsai378c1322019-04-25 23:48:08 -070053 extensionOffset offset
Damien Neilc37adef2019-04-01 13:49:56 -070054 unknownOffset offset
55 extensionFieldInfosMu sync.RWMutex
Joe Tsai89d49632019-06-04 16:20:00 -070056 extensionFieldInfos map[pref.ExtensionType]*extensionFieldInfo
Damien Neilc37adef2019-04-01 13:49:56 -070057}
58
59var prefMessageType = reflect.TypeOf((*pref.Message)(nil)).Elem()
60
Joe Tsai4fe96632019-05-22 05:12:36 -040061// getMessageInfo returns the MessageInfo (if any) for a type.
Damien Neilc37adef2019-04-01 13:49:56 -070062//
Joe Tsai4fe96632019-05-22 05:12:36 -040063// We find the MessageInfo by calling the ProtoReflect method on the type's
Damien Neilc37adef2019-04-01 13:49:56 -070064// zero value and looking at the returned type to see if it is a
Joe Tsai4fe96632019-05-22 05:12:36 -040065// messageReflectWrapper. Note that the MessageInfo may still be uninitialized
Damien Neilc37adef2019-04-01 13:49:56 -070066// at this point.
Joe Tsai4fe96632019-05-22 05:12:36 -040067func getMessageInfo(mt reflect.Type) (mi *MessageInfo, ok bool) {
Damien Neilc37adef2019-04-01 13:49:56 -070068 method, ok := mt.MethodByName("ProtoReflect")
69 if !ok {
70 return nil, false
71 }
72 if method.Type.NumIn() != 1 || method.Type.NumOut() != 1 || method.Type.Out(0) != prefMessageType {
73 return nil, false
74 }
75 ret := reflect.Zero(mt).Method(method.Index).Call(nil)
76 m, ok := ret[0].Elem().Interface().(*messageReflectWrapper)
77 if !ok {
78 return nil, ok
79 }
80 return m.mi, true
Joe Tsaifa02f4e2018-09-12 16:20:37 -070081}
82
Joe Tsai4fe96632019-05-22 05:12:36 -040083func (mi *MessageInfo) init() {
Damien Neilc37adef2019-04-01 13:49:56 -070084 // This function is called in the hot path. Inline the sync.Once
85 // logic, since allocating a closure for Once.Do is expensive.
86 // Keep init small to ensure that it can be inlined.
87 if atomic.LoadUint32(&mi.initDone) == 1 {
88 return
89 }
90 mi.initOnce()
91}
Joe Tsaic6b75612018-09-13 14:24:37 -070092
Joe Tsai4fe96632019-05-22 05:12:36 -040093func (mi *MessageInfo) initOnce() {
Damien Neilc37adef2019-04-01 13:49:56 -070094 mi.initMu.Lock()
95 defer mi.initMu.Unlock()
96 if mi.initDone == 1 {
97 return
98 }
99
100 t := mi.GoType
101 if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct {
102 panic(fmt.Sprintf("got %v, want *struct kind", t))
103 }
104
105 si := mi.makeStructInfo(t.Elem())
106 mi.makeKnownFieldsFunc(si)
107 mi.makeUnknownFieldsFunc(t.Elem())
108 mi.makeExtensionFieldsFunc(t.Elem())
109 mi.makeMethods(t.Elem())
110
111 atomic.StoreUint32(&mi.initDone, 1)
112}
113
Joe Tsai378c1322019-04-25 23:48:08 -0700114type (
115 SizeCache = int32
116 UnknownFields = []byte
117 ExtensionFields = map[int32]ExtensionField
118)
119
120var (
121 sizecacheType = reflect.TypeOf(SizeCache(0))
122 unknownFieldsType = reflect.TypeOf(UnknownFields(nil))
123 extensionFieldsType = reflect.TypeOf(ExtensionFields(nil))
124)
Damien Neilc37adef2019-04-01 13:49:56 -0700125
Joe Tsai4fe96632019-05-22 05:12:36 -0400126func (mi *MessageInfo) makeMethods(t reflect.Type) {
Damien Neilc37adef2019-04-01 13:49:56 -0700127 mi.sizecacheOffset = invalidOffset
128 if fx, _ := t.FieldByName("XXX_sizecache"); fx.Type == sizecacheType {
129 mi.sizecacheOffset = offsetOf(fx)
130 }
131 mi.unknownOffset = invalidOffset
Joe Tsai378c1322019-04-25 23:48:08 -0700132 if fx, _ := t.FieldByName("XXX_unrecognized"); fx.Type == unknownFieldsType {
Damien Neilc37adef2019-04-01 13:49:56 -0700133 mi.unknownOffset = offsetOf(fx)
134 }
Joe Tsai378c1322019-04-25 23:48:08 -0700135 mi.extensionOffset = invalidOffset
136 if fx, _ := t.FieldByName("XXX_InternalExtensions"); fx.Type == extensionFieldsType {
137 mi.extensionOffset = offsetOf(fx)
138 } else if fx, _ = t.FieldByName("XXX_extensions"); fx.Type == extensionFieldsType {
139 mi.extensionOffset = offsetOf(fx)
140 }
Damien Neilc37adef2019-04-01 13:49:56 -0700141 mi.methods.Flags = piface.MethodFlagDeterministicMarshal
142 mi.methods.MarshalAppend = mi.marshalAppend
143 mi.methods.Size = mi.size
Joe Tsaic6b75612018-09-13 14:24:37 -0700144}
145
Damien Neil3eaddf02019-05-09 11:33:55 -0700146type structInfo struct {
147 fieldsByNumber map[pref.FieldNumber]reflect.StructField
148 oneofsByName map[pref.Name]reflect.StructField
149 oneofWrappersByType map[reflect.Type]pref.FieldNumber
150 oneofWrappersByNumber map[pref.FieldNumber]reflect.Type
151}
152
Joe Tsai4fe96632019-05-22 05:12:36 -0400153func (mi *MessageInfo) makeStructInfo(t reflect.Type) structInfo {
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700154 // Generate a mapping of field numbers and names to Go struct field or type.
Damien Neil3eaddf02019-05-09 11:33:55 -0700155 si := structInfo{
156 fieldsByNumber: map[pref.FieldNumber]reflect.StructField{},
157 oneofsByName: map[pref.Name]reflect.StructField{},
158 oneofWrappersByType: map[reflect.Type]pref.FieldNumber{},
159 oneofWrappersByNumber: map[pref.FieldNumber]reflect.Type{},
160 }
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700161fieldLoop:
162 for i := 0; i < t.NumField(); i++ {
163 f := t.Field(i)
164 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
165 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
166 n, _ := strconv.ParseUint(s, 10, 64)
Damien Neil3eaddf02019-05-09 11:33:55 -0700167 si.fieldsByNumber[pref.FieldNumber(n)] = f
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700168 continue fieldLoop
169 }
170 }
171 if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
Damien Neil3eaddf02019-05-09 11:33:55 -0700172 si.oneofsByName[pref.Name(s)] = f
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700173 continue fieldLoop
174 }
175 }
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800176 var oneofWrappers []interface{}
Joe Tsai2c870bb2018-10-17 11:46:52 -0700177 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800178 oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{})
179 }
180 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
181 oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{})
182 }
183 for _, v := range oneofWrappers {
184 tf := reflect.TypeOf(v).Elem()
185 f := tf.Field(0)
186 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
187 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
188 n, _ := strconv.ParseUint(s, 10, 64)
Damien Neil3eaddf02019-05-09 11:33:55 -0700189 si.oneofWrappersByType[tf] = pref.FieldNumber(n)
190 si.oneofWrappersByNumber[pref.FieldNumber(n)] = tf
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800191 break
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700192 }
193 }
194 }
Damien Neil3eaddf02019-05-09 11:33:55 -0700195 return si
196}
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700197
Damien Neil3eaddf02019-05-09 11:33:55 -0700198// makeKnownFieldsFunc generates functions for operations that can be performed
199// on each protobuf message field. It takes in a reflect.Type representing the
200// Go struct and matches message fields with struct fields.
201//
202// This code assumes that the struct is well-formed and panics if there are
203// any discrepancies.
Joe Tsai4fe96632019-05-22 05:12:36 -0400204func (mi *MessageInfo) makeKnownFieldsFunc(si structInfo) {
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700205 mi.fields = map[pref.FieldNumber]*fieldInfo{}
Damien Neilc37adef2019-04-01 13:49:56 -0700206 mi.fieldsOrdered = make([]*fieldInfo, 0, mi.PBType.Fields().Len())
Joe Tsai0fc49f82019-05-01 12:29:25 -0700207 for i := 0; i < mi.PBType.Descriptor().Fields().Len(); i++ {
208 fd := mi.PBType.Descriptor().Fields().Get(i)
Damien Neil3eaddf02019-05-09 11:33:55 -0700209 fs := si.fieldsByNumber[fd.Number()]
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700210 var fi fieldInfo
211 switch {
Joe Tsaiac31a352019-05-13 14:32:56 -0700212 case fd.ContainingOneof() != nil:
213 fi = fieldInfoForOneof(fd, si.oneofsByName[fd.ContainingOneof().Name()], si.oneofWrappersByNumber[fd.Number()])
Damien Neilc37adef2019-04-01 13:49:56 -0700214 // There is one fieldInfo for each proto message field, but only one struct
215 // field for all message fields in a oneof. We install the encoder functions
216 // on the fieldInfo for the first field in the oneof.
217 //
218 // A slightly simpler approach would be to have each fieldInfo's encoder
219 // handle the case where that field is set, but this would require more
220 // checks against the current oneof type than a single map lookup.
221 if fd.ContainingOneof().Fields().Get(0).Name() == fd.Name() {
222 fi.funcs = makeOneofFieldCoder(si.oneofsByName[fd.ContainingOneof().Name()], fd.ContainingOneof(), si.fieldsByNumber, si.oneofWrappersByNumber)
223 }
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700224 case fd.IsMap():
225 fi = fieldInfoForMap(fd, fs)
Joe Tsaiac31a352019-05-13 14:32:56 -0700226 case fd.IsList():
Joe Tsai4b7aff62018-11-14 14:05:19 -0800227 fi = fieldInfoForList(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700228 case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700229 fi = fieldInfoForMessage(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700230 default:
231 fi = fieldInfoForScalar(fd, fs)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700232 }
Damien Neilc37adef2019-04-01 13:49:56 -0700233 fi.num = fd.Number()
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700234 mi.fields[fd.Number()] = &fi
Damien Neilc37adef2019-04-01 13:49:56 -0700235 mi.fieldsOrdered = append(mi.fieldsOrdered, &fi)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700236 }
Damien Neilc37adef2019-04-01 13:49:56 -0700237 sort.Slice(mi.fieldsOrdered, func(i, j int) bool {
238 return mi.fieldsOrdered[i].num < mi.fieldsOrdered[j].num
239 })
Joe Tsai4ec39c72019-04-03 13:40:53 -0700240
241 mi.oneofs = map[pref.Name]*oneofInfo{}
Joe Tsai0fc49f82019-05-01 12:29:25 -0700242 for i := 0; i < mi.PBType.Descriptor().Oneofs().Len(); i++ {
243 od := mi.PBType.Descriptor().Oneofs().Get(i)
Damien Neil3eaddf02019-05-09 11:33:55 -0700244 mi.oneofs[od.Name()] = makeOneofInfo(od, si.oneofsByName[od.Name()], si.oneofWrappersByType)
Joe Tsai4ec39c72019-04-03 13:40:53 -0700245 }
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700246}
Joe Tsaic6b75612018-09-13 14:24:37 -0700247
Joe Tsai4fe96632019-05-22 05:12:36 -0400248func (mi *MessageInfo) makeUnknownFieldsFunc(t reflect.Type) {
Joe Tsai378c1322019-04-25 23:48:08 -0700249 mi.unknownFields = makeLegacyUnknownFieldsFunc(t)
250
251 mi.getUnknown = func(pointer) pref.RawFields { return nil }
252 mi.setUnknown = func(pointer, pref.RawFields) { return }
253 fu, _ := t.FieldByName("XXX_unrecognized")
254 if fu.Type == unknownFieldsType {
255 fieldOffset := offsetOf(fu)
256 mi.getUnknown = func(p pointer) pref.RawFields {
257 if p.IsNil() {
258 return nil
259 }
260 rv := p.Apply(fieldOffset).AsValueOf(unknownFieldsType)
261 return pref.RawFields(*rv.Interface().(*[]byte))
262 }
263 mi.setUnknown = func(p pointer, b pref.RawFields) {
264 if p.IsNil() {
265 panic("invalid SetUnknown on nil Message")
266 }
267 rv := p.Apply(fieldOffset).AsValueOf(unknownFieldsType)
268 *rv.Interface().(*[]byte) = []byte(b)
269 }
270 } else {
271 mi.getUnknown = func(pointer) pref.RawFields {
272 return nil
273 }
274 mi.setUnknown = func(p pointer, _ pref.RawFields) {
275 if p.IsNil() {
276 panic("invalid SetUnknown on nil Message")
277 }
278 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700279 }
280}
281
Joe Tsai4fe96632019-05-22 05:12:36 -0400282func (mi *MessageInfo) makeExtensionFieldsFunc(t reflect.Type) {
Joe Tsai378c1322019-04-25 23:48:08 -0700283 mi.extensionFields = makeLegacyExtensionFieldsFunc(t)
284
285 fx, _ := t.FieldByName("XXX_extensions")
286 if fx.Type != extensionFieldsType {
287 fx, _ = t.FieldByName("XXX_InternalExtensions")
Joe Tsaif0c01e42018-11-06 13:05:20 -0800288 }
Joe Tsai378c1322019-04-25 23:48:08 -0700289 if fx.Type == extensionFieldsType {
290 fieldOffset := offsetOf(fx)
291 mi.extensionMap = func(p pointer) *extensionMap {
292 v := p.Apply(fieldOffset).AsValueOf(extensionFieldsType)
293 return (*extensionMap)(v.Interface().(*map[int32]ExtensionField))
294 }
295 } else {
296 mi.extensionMap = func(pointer) *extensionMap {
297 return (*extensionMap)(nil)
298 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700299 }
300}
301
Joe Tsai4fe96632019-05-22 05:12:36 -0400302func (mi *MessageInfo) MessageOf(p interface{}) pref.Message {
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700303 return (*messageReflectWrapper)(mi.dataTypeOf(p))
Joe Tsai08e00302018-11-26 22:32:06 -0800304}
305
Joe Tsai4fe96632019-05-22 05:12:36 -0400306func (mi *MessageInfo) Methods() *piface.Methods {
Damien Neilc37adef2019-04-01 13:49:56 -0700307 mi.init()
308 return &mi.methods
Damien Neil0d3e8cc2019-04-01 13:31:55 -0700309}
310
Joe Tsai4fe96632019-05-22 05:12:36 -0400311func (mi *MessageInfo) dataTypeOf(p interface{}) *messageDataType {
Damien Neil8012b442019-01-18 09:32:24 -0800312 // TODO: Remove this check? This API is primarily used by generated code,
313 // and should not violate this assumption. Leave this check in for now to
314 // provide some sanity checks during development. This can be removed if
315 // it proves to be detrimental to performance.
316 if reflect.TypeOf(p) != mi.GoType {
317 panic(fmt.Sprintf("type mismatch: got %T, want %v", p, mi.GoType))
318 }
Joe Tsai6cf80c42018-12-01 04:57:09 -0800319 return &messageDataType{pointerOfIface(p), mi}
Joe Tsaic6b75612018-09-13 14:24:37 -0700320}
321
322// messageDataType is a tuple of a pointer to the message data and
323// a pointer to the message type.
324//
Joe Tsai4fe96632019-05-22 05:12:36 -0400325// TODO: Unfortunately, we need to close over a pointer and MessageInfo,
Joe Tsaic6b75612018-09-13 14:24:37 -0700326// which incurs an an allocation. This pair is similar to a Go interface,
327// which is essentially a tuple of the same thing. We can make this efficient
328// with reflect.NamedOf (see https://golang.org/issues/16522).
329//
330// With that hypothetical API, we could dynamically create a new named type
Joe Tsai4fe96632019-05-22 05:12:36 -0400331// that has the same underlying type as MessageInfo.GoType, and
332// dynamically create methods that close over MessageInfo.
Joe Tsaic6b75612018-09-13 14:24:37 -0700333// Since the new type would have the same underlying type, we could directly
334// convert between pointers of those types, giving us an efficient way to swap
335// out the method set.
336//
337// Barring the ability to dynamically create named types, the workaround is
338// 1. either to accept the cost of an allocation for this wrapper struct or
339// 2. generate more types and methods, at the expense of binary size increase.
340type messageDataType struct {
341 p pointer
Joe Tsai4fe96632019-05-22 05:12:36 -0400342 mi *MessageInfo
Joe Tsaic6b75612018-09-13 14:24:37 -0700343}
344
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700345type messageReflectWrapper messageDataType
Joe Tsai08e00302018-11-26 22:32:06 -0800346
Joe Tsai0fc49f82019-05-01 12:29:25 -0700347func (m *messageReflectWrapper) Descriptor() pref.MessageDescriptor {
348 return m.mi.PBType.Descriptor()
349}
Joe Tsai0fc49f82019-05-01 12:29:25 -0700350func (m *messageReflectWrapper) New() pref.Message {
351 return m.mi.PBType.New()
352}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700353func (m *messageReflectWrapper) Interface() pref.ProtoMessage {
Joe Tsai08e00302018-11-26 22:32:06 -0800354 if m, ok := m.ProtoUnwrap().(pref.ProtoMessage); ok {
355 return m
356 }
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700357 return (*messageIfaceWrapper)(m)
Joe Tsai08e00302018-11-26 22:32:06 -0800358}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700359func (m *messageReflectWrapper) ProtoUnwrap() interface{} {
Damien Neil8012b442019-01-18 09:32:24 -0800360 return m.p.AsIfaceOf(m.mi.GoType.Elem())
Joe Tsai08e00302018-11-26 22:32:06 -0800361}
Joe Tsai08e00302018-11-26 22:32:06 -0800362
Joe Tsai378c1322019-04-25 23:48:08 -0700363func (m *messageReflectWrapper) Len() (cnt int) {
364 m.mi.init()
365 for _, fi := range m.mi.fields {
366 if fi.has(m.p) {
367 cnt++
368 }
369 }
370 return cnt + m.mi.extensionMap(m.p).Len()
371}
372func (m *messageReflectWrapper) Range(f func(pref.FieldDescriptor, pref.Value) bool) {
373 m.mi.init()
374 for _, fi := range m.mi.fields {
375 if fi.has(m.p) {
376 if !f(fi.fieldDesc, fi.get(m.p)) {
377 return
378 }
379 }
380 }
381 m.mi.extensionMap(m.p).Range(f)
382}
383func (m *messageReflectWrapper) Has(fd pref.FieldDescriptor) bool {
384 if fi, xt := m.checkField(fd); fi != nil {
385 return fi.has(m.p)
386 } else {
387 return m.mi.extensionMap(m.p).Has(xt)
388 }
389}
390func (m *messageReflectWrapper) Clear(fd pref.FieldDescriptor) {
391 if fi, xt := m.checkField(fd); fi != nil {
392 fi.clear(m.p)
393 } else {
394 m.mi.extensionMap(m.p).Clear(xt)
395 }
396}
397func (m *messageReflectWrapper) Get(fd pref.FieldDescriptor) pref.Value {
398 if fi, xt := m.checkField(fd); fi != nil {
399 return fi.get(m.p)
400 } else {
401 return m.mi.extensionMap(m.p).Get(xt)
402 }
403}
404func (m *messageReflectWrapper) Set(fd pref.FieldDescriptor, v pref.Value) {
405 if fi, xt := m.checkField(fd); fi != nil {
406 fi.set(m.p, v)
407 } else {
408 m.mi.extensionMap(m.p).Set(xt, v)
409 }
410}
411func (m *messageReflectWrapper) Mutable(fd pref.FieldDescriptor) pref.Value {
412 if fi, xt := m.checkField(fd); fi != nil {
413 return fi.mutable(m.p)
414 } else {
415 return m.mi.extensionMap(m.p).Mutable(xt)
416 }
417}
418func (m *messageReflectWrapper) NewMessage(fd pref.FieldDescriptor) pref.Message {
419 if fi, xt := m.checkField(fd); fi != nil {
420 return fi.newMessage()
421 } else {
422 return xt.New().Message()
423 }
424}
425func (m *messageReflectWrapper) WhichOneof(od pref.OneofDescriptor) pref.FieldDescriptor {
426 m.mi.init()
427 if oi := m.mi.oneofs[od.Name()]; oi != nil && oi.oneofDesc == od {
428 return od.Fields().ByNumber(oi.which(m.p))
429 }
430 panic("invalid oneof descriptor")
431}
432func (m *messageReflectWrapper) GetUnknown() pref.RawFields {
433 m.mi.init()
434 return m.mi.getUnknown(m.p)
435}
436func (m *messageReflectWrapper) SetUnknown(b pref.RawFields) {
437 m.mi.init()
438 m.mi.setUnknown(m.p, b)
439}
440
441// checkField verifies that the provided field descriptor is valid.
442// Exactly one of the returned values is populated.
443func (m *messageReflectWrapper) checkField(fd pref.FieldDescriptor) (*fieldInfo, pref.ExtensionType) {
444 m.mi.init()
445 if fi := m.mi.fields[fd.Number()]; fi != nil {
446 if fi.fieldDesc != fd {
447 panic("mismatching field descriptor")
448 }
449 return fi, nil
450 }
451 if fd.IsExtension() {
452 if fd.ContainingMessage().FullName() != m.mi.PBType.FullName() {
453 // TODO: Should this be exact containing message descriptor match?
454 panic("mismatching containing message")
455 }
456 if !m.mi.PBType.ExtensionRanges().Has(fd.Number()) {
457 panic("invalid extension field")
458 }
459 return nil, fd.(pref.ExtensionType)
460 }
461 panic("invalid field descriptor")
462}
463
464type extensionMap map[int32]ExtensionField
465
466func (m *extensionMap) Len() int {
467 if m != nil {
468 return len(*m)
469 }
470 return 0
471}
472func (m *extensionMap) Range(f func(pref.FieldDescriptor, pref.Value) bool) {
473 if m != nil {
474 for _, x := range *m {
475 xt := x.GetType()
476 if !f(xt, xt.ValueOf(x.GetValue())) {
477 return
478 }
479 }
480 }
481}
482func (m *extensionMap) Has(xt pref.ExtensionType) (ok bool) {
483 if m != nil {
484 _, ok = (*m)[int32(xt.Number())]
485 }
486 return ok
487}
488func (m *extensionMap) Clear(xt pref.ExtensionType) {
489 delete(*m, int32(xt.Number()))
490}
491func (m *extensionMap) Get(xt pref.ExtensionType) pref.Value {
492 if m != nil {
493 if x, ok := (*m)[int32(xt.Number())]; ok {
494 return xt.ValueOf(x.GetValue())
495 }
496 }
497 if !isComposite(xt) {
498 return defaultValueOf(xt)
499 }
500 return frozenValueOf(xt.New())
501}
502func (m *extensionMap) Set(xt pref.ExtensionType, v pref.Value) {
503 if *m == nil {
504 *m = make(map[int32]ExtensionField)
505 }
506 var x ExtensionField
507 x.SetType(xt)
508 x.SetEagerValue(xt.InterfaceOf(v))
509 (*m)[int32(xt.Number())] = x
510}
511func (m *extensionMap) Mutable(xt pref.ExtensionType) pref.Value {
512 if !isComposite(xt) {
513 panic("invalid Mutable on field with non-composite type")
514 }
515 if x, ok := (*m)[int32(xt.Number())]; ok {
516 return xt.ValueOf(x.GetValue())
517 }
518 v := xt.New()
519 m.Set(xt, v)
520 return v
521}
522
523func isComposite(fd pref.FieldDescriptor) bool {
524 return fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind || fd.IsList() || fd.IsMap()
525}
526
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700527var _ pvalue.Unwrapper = (*messageReflectWrapper)(nil)
528
529type messageIfaceWrapper messageDataType
530
531func (m *messageIfaceWrapper) ProtoReflect() pref.Message {
532 return (*messageReflectWrapper)(m)
533}
Damien Neil0d3e8cc2019-04-01 13:31:55 -0700534func (m *messageIfaceWrapper) XXX_Methods() *piface.Methods {
Damien Neilc37adef2019-04-01 13:49:56 -0700535 // TODO: Consider not recreating this on every call.
536 m.mi.init()
537 return &piface.Methods{
538 Flags: piface.MethodFlagDeterministicMarshal,
539 MarshalAppend: m.marshalAppend,
540 Size: m.size,
541 }
Damien Neil0d3e8cc2019-04-01 13:31:55 -0700542}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700543func (m *messageIfaceWrapper) ProtoUnwrap() interface{} {
544 return m.p.AsIfaceOf(m.mi.GoType.Elem())
545}
Damien Neilc37adef2019-04-01 13:49:56 -0700546func (m *messageIfaceWrapper) marshalAppend(b []byte, _ pref.ProtoMessage, opts piface.MarshalOptions) ([]byte, error) {
547 return m.mi.marshalAppendPointer(b, m.p, newMarshalOptions(opts))
548}
549func (m *messageIfaceWrapper) size(msg pref.ProtoMessage) (size int) {
550 return m.mi.sizePointer(m.p, 0)
551}