blob: df2fceeb43e308c90b8bc52df413e16ea136a947 [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 Tsai4a539f42019-06-17 12:30:25 -070048 methods piface.Methods
Damien Neilc37adef2019-04-01 13:49:56 -070049
Damien Neilc37adef2019-04-01 13:49:56 -070050 sizecacheOffset offset
Joe Tsai378c1322019-04-25 23:48:08 -070051 extensionOffset offset
Damien Neilc37adef2019-04-01 13:49:56 -070052 unknownOffset offset
53 extensionFieldInfosMu sync.RWMutex
Joe Tsai89d49632019-06-04 16:20:00 -070054 extensionFieldInfos map[pref.ExtensionType]*extensionFieldInfo
Damien Neilc37adef2019-04-01 13:49:56 -070055}
56
57var prefMessageType = reflect.TypeOf((*pref.Message)(nil)).Elem()
58
Joe Tsai4fe96632019-05-22 05:12:36 -040059// getMessageInfo returns the MessageInfo (if any) for a type.
Damien Neilc37adef2019-04-01 13:49:56 -070060//
Joe Tsai4fe96632019-05-22 05:12:36 -040061// We find the MessageInfo by calling the ProtoReflect method on the type's
Damien Neilc37adef2019-04-01 13:49:56 -070062// zero value and looking at the returned type to see if it is a
Joe Tsai4fe96632019-05-22 05:12:36 -040063// messageReflectWrapper. Note that the MessageInfo may still be uninitialized
Damien Neilc37adef2019-04-01 13:49:56 -070064// at this point.
Joe Tsai4fe96632019-05-22 05:12:36 -040065func getMessageInfo(mt reflect.Type) (mi *MessageInfo, ok bool) {
Damien Neilc37adef2019-04-01 13:49:56 -070066 method, ok := mt.MethodByName("ProtoReflect")
67 if !ok {
68 return nil, false
69 }
70 if method.Type.NumIn() != 1 || method.Type.NumOut() != 1 || method.Type.Out(0) != prefMessageType {
71 return nil, false
72 }
73 ret := reflect.Zero(mt).Method(method.Index).Call(nil)
74 m, ok := ret[0].Elem().Interface().(*messageReflectWrapper)
75 if !ok {
76 return nil, ok
77 }
78 return m.mi, true
Joe Tsaifa02f4e2018-09-12 16:20:37 -070079}
80
Joe Tsai4fe96632019-05-22 05:12:36 -040081func (mi *MessageInfo) init() {
Damien Neilc37adef2019-04-01 13:49:56 -070082 // This function is called in the hot path. Inline the sync.Once
83 // logic, since allocating a closure for Once.Do is expensive.
84 // Keep init small to ensure that it can be inlined.
85 if atomic.LoadUint32(&mi.initDone) == 1 {
86 return
87 }
88 mi.initOnce()
89}
Joe Tsaic6b75612018-09-13 14:24:37 -070090
Joe Tsai4fe96632019-05-22 05:12:36 -040091func (mi *MessageInfo) initOnce() {
Damien Neilc37adef2019-04-01 13:49:56 -070092 mi.initMu.Lock()
93 defer mi.initMu.Unlock()
94 if mi.initDone == 1 {
95 return
96 }
97
98 t := mi.GoType
99 if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct {
100 panic(fmt.Sprintf("got %v, want *struct kind", t))
101 }
102
103 si := mi.makeStructInfo(t.Elem())
104 mi.makeKnownFieldsFunc(si)
105 mi.makeUnknownFieldsFunc(t.Elem())
106 mi.makeExtensionFieldsFunc(t.Elem())
107 mi.makeMethods(t.Elem())
108
109 atomic.StoreUint32(&mi.initDone, 1)
110}
111
Joe Tsai378c1322019-04-25 23:48:08 -0700112type (
113 SizeCache = int32
114 UnknownFields = []byte
115 ExtensionFields = map[int32]ExtensionField
116)
117
118var (
119 sizecacheType = reflect.TypeOf(SizeCache(0))
120 unknownFieldsType = reflect.TypeOf(UnknownFields(nil))
121 extensionFieldsType = reflect.TypeOf(ExtensionFields(nil))
122)
Damien Neilc37adef2019-04-01 13:49:56 -0700123
Joe Tsai4fe96632019-05-22 05:12:36 -0400124func (mi *MessageInfo) makeMethods(t reflect.Type) {
Damien Neilc37adef2019-04-01 13:49:56 -0700125 mi.sizecacheOffset = invalidOffset
126 if fx, _ := t.FieldByName("XXX_sizecache"); fx.Type == sizecacheType {
127 mi.sizecacheOffset = offsetOf(fx)
128 }
129 mi.unknownOffset = invalidOffset
Joe Tsai378c1322019-04-25 23:48:08 -0700130 if fx, _ := t.FieldByName("XXX_unrecognized"); fx.Type == unknownFieldsType {
Damien Neilc37adef2019-04-01 13:49:56 -0700131 mi.unknownOffset = offsetOf(fx)
132 }
Joe Tsai378c1322019-04-25 23:48:08 -0700133 mi.extensionOffset = invalidOffset
134 if fx, _ := t.FieldByName("XXX_InternalExtensions"); fx.Type == extensionFieldsType {
135 mi.extensionOffset = offsetOf(fx)
136 } else if fx, _ = t.FieldByName("XXX_extensions"); fx.Type == extensionFieldsType {
137 mi.extensionOffset = offsetOf(fx)
138 }
Damien Neilc37adef2019-04-01 13:49:56 -0700139 mi.methods.Flags = piface.MethodFlagDeterministicMarshal
140 mi.methods.MarshalAppend = mi.marshalAppend
141 mi.methods.Size = mi.size
Joe Tsaic6b75612018-09-13 14:24:37 -0700142}
143
Damien Neil3eaddf02019-05-09 11:33:55 -0700144type structInfo struct {
145 fieldsByNumber map[pref.FieldNumber]reflect.StructField
146 oneofsByName map[pref.Name]reflect.StructField
147 oneofWrappersByType map[reflect.Type]pref.FieldNumber
148 oneofWrappersByNumber map[pref.FieldNumber]reflect.Type
149}
150
Joe Tsai4fe96632019-05-22 05:12:36 -0400151func (mi *MessageInfo) makeStructInfo(t reflect.Type) structInfo {
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700152 // Generate a mapping of field numbers and names to Go struct field or type.
Damien Neil3eaddf02019-05-09 11:33:55 -0700153 si := structInfo{
154 fieldsByNumber: map[pref.FieldNumber]reflect.StructField{},
155 oneofsByName: map[pref.Name]reflect.StructField{},
156 oneofWrappersByType: map[reflect.Type]pref.FieldNumber{},
157 oneofWrappersByNumber: map[pref.FieldNumber]reflect.Type{},
158 }
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700159fieldLoop:
160 for i := 0; i < t.NumField(); i++ {
161 f := t.Field(i)
162 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
163 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
164 n, _ := strconv.ParseUint(s, 10, 64)
Damien Neil3eaddf02019-05-09 11:33:55 -0700165 si.fieldsByNumber[pref.FieldNumber(n)] = f
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700166 continue fieldLoop
167 }
168 }
169 if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
Damien Neil3eaddf02019-05-09 11:33:55 -0700170 si.oneofsByName[pref.Name(s)] = f
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700171 continue fieldLoop
172 }
173 }
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800174 var oneofWrappers []interface{}
Joe Tsai2c870bb2018-10-17 11:46:52 -0700175 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800176 oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{})
177 }
178 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
179 oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{})
180 }
181 for _, v := range oneofWrappers {
182 tf := reflect.TypeOf(v).Elem()
183 f := tf.Field(0)
184 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
185 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
186 n, _ := strconv.ParseUint(s, 10, 64)
Damien Neil3eaddf02019-05-09 11:33:55 -0700187 si.oneofWrappersByType[tf] = pref.FieldNumber(n)
188 si.oneofWrappersByNumber[pref.FieldNumber(n)] = tf
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800189 break
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700190 }
191 }
192 }
Damien Neil3eaddf02019-05-09 11:33:55 -0700193 return si
194}
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700195
Damien Neil3eaddf02019-05-09 11:33:55 -0700196// makeKnownFieldsFunc generates functions for operations that can be performed
197// on each protobuf message field. It takes in a reflect.Type representing the
198// Go struct and matches message fields with struct fields.
199//
200// This code assumes that the struct is well-formed and panics if there are
201// any discrepancies.
Joe Tsai4fe96632019-05-22 05:12:36 -0400202func (mi *MessageInfo) makeKnownFieldsFunc(si structInfo) {
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700203 mi.fields = map[pref.FieldNumber]*fieldInfo{}
Damien Neilc37adef2019-04-01 13:49:56 -0700204 mi.fieldsOrdered = make([]*fieldInfo, 0, mi.PBType.Fields().Len())
Joe Tsai0fc49f82019-05-01 12:29:25 -0700205 for i := 0; i < mi.PBType.Descriptor().Fields().Len(); i++ {
206 fd := mi.PBType.Descriptor().Fields().Get(i)
Damien Neil3eaddf02019-05-09 11:33:55 -0700207 fs := si.fieldsByNumber[fd.Number()]
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700208 var fi fieldInfo
209 switch {
Joe Tsaiac31a352019-05-13 14:32:56 -0700210 case fd.ContainingOneof() != nil:
211 fi = fieldInfoForOneof(fd, si.oneofsByName[fd.ContainingOneof().Name()], si.oneofWrappersByNumber[fd.Number()])
Damien Neilc37adef2019-04-01 13:49:56 -0700212 // There is one fieldInfo for each proto message field, but only one struct
213 // field for all message fields in a oneof. We install the encoder functions
214 // on the fieldInfo for the first field in the oneof.
215 //
216 // A slightly simpler approach would be to have each fieldInfo's encoder
217 // handle the case where that field is set, but this would require more
218 // checks against the current oneof type than a single map lookup.
219 if fd.ContainingOneof().Fields().Get(0).Name() == fd.Name() {
220 fi.funcs = makeOneofFieldCoder(si.oneofsByName[fd.ContainingOneof().Name()], fd.ContainingOneof(), si.fieldsByNumber, si.oneofWrappersByNumber)
221 }
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700222 case fd.IsMap():
223 fi = fieldInfoForMap(fd, fs)
Joe Tsaiac31a352019-05-13 14:32:56 -0700224 case fd.IsList():
Joe Tsai4b7aff62018-11-14 14:05:19 -0800225 fi = fieldInfoForList(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700226 case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700227 fi = fieldInfoForMessage(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700228 default:
229 fi = fieldInfoForScalar(fd, fs)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700230 }
Damien Neilc37adef2019-04-01 13:49:56 -0700231 fi.num = fd.Number()
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700232 mi.fields[fd.Number()] = &fi
Damien Neilc37adef2019-04-01 13:49:56 -0700233 mi.fieldsOrdered = append(mi.fieldsOrdered, &fi)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700234 }
Damien Neilc37adef2019-04-01 13:49:56 -0700235 sort.Slice(mi.fieldsOrdered, func(i, j int) bool {
236 return mi.fieldsOrdered[i].num < mi.fieldsOrdered[j].num
237 })
Joe Tsai4ec39c72019-04-03 13:40:53 -0700238
239 mi.oneofs = map[pref.Name]*oneofInfo{}
Joe Tsai0fc49f82019-05-01 12:29:25 -0700240 for i := 0; i < mi.PBType.Descriptor().Oneofs().Len(); i++ {
241 od := mi.PBType.Descriptor().Oneofs().Get(i)
Damien Neil3eaddf02019-05-09 11:33:55 -0700242 mi.oneofs[od.Name()] = makeOneofInfo(od, si.oneofsByName[od.Name()], si.oneofWrappersByType)
Joe Tsai4ec39c72019-04-03 13:40:53 -0700243 }
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700244}
Joe Tsaic6b75612018-09-13 14:24:37 -0700245
Joe Tsai4fe96632019-05-22 05:12:36 -0400246func (mi *MessageInfo) makeUnknownFieldsFunc(t reflect.Type) {
Joe Tsai378c1322019-04-25 23:48:08 -0700247 mi.getUnknown = func(pointer) pref.RawFields { return nil }
248 mi.setUnknown = func(pointer, pref.RawFields) { return }
249 fu, _ := t.FieldByName("XXX_unrecognized")
250 if fu.Type == unknownFieldsType {
251 fieldOffset := offsetOf(fu)
252 mi.getUnknown = func(p pointer) pref.RawFields {
253 if p.IsNil() {
254 return nil
255 }
256 rv := p.Apply(fieldOffset).AsValueOf(unknownFieldsType)
257 return pref.RawFields(*rv.Interface().(*[]byte))
258 }
259 mi.setUnknown = func(p pointer, b pref.RawFields) {
260 if p.IsNil() {
261 panic("invalid SetUnknown on nil Message")
262 }
263 rv := p.Apply(fieldOffset).AsValueOf(unknownFieldsType)
264 *rv.Interface().(*[]byte) = []byte(b)
265 }
266 } else {
267 mi.getUnknown = func(pointer) pref.RawFields {
268 return nil
269 }
270 mi.setUnknown = func(p pointer, _ pref.RawFields) {
271 if p.IsNil() {
272 panic("invalid SetUnknown on nil Message")
273 }
274 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700275 }
276}
277
Joe Tsai4fe96632019-05-22 05:12:36 -0400278func (mi *MessageInfo) makeExtensionFieldsFunc(t reflect.Type) {
Joe Tsai378c1322019-04-25 23:48:08 -0700279 fx, _ := t.FieldByName("XXX_extensions")
280 if fx.Type != extensionFieldsType {
281 fx, _ = t.FieldByName("XXX_InternalExtensions")
Joe Tsaif0c01e42018-11-06 13:05:20 -0800282 }
Joe Tsai378c1322019-04-25 23:48:08 -0700283 if fx.Type == extensionFieldsType {
284 fieldOffset := offsetOf(fx)
285 mi.extensionMap = func(p pointer) *extensionMap {
286 v := p.Apply(fieldOffset).AsValueOf(extensionFieldsType)
287 return (*extensionMap)(v.Interface().(*map[int32]ExtensionField))
288 }
289 } else {
290 mi.extensionMap = func(pointer) *extensionMap {
291 return (*extensionMap)(nil)
292 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700293 }
294}
295
Joe Tsai4fe96632019-05-22 05:12:36 -0400296func (mi *MessageInfo) MessageOf(p interface{}) pref.Message {
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700297 return (*messageReflectWrapper)(mi.dataTypeOf(p))
Joe Tsai08e00302018-11-26 22:32:06 -0800298}
299
Joe Tsai4fe96632019-05-22 05:12:36 -0400300func (mi *MessageInfo) Methods() *piface.Methods {
Damien Neilc37adef2019-04-01 13:49:56 -0700301 mi.init()
302 return &mi.methods
Damien Neil0d3e8cc2019-04-01 13:31:55 -0700303}
304
Joe Tsai4fe96632019-05-22 05:12:36 -0400305func (mi *MessageInfo) dataTypeOf(p interface{}) *messageDataType {
Damien Neil8012b442019-01-18 09:32:24 -0800306 // TODO: Remove this check? This API is primarily used by generated code,
307 // and should not violate this assumption. Leave this check in for now to
308 // provide some sanity checks during development. This can be removed if
309 // it proves to be detrimental to performance.
310 if reflect.TypeOf(p) != mi.GoType {
311 panic(fmt.Sprintf("type mismatch: got %T, want %v", p, mi.GoType))
312 }
Joe Tsai6cf80c42018-12-01 04:57:09 -0800313 return &messageDataType{pointerOfIface(p), mi}
Joe Tsaic6b75612018-09-13 14:24:37 -0700314}
315
316// messageDataType is a tuple of a pointer to the message data and
317// a pointer to the message type.
318//
Joe Tsai4fe96632019-05-22 05:12:36 -0400319// TODO: Unfortunately, we need to close over a pointer and MessageInfo,
Joe Tsaic6b75612018-09-13 14:24:37 -0700320// which incurs an an allocation. This pair is similar to a Go interface,
321// which is essentially a tuple of the same thing. We can make this efficient
322// with reflect.NamedOf (see https://golang.org/issues/16522).
323//
324// With that hypothetical API, we could dynamically create a new named type
Joe Tsai4fe96632019-05-22 05:12:36 -0400325// that has the same underlying type as MessageInfo.GoType, and
326// dynamically create methods that close over MessageInfo.
Joe Tsaic6b75612018-09-13 14:24:37 -0700327// Since the new type would have the same underlying type, we could directly
328// convert between pointers of those types, giving us an efficient way to swap
329// out the method set.
330//
331// Barring the ability to dynamically create named types, the workaround is
332// 1. either to accept the cost of an allocation for this wrapper struct or
333// 2. generate more types and methods, at the expense of binary size increase.
334type messageDataType struct {
335 p pointer
Joe Tsai4fe96632019-05-22 05:12:36 -0400336 mi *MessageInfo
Joe Tsaic6b75612018-09-13 14:24:37 -0700337}
338
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700339type messageReflectWrapper messageDataType
Joe Tsai08e00302018-11-26 22:32:06 -0800340
Joe Tsai0fc49f82019-05-01 12:29:25 -0700341func (m *messageReflectWrapper) Descriptor() pref.MessageDescriptor {
342 return m.mi.PBType.Descriptor()
343}
Joe Tsai0fc49f82019-05-01 12:29:25 -0700344func (m *messageReflectWrapper) New() pref.Message {
345 return m.mi.PBType.New()
346}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700347func (m *messageReflectWrapper) Interface() pref.ProtoMessage {
Joe Tsai08e00302018-11-26 22:32:06 -0800348 if m, ok := m.ProtoUnwrap().(pref.ProtoMessage); ok {
349 return m
350 }
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700351 return (*messageIfaceWrapper)(m)
Joe Tsai08e00302018-11-26 22:32:06 -0800352}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700353func (m *messageReflectWrapper) ProtoUnwrap() interface{} {
Damien Neil8012b442019-01-18 09:32:24 -0800354 return m.p.AsIfaceOf(m.mi.GoType.Elem())
Joe Tsai08e00302018-11-26 22:32:06 -0800355}
Joe Tsai08e00302018-11-26 22:32:06 -0800356
Joe Tsai378c1322019-04-25 23:48:08 -0700357func (m *messageReflectWrapper) Len() (cnt int) {
358 m.mi.init()
359 for _, fi := range m.mi.fields {
360 if fi.has(m.p) {
361 cnt++
362 }
363 }
364 return cnt + m.mi.extensionMap(m.p).Len()
365}
366func (m *messageReflectWrapper) Range(f func(pref.FieldDescriptor, pref.Value) bool) {
367 m.mi.init()
368 for _, fi := range m.mi.fields {
369 if fi.has(m.p) {
370 if !f(fi.fieldDesc, fi.get(m.p)) {
371 return
372 }
373 }
374 }
375 m.mi.extensionMap(m.p).Range(f)
376}
377func (m *messageReflectWrapper) Has(fd pref.FieldDescriptor) bool {
378 if fi, xt := m.checkField(fd); fi != nil {
379 return fi.has(m.p)
380 } else {
381 return m.mi.extensionMap(m.p).Has(xt)
382 }
383}
384func (m *messageReflectWrapper) Clear(fd pref.FieldDescriptor) {
385 if fi, xt := m.checkField(fd); fi != nil {
386 fi.clear(m.p)
387 } else {
388 m.mi.extensionMap(m.p).Clear(xt)
389 }
390}
391func (m *messageReflectWrapper) Get(fd pref.FieldDescriptor) pref.Value {
392 if fi, xt := m.checkField(fd); fi != nil {
393 return fi.get(m.p)
394 } else {
395 return m.mi.extensionMap(m.p).Get(xt)
396 }
397}
398func (m *messageReflectWrapper) Set(fd pref.FieldDescriptor, v pref.Value) {
399 if fi, xt := m.checkField(fd); fi != nil {
400 fi.set(m.p, v)
401 } else {
402 m.mi.extensionMap(m.p).Set(xt, v)
403 }
404}
405func (m *messageReflectWrapper) Mutable(fd pref.FieldDescriptor) pref.Value {
406 if fi, xt := m.checkField(fd); fi != nil {
407 return fi.mutable(m.p)
408 } else {
409 return m.mi.extensionMap(m.p).Mutable(xt)
410 }
411}
412func (m *messageReflectWrapper) NewMessage(fd pref.FieldDescriptor) pref.Message {
413 if fi, xt := m.checkField(fd); fi != nil {
414 return fi.newMessage()
415 } else {
416 return xt.New().Message()
417 }
418}
419func (m *messageReflectWrapper) WhichOneof(od pref.OneofDescriptor) pref.FieldDescriptor {
420 m.mi.init()
421 if oi := m.mi.oneofs[od.Name()]; oi != nil && oi.oneofDesc == od {
422 return od.Fields().ByNumber(oi.which(m.p))
423 }
424 panic("invalid oneof descriptor")
425}
426func (m *messageReflectWrapper) GetUnknown() pref.RawFields {
427 m.mi.init()
428 return m.mi.getUnknown(m.p)
429}
430func (m *messageReflectWrapper) SetUnknown(b pref.RawFields) {
431 m.mi.init()
432 m.mi.setUnknown(m.p, b)
433}
434
435// checkField verifies that the provided field descriptor is valid.
436// Exactly one of the returned values is populated.
437func (m *messageReflectWrapper) checkField(fd pref.FieldDescriptor) (*fieldInfo, pref.ExtensionType) {
438 m.mi.init()
439 if fi := m.mi.fields[fd.Number()]; fi != nil {
440 if fi.fieldDesc != fd {
441 panic("mismatching field descriptor")
442 }
443 return fi, nil
444 }
445 if fd.IsExtension() {
446 if fd.ContainingMessage().FullName() != m.mi.PBType.FullName() {
447 // TODO: Should this be exact containing message descriptor match?
448 panic("mismatching containing message")
449 }
450 if !m.mi.PBType.ExtensionRanges().Has(fd.Number()) {
451 panic("invalid extension field")
452 }
453 return nil, fd.(pref.ExtensionType)
454 }
455 panic("invalid field descriptor")
456}
457
458type extensionMap map[int32]ExtensionField
459
460func (m *extensionMap) Len() int {
461 if m != nil {
462 return len(*m)
463 }
464 return 0
465}
466func (m *extensionMap) Range(f func(pref.FieldDescriptor, pref.Value) bool) {
467 if m != nil {
468 for _, x := range *m {
469 xt := x.GetType()
470 if !f(xt, xt.ValueOf(x.GetValue())) {
471 return
472 }
473 }
474 }
475}
476func (m *extensionMap) Has(xt pref.ExtensionType) (ok bool) {
477 if m != nil {
478 _, ok = (*m)[int32(xt.Number())]
479 }
480 return ok
481}
482func (m *extensionMap) Clear(xt pref.ExtensionType) {
483 delete(*m, int32(xt.Number()))
484}
485func (m *extensionMap) Get(xt pref.ExtensionType) pref.Value {
486 if m != nil {
487 if x, ok := (*m)[int32(xt.Number())]; ok {
488 return xt.ValueOf(x.GetValue())
489 }
490 }
491 if !isComposite(xt) {
492 return defaultValueOf(xt)
493 }
494 return frozenValueOf(xt.New())
495}
496func (m *extensionMap) Set(xt pref.ExtensionType, v pref.Value) {
497 if *m == nil {
498 *m = make(map[int32]ExtensionField)
499 }
500 var x ExtensionField
501 x.SetType(xt)
502 x.SetEagerValue(xt.InterfaceOf(v))
503 (*m)[int32(xt.Number())] = x
504}
505func (m *extensionMap) Mutable(xt pref.ExtensionType) pref.Value {
506 if !isComposite(xt) {
507 panic("invalid Mutable on field with non-composite type")
508 }
509 if x, ok := (*m)[int32(xt.Number())]; ok {
510 return xt.ValueOf(x.GetValue())
511 }
512 v := xt.New()
513 m.Set(xt, v)
514 return v
515}
516
517func isComposite(fd pref.FieldDescriptor) bool {
518 return fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind || fd.IsList() || fd.IsMap()
519}
520
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700521var _ pvalue.Unwrapper = (*messageReflectWrapper)(nil)
522
523type messageIfaceWrapper messageDataType
524
525func (m *messageIfaceWrapper) ProtoReflect() pref.Message {
526 return (*messageReflectWrapper)(m)
527}
Damien Neil0d3e8cc2019-04-01 13:31:55 -0700528func (m *messageIfaceWrapper) XXX_Methods() *piface.Methods {
Damien Neilc37adef2019-04-01 13:49:56 -0700529 // TODO: Consider not recreating this on every call.
530 m.mi.init()
531 return &piface.Methods{
532 Flags: piface.MethodFlagDeterministicMarshal,
533 MarshalAppend: m.marshalAppend,
534 Size: m.size,
535 }
Damien Neil0d3e8cc2019-04-01 13:31:55 -0700536}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700537func (m *messageIfaceWrapper) ProtoUnwrap() interface{} {
538 return m.p.AsIfaceOf(m.mi.GoType.Elem())
539}
Damien Neilc37adef2019-04-01 13:49:56 -0700540func (m *messageIfaceWrapper) marshalAppend(b []byte, _ pref.ProtoMessage, opts piface.MarshalOptions) ([]byte, error) {
541 return m.mi.marshalAppendPointer(b, m.p, newMarshalOptions(opts))
542}
543func (m *messageIfaceWrapper) size(msg pref.ProtoMessage) (size int) {
544 return m.mi.sizePointer(m.p, 0)
545}