1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc. All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 // * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 // * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 // * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 // Author: kenton@google.com (Kenton Varda)
32 // Based on original Protocol Buffers design by
33 // Sanjay Ghemawat, Jeff Dean, and others.
34 //
35 // Defines Message, the abstract interface implemented by non-lite
36 // protocol message objects. Although it's possible to implement this
37 // interface manually, most users will use the protocol compiler to
38 // generate implementations.
39 //
40 // Example usage:
41 //
42 // Say you have a message defined as:
43 //
44 // message Foo {
45 // optional string text = 1;
46 // repeated int32 numbers = 2;
47 // }
48 //
49 // Then, if you used the protocol compiler to generate a class from the above
50 // definition, you could use it like so:
51 //
52 // std::string data; // Will store a serialized version of the message.
53 //
54 // {
55 // // Create a message and serialize it.
56 // Foo foo;
57 // foo.set_text("Hello World!");
58 // foo.add_numbers(1);
59 // foo.add_numbers(5);
60 // foo.add_numbers(42);
61 //
62 // foo.SerializeToString(&data);
63 // }
64 //
65 // {
66 // // Parse the serialized message and check that it contains the
67 // // correct data.
68 // Foo foo;
69 // foo.ParseFromString(data);
70 //
71 // assert(foo.text() == "Hello World!");
72 // assert(foo.numbers_size() == 3);
73 // assert(foo.numbers(0) == 1);
74 // assert(foo.numbers(1) == 5);
75 // assert(foo.numbers(2) == 42);
76 // }
77 //
78 // {
79 // // Same as the last block, but do it dynamically via the Message
80 // // reflection interface.
81 // Message* foo = new Foo;
82 // const Descriptor* descriptor = foo->GetDescriptor();
83 //
84 // // Get the descriptors for the fields we're interested in and verify
85 // // their types.
86 // const FieldDescriptor* text_field = descriptor->FindFieldByName("text");
87 // assert(text_field != nullptr);
88 // assert(text_field->type() == FieldDescriptor::TYPE_STRING);
89 // assert(text_field->label() == FieldDescriptor::LABEL_OPTIONAL);
90 // const FieldDescriptor* numbers_field = descriptor->
91 // FindFieldByName("numbers");
92 // assert(numbers_field != nullptr);
93 // assert(numbers_field->type() == FieldDescriptor::TYPE_INT32);
94 // assert(numbers_field->label() == FieldDescriptor::LABEL_REPEATED);
95 //
96 // // Parse the message.
97 // foo->ParseFromString(data);
98 //
99 // // Use the reflection interface to examine the contents.
100 // const Reflection* reflection = foo->GetReflection();
101 // assert(reflection->GetString(*foo, text_field) == "Hello World!");
102 // assert(reflection->FieldSize(*foo, numbers_field) == 3);
103 // assert(reflection->GetRepeatedInt32(*foo, numbers_field, 0) == 1);
104 // assert(reflection->GetRepeatedInt32(*foo, numbers_field, 1) == 5);
105 // assert(reflection->GetRepeatedInt32(*foo, numbers_field, 2) == 42);
106 //
107 // delete foo;
108 // }
109
110 #ifndef GOOGLE_PROTOBUF_MESSAGE_H__
111 #define GOOGLE_PROTOBUF_MESSAGE_H__
112
113 #include <iosfwd>
114 #include <string>
115 #include <type_traits>
116 #include <vector>
117
118 #include <google/protobuf/stubs/casts.h>
119 #include <google/protobuf/stubs/common.h>
120 #include <google/protobuf/arena.h>
121 #include <google/protobuf/descriptor.h>
122 #include <google/protobuf/generated_message_reflection.h>
123 #include <google/protobuf/message_lite.h>
124 #include <google/protobuf/port.h>
125
126
127 #define GOOGLE_PROTOBUF_HAS_ONEOF
128 #define GOOGLE_PROTOBUF_HAS_ARENAS
129
130 #include <google/protobuf/port_def.inc>
131
132 #ifdef SWIG
133 #error "You cannot SWIG proto headers"
134 #endif
135
136 namespace google {
137 namespace protobuf {
138
139 // Defined in this file.
140 class Message;
141 class Reflection;
142 class MessageFactory;
143
144 // Defined in other files.
145 class AssignDescriptorsHelper;
146 class DynamicMessageFactory;
147 class GeneratedMessageReflectionTestHelper;
148 class MapKey;
149 class MapValueConstRef;
150 class MapValueRef;
151 class MapIterator;
152 class MapReflectionTester;
153
154 namespace internal {
155 struct DescriptorTable;
156 class MapFieldBase;
157 class SwapFieldHelper;
158 }
159 class UnknownFieldSet; // unknown_field_set.h
160 namespace io {
161 class ZeroCopyInputStream; // zero_copy_stream.h
162 class ZeroCopyOutputStream; // zero_copy_stream.h
163 class CodedInputStream; // coded_stream.h
164 class CodedOutputStream; // coded_stream.h
165 } // namespace io
166 namespace python {
167 class MapReflectionFriend; // scalar_map_container.h
168 class MessageReflectionFriend;
169 }
170 namespace expr {
171 class CelMapReflectionFriend; // field_backed_map_impl.cc
172 }
173
174 namespace internal {
175 class MapFieldPrinterHelper; // text_format.cc
176 }
177 namespace util {
178 class MessageDifferencer;
179 }
180
181
182 namespace internal {
183 class ReflectionAccessor; // message.cc
184 class ReflectionOps; // reflection_ops.h
185 class MapKeySorter; // wire_format.cc
186 class WireFormat; // wire_format.h
187 class MapFieldReflectionTest; // map_test.cc
188 } // namespace internal
189
190 template <typename T>
191 class RepeatedField; // repeated_field.h
192
193 template <typename T>
194 class RepeatedPtrField; // repeated_field.h
195
196 // A container to hold message metadata.
197 struct Metadata {
198 const Descriptor* descriptor;
199 const Reflection* reflection;
200 };
201
202 namespace internal {
203 template <class To>
GetPointerAtOffset(Message * message,uint32 offset)204 inline To* GetPointerAtOffset(Message* message, uint32 offset) {
205 return reinterpret_cast<To*>(reinterpret_cast<char*>(message) + offset);
206 }
207
208 template <class To>
GetConstPointerAtOffset(const Message * message,uint32 offset)209 const To* GetConstPointerAtOffset(const Message* message, uint32 offset) {
210 return reinterpret_cast<const To*>(reinterpret_cast<const char*>(message) +
211 offset);
212 }
213
214 template <class To>
GetConstRefAtOffset(const Message & message,uint32 offset)215 const To& GetConstRefAtOffset(const Message& message, uint32 offset) {
216 return *GetConstPointerAtOffset<To>(&message, offset);
217 }
218
219 bool CreateUnknownEnumValues(const FieldDescriptor* field);
220 } // namespace internal
221
222 // Abstract interface for protocol messages.
223 //
224 // See also MessageLite, which contains most every-day operations. Message
225 // adds descriptors and reflection on top of that.
226 //
227 // The methods of this class that are virtual but not pure-virtual have
228 // default implementations based on reflection. Message classes which are
229 // optimized for speed will want to override these with faster implementations,
230 // but classes optimized for code size may be happy with keeping them. See
231 // the optimize_for option in descriptor.proto.
232 //
233 // Users must not derive from this class. Only the protocol compiler and
234 // the internal library are allowed to create subclasses.
235 class PROTOBUF_EXPORT Message : public MessageLite {
236 public:
Message()237 constexpr Message() {}
238
239 // Basic Operations ------------------------------------------------
240
241 // Construct a new instance of the same type. Ownership is passed to the
242 // caller. (This is also defined in MessageLite, but is defined again here
243 // for return-type covariance.)
244 Message* New() const override = 0;
245
246 // Construct a new instance on the arena. Ownership is passed to the caller
247 // if arena is a nullptr. Default implementation allows for API compatibility
248 // during the Arena transition.
New(Arena * arena)249 Message* New(Arena* arena) const override {
250 Message* message = New();
251 if (arena != nullptr) {
252 arena->Own(message);
253 }
254 return message;
255 }
256
257 // Make this message into a copy of the given message. The given message
258 // must have the same descriptor, but need not necessarily be the same class.
259 // By default this is just implemented as "Clear(); MergeFrom(from);".
260 virtual void CopyFrom(const Message& from);
261
262 // Merge the fields from the given message into this message. Singular
263 // fields will be overwritten, if specified in from, except for embedded
264 // messages which will be merged. Repeated fields will be concatenated.
265 // The given message must be of the same type as this message (i.e. the
266 // exact same class).
267 virtual void MergeFrom(const Message& from);
268
269 // Verifies that IsInitialized() returns true. GOOGLE_CHECK-fails otherwise, with
270 // a nice error message.
271 void CheckInitialized() const;
272
273 // Slowly build a list of all required fields that are not set.
274 // This is much, much slower than IsInitialized() as it is implemented
275 // purely via reflection. Generally, you should not call this unless you
276 // have already determined that an error exists by calling IsInitialized().
277 void FindInitializationErrors(std::vector<std::string>* errors) const;
278
279 // Like FindInitializationErrors, but joins all the strings, delimited by
280 // commas, and returns them.
281 std::string InitializationErrorString() const override;
282
283 // Clears all unknown fields from this message and all embedded messages.
284 // Normally, if unknown tag numbers are encountered when parsing a message,
285 // the tag and value are stored in the message's UnknownFieldSet and
286 // then written back out when the message is serialized. This allows servers
287 // which simply route messages to other servers to pass through messages
288 // that have new field definitions which they don't yet know about. However,
289 // this behavior can have security implications. To avoid it, call this
290 // method after parsing.
291 //
292 // See Reflection::GetUnknownFields() for more on unknown fields.
293 virtual void DiscardUnknownFields();
294
295 // Computes (an estimate of) the total number of bytes currently used for
296 // storing the message in memory. The default implementation calls the
297 // Reflection object's SpaceUsed() method.
298 //
299 // SpaceUsed() is noticeably slower than ByteSize(), as it is implemented
300 // using reflection (rather than the generated code implementation for
301 // ByteSize()). Like ByteSize(), its CPU time is linear in the number of
302 // fields defined for the proto.
303 virtual size_t SpaceUsedLong() const;
304
305 PROTOBUF_DEPRECATED_MSG("Please use SpaceUsedLong() instead")
SpaceUsed()306 int SpaceUsed() const { return internal::ToIntSize(SpaceUsedLong()); }
307
308 // Debugging & Testing----------------------------------------------
309
310 // Generates a human readable form of this message, useful for debugging
311 // and other purposes.
312 std::string DebugString() const;
313 // Like DebugString(), but with less whitespace.
314 std::string ShortDebugString() const;
315 // Like DebugString(), but do not escape UTF-8 byte sequences.
316 std::string Utf8DebugString() const;
317 // Convenience function useful in GDB. Prints DebugString() to stdout.
318 void PrintDebugString() const;
319
320 // Reflection-based methods ----------------------------------------
321 // These methods are pure-virtual in MessageLite, but Message provides
322 // reflection-based default implementations.
323
324 std::string GetTypeName() const override;
325 void Clear() override;
326
327 // Returns whether all required fields have been set. Note that required
328 // fields no longer exist starting in proto3.
329 bool IsInitialized() const override;
330
331 void CheckTypeAndMergeFrom(const MessageLite& other) override;
332 // Reflective parser
333 const char* _InternalParse(const char* ptr,
334 internal::ParseContext* ctx) override;
335 size_t ByteSizeLong() const override;
336 uint8* _InternalSerialize(uint8* target,
337 io::EpsCopyOutputStream* stream) const override;
338
339 private:
340 // This is called only by the default implementation of ByteSize(), to
341 // update the cached size. If you override ByteSize(), you do not need
342 // to override this. If you do not override ByteSize(), you MUST override
343 // this; the default implementation will crash.
344 //
345 // The method is private because subclasses should never call it; only
346 // override it. Yes, C++ lets you do that. Crazy, huh?
347 virtual void SetCachedSize(int size) const;
348
349 public:
350 // Introspection ---------------------------------------------------
351
352
353 // Get a non-owning pointer to a Descriptor for this message's type. This
354 // describes what fields the message contains, the types of those fields, etc.
355 // This object remains property of the Message.
GetDescriptor()356 const Descriptor* GetDescriptor() const { return GetMetadata().descriptor; }
357
358 // Get a non-owning pointer to the Reflection interface for this Message,
359 // which can be used to read and modify the fields of the Message dynamically
360 // (in other words, without knowing the message type at compile time). This
361 // object remains property of the Message.
GetReflection()362 const Reflection* GetReflection() const { return GetMetadata().reflection; }
363
364 protected:
365 // Get a struct containing the metadata for the Message, which is used in turn
366 // to implement GetDescriptor() and GetReflection() above.
367 virtual Metadata GetMetadata() const = 0;
368
369 struct ClassData {
370 // Note: The order of arguments (to, then from) is chosen so that the ABI
371 // of this function is the same as the CopyFrom method. That is, the
372 // hidden "this" parameter comes first.
373 void (*copy_to_from)(Message* to, const Message& from_msg);
374 void (*merge_to_from)(Message* to, const Message& from_msg);
375 };
376 // GetClassData() returns a pointer to a ClassData struct which
377 // exists in global memory and is unique to each subclass. This uniqueness
378 // property is used in order to quickly determine whether two messages are
379 // of the same type.
380 // TODO(jorg): change to pure virtual
GetClassData()381 virtual const ClassData* GetClassData() const { return nullptr; }
382
383 // CopyWithSizeCheck calls Clear() and then MergeFrom(), and in debug
384 // builds, checks that calling Clear() on the destination message doesn't
385 // alter the size of the source. It assumes the messages are known to be
386 // of the same type, and thus uses GetClassData().
387 static void CopyWithSizeCheck(Message* to, const Message& from);
388
389 inline explicit Message(Arena* arena, bool is_message_owned = false)
MessageLite(arena,is_message_owned)390 : MessageLite(arena, is_message_owned) {}
391
392
393 protected:
394 static uint64 GetInvariantPerBuild(uint64 salt);
395
396 private:
397 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Message);
398 };
399
400 namespace internal {
401 // Forward-declare interfaces used to implement RepeatedFieldRef.
402 // These are protobuf internals that users shouldn't care about.
403 class RepeatedFieldAccessor;
404 } // namespace internal
405
406 // Forward-declare RepeatedFieldRef templates. The second type parameter is
407 // used for SFINAE tricks. Users should ignore it.
408 template <typename T, typename Enable = void>
409 class RepeatedFieldRef;
410
411 template <typename T, typename Enable = void>
412 class MutableRepeatedFieldRef;
413
414 // This interface contains methods that can be used to dynamically access
415 // and modify the fields of a protocol message. Their semantics are
416 // similar to the accessors the protocol compiler generates.
417 //
418 // To get the Reflection for a given Message, call Message::GetReflection().
419 //
420 // This interface is separate from Message only for efficiency reasons;
421 // the vast majority of implementations of Message will share the same
422 // implementation of Reflection (GeneratedMessageReflection,
423 // defined in generated_message.h), and all Messages of a particular class
424 // should share the same Reflection object (though you should not rely on
425 // the latter fact).
426 //
427 // There are several ways that these methods can be used incorrectly. For
428 // example, any of the following conditions will lead to undefined
429 // results (probably assertion failures):
430 // - The FieldDescriptor is not a field of this message type.
431 // - The method called is not appropriate for the field's type. For
432 // each field type in FieldDescriptor::TYPE_*, there is only one
433 // Get*() method, one Set*() method, and one Add*() method that is
434 // valid for that type. It should be obvious which (except maybe
435 // for TYPE_BYTES, which are represented using strings in C++).
436 // - A Get*() or Set*() method for singular fields is called on a repeated
437 // field.
438 // - GetRepeated*(), SetRepeated*(), or Add*() is called on a non-repeated
439 // field.
440 // - The Message object passed to any method is not of the right type for
441 // this Reflection object (i.e. message.GetReflection() != reflection).
442 //
443 // You might wonder why there is not any abstract representation for a field
444 // of arbitrary type. E.g., why isn't there just a "GetField()" method that
445 // returns "const Field&", where "Field" is some class with accessors like
446 // "GetInt32Value()". The problem is that someone would have to deal with
447 // allocating these Field objects. For generated message classes, having to
448 // allocate space for an additional object to wrap every field would at least
449 // double the message's memory footprint, probably worse. Allocating the
450 // objects on-demand, on the other hand, would be expensive and prone to
451 // memory leaks. So, instead we ended up with this flat interface.
452 class PROTOBUF_EXPORT Reflection final {
453 public:
454 // Get the UnknownFieldSet for the message. This contains fields which
455 // were seen when the Message was parsed but were not recognized according
456 // to the Message's definition.
457 const UnknownFieldSet& GetUnknownFields(const Message& message) const;
458 // Get a mutable pointer to the UnknownFieldSet for the message. This
459 // contains fields which were seen when the Message was parsed but were not
460 // recognized according to the Message's definition.
461 UnknownFieldSet* MutableUnknownFields(Message* message) const;
462
463 // Estimate the amount of memory used by the message object.
464 size_t SpaceUsedLong(const Message& message) const;
465
466 PROTOBUF_DEPRECATED_MSG("Please use SpaceUsedLong() instead")
SpaceUsed(const Message & message)467 int SpaceUsed(const Message& message) const {
468 return internal::ToIntSize(SpaceUsedLong(message));
469 }
470
471 // Check if the given non-repeated field is set.
472 bool HasField(const Message& message, const FieldDescriptor* field) const;
473
474 // Get the number of elements of a repeated field.
475 int FieldSize(const Message& message, const FieldDescriptor* field) const;
476
477 // Clear the value of a field, so that HasField() returns false or
478 // FieldSize() returns zero.
479 void ClearField(Message* message, const FieldDescriptor* field) const;
480
481 // Check if the oneof is set. Returns true if any field in oneof
482 // is set, false otherwise.
483 bool HasOneof(const Message& message,
484 const OneofDescriptor* oneof_descriptor) const;
485
486 void ClearOneof(Message* message,
487 const OneofDescriptor* oneof_descriptor) const;
488
489 // Returns the field descriptor if the oneof is set. nullptr otherwise.
490 const FieldDescriptor* GetOneofFieldDescriptor(
491 const Message& message, const OneofDescriptor* oneof_descriptor) const;
492
493 // Removes the last element of a repeated field.
494 // We don't provide a way to remove any element other than the last
495 // because it invites inefficient use, such as O(n^2) filtering loops
496 // that should have been O(n). If you want to remove an element other
497 // than the last, the best way to do it is to re-arrange the elements
498 // (using Swap()) so that the one you want removed is at the end, then
499 // call RemoveLast().
500 void RemoveLast(Message* message, const FieldDescriptor* field) const;
501 // Removes the last element of a repeated message field, and returns the
502 // pointer to the caller. Caller takes ownership of the returned pointer.
503 PROTOBUF_MUST_USE_RESULT Message* ReleaseLast(
504 Message* message, const FieldDescriptor* field) const;
505
506 // Swap the complete contents of two messages.
507 void Swap(Message* message1, Message* message2) const;
508
509 // Swap fields listed in fields vector of two messages.
510 void SwapFields(Message* message1, Message* message2,
511 const std::vector<const FieldDescriptor*>& fields) const;
512
513 // Swap two elements of a repeated field.
514 void SwapElements(Message* message, const FieldDescriptor* field, int index1,
515 int index2) const;
516
517 // List all fields of the message which are currently set, except for unknown
518 // fields, but including extension known to the parser (i.e. compiled in).
519 // Singular fields will only be listed if HasField(field) would return true
520 // and repeated fields will only be listed if FieldSize(field) would return
521 // non-zero. Fields (both normal fields and extension fields) will be listed
522 // ordered by field number.
523 // Use Reflection::GetUnknownFields() or message.unknown_fields() to also get
524 // access to fields/extensions unknown to the parser.
525 void ListFields(const Message& message,
526 std::vector<const FieldDescriptor*>* output) const;
527
528 // Singular field getters ------------------------------------------
529 // These get the value of a non-repeated field. They return the default
530 // value for fields that aren't set.
531
532 int32 GetInt32(const Message& message, const FieldDescriptor* field) const;
533 int64 GetInt64(const Message& message, const FieldDescriptor* field) const;
534 uint32 GetUInt32(const Message& message, const FieldDescriptor* field) const;
535 uint64 GetUInt64(const Message& message, const FieldDescriptor* field) const;
536 float GetFloat(const Message& message, const FieldDescriptor* field) const;
537 double GetDouble(const Message& message, const FieldDescriptor* field) const;
538 bool GetBool(const Message& message, const FieldDescriptor* field) const;
539 std::string GetString(const Message& message,
540 const FieldDescriptor* field) const;
541 const EnumValueDescriptor* GetEnum(const Message& message,
542 const FieldDescriptor* field) const;
543
544 // GetEnumValue() returns an enum field's value as an integer rather than
545 // an EnumValueDescriptor*. If the integer value does not correspond to a
546 // known value descriptor, a new value descriptor is created. (Such a value
547 // will only be present when the new unknown-enum-value semantics are enabled
548 // for a message.)
549 int GetEnumValue(const Message& message, const FieldDescriptor* field) const;
550
551 // See MutableMessage() for the meaning of the "factory" parameter.
552 const Message& GetMessage(const Message& message,
553 const FieldDescriptor* field,
554 MessageFactory* factory = nullptr) const;
555
556 // Get a string value without copying, if possible.
557 //
558 // GetString() necessarily returns a copy of the string. This can be
559 // inefficient when the std::string is already stored in a std::string object
560 // in the underlying message. GetStringReference() will return a reference to
561 // the underlying std::string in this case. Otherwise, it will copy the
562 // string into *scratch and return that.
563 //
564 // Note: It is perfectly reasonable and useful to write code like:
565 // str = reflection->GetStringReference(message, field, &str);
566 // This line would ensure that only one copy of the string is made
567 // regardless of the field's underlying representation. When initializing
568 // a newly-constructed string, though, it's just as fast and more
569 // readable to use code like:
570 // std::string str = reflection->GetString(message, field);
571 const std::string& GetStringReference(const Message& message,
572 const FieldDescriptor* field,
573 std::string* scratch) const;
574
575
576 // Singular field mutators -----------------------------------------
577 // These mutate the value of a non-repeated field.
578
579 void SetInt32(Message* message, const FieldDescriptor* field,
580 int32 value) const;
581 void SetInt64(Message* message, const FieldDescriptor* field,
582 int64 value) const;
583 void SetUInt32(Message* message, const FieldDescriptor* field,
584 uint32 value) const;
585 void SetUInt64(Message* message, const FieldDescriptor* field,
586 uint64 value) const;
587 void SetFloat(Message* message, const FieldDescriptor* field,
588 float value) const;
589 void SetDouble(Message* message, const FieldDescriptor* field,
590 double value) const;
591 void SetBool(Message* message, const FieldDescriptor* field,
592 bool value) const;
593 void SetString(Message* message, const FieldDescriptor* field,
594 std::string value) const;
595 void SetEnum(Message* message, const FieldDescriptor* field,
596 const EnumValueDescriptor* value) const;
597 // Set an enum field's value with an integer rather than EnumValueDescriptor.
598 // For proto3 this is just setting the enum field to the value specified, for
599 // proto2 it's more complicated. If value is a known enum value the field is
600 // set as usual. If the value is unknown then it is added to the unknown field
601 // set. Note this matches the behavior of parsing unknown enum values.
602 // If multiple calls with unknown values happen than they are all added to the
603 // unknown field set in order of the calls.
604 void SetEnumValue(Message* message, const FieldDescriptor* field,
605 int value) const;
606
607 // Get a mutable pointer to a field with a message type. If a MessageFactory
608 // is provided, it will be used to construct instances of the sub-message;
609 // otherwise, the default factory is used. If the field is an extension that
610 // does not live in the same pool as the containing message's descriptor (e.g.
611 // it lives in an overlay pool), then a MessageFactory must be provided.
612 // If you have no idea what that meant, then you probably don't need to worry
613 // about it (don't provide a MessageFactory). WARNING: If the
614 // FieldDescriptor is for a compiled-in extension, then
615 // factory->GetPrototype(field->message_type()) MUST return an instance of
616 // the compiled-in class for this type, NOT DynamicMessage.
617 Message* MutableMessage(Message* message, const FieldDescriptor* field,
618 MessageFactory* factory = nullptr) const;
619
620 // Replaces the message specified by 'field' with the already-allocated object
621 // sub_message, passing ownership to the message. If the field contained a
622 // message, that message is deleted. If sub_message is nullptr, the field is
623 // cleared.
624 void SetAllocatedMessage(Message* message, Message* sub_message,
625 const FieldDescriptor* field) const;
626
627 // Similar to `SetAllocatedMessage`, but omits all internal safety and
628 // ownership checks. This method should only be used when the objects are on
629 // the same arena or paired with a call to `UnsafeArenaReleaseMessage`.
630 void UnsafeArenaSetAllocatedMessage(Message* message, Message* sub_message,
631 const FieldDescriptor* field) const;
632
633 // Releases the message specified by 'field' and returns the pointer,
634 // ReleaseMessage() will return the message the message object if it exists.
635 // Otherwise, it may or may not return nullptr. In any case, if the return
636 // value is non-null, the caller takes ownership of the pointer.
637 // If the field existed (HasField() is true), then the returned pointer will
638 // be the same as the pointer returned by MutableMessage().
639 // This function has the same effect as ClearField().
640 PROTOBUF_MUST_USE_RESULT Message* ReleaseMessage(
641 Message* message, const FieldDescriptor* field,
642 MessageFactory* factory = nullptr) const;
643
644 // Similar to `ReleaseMessage`, but omits all internal safety and ownership
645 // checks. This method should only be used when the objects are on the same
646 // arena or paired with a call to `UnsafeArenaSetAllocatedMessage`.
647 Message* UnsafeArenaReleaseMessage(Message* message,
648 const FieldDescriptor* field,
649 MessageFactory* factory = nullptr) const;
650
651
652 // Repeated field getters ------------------------------------------
653 // These get the value of one element of a repeated field.
654
655 int32 GetRepeatedInt32(const Message& message, const FieldDescriptor* field,
656 int index) const;
657 int64 GetRepeatedInt64(const Message& message, const FieldDescriptor* field,
658 int index) const;
659 uint32 GetRepeatedUInt32(const Message& message, const FieldDescriptor* field,
660 int index) const;
661 uint64 GetRepeatedUInt64(const Message& message, const FieldDescriptor* field,
662 int index) const;
663 float GetRepeatedFloat(const Message& message, const FieldDescriptor* field,
664 int index) const;
665 double GetRepeatedDouble(const Message& message, const FieldDescriptor* field,
666 int index) const;
667 bool GetRepeatedBool(const Message& message, const FieldDescriptor* field,
668 int index) const;
669 std::string GetRepeatedString(const Message& message,
670 const FieldDescriptor* field, int index) const;
671 const EnumValueDescriptor* GetRepeatedEnum(const Message& message,
672 const FieldDescriptor* field,
673 int index) const;
674 // GetRepeatedEnumValue() returns an enum field's value as an integer rather
675 // than an EnumValueDescriptor*. If the integer value does not correspond to a
676 // known value descriptor, a new value descriptor is created. (Such a value
677 // will only be present when the new unknown-enum-value semantics are enabled
678 // for a message.)
679 int GetRepeatedEnumValue(const Message& message, const FieldDescriptor* field,
680 int index) const;
681 const Message& GetRepeatedMessage(const Message& message,
682 const FieldDescriptor* field,
683 int index) const;
684
685 // See GetStringReference(), above.
686 const std::string& GetRepeatedStringReference(const Message& message,
687 const FieldDescriptor* field,
688 int index,
689 std::string* scratch) const;
690
691
692 // Repeated field mutators -----------------------------------------
693 // These mutate the value of one element of a repeated field.
694
695 void SetRepeatedInt32(Message* message, const FieldDescriptor* field,
696 int index, int32 value) const;
697 void SetRepeatedInt64(Message* message, const FieldDescriptor* field,
698 int index, int64 value) const;
699 void SetRepeatedUInt32(Message* message, const FieldDescriptor* field,
700 int index, uint32 value) const;
701 void SetRepeatedUInt64(Message* message, const FieldDescriptor* field,
702 int index, uint64 value) const;
703 void SetRepeatedFloat(Message* message, const FieldDescriptor* field,
704 int index, float value) const;
705 void SetRepeatedDouble(Message* message, const FieldDescriptor* field,
706 int index, double value) const;
707 void SetRepeatedBool(Message* message, const FieldDescriptor* field,
708 int index, bool value) const;
709 void SetRepeatedString(Message* message, const FieldDescriptor* field,
710 int index, std::string value) const;
711 void SetRepeatedEnum(Message* message, const FieldDescriptor* field,
712 int index, const EnumValueDescriptor* value) const;
713 // Set an enum field's value with an integer rather than EnumValueDescriptor.
714 // For proto3 this is just setting the enum field to the value specified, for
715 // proto2 it's more complicated. If value is a known enum value the field is
716 // set as usual. If the value is unknown then it is added to the unknown field
717 // set. Note this matches the behavior of parsing unknown enum values.
718 // If multiple calls with unknown values happen than they are all added to the
719 // unknown field set in order of the calls.
720 void SetRepeatedEnumValue(Message* message, const FieldDescriptor* field,
721 int index, int value) const;
722 // Get a mutable pointer to an element of a repeated field with a message
723 // type.
724 Message* MutableRepeatedMessage(Message* message,
725 const FieldDescriptor* field,
726 int index) const;
727
728
729 // Repeated field adders -------------------------------------------
730 // These add an element to a repeated field.
731
732 void AddInt32(Message* message, const FieldDescriptor* field,
733 int32 value) const;
734 void AddInt64(Message* message, const FieldDescriptor* field,
735 int64 value) const;
736 void AddUInt32(Message* message, const FieldDescriptor* field,
737 uint32 value) const;
738 void AddUInt64(Message* message, const FieldDescriptor* field,
739 uint64 value) const;
740 void AddFloat(Message* message, const FieldDescriptor* field,
741 float value) const;
742 void AddDouble(Message* message, const FieldDescriptor* field,
743 double value) const;
744 void AddBool(Message* message, const FieldDescriptor* field,
745 bool value) const;
746 void AddString(Message* message, const FieldDescriptor* field,
747 std::string value) const;
748 void AddEnum(Message* message, const FieldDescriptor* field,
749 const EnumValueDescriptor* value) const;
750 // Add an integer value to a repeated enum field rather than
751 // EnumValueDescriptor. For proto3 this is just setting the enum field to the
752 // value specified, for proto2 it's more complicated. If value is a known enum
753 // value the field is set as usual. If the value is unknown then it is added
754 // to the unknown field set. Note this matches the behavior of parsing unknown
755 // enum values. If multiple calls with unknown values happen than they are all
756 // added to the unknown field set in order of the calls.
757 void AddEnumValue(Message* message, const FieldDescriptor* field,
758 int value) const;
759 // See MutableMessage() for comments on the "factory" parameter.
760 Message* AddMessage(Message* message, const FieldDescriptor* field,
761 MessageFactory* factory = nullptr) const;
762
763 // Appends an already-allocated object 'new_entry' to the repeated field
764 // specified by 'field' passing ownership to the message.
765 void AddAllocatedMessage(Message* message, const FieldDescriptor* field,
766 Message* new_entry) const;
767
768
769 // Get a RepeatedFieldRef object that can be used to read the underlying
770 // repeated field. The type parameter T must be set according to the
771 // field's cpp type. The following table shows the mapping from cpp type
772 // to acceptable T.
773 //
774 // field->cpp_type() T
775 // CPPTYPE_INT32 int32
776 // CPPTYPE_UINT32 uint32
777 // CPPTYPE_INT64 int64
778 // CPPTYPE_UINT64 uint64
779 // CPPTYPE_DOUBLE double
780 // CPPTYPE_FLOAT float
781 // CPPTYPE_BOOL bool
782 // CPPTYPE_ENUM generated enum type or int32
783 // CPPTYPE_STRING std::string
784 // CPPTYPE_MESSAGE generated message type or google::protobuf::Message
785 //
786 // A RepeatedFieldRef object can be copied and the resulted object will point
787 // to the same repeated field in the same message. The object can be used as
788 // long as the message is not destroyed.
789 //
790 // Note that to use this method users need to include the header file
791 // "reflection.h" (which defines the RepeatedFieldRef class templates).
792 template <typename T>
793 RepeatedFieldRef<T> GetRepeatedFieldRef(const Message& message,
794 const FieldDescriptor* field) const;
795
796 // Like GetRepeatedFieldRef() but return an object that can also be used
797 // manipulate the underlying repeated field.
798 template <typename T>
799 MutableRepeatedFieldRef<T> GetMutableRepeatedFieldRef(
800 Message* message, const FieldDescriptor* field) const;
801
802 // DEPRECATED. Please use Get(Mutable)RepeatedFieldRef() for repeated field
803 // access. The following repeated field accessors will be removed in the
804 // future.
805 //
806 // Repeated field accessors -------------------------------------------------
807 // The methods above, e.g. GetRepeatedInt32(msg, fd, index), provide singular
808 // access to the data in a RepeatedField. The methods below provide aggregate
809 // access by exposing the RepeatedField object itself with the Message.
810 // Applying these templates to inappropriate types will lead to an undefined
811 // reference at link time (e.g. GetRepeatedField<***double>), or possibly a
812 // template matching error at compile time (e.g. GetRepeatedPtrField<File>).
813 //
814 // Usage example: my_doubs = refl->GetRepeatedField<double>(msg, fd);
815
816 // DEPRECATED. Please use GetRepeatedFieldRef().
817 //
818 // for T = Cord and all protobuf scalar types except enums.
819 template <typename T>
820 PROTOBUF_DEPRECATED_MSG("Please use GetRepeatedFieldRef() instead")
GetRepeatedField(const Message & msg,const FieldDescriptor * d)821 const RepeatedField<T>& GetRepeatedField(const Message& msg,
822 const FieldDescriptor* d) const {
823 return GetRepeatedFieldInternal<T>(msg, d);
824 }
825
826 // DEPRECATED. Please use GetMutableRepeatedFieldRef().
827 //
828 // for T = Cord and all protobuf scalar types except enums.
829 template <typename T>
830 PROTOBUF_DEPRECATED_MSG("Please use GetMutableRepeatedFieldRef() instead")
MutableRepeatedField(Message * msg,const FieldDescriptor * d)831 RepeatedField<T>* MutableRepeatedField(Message* msg,
832 const FieldDescriptor* d) const {
833 return MutableRepeatedFieldInternal<T>(msg, d);
834 }
835
836 // DEPRECATED. Please use GetRepeatedFieldRef().
837 //
838 // for T = std::string, google::protobuf::internal::StringPieceField
839 // google::protobuf::Message & descendants.
840 template <typename T>
841 PROTOBUF_DEPRECATED_MSG("Please use GetRepeatedFieldRef() instead")
GetRepeatedPtrField(const Message & msg,const FieldDescriptor * d)842 const RepeatedPtrField<T>& GetRepeatedPtrField(
843 const Message& msg, const FieldDescriptor* d) const {
844 return GetRepeatedPtrFieldInternal<T>(msg, d);
845 }
846
847 // DEPRECATED. Please use GetMutableRepeatedFieldRef().
848 //
849 // for T = std::string, google::protobuf::internal::StringPieceField
850 // google::protobuf::Message & descendants.
851 template <typename T>
852 PROTOBUF_DEPRECATED_MSG("Please use GetMutableRepeatedFieldRef() instead")
MutableRepeatedPtrField(Message * msg,const FieldDescriptor * d)853 RepeatedPtrField<T>* MutableRepeatedPtrField(Message* msg,
854 const FieldDescriptor* d) const {
855 return MutableRepeatedPtrFieldInternal<T>(msg, d);
856 }
857
858 // Extensions ----------------------------------------------------------------
859
860 // Try to find an extension of this message type by fully-qualified field
861 // name. Returns nullptr if no extension is known for this name or number.
862 const FieldDescriptor* FindKnownExtensionByName(
863 const std::string& name) const;
864
865 // Try to find an extension of this message type by field number.
866 // Returns nullptr if no extension is known for this name or number.
867 const FieldDescriptor* FindKnownExtensionByNumber(int number) const;
868
869 // Feature Flags -------------------------------------------------------------
870
871 // Does this message support storing arbitrary integer values in enum fields?
872 // If |true|, GetEnumValue/SetEnumValue and associated repeated-field versions
873 // take arbitrary integer values, and the legacy GetEnum() getter will
874 // dynamically create an EnumValueDescriptor for any integer value without
875 // one. If |false|, setting an unknown enum value via the integer-based
876 // setters results in undefined behavior (in practice, GOOGLE_DCHECK-fails).
877 //
878 // Generic code that uses reflection to handle messages with enum fields
879 // should check this flag before using the integer-based setter, and either
880 // downgrade to a compatible value or use the UnknownFieldSet if not. For
881 // example:
882 //
883 // int new_value = GetValueFromApplicationLogic();
884 // if (reflection->SupportsUnknownEnumValues()) {
885 // reflection->SetEnumValue(message, field, new_value);
886 // } else {
887 // if (field_descriptor->enum_type()->
888 // FindValueByNumber(new_value) != nullptr) {
889 // reflection->SetEnumValue(message, field, new_value);
890 // } else if (emit_unknown_enum_values) {
891 // reflection->MutableUnknownFields(message)->AddVarint(
892 // field->number(), new_value);
893 // } else {
894 // // convert value to a compatible/default value.
895 // new_value = CompatibleDowngrade(new_value);
896 // reflection->SetEnumValue(message, field, new_value);
897 // }
898 // }
899 bool SupportsUnknownEnumValues() const;
900
901 // Returns the MessageFactory associated with this message. This can be
902 // useful for determining if a message is a generated message or not, for
903 // example:
904 // if (message->GetReflection()->GetMessageFactory() ==
905 // google::protobuf::MessageFactory::generated_factory()) {
906 // // This is a generated message.
907 // }
908 // It can also be used to create more messages of this type, though
909 // Message::New() is an easier way to accomplish this.
910 MessageFactory* GetMessageFactory() const;
911
912 private:
913 template <typename T>
914 const RepeatedField<T>& GetRepeatedFieldInternal(
915 const Message& message, const FieldDescriptor* field) const;
916 template <typename T>
917 RepeatedField<T>* MutableRepeatedFieldInternal(
918 Message* message, const FieldDescriptor* field) const;
919 template <typename T>
920 const RepeatedPtrField<T>& GetRepeatedPtrFieldInternal(
921 const Message& message, const FieldDescriptor* field) const;
922 template <typename T>
923 RepeatedPtrField<T>* MutableRepeatedPtrFieldInternal(
924 Message* message, const FieldDescriptor* field) const;
925 // Obtain a pointer to a Repeated Field Structure and do some type checking:
926 // on field->cpp_type(),
927 // on field->field_option().ctype() (if ctype >= 0)
928 // of field->message_type() (if message_type != nullptr).
929 // We use 2 routine rather than 4 (const vs mutable) x (scalar vs pointer).
930 void* MutableRawRepeatedField(Message* message, const FieldDescriptor* field,
931 FieldDescriptor::CppType, int ctype,
932 const Descriptor* message_type) const;
933
934 const void* GetRawRepeatedField(const Message& message,
935 const FieldDescriptor* field,
936 FieldDescriptor::CppType cpptype, int ctype,
937 const Descriptor* message_type) const;
938
939 // The following methods are used to implement (Mutable)RepeatedFieldRef.
940 // A Ref object will store a raw pointer to the repeated field data (obtained
941 // from RepeatedFieldData()) and a pointer to a Accessor (obtained from
942 // RepeatedFieldAccessor) which will be used to access the raw data.
943
944 // Returns a raw pointer to the repeated field
945 //
946 // "cpp_type" and "message_type" are deduced from the type parameter T passed
947 // to Get(Mutable)RepeatedFieldRef. If T is a generated message type,
948 // "message_type" should be set to its descriptor. Otherwise "message_type"
949 // should be set to nullptr. Implementations of this method should check
950 // whether "cpp_type"/"message_type" is consistent with the actual type of the
951 // field. We use 1 routine rather than 2 (const vs mutable) because it is
952 // protected and it doesn't change the message.
953 void* RepeatedFieldData(Message* message, const FieldDescriptor* field,
954 FieldDescriptor::CppType cpp_type,
955 const Descriptor* message_type) const;
956
957 // The returned pointer should point to a singleton instance which implements
958 // the RepeatedFieldAccessor interface.
959 const internal::RepeatedFieldAccessor* RepeatedFieldAccessor(
960 const FieldDescriptor* field) const;
961
962 // Lists all fields of the message which are currently set, except for unknown
963 // fields and stripped fields. See ListFields for details.
964 void ListFieldsOmitStripped(
965 const Message& message,
966 std::vector<const FieldDescriptor*>* output) const;
967
IsMessageStripped(const Descriptor * descriptor)968 bool IsMessageStripped(const Descriptor* descriptor) const {
969 return schema_.IsMessageStripped(descriptor);
970 }
971
972 friend class TextFormat;
973
974 void ListFieldsMayFailOnStripped(
975 const Message& message, bool should_fail,
976 std::vector<const FieldDescriptor*>* output) const;
977
978 // Returns true if the message field is backed by a LazyField.
979 //
980 // A message field may be backed by a LazyField without the user annotation
981 // ([lazy = true]). While the user-annotated LazyField is lazily verified on
982 // first touch (i.e. failure on access rather than parsing if the LazyField is
983 // not initialized), the inferred LazyField is eagerly verified to avoid lazy
984 // parsing error at the cost of lower efficiency. When reflecting a message
985 // field, use this API instead of checking field->options().lazy().
IsLazyField(const FieldDescriptor * field)986 bool IsLazyField(const FieldDescriptor* field) const {
987 return IsLazilyVerifiedLazyField(field) ||
988 IsEagerlyVerifiedLazyField(field);
989 }
990
991 bool IsLazilyVerifiedLazyField(const FieldDescriptor* field) const;
992 bool IsEagerlyVerifiedLazyField(const FieldDescriptor* field) const;
993
994 friend class FastReflectionMessageMutator;
995
996 const Descriptor* const descriptor_;
997 const internal::ReflectionSchema schema_;
998 const DescriptorPool* const descriptor_pool_;
999 MessageFactory* const message_factory_;
1000
1001 // Last non weak field index. This is an optimization when most weak fields
1002 // are at the end of the containing message. If a message proto doesn't
1003 // contain weak fields, then this field equals descriptor_->field_count().
1004 int last_non_weak_field_index_;
1005
1006 template <typename T, typename Enable>
1007 friend class RepeatedFieldRef;
1008 template <typename T, typename Enable>
1009 friend class MutableRepeatedFieldRef;
1010 friend class ::PROTOBUF_NAMESPACE_ID::MessageLayoutInspector;
1011 friend class ::PROTOBUF_NAMESPACE_ID::AssignDescriptorsHelper;
1012 friend class DynamicMessageFactory;
1013 friend class GeneratedMessageReflectionTestHelper;
1014 friend class python::MapReflectionFriend;
1015 friend class python::MessageReflectionFriend;
1016 friend class util::MessageDifferencer;
1017 #define GOOGLE_PROTOBUF_HAS_CEL_MAP_REFLECTION_FRIEND
1018 friend class expr::CelMapReflectionFriend;
1019 friend class internal::MapFieldReflectionTest;
1020 friend class internal::MapKeySorter;
1021 friend class internal::WireFormat;
1022 friend class internal::ReflectionOps;
1023 friend class internal::SwapFieldHelper;
1024 // Needed for implementing text format for map.
1025 friend class internal::MapFieldPrinterHelper;
1026
1027 Reflection(const Descriptor* descriptor,
1028 const internal::ReflectionSchema& schema,
1029 const DescriptorPool* pool, MessageFactory* factory);
1030
1031 // Special version for specialized implementations of string. We can't
1032 // call MutableRawRepeatedField directly here because we don't have access to
1033 // FieldOptions::* which are defined in descriptor.pb.h. Including that
1034 // file here is not possible because it would cause a circular include cycle.
1035 // We use 1 routine rather than 2 (const vs mutable) because it is private
1036 // and mutable a repeated string field doesn't change the message.
1037 void* MutableRawRepeatedString(Message* message, const FieldDescriptor* field,
1038 bool is_string) const;
1039
1040 friend class MapReflectionTester;
1041 // Returns true if key is in map. Returns false if key is not in map field.
1042 bool ContainsMapKey(const Message& message, const FieldDescriptor* field,
1043 const MapKey& key) const;
1044
1045 // If key is in map field: Saves the value pointer to val and returns
1046 // false. If key in not in map field: Insert the key into map, saves
1047 // value pointer to val and returns true. Users are able to modify the
1048 // map value by MapValueRef.
1049 bool InsertOrLookupMapValue(Message* message, const FieldDescriptor* field,
1050 const MapKey& key, MapValueRef* val) const;
1051
1052 // If key is in map field: Saves the value pointer to val and returns true.
1053 // Returns false if key is not in map field. Users are NOT able to modify
1054 // the value by MapValueConstRef.
1055 bool LookupMapValue(const Message& message, const FieldDescriptor* field,
1056 const MapKey& key, MapValueConstRef* val) const;
1057 bool LookupMapValue(const Message&, const FieldDescriptor*, const MapKey&,
1058 MapValueRef*) const = delete;
1059
1060 // Delete and returns true if key is in the map field. Returns false
1061 // otherwise.
1062 bool DeleteMapValue(Message* message, const FieldDescriptor* field,
1063 const MapKey& key) const;
1064
1065 // Returns a MapIterator referring to the first element in the map field.
1066 // If the map field is empty, this function returns the same as
1067 // reflection::MapEnd. Mutation to the field may invalidate the iterator.
1068 MapIterator MapBegin(Message* message, const FieldDescriptor* field) const;
1069
1070 // Returns a MapIterator referring to the theoretical element that would
1071 // follow the last element in the map field. It does not point to any
1072 // real element. Mutation to the field may invalidate the iterator.
1073 MapIterator MapEnd(Message* message, const FieldDescriptor* field) const;
1074
1075 // Get the number of <key, value> pair of a map field. The result may be
1076 // different from FieldSize which can have duplicate keys.
1077 int MapSize(const Message& message, const FieldDescriptor* field) const;
1078
1079 // Help method for MapIterator.
1080 friend class MapIterator;
1081 friend class WireFormatForMapFieldTest;
1082 internal::MapFieldBase* MutableMapData(Message* message,
1083 const FieldDescriptor* field) const;
1084
1085 const internal::MapFieldBase* GetMapData(const Message& message,
1086 const FieldDescriptor* field) const;
1087
1088 template <class T>
1089 const T& GetRawNonOneof(const Message& message,
1090 const FieldDescriptor* field) const;
1091 template <class T>
1092 T* MutableRawNonOneof(Message* message, const FieldDescriptor* field) const;
1093
1094 template <typename Type>
1095 const Type& GetRaw(const Message& message,
1096 const FieldDescriptor* field) const;
1097 template <typename Type>
1098 inline Type* MutableRaw(Message* message, const FieldDescriptor* field) const;
1099 template <typename Type>
1100 const Type& DefaultRaw(const FieldDescriptor* field) const;
1101
1102 const Message* GetDefaultMessageInstance(const FieldDescriptor* field) const;
1103
1104 inline const uint32* GetHasBits(const Message& message) const;
1105 inline uint32* MutableHasBits(Message* message) const;
1106 inline uint32 GetOneofCase(const Message& message,
1107 const OneofDescriptor* oneof_descriptor) const;
1108 inline uint32* MutableOneofCase(
1109 Message* message, const OneofDescriptor* oneof_descriptor) const;
HasExtensionSet(const Message &)1110 inline bool HasExtensionSet(const Message& /* message */) const {
1111 return schema_.HasExtensionSet();
1112 }
1113 const internal::ExtensionSet& GetExtensionSet(const Message& message) const;
1114 internal::ExtensionSet* MutableExtensionSet(Message* message) const;
1115
1116 inline const internal::InternalMetadata& GetInternalMetadata(
1117 const Message& message) const;
1118
1119 internal::InternalMetadata* MutableInternalMetadata(Message* message) const;
1120
1121 inline bool HasBit(const Message& message,
1122 const FieldDescriptor* field) const;
1123 inline void SetBit(Message* message, const FieldDescriptor* field) const;
1124 inline void ClearBit(Message* message, const FieldDescriptor* field) const;
1125 inline void SwapBit(Message* message1, Message* message2,
1126 const FieldDescriptor* field) const;
1127
1128 // Shallow-swap fields listed in fields vector of two messages. It is the
1129 // caller's responsibility to make sure shallow swap is safe.
1130 void UnsafeShallowSwapFields(
1131 Message* message1, Message* message2,
1132 const std::vector<const FieldDescriptor*>& fields) const;
1133
1134 // This function only swaps the field. Should swap corresponding has_bit
1135 // before or after using this function.
1136 void SwapField(Message* message1, Message* message2,
1137 const FieldDescriptor* field) const;
1138
1139 // Unsafe but shallow version of SwapField.
1140 void UnsafeShallowSwapField(Message* message1, Message* message2,
1141 const FieldDescriptor* field) const;
1142
1143 template <bool unsafe_shallow_swap>
1144 void SwapFieldsImpl(Message* message1, Message* message2,
1145 const std::vector<const FieldDescriptor*>& fields) const;
1146
1147 void SwapOneofField(Message* message1, Message* message2,
1148 const OneofDescriptor* oneof_descriptor) const;
1149
1150 // Unsafe but shallow version of SwapOneofField.
1151 void UnsafeShallowSwapOneofField(
1152 Message* message1, Message* message2,
1153 const OneofDescriptor* oneof_descriptor) const;
1154
1155 inline bool HasOneofField(const Message& message,
1156 const FieldDescriptor* field) const;
1157 inline void SetOneofCase(Message* message,
1158 const FieldDescriptor* field) const;
1159 inline void ClearOneofField(Message* message,
1160 const FieldDescriptor* field) const;
1161
1162 template <typename Type>
1163 inline const Type& GetField(const Message& message,
1164 const FieldDescriptor* field) const;
1165 template <typename Type>
1166 inline void SetField(Message* message, const FieldDescriptor* field,
1167 const Type& value) const;
1168 template <typename Type>
1169 inline Type* MutableField(Message* message,
1170 const FieldDescriptor* field) const;
1171 template <typename Type>
1172 inline const Type& GetRepeatedField(const Message& message,
1173 const FieldDescriptor* field,
1174 int index) const;
1175 template <typename Type>
1176 inline const Type& GetRepeatedPtrField(const Message& message,
1177 const FieldDescriptor* field,
1178 int index) const;
1179 template <typename Type>
1180 inline void SetRepeatedField(Message* message, const FieldDescriptor* field,
1181 int index, Type value) const;
1182 template <typename Type>
1183 inline Type* MutableRepeatedField(Message* message,
1184 const FieldDescriptor* field,
1185 int index) const;
1186 template <typename Type>
1187 inline void AddField(Message* message, const FieldDescriptor* field,
1188 const Type& value) const;
1189 template <typename Type>
1190 inline Type* AddField(Message* message, const FieldDescriptor* field) const;
1191
1192 int GetExtensionNumberOrDie(const Descriptor* type) const;
1193
1194 // Internal versions of EnumValue API perform no checking. Called after checks
1195 // by public methods.
1196 void SetEnumValueInternal(Message* message, const FieldDescriptor* field,
1197 int value) const;
1198 void SetRepeatedEnumValueInternal(Message* message,
1199 const FieldDescriptor* field, int index,
1200 int value) const;
1201 void AddEnumValueInternal(Message* message, const FieldDescriptor* field,
1202 int value) const;
1203
1204 friend inline // inline so nobody can call this function.
1205 void
1206 RegisterAllTypesInternal(const Metadata* file_level_metadata, int size);
1207 friend inline const char* ParseLenDelim(int field_number,
1208 const FieldDescriptor* field,
1209 Message* msg,
1210 const Reflection* reflection,
1211 const char* ptr,
1212 internal::ParseContext* ctx);
1213 friend inline const char* ParsePackedField(const FieldDescriptor* field,
1214 Message* msg,
1215 const Reflection* reflection,
1216 const char* ptr,
1217 internal::ParseContext* ctx);
1218
1219 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Reflection);
1220 };
1221
1222 // Abstract interface for a factory for message objects.
1223 class PROTOBUF_EXPORT MessageFactory {
1224 public:
MessageFactory()1225 inline MessageFactory() {}
1226 virtual ~MessageFactory();
1227
1228 // Given a Descriptor, gets or constructs the default (prototype) Message
1229 // of that type. You can then call that message's New() method to construct
1230 // a mutable message of that type.
1231 //
1232 // Calling this method twice with the same Descriptor returns the same
1233 // object. The returned object remains property of the factory. Also, any
1234 // objects created by calling the prototype's New() method share some data
1235 // with the prototype, so these must be destroyed before the MessageFactory
1236 // is destroyed.
1237 //
1238 // The given descriptor must outlive the returned message, and hence must
1239 // outlive the MessageFactory.
1240 //
1241 // Some implementations do not support all types. GetPrototype() will
1242 // return nullptr if the descriptor passed in is not supported.
1243 //
1244 // This method may or may not be thread-safe depending on the implementation.
1245 // Each implementation should document its own degree thread-safety.
1246 virtual const Message* GetPrototype(const Descriptor* type) = 0;
1247
1248 // Gets a MessageFactory which supports all generated, compiled-in messages.
1249 // In other words, for any compiled-in type FooMessage, the following is true:
1250 // MessageFactory::generated_factory()->GetPrototype(
1251 // FooMessage::descriptor()) == FooMessage::default_instance()
1252 // This factory supports all types which are found in
1253 // DescriptorPool::generated_pool(). If given a descriptor from any other
1254 // pool, GetPrototype() will return nullptr. (You can also check if a
1255 // descriptor is for a generated message by checking if
1256 // descriptor->file()->pool() == DescriptorPool::generated_pool().)
1257 //
1258 // This factory is 100% thread-safe; calling GetPrototype() does not modify
1259 // any shared data.
1260 //
1261 // This factory is a singleton. The caller must not delete the object.
1262 static MessageFactory* generated_factory();
1263
1264 // For internal use only: Registers a .proto file at static initialization
1265 // time, to be placed in generated_factory. The first time GetPrototype()
1266 // is called with a descriptor from this file, |register_messages| will be
1267 // called, with the file name as the parameter. It must call
1268 // InternalRegisterGeneratedMessage() (below) to register each message type
1269 // in the file. This strange mechanism is necessary because descriptors are
1270 // built lazily, so we can't register types by their descriptor until we
1271 // know that the descriptor exists. |filename| must be a permanent string.
1272 static void InternalRegisterGeneratedFile(
1273 const google::protobuf::internal::DescriptorTable* table);
1274
1275 // For internal use only: Registers a message type. Called only by the
1276 // functions which are registered with InternalRegisterGeneratedFile(),
1277 // above.
1278 static void InternalRegisterGeneratedMessage(const Descriptor* descriptor,
1279 const Message* prototype);
1280
1281
1282 private:
1283 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFactory);
1284 };
1285
1286 #define DECLARE_GET_REPEATED_FIELD(TYPE) \
1287 template <> \
1288 PROTOBUF_EXPORT const RepeatedField<TYPE>& \
1289 Reflection::GetRepeatedFieldInternal<TYPE>( \
1290 const Message& message, const FieldDescriptor* field) const; \
1291 \
1292 template <> \
1293 PROTOBUF_EXPORT RepeatedField<TYPE>* \
1294 Reflection::MutableRepeatedFieldInternal<TYPE>( \
1295 Message * message, const FieldDescriptor* field) const;
1296
1297 DECLARE_GET_REPEATED_FIELD(int32)
DECLARE_GET_REPEATED_FIELD(int64)1298 DECLARE_GET_REPEATED_FIELD(int64)
1299 DECLARE_GET_REPEATED_FIELD(uint32)
1300 DECLARE_GET_REPEATED_FIELD(uint64)
1301 DECLARE_GET_REPEATED_FIELD(float)
1302 DECLARE_GET_REPEATED_FIELD(double)
1303 DECLARE_GET_REPEATED_FIELD(bool)
1304
1305 #undef DECLARE_GET_REPEATED_FIELD
1306
1307 // Tries to downcast this message to a generated message type. Returns nullptr
1308 // if this class is not an instance of T. This works even if RTTI is disabled.
1309 //
1310 // This also has the effect of creating a strong reference to T that will
1311 // prevent the linker from stripping it out at link time. This can be important
1312 // if you are using a DynamicMessageFactory that delegates to the generated
1313 // factory.
1314 template <typename T>
1315 const T* DynamicCastToGenerated(const Message* from) {
1316 // Compile-time assert that T is a generated type that has a
1317 // default_instance() accessor, but avoid actually calling it.
1318 const T& (*get_default_instance)() = &T::default_instance;
1319 (void)get_default_instance;
1320
1321 // Compile-time assert that T is a subclass of google::protobuf::Message.
1322 const Message* unused = static_cast<T*>(nullptr);
1323 (void)unused;
1324
1325 #if PROTOBUF_RTTI
1326 return dynamic_cast<const T*>(from);
1327 #else
1328 bool ok = from != nullptr &&
1329 T::default_instance().GetReflection() == from->GetReflection();
1330 return ok ? down_cast<const T*>(from) : nullptr;
1331 #endif
1332 }
1333
1334 template <typename T>
DynamicCastToGenerated(Message * from)1335 T* DynamicCastToGenerated(Message* from) {
1336 const Message* message_const = from;
1337 return const_cast<T*>(DynamicCastToGenerated<T>(message_const));
1338 }
1339
1340 // Call this function to ensure that this message's reflection is linked into
1341 // the binary:
1342 //
1343 // google::protobuf::LinkMessageReflection<FooMessage>();
1344 //
1345 // This will ensure that the following lookup will succeed:
1346 //
1347 // DescriptorPool::generated_pool()->FindMessageTypeByName("FooMessage");
1348 //
1349 // As a side-effect, it will also guarantee that anything else from the same
1350 // .proto file will also be available for lookup in the generated pool.
1351 //
1352 // This function does not actually register the message, so it does not need
1353 // to be called before the lookup. However it does need to occur in a function
1354 // that cannot be stripped from the binary (ie. it must be reachable from main).
1355 //
1356 // Best practice is to call this function as close as possible to where the
1357 // reflection is actually needed. This function is very cheap to call, so you
1358 // should not need to worry about its runtime overhead except in the tightest
1359 // of loops (on x86-64 it compiles into two "mov" instructions).
1360 template <typename T>
LinkMessageReflection()1361 void LinkMessageReflection() {
1362 internal::StrongReference(T::default_instance);
1363 }
1364
1365 // =============================================================================
1366 // Implementation details for {Get,Mutable}RawRepeatedPtrField. We provide
1367 // specializations for <std::string>, <StringPieceField> and <Message> and
1368 // handle everything else with the default template which will match any type
1369 // having a method with signature "static const google::protobuf::Descriptor*
1370 // descriptor()". Such a type presumably is a descendant of google::protobuf::Message.
1371
1372 template <>
1373 inline const RepeatedPtrField<std::string>&
1374 Reflection::GetRepeatedPtrFieldInternal<std::string>(
1375 const Message& message, const FieldDescriptor* field) const {
1376 return *static_cast<RepeatedPtrField<std::string>*>(
1377 MutableRawRepeatedString(const_cast<Message*>(&message), field, true));
1378 }
1379
1380 template <>
1381 inline RepeatedPtrField<std::string>*
1382 Reflection::MutableRepeatedPtrFieldInternal<std::string>(
1383 Message* message, const FieldDescriptor* field) const {
1384 return static_cast<RepeatedPtrField<std::string>*>(
1385 MutableRawRepeatedString(message, field, true));
1386 }
1387
1388
1389 // -----
1390
1391 template <>
GetRepeatedPtrFieldInternal(const Message & message,const FieldDescriptor * field)1392 inline const RepeatedPtrField<Message>& Reflection::GetRepeatedPtrFieldInternal(
1393 const Message& message, const FieldDescriptor* field) const {
1394 return *static_cast<const RepeatedPtrField<Message>*>(GetRawRepeatedField(
1395 message, field, FieldDescriptor::CPPTYPE_MESSAGE, -1, nullptr));
1396 }
1397
1398 template <>
MutableRepeatedPtrFieldInternal(Message * message,const FieldDescriptor * field)1399 inline RepeatedPtrField<Message>* Reflection::MutableRepeatedPtrFieldInternal(
1400 Message* message, const FieldDescriptor* field) const {
1401 return static_cast<RepeatedPtrField<Message>*>(MutableRawRepeatedField(
1402 message, field, FieldDescriptor::CPPTYPE_MESSAGE, -1, nullptr));
1403 }
1404
1405 template <typename PB>
GetRepeatedPtrFieldInternal(const Message & message,const FieldDescriptor * field)1406 inline const RepeatedPtrField<PB>& Reflection::GetRepeatedPtrFieldInternal(
1407 const Message& message, const FieldDescriptor* field) const {
1408 return *static_cast<const RepeatedPtrField<PB>*>(
1409 GetRawRepeatedField(message, field, FieldDescriptor::CPPTYPE_MESSAGE, -1,
1410 PB::default_instance().GetDescriptor()));
1411 }
1412
1413 template <typename PB>
MutableRepeatedPtrFieldInternal(Message * message,const FieldDescriptor * field)1414 inline RepeatedPtrField<PB>* Reflection::MutableRepeatedPtrFieldInternal(
1415 Message* message, const FieldDescriptor* field) const {
1416 return static_cast<RepeatedPtrField<PB>*>(
1417 MutableRawRepeatedField(message, field, FieldDescriptor::CPPTYPE_MESSAGE,
1418 -1, PB::default_instance().GetDescriptor()));
1419 }
1420
1421 template <typename Type>
DefaultRaw(const FieldDescriptor * field)1422 const Type& Reflection::DefaultRaw(const FieldDescriptor* field) const {
1423 return *reinterpret_cast<const Type*>(schema_.GetFieldDefault(field));
1424 }
1425 } // namespace protobuf
1426 } // namespace google
1427
1428 #include <google/protobuf/port_undef.inc>
1429
1430 #endif // GOOGLE_PROTOBUF_MESSAGE_H__
1431