blob: a9eb7a96505ecb32b6d1ec400bd33d78e30250b9 [file] [log] [blame]
Joe Tsai82760ce2019-06-20 03:09:57 -07001// 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
5package impl
6
7import (
8 "fmt"
9 "reflect"
10
11 "google.golang.org/protobuf/internal/pragma"
12 pvalue "google.golang.org/protobuf/internal/value"
13 pref "google.golang.org/protobuf/reflect/protoreflect"
14 piface "google.golang.org/protobuf/runtime/protoiface"
15)
16
17// MessageState is a data structure that is nested as the first field in a
18// concrete message. It provides a way to implement the ProtoReflect method
19// in an allocation-free way without needing to have a shadow Go type generated
20// for every message type. This technique only works using unsafe.
21//
22//
23// Example generated code:
24//
25// type M struct {
26// state protoimpl.MessageState
27//
28// Field1 int32
29// Field2 string
30// Field3 *BarMessage
31// ...
32// }
33//
34// func (m *M) ProtoReflect() protoreflect.Message {
35// mi := &file_fizz_buzz_proto_msgInfos[5]
36// if protoimpl.UnsafeEnabled && m != nil {
37// ms := protoimpl.X.MessageStateOf(Pointer(m))
38// if ms.LoadMessageInfo() == nil {
39// ms.StoreMessageInfo(mi)
40// }
41// return ms
42// }
43// return mi.MessageOf(m)
44// }
45//
46// The MessageState type holds a *MessageInfo, which must be atomically set to
47// the message info associated with a given message instance.
48// By unsafely converting a *M into a *MessageState, the MessageState object
49// has access to all the information needed to implement protobuf reflection.
50// It has access to the message info as its first field, and a pointer to the
51// MessageState is identical to a pointer to the concrete message value.
52//
53//
54// Requirements:
55// • The type M must implement protoreflect.ProtoMessage.
56// • The address of m must not be nil.
57// • The address of m and the address of m.state must be equal,
58// even though they are different Go types.
59type MessageState struct {
60 pragma.NoUnkeyedLiterals
61 pragma.DoNotCompare
62 pragma.DoNotCopy
63
64 mi *MessageInfo
65}
66
67type messageState MessageState
68
69var (
70 _ pref.Message = (*messageState)(nil)
71 _ pvalue.Unwrapper = (*messageState)(nil)
72)
73
74// messageDataType is a tuple of a pointer to the message data and
75// a pointer to the message type. It is a generalized way of providing a
76// reflective view over a message instance. The disadvantage of this approach
77// is the need to allocate this tuple of 16B.
78type messageDataType struct {
79 p pointer
80 mi *MessageInfo
81}
82
83type (
84 messageIfaceWrapper messageDataType
85 messageReflectWrapper messageDataType
86)
87
88var (
89 _ pref.Message = (*messageReflectWrapper)(nil)
90 _ pvalue.Unwrapper = (*messageReflectWrapper)(nil)
91 _ pref.ProtoMessage = (*messageIfaceWrapper)(nil)
92 _ pvalue.Unwrapper = (*messageIfaceWrapper)(nil)
93)
94
95// MessageOf returns a reflective view over a message. The input must be a
96// pointer to a named Go struct. If the provided type has a ProtoReflect method,
97// it must be implemented by calling this method.
98func (mi *MessageInfo) MessageOf(m interface{}) pref.Message {
99 // TODO: Switch the input to be an opaque Pointer.
100 if reflect.TypeOf(m) != mi.GoType {
101 panic(fmt.Sprintf("type mismatch: got %T, want %v", m, mi.GoType))
102 }
103 p := pointerOfIface(m)
104 if p.IsNil() {
105 return mi.nilMessage.Init(mi)
106 }
107 return &messageReflectWrapper{p, mi}
108}
109
110func (m *messageReflectWrapper) pointer() pointer { return m.p }
111
112func (m *messageIfaceWrapper) ProtoReflect() pref.Message {
113 return (*messageReflectWrapper)(m)
114}
115func (m *messageIfaceWrapper) XXX_Methods() *piface.Methods {
116 // TODO: Consider not recreating this on every call.
117 m.mi.init()
118 return &piface.Methods{
119 Flags: piface.MethodFlagDeterministicMarshal,
120 MarshalAppend: m.marshalAppend,
121 Unmarshal: m.unmarshal,
122 Size: m.size,
123 IsInitialized: m.isInitialized,
124 }
125}
126func (m *messageIfaceWrapper) ProtoUnwrap() interface{} {
127 return m.p.AsIfaceOf(m.mi.GoType.Elem())
128}
129func (m *messageIfaceWrapper) marshalAppend(b []byte, _ pref.ProtoMessage, opts piface.MarshalOptions) ([]byte, error) {
130 return m.mi.marshalAppendPointer(b, m.p, newMarshalOptions(opts))
131}
132func (m *messageIfaceWrapper) unmarshal(b []byte, _ pref.ProtoMessage, opts piface.UnmarshalOptions) error {
133 _, err := m.mi.unmarshalPointer(b, m.p, 0, newUnmarshalOptions(opts))
134 return err
135}
136func (m *messageIfaceWrapper) size(msg pref.ProtoMessage) (size int) {
137 return m.mi.sizePointer(m.p, 0)
138}
139func (m *messageIfaceWrapper) isInitialized(_ pref.ProtoMessage) error {
140 return m.mi.isInitializedPointer(m.p)
141}
142
143type extensionMap map[int32]ExtensionField
144
145func (m *extensionMap) Range(f func(pref.FieldDescriptor, pref.Value) bool) {
146 if m != nil {
147 for _, x := range *m {
148 xt := x.GetType()
149 if !f(xt, xt.ValueOf(x.GetValue())) {
150 return
151 }
152 }
153 }
154}
155func (m *extensionMap) Has(xt pref.ExtensionType) (ok bool) {
156 if m != nil {
157 _, ok = (*m)[int32(xt.Number())]
158 }
159 return ok
160}
161func (m *extensionMap) Clear(xt pref.ExtensionType) {
162 delete(*m, int32(xt.Number()))
163}
164func (m *extensionMap) Get(xt pref.ExtensionType) pref.Value {
165 if m != nil {
166 if x, ok := (*m)[int32(xt.Number())]; ok {
167 return xt.ValueOf(x.GetValue())
168 }
169 }
170 if !isComposite(xt) {
171 return defaultValueOf(xt)
172 }
173 return frozenValueOf(xt.New())
174}
175func (m *extensionMap) Set(xt pref.ExtensionType, v pref.Value) {
176 if *m == nil {
177 *m = make(map[int32]ExtensionField)
178 }
179 var x ExtensionField
180 x.SetType(xt)
181 x.SetEagerValue(xt.InterfaceOf(v))
182 (*m)[int32(xt.Number())] = x
183}
184func (m *extensionMap) Mutable(xt pref.ExtensionType) pref.Value {
185 if !isComposite(xt) {
186 panic("invalid Mutable on field with non-composite type")
187 }
188 if x, ok := (*m)[int32(xt.Number())]; ok {
189 return xt.ValueOf(x.GetValue())
190 }
191 v := xt.New()
192 m.Set(xt, v)
193 return v
194}
195
196func isComposite(fd pref.FieldDescriptor) bool {
197 return fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind || fd.IsList() || fd.IsMap()
198}
199
200// checkField verifies that the provided field descriptor is valid.
201// Exactly one of the returned values is populated.
202func (mi *MessageInfo) checkField(fd pref.FieldDescriptor) (*fieldInfo, pref.ExtensionType) {
203 if fi := mi.fields[fd.Number()]; fi != nil {
204 if fi.fieldDesc != fd {
205 panic("mismatching field descriptor")
206 }
207 return fi, nil
208 }
209 if fd.IsExtension() {
210 if fd.ContainingMessage().FullName() != mi.PBType.FullName() {
211 // TODO: Should this be exact containing message descriptor match?
212 panic("mismatching containing message")
213 }
214 if !mi.PBType.ExtensionRanges().Has(fd.Number()) {
215 panic("invalid extension field")
216 }
217 return nil, fd.(pref.ExtensionType)
218 }
219 panic("invalid field descriptor")
220}