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