-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathmessage.go
More file actions
380 lines (333 loc) · 11 KB
/
message.go
File metadata and controls
380 lines (333 loc) · 11 KB
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
// Copyright 2025 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hyperpb
import (
"errors"
"fmt"
"unsafe"
_ "unsafe"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/runtime/protoiface"
"buf.build/go/hyperpb/internal/debug"
"buf.build/go/hyperpb/internal/tdp/dynamic"
"buf.build/go/hyperpb/internal/tdp/empty"
"buf.build/go/hyperpb/internal/tdp/vm"
"buf.build/go/hyperpb/internal/xprotoreflect"
"buf.build/go/hyperpb/internal/xunsafe"
)
var (
_ proto.Message = new(Message)
_ protoreflect.Message = new(Message)
errInvalid = errors.New("hyperpb: invalid message")
//go:linkname hyperpbMessage buf.build/go/hyperpb/internal/tdp/profile.hyperpbMessage
hyperpbMessage = xunsafe.AnyType((*Message)(nil))
)
// Message implements [protoreflect.Message].
type Message struct {
impl dynamic.Message
}
// NewMessage allocates a new [Message] of the given [MessageType].
//
// See [Shared.NewMessage].
func NewMessage(ty *MessageType) *Message {
return new(Shared).NewMessage(ty)
}
// Unmarshal is like [proto.Unmarshal], but permits hyperpb-specific
// tuning options to be set.
//
// Calling this function may be much faster than calling proto.Unmarshal if
// the message is small; proto.Unmarshal includes several nanoseconds of
// overhead that can become noticeable for message in the 16 byte regime.
//
// The returned error may additionally implement a method with the signature
//
// Offset() int
//
// This function will return the approximate offset into data at which the
// error occurred.
func (m *Message) Unmarshal(data []byte, options ...UnmarshalOption) error {
opts := vm.NewOptions()
for _, opt := range options {
if opt.apply != nil {
// Avoid having opt pointlessly escape to the heap.
// Users cannot create their own UnmarshalOptions, so violation
// of memory safety isn't a thing we need to worry about.
opt.apply(xunsafe.NoEscape(&opts))
}
}
return vm.Run(&m.impl, data, opts)
}
// Shared returns state shared by this message and its submessages.
func (m *Message) Shared() *Shared {
return wrapShared(m.impl.Shared)
}
// ProtoReflect implements [proto.Message].
func (m *Message) ProtoReflect() protoreflect.Message {
return m
}
// Descriptor returns message descriptor, which contains only the Protobuf
// type information for the message.
//
// Descriptor implements [protoreflect.Message].
func (m *Message) Descriptor() protoreflect.MessageDescriptor {
return m.impl.Type().Descriptor
}
// Type returns the message type, which encapsulates both Go and Protobuf
// type information. If the Go type information is not needed,
// it is recommended that the message descriptor be used instead.
//
// Type implements [protoreflect.Message]; Always returns *[MessageType].
func (m *Message) Type() protoreflect.MessageType {
return m.HyperType()
}
// HyperType returns the [MessageType] for this value.
func (m *Message) HyperType() *MessageType {
return wrapType(m.impl.Type())
}
// New returns a newly allocated empty message.
//
// New implements [protoreflect.Message].
func (m *Message) New() protoreflect.Message {
return wrapType(m.impl.Type()).New()
}
// Interface returns m.
//
// Interface implements [protoreflect.Message].
func (m *Message) Interface() protoreflect.ProtoMessage {
return m
}
// Range iterates over every populated field in an undefined order,
// calling f for each field descriptor and value encountered.
// Range returns immediately if f returns false.
//
// Range implements [protoreflect.Message].
func (m *Message) Range(yield func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {
m.impl.Range(yield)
}
// Has reports whether a field is populated.
//
// Some fields have the property of nullability where it is possible to
// distinguish between the default value of a field and whether the field
// was explicitly populated with the default value. Singular message fields,
// member fields of a oneof, and proto2 scalar fields are nullable. Such
// fields are populated only if explicitly set.
//
// In other cases (aside from the nullable cases above),
// a proto3 scalar field is populated if it contains a non-zero value, and
// a repeated field is populated if it is non-empty.
//
// Has implements [protoreflect.Message].
func (m *Message) Has(fd protoreflect.FieldDescriptor) bool {
return m.impl.Has(fd)
}
// Clear panics, unless this message has not been unmarshaled yet.
//
// Clear implements [protoreflect.Message].
func (m *Message) Clear(protoreflect.FieldDescriptor) {
if m.Shared().impl.Src == nil {
return
}
panic(debug.Unsupported())
}
// Reset panics, unless this message has not been unmarshaled yet
//
// Implements an interface used to speed up [proto.Reset]. It is not part of
// the [protoreflect.Message] interface.
func (m *Message) Reset() { m.Clear(nil) }
// Initialized returns whether m contains any unset required fields.
//
// Returns an error if any fields are not set.
func (m *Message) Initialized() error {
// NOTE: This method does not implement an interface, but it does need to
// match a protoiface method interface. See requiredShim below.
if !m.IsValid() {
return errInvalid
}
r := m.impl.Type().Required
if r == nil {
// Fast path!
return nil
}
for _, idx := range r {
if idx >= 0 {
// This field is guaranteed to be singular.
f := m.impl.Type().ByIndex(int(idx))
v := f.Get(unsafe.Pointer(m))
if !v.IsValid() {
return fmt.Errorf(
"hyperpb: uninitialized required field: %v",
m.impl.Type().FieldDescriptors[idx],
)
}
if _, empty := v.Interface().(empty.Message); empty {
return fmt.Errorf(
"hyperpb: uninitialized required field: %v",
m.impl.Type().FieldDescriptors[idx],
)
}
continue
}
// This is a message field, which we need to recurse into.
f := m.impl.Type().ByIndex(int(^idx))
switch v := f.Get(unsafe.Pointer(m)).Interface().(type) {
case empty.Message:
continue
case *Message:
if err := v.Initialized(); err != nil {
return err
}
case protoreflect.List:
for i := range v.Len() {
m := xprotoreflect.GetMessage[*Message](v.Get(i))
if err := m.Initialized(); err != nil {
return err
}
}
case protoreflect.Map:
for _, v := range v.Range {
m := xprotoreflect.GetMessage[*Message](v)
if err := m.Initialized(); err != nil {
return err
}
}
}
}
return nil
}
// Get retrieves the value for a field.
//
// For unpopulated scalars, it returns the default value, where
// the default value of a bytes scalar is guaranteed to be a copy.
// For unpopulated composite types, it returns an empty, read-only view
// of the value.
//
// Get implements [protoreflect.Message].
func (m *Message) Get(fd protoreflect.FieldDescriptor) protoreflect.Value {
return m.impl.Get(fd)
}
// Set panics.
//
// Set implements [protoreflect.Message].
func (m *Message) Set(protoreflect.FieldDescriptor, protoreflect.Value) {
panic(debug.Unsupported())
}
// Mutable panics.
//
// Mutable implements [protoreflect.Message].
func (m *Message) Mutable(protoreflect.FieldDescriptor) protoreflect.Value {
panic(debug.Unsupported())
}
// NewField panics.
//
// NewField implements [protoreflect.Message].
func (m *Message) NewField(protoreflect.FieldDescriptor) protoreflect.Value {
panic(debug.Unsupported())
}
// WhichOneof reports which field within the oneof is populated,
// returning nil if none are populated.
// It panics if the oneof descriptor does not belong to this message.
//
// WhichOneof implements [protoreflect.Message].
func (m *Message) WhichOneof(od protoreflect.OneofDescriptor) protoreflect.FieldDescriptor {
if !m.IsValid() {
return nil
}
fd := od.Fields().Get(0)
f := m.impl.Type().ByDescriptor(fd)
if !f.IsValid() {
panic("invalid oneof descriptor " + string(od.FullName()) + " for message " + string(m.Descriptor().FullName()))
}
if f.Offset.Number == 0 {
// Not implemented internally as a oneof.
if !m.Has(fd) {
return nil
}
return fd
}
which := xunsafe.ByteLoad[uint32](m, f.Offset.Bit)
return fd.ContainingMessage().Fields().ByNumber(protoreflect.FieldNumber(which))
}
// GetUnknown retrieves the entire list of unknown fields.
//
// GetUnknown implements [protoreflect.Message].
func (m *Message) GetUnknown() protoreflect.RawFields {
cold := m.impl.Cold()
if cold == nil {
return nil
}
if cold.Unknown.Len() == 1 {
return cold.Unknown.Ptr().Bytes(m.Shared().impl.Src)
}
var out []byte
for _, zc := range cold.Unknown.Raw() {
out = append(out, zc.Bytes(m.Shared().impl.Src)...)
}
return out
}
// SetUnknown panics, unless raw is zero-length, in which case it does nothing.
//
// SetUnknown implements [protoreflect.Message].
func (m *Message) SetUnknown(raw protoreflect.RawFields) {
if len(raw) == 0 {
return
}
panic(debug.Unsupported())
}
// IsValid reports whether the message is valid.
//
// An invalid message is an empty, read-only value.
//
// An invalid message often corresponds to a nil pointer of the concrete
// message type, but the details are implementation dependent.
// Validity is not part of the protobuf data model, and may not
// be preserved in marshaling or other operations.
//
// IsValid implements [protoreflect.Message].
func (m *Message) IsValid() bool {
return m != nil
}
// ProtoMethods returns optional fast-path implementations of various operations.
//
// ProtoMethods implements [protoreflect.Message].
func (m *Message) ProtoMethods() *protoiface.Methods {
return &m.impl.Type().Methods
}
// unmarshalShim implements [protoiface.Methods].Unmarshal.
func unmarshalShim(in protoiface.UnmarshalInput) (out protoiface.UnmarshalOutput, err error) {
// Gencode can pass non-Message types here, but they're all *dynamic.Messages internally.
raw := xunsafe.AnyData(in.Message)
m := xunsafe.Cast[Message](raw)
err = m.Unmarshal(
in.Buf,
WithDiscardUnknown(in.Flags&protoiface.UnmarshalDiscardUnknown != 0),
)
if m.impl.Type().Required == nil {
out.Flags |= protoiface.UnmarshalInitialized
}
return out, err
}
// requiredShim implements [protoiface.Methods].CheckInitialized.
func requiredShim(in protoiface.CheckInitializedInput) (out protoiface.CheckInitializedOutput, err error) {
//nolint:errcheck // This conversion will never fail.
return out, in.Message.(*Message).Initialized()
}
// wrapMessage wraps an internal Message pointer.
func wrapMessage(m *dynamic.Message) *Message {
return xunsafe.Cast[Message](m)
}
//go:linkname protoReflect buf.build/go/hyperpb/internal/tdp/dynamic.hyperpb_ProtoReflect
func protoReflect(m *dynamic.Message) protoreflect.Message {
return wrapMessage(m)
}