Back to home page

EIC code displayed by LXR

 
 

    


Warning, file /include/google/protobuf/message.h was not indexed or was modified since last indexation (in which case cross-reference links may be missing, inaccurate or erroneous).

0001 // Protocol Buffers - Google's data interchange format
0002 // Copyright 2008 Google Inc.  All rights reserved.
0003 //
0004 // Use of this source code is governed by a BSD-style
0005 // license that can be found in the LICENSE file or at
0006 // https://developers.google.com/open-source/licenses/bsd
0007 
0008 // Author: kenton@google.com (Kenton Varda)
0009 //  Based on original Protocol Buffers design by
0010 //  Sanjay Ghemawat, Jeff Dean, and others.
0011 //
0012 // Defines Message, the abstract interface implemented by non-lite
0013 // protocol message objects.
0014 //
0015 // This is only intended to be extended by protoc created gencode or types
0016 // defined in the Protobuf runtime. It is not intended or supported for
0017 // application code to extend this class, and any protected methods may be
0018 // removed without being it being considered a breaking change as long as the
0019 // corresponding gencode does not use it.
0020 //
0021 // Example usage:
0022 //
0023 // Say you have a message defined as:
0024 //
0025 //   message Foo {
0026 //     optional string text = 1;
0027 //     repeated int32 numbers = 2;
0028 //   }
0029 //
0030 // Then, if you used the protocol compiler to generate a class from the above
0031 // definition, you could use it like so:
0032 //
0033 //   std::string data;  // Will store a serialized version of the message.
0034 //
0035 //   {
0036 //     // Create a message and serialize it.
0037 //     Foo foo;
0038 //     foo.set_text("Hello World!");
0039 //     foo.add_numbers(1);
0040 //     foo.add_numbers(5);
0041 //     foo.add_numbers(42);
0042 //
0043 //     foo.SerializeToString(&data);
0044 //   }
0045 //
0046 //   {
0047 //     // Parse the serialized message and check that it contains the
0048 //     // correct data.
0049 //     Foo foo;
0050 //     foo.ParseFromString(data);
0051 //
0052 //     assert(foo.text() == "Hello World!");
0053 //     assert(foo.numbers_size() == 3);
0054 //     assert(foo.numbers(0) == 1);
0055 //     assert(foo.numbers(1) == 5);
0056 //     assert(foo.numbers(2) == 42);
0057 //   }
0058 //
0059 //   {
0060 //     // Same as the last block, but do it dynamically via the Message
0061 //     // reflection interface.
0062 //     Message* foo = new Foo;
0063 //     const Descriptor* descriptor = foo->GetDescriptor();
0064 //
0065 //     // Get the descriptors for the fields we're interested in and verify
0066 //     // their types.
0067 //     const FieldDescriptor* text_field = descriptor->FindFieldByName("text");
0068 //     assert(text_field != nullptr);
0069 //     assert(text_field->type() == FieldDescriptor::TYPE_STRING);
0070 //     assert(!text_field->is_required());
0071 //     assert(!text_field->is_repeated());
0072 //     const FieldDescriptor* numbers_field = descriptor->
0073 //                                            FindFieldByName("numbers");
0074 //     assert(numbers_field != nullptr);
0075 //     assert(numbers_field->type() == FieldDescriptor::TYPE_INT32);
0076 //     assert(numbers_field->is_repeated());
0077 //
0078 //     // Parse the message.
0079 //     foo->ParseFromString(data);
0080 //
0081 //     // Use the reflection interface to examine the contents.
0082 //     const Reflection* reflection = foo->GetReflection();
0083 //     assert(reflection->GetString(*foo, text_field) == "Hello World!");
0084 //     assert(reflection->FieldSize(*foo, numbers_field) == 3);
0085 //     assert(reflection->GetRepeatedInt32(*foo, numbers_field, 0) == 1);
0086 //     assert(reflection->GetRepeatedInt32(*foo, numbers_field, 1) == 5);
0087 //     assert(reflection->GetRepeatedInt32(*foo, numbers_field, 2) == 42);
0088 //
0089 //     delete foo;
0090 //   }
0091 
0092 #ifndef GOOGLE_PROTOBUF_MESSAGE_H__
0093 #define GOOGLE_PROTOBUF_MESSAGE_H__
0094 
0095 #include <cstddef>
0096 #include <cstdint>
0097 #include <memory>
0098 #include <optional>
0099 #include <string>
0100 #include <type_traits>
0101 #include <vector>
0102 
0103 #include "absl/base/attributes.h"
0104 #include "absl/base/call_once.h"
0105 #include "absl/base/macros.h"
0106 #include "absl/base/optimization.h"
0107 #include "absl/log/absl_check.h"
0108 #include "absl/memory/memory.h"
0109 #include "absl/strings/cord.h"
0110 #include "absl/strings/string_view.h"
0111 #include "google/protobuf/arena.h"
0112 #include "google/protobuf/descriptor.h"
0113 #include "google/protobuf/generated_message_reflection.h"
0114 #include "google/protobuf/generated_message_tctable_decl.h"
0115 #include "google/protobuf/generated_message_util.h"
0116 #include "google/protobuf/map.h"  // TODO: cleanup
0117 #include "google/protobuf/message_lite.h"
0118 #include "google/protobuf/port.h"
0119 #include "google/protobuf/reflection.h"
0120 
0121 // Must be included last.
0122 #include "google/protobuf/port_def.inc"
0123 
0124 #ifdef SWIG
0125 #error "You cannot SWIG proto headers"
0126 #endif
0127 
0128 namespace google {
0129 namespace protobuf {
0130 
0131 // Defined in this file.
0132 class Message;
0133 class Reflection;
0134 class MessageFactory;
0135 
0136 // Defined in other files.
0137 class AssignDescriptorsHelper;
0138 class ConstMapIterator;
0139 class DynamicMessageFactory;
0140 class GeneratedMessageReflectionTestHelper;
0141 class MapKey;
0142 class MapValueConstRef;
0143 class MapValueRef;
0144 class MapIterator;
0145 class MapReflectionTester;
0146 class TextFormat;
0147 
0148 namespace internal {
0149 struct FuzzPeer;
0150 struct DescriptorTable;
0151 template <bool is_oneof>
0152 struct DynamicFieldInfoHelper;
0153 class MapFieldBase;
0154 class MessageUtil;
0155 class ReflectionVisit;
0156 class SwapFieldHelper;
0157 class CachedSize;
0158 struct TailCallTableInfo;
0159 template <typename MessageT, typename FieldT>
0160 struct RepeatedEntityDynamicFieldInfoBase;
0161 template <typename MessageT, typename FieldT>
0162 struct RepeatedPtrEntityDynamicFieldInfoBase;
0163 
0164 namespace field_layout {
0165 enum TransformValidation : uint16_t;
0166 }  // namespace field_layout
0167 
0168 namespace v2 {
0169 class V2TableGenTester;
0170 }  // namespace v2
0171 }  // namespace internal
0172 class UnknownFieldSet;  // unknown_field_set.h
0173 namespace io {
0174 class EpsCopyOutputStream;   // coded_stream.h
0175 class ZeroCopyInputStream;   // zero_copy_stream.h
0176 class ZeroCopyOutputStream;  // zero_copy_stream.h
0177 class CodedInputStream;      // coded_stream.h
0178 class CodedOutputStream;     // coded_stream.h
0179 }  // namespace io
0180 namespace python {
0181 class MapReflectionFriend;  // scalar_map_container.h
0182 class MessageReflectionFriend;
0183 }  // namespace python
0184 namespace expr {
0185 class CelMapReflectionFriend;  // field_backed_map_impl.cc
0186 class SudoMapReflectionFriend;
0187 }  // namespace expr
0188 
0189 namespace internal {
0190 class MapFieldPrinterHelper;  // text_format.cc
0191 PROTOBUF_EXPORT std::string StringifyMessage(
0192     const Message& message);  // text_format.cc
0193 }  // namespace internal
0194 PROTOBUF_EXPORT std::string ShortFormat(
0195     const Message& message);  // text_format.cc
0196 PROTOBUF_EXPORT std::string Utf8Format(
0197     const Message& message);  // text_format.cc
0198 namespace util {
0199 class MessageDifferencer;
0200 }
0201 
0202 
0203 namespace internal {
0204 class ReflectionAccessor;      // message.cc
0205 class ReflectionOps;           // reflection_ops.h
0206 class MapKeySorter;            // wire_format.cc
0207 class WireFormat;              // wire_format.h
0208 class MapFieldReflectionTest;  // map_test.cc
0209 }  // namespace internal
0210 
0211 template <typename T>
0212 class RepeatedField;  // repeated_field.h
0213 
0214 template <typename T>
0215 class RepeatedPtrField;  // repeated_field.h
0216 
0217 // A container to hold message metadata.
0218 struct Metadata {
0219   const Descriptor* descriptor;
0220   const Reflection* reflection;
0221 };
0222 
0223 namespace internal {
0224 template <class To>
0225 inline To* GetPointerAtOffset(void* message, uint32_t offset) {
0226   return reinterpret_cast<To*>(reinterpret_cast<char*>(message) + offset);
0227 }
0228 
0229 template <class To>
0230 const To* GetConstPointerAtOffset(const void* message, uint32_t offset) {
0231   return reinterpret_cast<const To*>(reinterpret_cast<const char*>(message) +
0232                                      offset);
0233 }
0234 
0235 template <class To>
0236 const To& GetConstRefAtOffset(const Message& message, uint32_t offset) {
0237   return *GetConstPointerAtOffset<To>(&message, offset);
0238 }
0239 
0240 bool CreateUnknownEnumValues(const FieldDescriptor* field);
0241 
0242 // Returns true if "message" is a descendant of "root".
0243 PROTOBUF_EXPORT bool IsDescendant(Message& root, const Message& message);
0244 
0245 inline void MaybePoisonAfterClear(Message* root);
0246 }  // namespace internal
0247 
0248 // Abstract interface for protocol messages.
0249 //
0250 // See also MessageLite, which contains most every-day operations.  Message
0251 // adds descriptors and reflection on top of that.
0252 //
0253 // The methods of this class that are virtual but not pure-virtual have
0254 // default implementations based on reflection.  Message classes which are
0255 // optimized for speed will want to override these with faster implementations,
0256 // but classes optimized for code size may be happy with keeping them.  See
0257 // the optimize_for option in descriptor.proto.
0258 //
0259 // Users must not derive from this class. Only the protocol compiler and
0260 // the internal library are allowed to create subclasses.
0261 class PROTOBUF_EXPORT Message : public MessageLite {
0262  public:
0263   Message(const Message&) = delete;
0264   Message& operator=(const Message&) = delete;
0265 
0266   // Basic Operations ------------------------------------------------
0267 
0268   // Construct a new instance of the same type.  Ownership is passed to the
0269   // caller.  (This is also defined in MessageLite, but is defined again here
0270   // for return-type covariance.)
0271   Message* New() const { return New(nullptr); }
0272 
0273   // Construct a new instance on the arena. Ownership is passed to the caller
0274   // if arena is a nullptr.
0275   Message* New(Arena* arena) const {
0276     return static_cast<Message*>(MessageLite::New(arena));
0277   }
0278 
0279   // Make this message into a copy of the given message.  The given message
0280   // must have the same descriptor, but need not necessarily be the same class.
0281   // By default this is just implemented as "Clear(); MergeFrom(from);".
0282   void CopyFrom(const Message& from);
0283 
0284   // Merge the fields from the given message into this message.  Singular
0285   // fields will be overwritten, if specified in from, except for embedded
0286   // messages which will be merged.  Repeated fields will be concatenated.
0287   // The given message must be of the same type as this message (i.e. the
0288   // exact same class).
0289   void MergeFrom(const Message& from);
0290 
0291   // Verifies that IsInitialized() returns true.  ABSL_CHECK-fails otherwise,
0292   // with a nice error message.
0293   void CheckInitialized() const;
0294 
0295   // Slowly build a list of all required fields that are not set.
0296   // This is much, much slower than IsInitialized() as it is implemented
0297   // purely via reflection.  Generally, you should not call this unless you
0298   // have already determined that an error exists by calling IsInitialized().
0299   void FindInitializationErrors(std::vector<std::string>* errors) const;
0300 
0301   // Like FindInitializationErrors, but joins all the strings, delimited by
0302   // commas, and returns them.
0303   std::string InitializationErrorString() const;
0304 
0305   // Clears all unknown fields from this message and all embedded messages.
0306   // Normally, if unknown tag numbers are encountered when parsing a message,
0307   // the tag and value are stored in the message's UnknownFieldSet and
0308   // then written back out when the message is serialized.  This allows servers
0309   // which simply route messages to other servers to pass through messages
0310   // that have new field definitions which they don't yet know about.  However,
0311   // this behavior can have security implications.  To avoid it, call this
0312   // method after parsing.
0313   //
0314   // See Reflection::GetUnknownFields() for more on unknown fields.
0315   void DiscardUnknownFields();
0316 
0317   // Computes (an estimate of) the total number of bytes currently used for
0318   // storing the message in memory.
0319   //
0320   // SpaceUsed() is noticeably slower than ByteSize(), as it is implemented
0321   // using reflection (rather than the generated code implementation for
0322   // ByteSize()). Like ByteSize(), its CPU time is linear in the number of
0323   // fields defined for the proto.
0324   //
0325   // Note: The precise value of this method should never be depended on, and can
0326   // change substantially due to internal details.  In debug builds, this will
0327   // include a random fuzz factor to prevent these dependencies.
0328   size_t SpaceUsedLong() const;
0329 
0330   [[deprecated("Please use SpaceUsedLong() instead")]] int SpaceUsed() const {
0331     return internal::ToIntSize(SpaceUsedLong());
0332   }
0333 
0334   // Debugging & Testing----------------------------------------------
0335 
0336   // Generates a human-readable form of this message for debugging purposes.
0337   // Note that the format and content of a debug string is not guaranteed, may
0338   // change without notice, and should not be depended on. Code that does
0339   // anything except display a string to assist in debugging should use
0340   // TextFormat instead.
0341   std::string DebugString() const;
0342   // Like DebugString(), but with less whitespace.
0343   std::string ShortDebugString() const;
0344   // Like DebugString(), but do not escape UTF-8 byte sequences.
0345   std::string Utf8DebugString() const;
0346   // Convenience function useful in GDB.  Prints DebugString() to stdout.
0347   void PrintDebugString() const;
0348 
0349   // Implementation of the `AbslStringify` interface. This adds something
0350   // similar to either `ShortDebugString()` or `DebugString()` to the sink.
0351   // Do not rely on exact format.
0352   template <typename Sink>
0353   friend void AbslStringify(Sink& sink, const google::protobuf::Message& message) {
0354     sink.Append(internal::StringifyMessage(message));
0355   }
0356 
0357   // Reflection-based methods ----------------------------------------
0358   // These methods are pure-virtual in MessageLite, but Message provides
0359   // reflection-based default implementations.
0360 #if !defined(PROTOBUF_CUSTOM_VTABLE)
0361   void Clear() override;
0362 
0363   size_t ByteSizeLong() const override;
0364   uint8_t* _InternalSerialize(uint8_t* target,
0365                               io::EpsCopyOutputStream* stream) const override;
0366 #endif  // !PROTOBUF_CUSTOM_VTABLE
0367 
0368   // Introspection ---------------------------------------------------
0369 
0370 
0371   // Get a non-owning pointer to a Descriptor for this message's type.  This
0372   // describes what fields the message contains, the types of those fields, etc.
0373   // This object remains property of the Message.
0374   const Descriptor* GetDescriptor() const { return GetMetadata().descriptor; }
0375 
0376   // Get a non-owning pointer to the Reflection interface for this Message,
0377   // which can be used to read and modify the fields of the Message dynamically
0378   // (in other words, without knowing the message type at compile time).  This
0379   // object remains property of the Message.
0380   const Reflection* GetReflection() const { return GetMetadata().reflection; }
0381 
0382  protected:
0383 #if !defined(PROTOBUF_CUSTOM_VTABLE)
0384   constexpr Message() {}
0385 #endif  // PROTOBUF_CUSTOM_VTABLE
0386   using MessageLite::MessageLite;
0387 
0388   // Get a struct containing the metadata for the Message, which is used in turn
0389   // to implement GetDescriptor() and GetReflection() above.
0390   Metadata GetMetadata() const;
0391   static Metadata GetMetadataImpl(const internal::ClassDataFull& data);
0392 
0393   // For CODE_SIZE types
0394   static bool IsInitializedImpl(const MessageLite&);
0395 
0396   size_t ComputeUnknownFieldsSize(
0397       size_t total_size, const internal::CachedSize* cached_size) const;
0398   size_t MaybeComputeUnknownFieldsSize(
0399       size_t total_size, const internal::CachedSize* cached_size) const;
0400 
0401 
0402   // Reflection based version for reflection based types.
0403   static absl::string_view GetTypeNameImpl(const internal::ClassData* data);
0404   static void MergeImpl(MessageLite& to, const MessageLite& from);
0405   void ClearImpl();
0406   static size_t ByteSizeLongImpl(const MessageLite& msg);
0407   static uint8_t* _InternalSerializeImpl(const MessageLite& msg,
0408                                          uint8_t* target,
0409                                          io::EpsCopyOutputStream* stream);
0410 
0411   static const internal::TcParseTableBase* GetTcParseTableImpl(
0412       const MessageLite& msg);
0413 
0414   static size_t SpaceUsedLongImpl(const MessageLite& msg_lite);
0415 
0416   static const internal::DescriptorMethods kDescriptorMethods;
0417 
0418 };
0419 
0420 namespace internal {
0421 // Creates and returns an allocation for a split message.
0422 void* CreateSplitMessageGeneric(Arena* arena, const void* default_split,
0423                                 size_t size, const void* message,
0424                                 const void* default_message);
0425 
0426 // Forward-declare interfaces used to implement RepeatedFieldRef.
0427 // These are protobuf internals that users shouldn't care about.
0428 class RepeatedFieldAccessor;
0429 }  // namespace internal
0430 
0431 // This interface contains methods that can be used to dynamically access
0432 // and modify the fields of a protocol message.  Their semantics are
0433 // similar to the accessors the protocol compiler generates.
0434 //
0435 // To get the Reflection for a given Message, call Message::GetReflection().
0436 //
0437 // This interface is separate from Message only for efficiency reasons;
0438 // the vast majority of implementations of Message will share the same
0439 // implementation of Reflection (GeneratedMessageReflection,
0440 // defined in generated_message.h), and all Messages of a particular class
0441 // should share the same Reflection object (though you should not rely on
0442 // the latter fact).
0443 //
0444 // There are several ways that these methods can be used incorrectly.  For
0445 // example, any of the following conditions will lead to undefined
0446 // results (probably assertion failures):
0447 // - The FieldDescriptor is not a field of this message type.
0448 // - The method called is not appropriate for the field's type.  For
0449 //   each field type in FieldDescriptor::TYPE_*, there is only one
0450 //   Get*() method, one Set*() method, and one Add*() method that is
0451 //   valid for that type.  It should be obvious which (except maybe
0452 //   for TYPE_BYTES, which are represented using strings in C++).
0453 // - A Get*() or Set*() method for singular fields is called on a repeated
0454 //   field.
0455 // - GetRepeated*(), SetRepeated*(), or Add*() is called on a non-repeated
0456 //   field.
0457 // - The Message object passed to any method is not of the right type for
0458 //   this Reflection object (i.e. message.GetReflection() != reflection).
0459 //
0460 // You might wonder why there is not any abstract representation for a field
0461 // of arbitrary type.  E.g., why isn't there just a "GetField()" method that
0462 // returns "const Field&", where "Field" is some class with accessors like
0463 // "GetInt32Value()".  The problem is that someone would have to deal with
0464 // allocating these Field objects.  For generated message classes, having to
0465 // allocate space for an additional object to wrap every field would at least
0466 // double the message's memory footprint, probably worse.  Allocating the
0467 // objects on-demand, on the other hand, would be expensive and prone to
0468 // memory leaks.  So, instead we ended up with this flat interface.
0469 class PROTOBUF_EXPORT Reflection final {
0470  public:
0471   Reflection(const Reflection&) = delete;
0472   Reflection& operator=(const Reflection&) = delete;
0473   ~Reflection();
0474 
0475   // Get the UnknownFieldSet for the message.  This contains fields which
0476   // were seen when the Message was parsed but were not recognized according
0477   // to the Message's definition.
0478   const UnknownFieldSet& GetUnknownFields(const Message& message) const;
0479   // Get a mutable pointer to the UnknownFieldSet for the message.  This
0480   // contains fields which were seen when the Message was parsed but were not
0481   // recognized according to the Message's definition.
0482   UnknownFieldSet* MutableUnknownFields(Message* message) const;
0483 
0484   // Estimate the amount of memory used by the message object.
0485   size_t SpaceUsedLong(const Message& message) const;
0486 
0487   [[deprecated("Please use SpaceUsedLong() instead")]] int SpaceUsed(
0488       const Message& message) const {
0489     return internal::ToIntSize(SpaceUsedLong(message));
0490   }
0491 
0492   // Returns true if the given message is a default message instance.
0493   bool IsDefaultInstance(const Message& message) const {
0494     ABSL_DCHECK_EQ(message.GetReflection(), this);
0495     return schema_.IsDefaultInstance(message);
0496   }
0497 
0498   // Check if the given non-repeated field is set.
0499   bool HasField(const Message& message, const FieldDescriptor* field) const;
0500 
0501   // Get the number of elements of a repeated field.
0502   int FieldSize(const Message& message, const FieldDescriptor* field) const;
0503 
0504   // Clear the value of a field, so that HasField() returns false or
0505   // FieldSize() returns zero.
0506   void ClearField(Message* message, const FieldDescriptor* field) const;
0507 
0508   // Check if the oneof is set. Returns true if any field in oneof
0509   // is set, false otherwise.
0510   bool HasOneof(const Message& message,
0511                 const OneofDescriptor* oneof_descriptor) const;
0512 
0513   void ClearOneof(Message* message,
0514                   const OneofDescriptor* oneof_descriptor) const;
0515 
0516   // Returns the field descriptor if the oneof is set. nullptr otherwise.
0517   const FieldDescriptor* GetOneofFieldDescriptor(
0518       const Message& message, const OneofDescriptor* oneof_descriptor) const;
0519 
0520   // Removes the last element of a repeated field.
0521   // We don't provide a way to remove any element other than the last
0522   // because it invites inefficient use, such as O(n^2) filtering loops
0523   // that should have been O(n).  If you want to remove an element other
0524   // than the last, the best way to do it is to re-arrange the elements
0525   // (using Swap()) so that the one you want removed is at the end, then
0526   // call RemoveLast().
0527   void RemoveLast(Message* message, const FieldDescriptor* field) const;
0528   // Removes the last element of a repeated message field, and returns the
0529   // pointer to the caller.  Caller takes ownership of the returned pointer.
0530   [[nodiscard]] Message* ReleaseLast(Message* message,
0531                                      const FieldDescriptor* field) const;
0532 
0533   // Similar to ReleaseLast() without internal safety and ownershp checks. This
0534   // method should only be used when the objects are on the same arena or paired
0535   // with a call to `UnsafeArenaAddAllocatedMessage`.
0536   Message* UnsafeArenaReleaseLast(Message* message,
0537                                   const FieldDescriptor* field) const;
0538 
0539   // Swap the complete contents of two messages.
0540   void Swap(Message* message1, Message* message2) const;
0541 
0542   // Swap fields listed in fields vector of two messages.
0543   void SwapFields(Message* message1, Message* message2,
0544                   const std::vector<const FieldDescriptor*>& fields) const;
0545 
0546   // Swap two elements of a repeated field.
0547   void SwapElements(Message* message, const FieldDescriptor* field, int index1,
0548                     int index2) const;
0549 
0550   // Swap without internal safety and ownership checks. This method should only
0551   // be used when the objects are on the same arena.
0552   void UnsafeArenaSwap(Message* lhs, Message* rhs) const;
0553 
0554   // SwapFields without internal safety and ownership checks. This method should
0555   // only be used when the objects are on the same arena.
0556   void UnsafeArenaSwapFields(
0557       Message* lhs, Message* rhs,
0558       const std::vector<const FieldDescriptor*>& fields) const;
0559 
0560   // List all fields of the message which are currently set, except for unknown
0561   // fields, but including extension known to the parser (i.e. compiled in).
0562   // Singular fields will only be listed if HasField(field) would return true
0563   // and repeated fields will only be listed if FieldSize(field) would return
0564   // non-zero.  Fields (both normal fields and extension fields) will be listed
0565   // ordered by field number.
0566   // Use Reflection::GetUnknownFields() or message.unknown_fields() to also get
0567   // access to fields/extensions unknown to the parser.
0568   void ListFields(const Message& message,
0569                   std::vector<const FieldDescriptor*>* output) const;
0570 
0571   // Singular field getters ------------------------------------------
0572   // These get the value of a non-repeated field.  They return the default
0573   // value for fields that aren't set.
0574 
0575   int32_t GetInt32(const Message& message, const FieldDescriptor* field) const;
0576   int64_t GetInt64(const Message& message, const FieldDescriptor* field) const;
0577   uint32_t GetUInt32(const Message& message,
0578                      const FieldDescriptor* field) const;
0579   uint64_t GetUInt64(const Message& message,
0580                      const FieldDescriptor* field) const;
0581   float GetFloat(const Message& message, const FieldDescriptor* field) const;
0582   double GetDouble(const Message& message, const FieldDescriptor* field) const;
0583   bool GetBool(const Message& message, const FieldDescriptor* field) const;
0584   std::string GetString(const Message& message,
0585                         const FieldDescriptor* field) const;
0586   const EnumValueDescriptor* GetEnum(const Message& message,
0587                                      const FieldDescriptor* field) const;
0588 
0589   // GetEnumValue() returns an enum field's value as an integer rather than
0590   // an EnumValueDescriptor*. If the integer value does not correspond to a
0591   // known value descriptor, a new value descriptor is created. (Such a value
0592   // will only be present when the new unknown-enum-value semantics are enabled
0593   // for a message.)
0594   int GetEnumValue(const Message& message, const FieldDescriptor* field) const;
0595 
0596   // See MutableMessage() for the meaning of the "factory" parameter.
0597   const Message& GetMessage(const Message& message,
0598                             const FieldDescriptor* field,
0599                             MessageFactory* factory = nullptr) const;
0600 
0601   // Get a string value without copying, if possible.
0602   //
0603   // GetString() necessarily returns a copy of the string.  This can be
0604   // inefficient when the std::string is already stored in a std::string object
0605   // in the underlying message.  GetStringReference() will return a reference to
0606   // the underlying std::string in this case.  Otherwise, it will copy the
0607   // string into *scratch and return that.
0608   //
0609   // Note:  It is perfectly reasonable and useful to write code like:
0610   //     str = reflection->GetStringReference(message, field, &str);
0611   //   This line would ensure that only one copy of the string is made
0612   //   regardless of the field's underlying representation.  When initializing
0613   //   a newly-constructed string, though, it's just as fast and more
0614   //   readable to use code like:
0615   //     std::string str = reflection->GetString(message, field);
0616   const std::string& GetStringReference(const Message& message,
0617                                         const FieldDescriptor* field,
0618                                         std::string* scratch) const;
0619 
0620   // Returns a Cord containing the value of the string field.  If the
0621   // underlying field is stored as a cord (e.g. it has the [ctype=CORD]
0622   // option), this involves no copies (just reference counting).  If the
0623   // underlying representation is not a Cord, a copy will have to be made.
0624   absl::Cord GetCord(const Message& message,
0625                      const FieldDescriptor* field) const;
0626 
0627   // Enables GetStringView() and GetRepeatedStringView() APIs to return
0628   // absl::string_view even though the underlying implementation doesn't have
0629   // contiguous bytes; e.g. absl::Cord.
0630   class ScratchSpace {
0631    public:
0632     ScratchSpace() = default;
0633 
0634     ScratchSpace(const ScratchSpace&) = delete;
0635     ScratchSpace& operator=(const ScratchSpace&) = delete;
0636 
0637    private:
0638     friend class Reflection;
0639 
0640     absl::string_view CopyFromCord(const absl::Cord& cord) {
0641       if (auto flat = cord.TryFlat()) {
0642         return *flat;
0643       }
0644       if (!buffer_) {
0645         buffer_ = absl::make_unique<std::string>();
0646       }
0647       absl::CopyCordToString(cord, buffer_.get());
0648       return *buffer_;
0649     }
0650 
0651     std::unique_ptr<std::string> buffer_;
0652   };
0653 
0654   // Returns a view into the contents of a string field. "scratch" is used to
0655   // flatten bytes if it is non-contiguous. The lifetime of absl::string_view is
0656   // either tied to "message" (contiguous) or "scratch" (otherwise).
0657   absl::string_view GetStringView(
0658       const Message& message, const FieldDescriptor* field,
0659       ScratchSpace& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) const;
0660 
0661 
0662   // Singular field mutators -----------------------------------------
0663   // These mutate the value of a non-repeated field.
0664 
0665   void SetInt32(Message* message, const FieldDescriptor* field,
0666                 int32_t value) const;
0667   void SetInt64(Message* message, const FieldDescriptor* field,
0668                 int64_t value) const;
0669   void SetUInt32(Message* message, const FieldDescriptor* field,
0670                  uint32_t value) const;
0671   void SetUInt64(Message* message, const FieldDescriptor* field,
0672                  uint64_t value) const;
0673   void SetFloat(Message* message, const FieldDescriptor* field,
0674                 float value) const;
0675   void SetDouble(Message* message, const FieldDescriptor* field,
0676                  double value) const;
0677   void SetBool(Message* message, const FieldDescriptor* field,
0678                bool value) const;
0679   void SetString(Message* message, const FieldDescriptor* field,
0680                  std::string value) const;
0681   // Set a string field to a Cord value.  If the underlying field is
0682   // represented using a Cord already, this involves no copies  (just
0683   // reference counting).  Otherwise, a copy must be made.
0684   void SetString(Message* message, const FieldDescriptor* field,
0685                  const absl::Cord& value) const;
0686   void SetEnum(Message* message, const FieldDescriptor* field,
0687                const EnumValueDescriptor* value) const;
0688   // Set an enum field's value with an integer rather than EnumValueDescriptor.
0689   // For proto3 this is just setting the enum field to the value specified, for
0690   // proto2 it's more complicated. If value is a known enum value the field is
0691   // set as usual. If the value is unknown then it is added to the unknown field
0692   // set. Note this matches the behavior of parsing unknown enum values.
0693   // If multiple calls with unknown values happen than they are all added to the
0694   // unknown field set in order of the calls.
0695   void SetEnumValue(Message* message, const FieldDescriptor* field,
0696                     int value) const;
0697 
0698   // Get a mutable pointer to a field with a message type.  If a MessageFactory
0699   // is provided, it will be used to construct instances of the sub-message;
0700   // otherwise, the default factory is used.  If the field is an extension that
0701   // does not live in the same pool as the containing message's descriptor (e.g.
0702   // it lives in an overlay pool), then a MessageFactory must be provided.
0703   // If you have no idea what that meant, then you probably don't need to worry
0704   // about it (don't provide a MessageFactory).  WARNING:  If the
0705   // FieldDescriptor is for a compiled-in extension, then
0706   // factory->GetPrototype(field->message_type()) MUST return an instance of
0707   // the compiled-in class for this type, NOT DynamicMessage.
0708   Message* MutableMessage(Message* message, const FieldDescriptor* field,
0709                           MessageFactory* factory = nullptr) const;
0710 
0711   // Replaces the message specified by 'field' with the already-allocated object
0712   // sub_message, passing ownership to the message.  If the field contained a
0713   // message, that message is deleted.  If sub_message is nullptr, the field is
0714   // cleared.
0715   void SetAllocatedMessage(Message* message, Message* sub_message,
0716                            const FieldDescriptor* field) const;
0717 
0718   // Similar to `SetAllocatedMessage`, but omits all internal safety and
0719   // ownership checks.  This method should only be used when the objects are on
0720   // the same arena or paired with a call to `UnsafeArenaReleaseMessage`.
0721   void UnsafeArenaSetAllocatedMessage(Message* message, Message* sub_message,
0722                                       const FieldDescriptor* field) const;
0723 
0724   // Releases the message specified by 'field' and returns the pointer,
0725   // ReleaseMessage() will return the message the message object if it exists.
0726   // Otherwise, it may or may not return nullptr.  In any case, if the return
0727   // value is non-null, the caller takes ownership of the pointer.
0728   // If the field existed (HasField() is true), then the returned pointer will
0729   // be the same as the pointer returned by MutableMessage().
0730   // This function has the same effect as ClearField().
0731   [[nodiscard]] Message* ReleaseMessage(
0732       Message* message, const FieldDescriptor* field,
0733       MessageFactory* factory = nullptr) const;
0734 
0735   // Similar to `ReleaseMessage`, but omits all internal safety and ownership
0736   // checks.  This method should only be used when the objects are on the same
0737   // arena or paired with a call to `UnsafeArenaSetAllocatedMessage`.
0738   Message* UnsafeArenaReleaseMessage(Message* message,
0739                                      const FieldDescriptor* field,
0740                                      MessageFactory* factory = nullptr) const;
0741 
0742 
0743   // Repeated field getters ------------------------------------------
0744   // These get the value of one element of a repeated field.
0745 
0746   int32_t GetRepeatedInt32(const Message& message, const FieldDescriptor* field,
0747                            int index) const;
0748   int64_t GetRepeatedInt64(const Message& message, const FieldDescriptor* field,
0749                            int index) const;
0750   uint32_t GetRepeatedUInt32(const Message& message,
0751                              const FieldDescriptor* field, int index) const;
0752   uint64_t GetRepeatedUInt64(const Message& message,
0753                              const FieldDescriptor* field, int index) const;
0754   float GetRepeatedFloat(const Message& message, const FieldDescriptor* field,
0755                          int index) const;
0756   double GetRepeatedDouble(const Message& message, const FieldDescriptor* field,
0757                            int index) const;
0758   bool GetRepeatedBool(const Message& message, const FieldDescriptor* field,
0759                        int index) const;
0760   std::string GetRepeatedString(const Message& message,
0761                                 const FieldDescriptor* field, int index) const;
0762   const EnumValueDescriptor* GetRepeatedEnum(const Message& message,
0763                                              const FieldDescriptor* field,
0764                                              int index) const;
0765   // GetRepeatedEnumValue() returns an enum field's value as an integer rather
0766   // than an EnumValueDescriptor*. If the integer value does not correspond to a
0767   // known value descriptor, a new value descriptor is created. (Such a value
0768   // will only be present when the new unknown-enum-value semantics are enabled
0769   // for a message.)
0770   int GetRepeatedEnumValue(const Message& message, const FieldDescriptor* field,
0771                            int index) const;
0772   const Message& GetRepeatedMessage(const Message& message,
0773                                     const FieldDescriptor* field,
0774                                     int index) const;
0775 
0776   // See GetStringReference(), above.
0777   const std::string& GetRepeatedStringReference(const Message& message,
0778                                                 const FieldDescriptor* field,
0779                                                 int index,
0780                                                 std::string* scratch) const;
0781 
0782   // See GetStringView(), above.
0783   absl::string_view GetRepeatedStringView(
0784       const Message& message, const FieldDescriptor* field, int index,
0785       ScratchSpace& scratch ABSL_ATTRIBUTE_LIFETIME_BOUND) const;
0786 
0787 
0788   // Repeated field mutators -----------------------------------------
0789   // These mutate the value of one element of a repeated field.
0790 
0791   void SetRepeatedInt32(Message* message, const FieldDescriptor* field,
0792                         int index, int32_t value) const;
0793   void SetRepeatedInt64(Message* message, const FieldDescriptor* field,
0794                         int index, int64_t value) const;
0795   void SetRepeatedUInt32(Message* message, const FieldDescriptor* field,
0796                          int index, uint32_t value) const;
0797   void SetRepeatedUInt64(Message* message, const FieldDescriptor* field,
0798                          int index, uint64_t value) const;
0799   void SetRepeatedFloat(Message* message, const FieldDescriptor* field,
0800                         int index, float value) const;
0801   void SetRepeatedDouble(Message* message, const FieldDescriptor* field,
0802                          int index, double value) const;
0803   void SetRepeatedBool(Message* message, const FieldDescriptor* field,
0804                        int index, bool value) const;
0805   void SetRepeatedString(Message* message, const FieldDescriptor* field,
0806                          int index, std::string value) const;
0807   void SetRepeatedEnum(Message* message, const FieldDescriptor* field,
0808                        int index, const EnumValueDescriptor* value) const;
0809   // Set an enum field's value with an integer rather than EnumValueDescriptor.
0810   // For proto3 this is just setting the enum field to the value specified, for
0811   // proto2 it's more complicated. If value is a known enum value the field is
0812   // set as usual. If the value is unknown then it is added to the unknown field
0813   // set. Note this matches the behavior of parsing unknown enum values.
0814   // If multiple calls with unknown values happen than they are all added to the
0815   // unknown field set in order of the calls.
0816   void SetRepeatedEnumValue(Message* message, const FieldDescriptor* field,
0817                             int index, int value) const;
0818   // Get a mutable pointer to an element of a repeated field with a message
0819   // type.
0820   Message* MutableRepeatedMessage(Message* message,
0821                                   const FieldDescriptor* field,
0822                                   int index) const;
0823 
0824 
0825   // Repeated field adders -------------------------------------------
0826   // These add an element to a repeated field.
0827 
0828   void AddInt32(Message* message, const FieldDescriptor* field,
0829                 int32_t value) const;
0830   void AddInt64(Message* message, const FieldDescriptor* field,
0831                 int64_t value) const;
0832   void AddUInt32(Message* message, const FieldDescriptor* field,
0833                  uint32_t value) const;
0834   void AddUInt64(Message* message, const FieldDescriptor* field,
0835                  uint64_t value) const;
0836   void AddFloat(Message* message, const FieldDescriptor* field,
0837                 float value) const;
0838   void AddDouble(Message* message, const FieldDescriptor* field,
0839                  double value) const;
0840   void AddBool(Message* message, const FieldDescriptor* field,
0841                bool value) const;
0842   void AddString(Message* message, const FieldDescriptor* field,
0843                  std::string value) const;
0844   void AddEnum(Message* message, const FieldDescriptor* field,
0845                const EnumValueDescriptor* value) const;
0846 
0847   // Add an integer value to a repeated enum field rather than
0848   // EnumValueDescriptor. For proto3 this is just setting the enum field to the
0849   // value specified, for proto2 it's more complicated. If value is a known enum
0850   // value the field is set as usual. If the value is unknown then it is added
0851   // to the unknown field set. Note this matches the behavior of parsing unknown
0852   // enum values. If multiple calls with unknown values happen than they are all
0853   // added to the unknown field set in order of the calls.
0854   void AddEnumValue(Message* message, const FieldDescriptor* field,
0855                     int value) const;
0856   // See MutableMessage() for comments on the "factory" parameter.
0857   Message* AddMessage(Message* message, const FieldDescriptor* field,
0858                       MessageFactory* factory = nullptr) const;
0859 
0860   // Appends an already-allocated object 'new_entry' to the repeated field
0861   // specified by 'field' passing ownership to the message.
0862   void AddAllocatedMessage(Message* message, const FieldDescriptor* field,
0863                            Message* new_entry) const;
0864 
0865   // Similar to AddAllocatedMessage() without internal safety and ownership
0866   // checks. This method should only be used when the objects are on the same
0867   // arena or paired with a call to `UnsafeArenaReleaseLast`.
0868   void UnsafeArenaAddAllocatedMessage(Message* message,
0869                                       const FieldDescriptor* field,
0870                                       Message* new_entry) const;
0871 
0872 
0873   // Get a RepeatedFieldRef object that can be used to read the underlying
0874   // repeated field. The type parameter T must be set according to the
0875   // field's cpp type. The following table shows the mapping from cpp type
0876   // to acceptable T.
0877   //
0878   //   field->cpp_type()      T
0879   //   CPPTYPE_INT32        int32_t
0880   //   CPPTYPE_UINT32       uint32_t
0881   //   CPPTYPE_INT64        int64_t
0882   //   CPPTYPE_UINT64       uint64_t
0883   //   CPPTYPE_DOUBLE       double
0884   //   CPPTYPE_FLOAT        float
0885   //   CPPTYPE_BOOL         bool
0886   //   CPPTYPE_ENUM         generated enum type or int32_t
0887   //   CPPTYPE_STRING       std::string
0888   //   CPPTYPE_MESSAGE      generated message type or google::protobuf::Message
0889   //
0890   // A RepeatedFieldRef object can be copied and the resulted object will point
0891   // to the same repeated field in the same message. The object can be used as
0892   // long as the message is not destroyed.
0893   //
0894   // Note that to use this method users need to include the header file
0895   // "reflection.h" (which defines the RepeatedFieldRef class templates).
0896   template <typename T>
0897   RepeatedFieldRef<T> GetRepeatedFieldRef(const Message& message,
0898                                           const FieldDescriptor* field) const;
0899 
0900   // Like GetRepeatedFieldRef() but return an object that can also be used
0901   // manipulate the underlying repeated field.
0902   template <typename T>
0903   MutableRepeatedFieldRef<T> GetMutableRepeatedFieldRef(
0904       Message* message, const FieldDescriptor* field) const;
0905 
0906   // DEPRECATED. Please use Get(Mutable)RepeatedFieldRef() for repeated field
0907   // access. The following repeated field accessors will be removed in the
0908   // future.
0909   //
0910   // Repeated field accessors  -------------------------------------------------
0911   // The methods above, e.g. GetRepeatedInt32(msg, fd, index), provide singular
0912   // access to the data in a RepeatedField.  The methods below provide aggregate
0913   // access by exposing the RepeatedField object itself with the Message.
0914   // Applying these templates to inappropriate types will lead to an undefined
0915   // reference at link time (e.g. GetRepeatedField<***double>), or possibly a
0916   // template matching error at compile time (e.g. GetRepeatedPtrField<File>).
0917   //
0918   // Usage example: my_doubs = refl->GetRepeatedField<double>(msg, fd);
0919 
0920   // DEPRECATED. Please use GetRepeatedFieldRef().
0921   //
0922   // for T = Cord and all protobuf scalar types except enums.
0923   template <typename T>
0924   [[deprecated(
0925       "Please use GetRepeatedFieldRef() instead")]] const RepeatedField<T>&
0926   GetRepeatedField(const Message& msg, const FieldDescriptor* d) const {
0927     return GetRepeatedFieldInternal<T>(msg, d);
0928   }
0929 
0930   // DEPRECATED. Please use GetMutableRepeatedFieldRef().
0931   //
0932   // for T = Cord and all protobuf scalar types except enums.
0933   template <typename T>
0934   [[deprecated(
0935       "Please use GetMutableRepeatedFieldRef() instead")]] RepeatedField<T>*
0936   MutableRepeatedField(Message* msg, const FieldDescriptor* d) const {
0937     return MutableRepeatedFieldInternal<T>(msg, d);
0938   }
0939 
0940   // DEPRECATED. Please use GetRepeatedFieldRef().
0941   //
0942   // for T = std::string, google::protobuf::internal::StringPieceField
0943   //         google::protobuf::Message & descendants.
0944   template <typename T>
0945   [[deprecated(
0946       "Please use GetRepeatedFieldRef() instead")]] const RepeatedPtrField<T>&
0947   GetRepeatedPtrField(const Message& msg, const FieldDescriptor* d) const {
0948     return GetRepeatedPtrFieldInternal<T>(msg, d);
0949   }
0950 
0951   // DEPRECATED. Please use GetMutableRepeatedFieldRef().
0952   //
0953   // for T = std::string, google::protobuf::internal::StringPieceField
0954   //         google::protobuf::Message & descendants.
0955   template <typename T>
0956   [[deprecated(
0957       "Please use GetMutableRepeatedFieldRef() instead")]] RepeatedPtrField<T>*
0958   MutableRepeatedPtrField(Message* msg, const FieldDescriptor* d) const {
0959     return MutableRepeatedPtrFieldInternal<T>(msg, d);
0960   }
0961 
0962   // Extensions ----------------------------------------------------------------
0963 
0964   // Try to find an extension of this message type by fully-qualified field
0965   // name.  Returns nullptr if no extension is known for this name or number.
0966   const FieldDescriptor* FindKnownExtensionByName(absl::string_view name) const;
0967 
0968   // Try to find an extension of this message type by field number.
0969   // Returns nullptr if no extension is known for this name or number.
0970   const FieldDescriptor* FindKnownExtensionByNumber(int number) const;
0971 
0972   // Returns the MessageFactory associated with this message.  This can be
0973   // useful for determining if a message is a generated message or not, for
0974   // example:
0975   //   if (message->GetReflection()->GetMessageFactory() ==
0976   //       google::protobuf::MessageFactory::generated_factory()) {
0977   //     // This is a generated message.
0978   //   }
0979   // It can also be used to create more messages of this type, though
0980   // Message::New() is an easier way to accomplish this.
0981   MessageFactory* GetMessageFactory() const;
0982 
0983  private:
0984   template <typename T>
0985   const RepeatedField<T>& GetRepeatedFieldInternal(
0986       const Message& message, const FieldDescriptor* field) const;
0987   template <typename T>
0988   RepeatedField<T>* MutableRepeatedFieldInternal(
0989       Message* message, const FieldDescriptor* field) const;
0990   template <typename T>
0991   const RepeatedPtrField<T>& GetRepeatedPtrFieldInternal(
0992       const Message& message, const FieldDescriptor* field) const;
0993   template <typename T>
0994   RepeatedPtrField<T>* MutableRepeatedPtrFieldInternal(
0995       Message* message, const FieldDescriptor* field) const;
0996 
0997   // REQUIRES: If the field is Cord, then `scratch != nullptr`.
0998   absl::string_view GetStringViewImpl(const Message& message,
0999                                       const FieldDescriptor* field,
1000                                       ScratchSpace* scratch) const;
1001   absl::string_view GetRepeatedStringViewImpl(const Message& message,
1002                                               const FieldDescriptor* field,
1003                                               int index,
1004                                               ScratchSpace* scratch) const;
1005 
1006   // Obtain a pointer to a Repeated Field Structure and do some type checking:
1007   //   on field->cpp_type(),
1008   //   on field->field_option().ctype() (if ctype >= 0)
1009   //   of field->message_type() (if message_type != nullptr).
1010   // We use 2 routine rather than 4 (const vs mutable) x (scalar vs pointer).
1011   void* MutableRawRepeatedField(Message* message, const FieldDescriptor* field,
1012                                 FieldDescriptor::CppType cpptype, int ctype,
1013                                 const Descriptor* desc) const;
1014 
1015   const void* GetRawRepeatedField(const Message& message,
1016                                   const FieldDescriptor* field,
1017                                   FieldDescriptor::CppType cpptype, int ctype,
1018                                   const Descriptor* desc) const;
1019 
1020   // The following methods are used to implement (Mutable)RepeatedFieldRef.
1021   // A Ref object will store a raw pointer to the repeated field data (obtained
1022   // from RepeatedFieldData()) and a pointer to a Accessor (obtained from
1023   // RepeatedFieldAccessor) which will be used to access the raw data.
1024 
1025   // Returns a raw pointer to the repeated field
1026   //
1027   // "cpp_type" and "message_type" are deduced from the type parameter T passed
1028   // to Get(Mutable)RepeatedFieldRef. If T is a generated message type,
1029   // "message_type" should be set to its descriptor. Otherwise "message_type"
1030   // should be set to nullptr. Implementations of this method should check
1031   // whether "cpp_type"/"message_type" is consistent with the actual type of the
1032   // field.
1033   const void* RepeatedFieldData(const Message& message,
1034                                 const FieldDescriptor* field,
1035                                 FieldDescriptor::CppType cpp_type,
1036                                 const Descriptor* message_type) const;
1037   void* RepeatedFieldData(Message* message, const FieldDescriptor* field,
1038                           FieldDescriptor::CppType cpp_type,
1039                           const Descriptor* message_type) const;
1040 
1041   // The returned pointer should point to a singleton instance which implements
1042   // the RepeatedFieldAccessor interface.
1043   const internal::RepeatedFieldAccessor* RepeatedFieldAccessor(
1044       const FieldDescriptor* field) const;
1045 
1046   // Returns true if the message field is backed by a LazyField.
1047   //
1048   // A message field may be backed by a LazyField without the user annotation
1049   // ([lazy = true]). While the user-annotated LazyField is lazily verified on
1050   // first touch (i.e. failure on access rather than parsing if the LazyField is
1051   // not initialized), the inferred LazyField is eagerly verified to avoid lazy
1052   // parsing error at the cost of lower efficiency. When reflecting a message
1053   // field, use this API instead of checking field->options().lazy().
1054   bool IsLazyField(const FieldDescriptor* field) const {
1055     return IsLazilyVerifiedLazyField(field) ||
1056            IsEagerlyVerifiedLazyField(field);
1057   }
1058 
1059   // Returns true if the field is lazy extension. It is meant to allow python
1060   // reparse lazy field until b/157559327 is fixed.
1061   bool IsLazyExtension(const Message& message,
1062                        const FieldDescriptor* field) const;
1063 
1064   bool IsLazilyVerifiedLazyField(const FieldDescriptor* field) const;
1065   bool IsEagerlyVerifiedLazyField(const FieldDescriptor* field) const;
1066   internal::field_layout::TransformValidation GetLazyStyle(
1067       const FieldDescriptor* field) const;
1068 
1069   bool IsSplit(const FieldDescriptor* field) const {
1070     return schema_.IsSplit(field);
1071   }
1072 
1073   // Walks the message tree from "root" and poisons (under ASAN) the memory to
1074   // force subsequent accesses to fail. Always calls Clear beforehand to clear
1075   // strings, etc.
1076   void MaybePoisonAfterClear(Message& root) const;
1077 
1078   friend class FastReflectionBase;
1079   friend class FastReflectionMessageMutator;
1080   friend class internal::ReflectionVisit;
1081   friend bool internal::IsDescendant(Message& root, const Message& message);
1082   friend void internal::MaybePoisonAfterClear(Message* root);
1083 
1084   const Descriptor* const descriptor_;
1085   const internal::ReflectionSchema schema_;
1086   const DescriptorPool* const descriptor_pool_;
1087   MessageFactory* const message_factory_;
1088 
1089   // Last non weak field index. This is an optimization when most weak fields
1090   // are at the end of the containing message. If a message proto doesn't
1091   // contain weak fields, then this field equals descriptor_->field_count().
1092   int last_non_weak_field_index_;
1093 
1094   // The table-driven parser table.
1095   // This table is generated on demand for Message types that did not override
1096   // _InternalParse. It uses the reflection information to do so.
1097   mutable absl::once_flag tcparse_table_once_;
1098   using TcParseTableBase = internal::TcParseTableBase;
1099   mutable const TcParseTableBase* tcparse_table_ = nullptr;
1100 
1101   const TcParseTableBase* GetTcParseTable() const {
1102     absl::call_once(tcparse_table_once_,
1103                     [&] { tcparse_table_ = CreateTcParseTable(); });
1104     return tcparse_table_;
1105   }
1106 
1107   const TcParseTableBase* CreateTcParseTable() const;
1108   void PopulateTcParseFastEntries(
1109       const internal::TailCallTableInfo& table_info,
1110       TcParseTableBase::FastFieldEntry* fast_entries) const;
1111   void PopulateTcParseEntries(internal::TailCallTableInfo& table_info,
1112                               TcParseTableBase::FieldEntry* entries) const;
1113   void PopulateTcParseFieldAux(const internal::TailCallTableInfo& table_info,
1114                                TcParseTableBase::FieldAux* field_aux) const;
1115 
1116   template <typename T, typename Enable>
1117   friend class RepeatedFieldRef;
1118   template <typename T, typename Enable>
1119   friend class MutableRepeatedFieldRef;
1120   template <typename MessageT, typename FieldT>
1121   friend struct internal::RepeatedEntityDynamicFieldInfoBase;
1122   template <typename MessageT, typename FieldT>
1123   friend struct internal::RepeatedPtrEntityDynamicFieldInfoBase;
1124   friend class Message;
1125   friend class MessageLayoutInspector;
1126   friend class AssignDescriptorsHelper;
1127   friend class DynamicMessageFactory;
1128   friend class GeneratedMessageReflectionTestHelper;
1129   friend class python::MapReflectionFriend;
1130   friend class python::MessageReflectionFriend;
1131   friend class util::MessageDifferencer;
1132 #define GOOGLE_PROTOBUF_HAS_CEL_MAP_REFLECTION_FRIEND
1133   friend class expr::CelMapReflectionFriend;
1134   friend class internal::MapFieldReflectionTest;
1135   friend class internal::MapKeySorter;
1136   friend class internal::MessageUtil;
1137   friend class internal::WireFormat;
1138   friend class internal::ReflectionOps;
1139   friend class internal::SwapFieldHelper;
1140   template <bool is_oneof>
1141   friend struct internal::DynamicFieldInfoHelper;
1142   friend struct internal::FuzzPeer;
1143   // Needed for implementing text format for map.
1144   friend class internal::MapFieldPrinterHelper;
1145 
1146   Reflection(const Descriptor* descriptor,
1147              const internal::ReflectionSchema& schema,
1148              const DescriptorPool* pool, MessageFactory* factory);
1149 
1150   // Special version for specialized implementations of string.  We can't
1151   // call MutableRawRepeatedField directly here because we don't have access to
1152   // FieldOptions::* which are defined in descriptor.pb.h.  Including that
1153   // file here is not possible because it would cause a circular include cycle.
1154   const void* GetRawRepeatedString(const Message& message,
1155                                    const FieldDescriptor* field,
1156                                    bool is_string) const;
1157   void* MutableRawRepeatedString(Message* message, const FieldDescriptor* field,
1158                                  bool is_string) const;
1159 
1160   friend class MapReflectionTester;
1161   friend class internal::v2::V2TableGenTester;
1162 
1163   // Returns true if key is in map. Returns false if key is not in map field.
1164   bool ContainsMapKey(const Message& message, const FieldDescriptor* field,
1165                       const MapKey& key) const;
1166 
1167   // If key is in map field: Saves the value pointer to val and returns
1168   // false. If key in not in map field: Insert the key into map, saves
1169   // value pointer to val and returns true. Users are able to modify the
1170   // map value by MapValueRef.
1171   bool InsertOrLookupMapValue(Message* message, const FieldDescriptor* field,
1172                               const MapKey& key, MapValueRef* val) const;
1173 
1174   // If key is in map field: Saves the value pointer to val and returns true.
1175   // Returns false if key is not in map field. Users are NOT able to modify
1176   // the value by MapValueConstRef.
1177   bool LookupMapValue(const Message& message, const FieldDescriptor* field,
1178                       const MapKey& key, MapValueConstRef* val) const;
1179   bool LookupMapValue(const Message&, const FieldDescriptor*, const MapKey&,
1180                       MapValueRef*) const = delete;
1181 
1182   // Delete and returns true if key is in the map field. Returns false
1183   // otherwise.
1184   bool DeleteMapValue(Message* message, const FieldDescriptor* field,
1185                       const MapKey& key) const;
1186 
1187   // Returns a MapIterator referring to the first element in the map field.
1188   // If the map field is empty, this function returns the same as
1189   // reflection::MapEnd. Mutation to the field may invalidate the iterator.
1190   MapIterator MapBegin(Message* message, const FieldDescriptor* field) const;
1191 
1192   // Returns a MapIterator referring to the theoretical element that would
1193   // follow the last element in the map field. It does not point to any
1194   // real element. Mutation to the field may invalidate the iterator.
1195   MapIterator MapEnd(Message* message, const FieldDescriptor* field) const;
1196 
1197   // Returns a ConstMapIterator referring to the first element in the map field.
1198   // If the map field is empty, this function returns the same as
1199   // reflection::ConstMapEnd. Mutation to the field may invalidate the iterator.
1200   ConstMapIterator ConstMapBegin(const Message* message,
1201                                  const FieldDescriptor* field) const;
1202 
1203   // Returns a ConstMapIterator referring to the theoretical element that would
1204   // follow the last element in the map field. It does not point to any
1205   // real element. Mutation to the field may invalidate the iterator.
1206   ConstMapIterator ConstMapEnd(const Message* message,
1207                                const FieldDescriptor* field) const;
1208 
1209   // Get the number of <key, value> pair of a map field. The result may be
1210   // different from FieldSize which can have duplicate keys.
1211   int MapSize(const Message& message, const FieldDescriptor* field) const;
1212 
1213   // Help method for MapIterator.
1214   template <bool>
1215   friend class MapIteratorBase;
1216   friend class WireFormatForMapFieldTest;
1217   internal::MapFieldBase* MutableMapData(Message* message,
1218                                          const FieldDescriptor* field) const;
1219 
1220   const internal::MapFieldBase* GetMapData(const Message& message,
1221                                            const FieldDescriptor* field) const;
1222 
1223   // Check that the type passed for the unsafe cast matches what we expect from
1224   // the field.
1225   // This makes it easier to catch bugs in callers.
1226   template <typename T>
1227   void VerifyFieldType(const FieldDescriptor* field) const;
1228 
1229   template <typename Type>
1230   const Type& GetRaw(const Message& message,
1231                      const FieldDescriptor* field) const;
1232 
1233   void* MutableRawSplitImpl(Message* message,
1234                             const FieldDescriptor* field) const;
1235 
1236   template <typename Type>
1237   Type* MutableRaw(Message* message, const FieldDescriptor* field) const;
1238 
1239   template <typename Type>
1240   const Type& DefaultRaw(const FieldDescriptor* field) const;
1241 
1242   const Message* GetDefaultMessageInstance(const FieldDescriptor* field) const;
1243 
1244   const uint32_t* GetHasBits(const Message& message) const;
1245   inline uint32_t* MutableHasBits(Message* message) const;
1246   uint32_t GetOneofCase(const Message& message,
1247                         const OneofDescriptor* oneof_descriptor) const;
1248   inline uint32_t* MutableOneofCase(
1249       Message* message, const OneofDescriptor* oneof_descriptor) const;
1250   inline bool HasExtensionSet(const Message& /* message */) const {
1251     return schema_.HasExtensionSet();
1252   }
1253   const internal::ExtensionSet& GetExtensionSet(const Message& message) const;
1254   internal::ExtensionSet* MutableExtensionSet(Message* message) const;
1255 
1256   const internal::InternalMetadata& GetInternalMetadata(
1257       const Message& message) const {
1258     return message._internal_metadata_;
1259   }
1260 
1261   internal::InternalMetadata* MutableInternalMetadata(Message* message) const {
1262     return &message->_internal_metadata_;
1263   }
1264 
1265   inline bool IsInlined(const FieldDescriptor* field) const {
1266     return schema_.IsFieldInlined(field);
1267   }
1268 
1269   inline bool IsMicroString(const FieldDescriptor* field) const {
1270     return schema_.IsFieldMicroString(field);
1271   }
1272 
1273   // For "proto3 non-optional" primitive fields, aka implicit-presence fields,
1274   // returns true if the field is populated, i.e., nonzero. False otherwise.
1275   bool IsSingularFieldNonEmpty(const Message& message,
1276                                const FieldDescriptor* field) const;
1277   // Returns whether the field is present if there are usable hasbits in the
1278   // field schema. (Note that in some cases hasbits are merely a hint to
1279   // indicate "possible presence", and another empty-check is required).
1280   bool IsFieldPresentGivenHasbits(const Message& message,
1281                                   const FieldDescriptor* field,
1282                                   const uint32_t* hasbits,
1283                                   uint32_t hasbit_index) const;
1284   // Returns true if the field is considered to be present.
1285   // Requires the input to be 'singular' i.e. non-extension, non-oneof, non-weak
1286   // field.
1287   // For explicit presence fields, a field is present iff the hasbit is set.
1288   // For implicit presence fields, a field is present iff it is nonzero.
1289   bool HasFieldSingular(const Message& message,
1290                         const FieldDescriptor* field) const;
1291   void SetHasBit(Message* message, const FieldDescriptor* field) const;
1292   inline void ClearHasBit(Message* message, const FieldDescriptor* field) const;
1293   // Naively swaps the hasbit without checking for field existence.
1294   // For explicit presence fields, the hasbit is swapped normally.
1295   // For implicit presence fields, the hasbit is swapped without checking for
1296   // field emptiness. That is, the destination message may have hasbit set even
1297   // if the field is empty. This should still result in correct behaviour due to
1298   // HasbitMode being set to kHintHasbits for implicit presence fields.
1299   inline void NaiveSwapHasBit(Message* message1, Message* message2,
1300                               const FieldDescriptor* field) const;
1301 
1302   inline const uint32_t* GetInlinedStringDonatedArray(
1303       const Message& message) const;
1304   inline uint32_t* MutableInlinedStringDonatedArray(Message* message) const;
1305   inline bool IsInlinedStringDonated(const Message& message,
1306                                      const FieldDescriptor* field) const;
1307   inline void SwapInlinedStringDonated(Message* lhs, Message* rhs,
1308                                        const FieldDescriptor* field) const;
1309 
1310   // Returns the `_split_` pointer. Requires: IsSplit() == true.
1311   inline const void* GetSplitField(const Message* message) const;
1312   // Returns the address of the `_split_` pointer. Requires: IsSplit() == true.
1313   inline void** MutableSplitField(Message* message) const;
1314 
1315   // Allocate the split instance if needed.
1316   void PrepareSplitMessageForWrite(Message* message) const;
1317 
1318   // Shallow-swap fields listed in fields vector of two messages. It is the
1319   // caller's responsibility to make sure shallow swap is safe.
1320   void UnsafeShallowSwapFields(
1321       Message* message1, Message* message2,
1322       const std::vector<const FieldDescriptor*>& fields) const;
1323 
1324   // This function only swaps the field. Should swap corresponding has_bit
1325   // before or after using this function.
1326   void SwapField(Message* message1, Message* message2,
1327                  const FieldDescriptor* field) const;
1328 
1329   // Unsafe but shallow version of SwapField.
1330   void UnsafeShallowSwapField(Message* message1, Message* message2,
1331                               const FieldDescriptor* field) const;
1332 
1333   template <bool unsafe_shallow_swap>
1334   void SwapFieldsImpl(Message* message1, Message* message2,
1335                       const std::vector<const FieldDescriptor*>& fields) const;
1336 
1337   template <bool unsafe_shallow_swap, typename FromType, typename ToType>
1338   void InternalMoveOneofField(const FieldDescriptor* field, FromType* from,
1339                               ToType* to) const;
1340 
1341   template <bool unsafe_shallow_swap>
1342   void SwapOneofField(Message* lhs, Message* rhs,
1343                       const OneofDescriptor* oneof_descriptor) const;
1344 
1345   void InternalSwap(Message* lhs, Message* rhs) const;
1346 
1347   inline bool HasOneofField(const Message& message,
1348                             const FieldDescriptor* field) const;
1349   inline void SetOneofCase(Message* message,
1350                            const FieldDescriptor* field) const;
1351   void ClearOneofField(Message* message, const FieldDescriptor* field) const;
1352 
1353   template <typename Type>
1354   inline const Type& GetField(const Message& message,
1355                               const FieldDescriptor* field) const;
1356   template <typename Type>
1357   inline void SetField(Message* message, const FieldDescriptor* field,
1358                        const Type& value) const;
1359   template <typename Type>
1360   inline Type* MutableField(Message* message,
1361                             const FieldDescriptor* field) const;
1362   template <typename Type>
1363   inline const Type& GetRepeatedField(const Message& message,
1364                                       const FieldDescriptor* field,
1365                                       int index) const;
1366   template <typename Type>
1367   inline const Type& GetRepeatedPtrField(const Message& message,
1368                                          const FieldDescriptor* field,
1369                                          int index) const;
1370   template <typename Type>
1371   inline void SetRepeatedField(Message* message, const FieldDescriptor* field,
1372                                int index, Type value) const;
1373   template <typename Type>
1374   inline Type* MutableRepeatedField(Message* message,
1375                                     const FieldDescriptor* field,
1376                                     int index) const;
1377   template <typename Type>
1378   inline void AddField(Message* message, const FieldDescriptor* field,
1379                        const Type& value) const;
1380   template <typename Type>
1381   inline Type* AddField(Message* message, const FieldDescriptor* field) const;
1382 
1383   int GetExtensionNumberOrDie(const Descriptor* type) const;
1384 
1385   // Internal versions of EnumValue API perform no checking. Called after checks
1386   // by public methods.
1387   void SetEnumValueInternal(Message* message, const FieldDescriptor* field,
1388                             int value) const;
1389   void SetRepeatedEnumValueInternal(Message* message,
1390                                     const FieldDescriptor* field, int index,
1391                                     int value) const;
1392   void AddEnumValueInternal(Message* message, const FieldDescriptor* field,
1393                             int value) const;
1394 
1395   friend inline const char* ParseLenDelim(int field_number,
1396                                           const FieldDescriptor* field,
1397                                           Message* msg,
1398                                           const Reflection* reflection,
1399                                           const char* ptr,
1400                                           internal::ParseContext* ctx);
1401   friend inline const char* ParsePackedField(const FieldDescriptor* field,
1402                                              Message* msg,
1403                                              const Reflection* reflection,
1404                                              const char* ptr,
1405                                              internal::ParseContext* ctx);
1406 };
1407 
1408 extern template void Reflection::SwapFieldsImpl<true>(
1409     Message* message1, Message* message2,
1410     const std::vector<const FieldDescriptor*>& fields) const;
1411 
1412 extern template void Reflection::SwapFieldsImpl<false>(
1413     Message* message1, Message* message2,
1414     const std::vector<const FieldDescriptor*>& fields) const;
1415 
1416 // Abstract interface for a factory for message objects.
1417 //
1418 // The thread safety for this class is implementation dependent, see comments
1419 // around GetPrototype for details
1420 class PROTOBUF_EXPORT MessageFactory {
1421  public:
1422   inline MessageFactory() = default;
1423   MessageFactory(const MessageFactory&) = delete;
1424   MessageFactory& operator=(const MessageFactory&) = delete;
1425   virtual ~MessageFactory();
1426 
1427   // Given a Descriptor, gets or constructs the default (prototype) Message
1428   // of that type.  You can then call that message's New() method to construct
1429   // a mutable message of that type.
1430   //
1431   // Calling this method twice with the same Descriptor returns the same
1432   // object.  The returned object remains property of the factory.  Also, any
1433   // objects created by calling the prototype's New() method share some data
1434   // with the prototype, so these must be destroyed before the MessageFactory
1435   // is destroyed.
1436   //
1437   // The given descriptor must outlive the returned message, and hence must
1438   // outlive the MessageFactory.
1439   //
1440   // Some implementations do not support all types.  GetPrototype() will
1441   // return nullptr if the descriptor passed in is not supported.
1442   //
1443   // This method may or may not be thread-safe depending on the implementation.
1444   // Each implementation should document its own degree thread-safety.
1445   virtual const Message* GetPrototype(const Descriptor* type) = 0;
1446 
1447   // Gets a MessageFactory which supports all generated, compiled-in messages.
1448   // In other words, for any compiled-in type FooMessage, the following is true:
1449   //   MessageFactory::generated_factory()->GetPrototype(
1450   //     FooMessage::descriptor()) == FooMessage::default_instance()
1451   // This factory supports all types which are found in
1452   // DescriptorPool::generated_pool().  If given a descriptor from any other
1453   // pool, GetPrototype() will return nullptr.  (You can also check if a
1454   // descriptor is for a generated message by checking if
1455   // descriptor->file()->pool() == DescriptorPool::generated_pool().)
1456   //
1457   // This factory is 100% thread-safe; calling GetPrototype() does not modify
1458   // any shared data.
1459   //
1460   // This factory is a singleton.  The caller must not delete the object.
1461   static MessageFactory* generated_factory();
1462 
1463   // For internal use only:  Registers a .proto file at static initialization
1464   // time, to be placed in generated_factory.  The first time GetPrototype()
1465   // is called with a descriptor from this file, |register_messages| will be
1466   // called, with the file name as the parameter.  It must call
1467   // InternalRegisterGeneratedMessage() (below) to register each message type
1468   // in the file.  This strange mechanism is necessary because descriptors are
1469   // built lazily, so we can't register types by their descriptor until we
1470   // know that the descriptor exists.  |filename| must be a permanent string.
1471   static void InternalRegisterGeneratedFile(
1472       const google::protobuf::internal::DescriptorTable* table);
1473 
1474   // For internal use only:  Registers a message type.  Called only by the
1475   // functions which are registered with InternalRegisterGeneratedFile(),
1476   // above.
1477   static void InternalRegisterGeneratedMessage(const Descriptor* descriptor,
1478                                                const Message* prototype);
1479 
1480 
1481  private:
1482   friend class DynamicMessageFactory;
1483   static const Message* TryGetGeneratedPrototype(const Descriptor* type);
1484 };
1485 
1486 #define DECLARE_GET_REPEATED_FIELD(TYPE)                           \
1487   template <>                                                      \
1488   PROTOBUF_EXPORT const RepeatedField<TYPE>&                       \
1489   Reflection::GetRepeatedFieldInternal<TYPE>(                      \
1490       const Message& message, const FieldDescriptor* field) const; \
1491                                                                    \
1492   template <>                                                      \
1493   PROTOBUF_EXPORT RepeatedField<TYPE>*                             \
1494   Reflection::MutableRepeatedFieldInternal<TYPE>(                  \
1495       Message * message, const FieldDescriptor* field) const;
1496 
1497 DECLARE_GET_REPEATED_FIELD(int32_t)
1498 DECLARE_GET_REPEATED_FIELD(int64_t)
1499 DECLARE_GET_REPEATED_FIELD(uint32_t)
1500 DECLARE_GET_REPEATED_FIELD(uint64_t)
1501 DECLARE_GET_REPEATED_FIELD(float)
1502 DECLARE_GET_REPEATED_FIELD(double)
1503 DECLARE_GET_REPEATED_FIELD(bool)
1504 
1505 #undef DECLARE_GET_REPEATED_FIELD
1506 
1507 // Call this function to ensure that this message's reflection is linked into
1508 // the binary:
1509 //
1510 //   google::protobuf::LinkMessageReflection<pkg::FooMessage>();
1511 //
1512 // This will ensure that the following lookup will succeed:
1513 //
1514 //   DescriptorPool::generated_pool()->FindMessageTypeByName("pkg.FooMessage");
1515 //
1516 // As a side-effect, it will also guarantee that anything else from the same
1517 // .proto file will also be available for lookup in the generated pool.
1518 //
1519 // This function does not actually register the message, so it does not need
1520 // to be called before the lookup.  However it does need to occur in a function
1521 // that cannot be stripped from the binary (ie. it must be reachable from main).
1522 //
1523 // Best practice is to call this function as close as possible to where the
1524 // reflection is actually needed.  This function is very cheap to call, so you
1525 // should not need to worry about its runtime overhead except in the tightest
1526 // of loops (on x86-64 it compiles into two "mov" instructions).
1527 template <typename T>
1528 void LinkMessageReflection() {
1529   internal::StrongReferenceToType<T>();
1530 }
1531 
1532 // Specializations to handle cast to `Message`. We can check the `is_lite` bit
1533 // in the class data.
1534 template <>
1535 inline const Message* DynamicCastMessage(const MessageLite* from) {
1536   return from == nullptr || internal::GetClassData(*from)->is_lite
1537              ? nullptr
1538              : static_cast<const Message*>(from);
1539 }
1540 template <>
1541 inline const Message* DownCastMessage(const MessageLite* from) {
1542   ABSL_DCHECK_EQ(DynamicCastMessage<Message>(from), from)
1543       << "Cannot downcast " << from->GetTypeName() << " to Message";
1544   return static_cast<const Message*>(from);
1545 }
1546 
1547 // =============================================================================
1548 // Implementation details for {Get,Mutable}RawRepeatedPtrField.  We provide
1549 // specializations for <std::string>, <StringPieceField> and <Message> and
1550 // handle everything else with the default template which will match any type
1551 // having a method with signature "static const google::protobuf::Descriptor*
1552 // descriptor()". Such a type presumably is a descendant of google::protobuf::Message.
1553 
1554 template <>
1555 inline const RepeatedPtrField<std::string>&
1556 Reflection::GetRepeatedPtrFieldInternal<std::string>(
1557     const Message& message, const FieldDescriptor* field) const {
1558   return *static_cast<const RepeatedPtrField<std::string>*>(
1559       GetRawRepeatedString(message, field, true));
1560 }
1561 
1562 template <>
1563 inline RepeatedPtrField<std::string>*
1564 Reflection::MutableRepeatedPtrFieldInternal<std::string>(
1565     Message* message, const FieldDescriptor* field) const {
1566   return static_cast<RepeatedPtrField<std::string>*>(
1567       MutableRawRepeatedString(message, field, true));
1568 }
1569 
1570 
1571 // -----
1572 
1573 template <>
1574 inline const RepeatedPtrField<Message>& Reflection::GetRepeatedPtrFieldInternal(
1575     const Message& message, const FieldDescriptor* field) const {
1576   return *static_cast<const RepeatedPtrField<Message>*>(GetRawRepeatedField(
1577       message, field, FieldDescriptor::CPPTYPE_MESSAGE, -1, nullptr));
1578 }
1579 
1580 template <>
1581 inline RepeatedPtrField<Message>* Reflection::MutableRepeatedPtrFieldInternal(
1582     Message* message, const FieldDescriptor* field) const {
1583   return static_cast<RepeatedPtrField<Message>*>(MutableRawRepeatedField(
1584       message, field, FieldDescriptor::CPPTYPE_MESSAGE, -1, nullptr));
1585 }
1586 
1587 template <typename PB>
1588 inline const RepeatedPtrField<PB>& Reflection::GetRepeatedPtrFieldInternal(
1589     const Message& message, const FieldDescriptor* field) const {
1590   return *static_cast<const RepeatedPtrField<PB>*>(
1591       GetRawRepeatedField(message, field, FieldDescriptor::CPPTYPE_MESSAGE, -1,
1592                           PB::default_instance().GetDescriptor()));
1593 }
1594 
1595 template <typename PB>
1596 inline RepeatedPtrField<PB>* Reflection::MutableRepeatedPtrFieldInternal(
1597     Message* message, const FieldDescriptor* field) const {
1598   return static_cast<RepeatedPtrField<PB>*>(
1599       MutableRawRepeatedField(message, field, FieldDescriptor::CPPTYPE_MESSAGE,
1600                               -1, PB::default_instance().GetDescriptor()));
1601 }
1602 
1603 template <typename Type>
1604 const Type& Reflection::DefaultRaw(const FieldDescriptor* field) const {
1605   return *reinterpret_cast<const Type*>(schema_.GetFieldDefault(field));
1606 }
1607 
1608 bool Reflection::HasOneofField(const Message& message,
1609                                const FieldDescriptor* field) const {
1610   return (GetOneofCase(message, field->containing_oneof()) ==
1611           static_cast<uint32_t>(field->number()));
1612 }
1613 
1614 const void* Reflection::GetSplitField(const Message* message) const {
1615   ABSL_DCHECK(schema_.IsSplit());
1616   return *internal::GetConstPointerAtOffset<void*>(message,
1617                                                    schema_.SplitOffset());
1618 }
1619 
1620 void** Reflection::MutableSplitField(Message* message) const {
1621   ABSL_DCHECK(schema_.IsSplit());
1622   return internal::GetPointerAtOffset<void*>(message, schema_.SplitOffset());
1623 }
1624 
1625 namespace internal {
1626 
1627 // In some cases, (Get|Mutable)Raw may be called with a type that is different
1628 // from the final type; e.g. char. As a defensive coding to this unfortunate
1629 // practices, we should only assume extra indirection (or a lack thereof) for
1630 // the well known, complex types.
1631 template <typename T>
1632 bool SplitFieldHasExtraIndirectionStatic(const FieldDescriptor* field) {
1633   if (std::is_base_of<RepeatedFieldBase, T>() ||
1634       std::is_base_of<RepeatedPtrFieldBase, T>()) {
1635     ABSL_DCHECK(SplitFieldHasExtraIndirection(field));
1636     return true;
1637   } else if (std::is_base_of<MessageLite, T>()) {
1638     ABSL_DCHECK(!SplitFieldHasExtraIndirection(field));
1639     return false;
1640   }
1641   return SplitFieldHasExtraIndirection(field);
1642 }
1643 
1644 inline void MaybePoisonAfterClear(Message* root) {
1645   if (root == nullptr) return;
1646   if constexpr (HasMemoryPoisoning()) {
1647     const Reflection* reflection = root->GetReflection();
1648     reflection->MaybePoisonAfterClear(*root);
1649   } else {
1650     root->Clear();
1651   }
1652 }
1653 
1654 template <typename T>
1655 inline constexpr std::false_type IsRepeatedT{};
1656 template <typename T>
1657 inline constexpr std::true_type IsRepeatedT<RepeatedField<T>>{};
1658 template <typename T>
1659 inline constexpr std::true_type IsRepeatedT<RepeatedPtrField<T>>{};
1660 template <>
1661 inline constexpr std::true_type IsRepeatedT<internal::RepeatedPtrFieldBase>{};
1662 template <>
1663 inline constexpr std::true_type IsRepeatedT<internal::MapFieldBase>{};
1664 
1665 template <typename T>
1666 constexpr FieldDescriptor::CppType GetCppType() {
1667   if constexpr (IsRepeatedT<T>) {
1668     return GetCppType<typename T::value_type>();
1669   } else {
1670     if (std::is_same_v<T, int32_t>) return FieldDescriptor::CPPTYPE_INT32;
1671     if (std::is_same_v<T, int64_t>) return FieldDescriptor::CPPTYPE_INT64;
1672     if (std::is_same_v<T, uint32_t>) return FieldDescriptor::CPPTYPE_UINT32;
1673     if (std::is_same_v<T, uint64_t>) return FieldDescriptor::CPPTYPE_UINT64;
1674     if (std::is_same_v<T, float>) return FieldDescriptor::CPPTYPE_FLOAT;
1675     if (std::is_same_v<T, double>) return FieldDescriptor::CPPTYPE_DOUBLE;
1676     if (std::is_same_v<T, bool>) return FieldDescriptor::CPPTYPE_BOOL;
1677 
1678     using PCV = std::remove_cv_t<std::remove_pointer_t<T>>;
1679 
1680     // strings
1681     if (std::is_same_v<PCV, internal::ArenaStringPtr> ||
1682         std::is_same_v<PCV, std::string> ||
1683         std::is_same_v<PCV, internal::MicroString> ||
1684         std::is_same_v<PCV, absl::Cord>) {
1685       return FieldDescriptor::CPPTYPE_STRING;
1686     }
1687 
1688     // messages
1689     if (std::is_same_v<PCV, Message> ||      //
1690         std::is_same_v<PCV, MessageLite> ||  //
1691         std::is_same_v<PCV, internal::LazyField>) {
1692       return FieldDescriptor::CPPTYPE_MESSAGE;
1693     }
1694   }
1695 
1696   // Return an invalid type to make the caller fail with a nice error message in
1697   // case we missed something.
1698   return FieldDescriptor::CppType{};
1699 }
1700 
1701 }  // namespace internal
1702 
1703 template <typename T>
1704 void Reflection::VerifyFieldType(const FieldDescriptor* field) const {
1705   if constexpr (!internal::PerformDebugChecks()) {
1706     return;
1707   }
1708   if constexpr (std::is_const_v<T>) {
1709     return VerifyFieldType<std::remove_const_t<T>>(field);
1710   }
1711 
1712   // `char` and `void` are used in places where we don't know the type yet.
1713   if constexpr (std::is_same_v<T, char> || std::is_same_v<T, void>) {
1714     return;
1715   }
1716 
1717   const auto error = [&] {
1718     return absl::StrFormat("Invalid cast of %s to type %s.", field->full_name(),
1719                            internal::RttiTypeName<T>().value_or("unknown"));
1720   };
1721 
1722   ABSL_DCHECK_EQ(field->is_repeated(), internal::IsRepeatedT<T>) << error();
1723   if constexpr (std::is_same_v<T, internal::MapFieldBase>) {
1724     ABSL_DCHECK(field->is_map()) << error();
1725   } else if constexpr (std::is_same_v<T, internal::RepeatedPtrFieldBase>) {
1726     // It has to be string or message.
1727     ABSL_DCHECK(field->cpp_type() == field->CPPTYPE_STRING ||
1728                 field->cpp_type() == field->CPPTYPE_MESSAGE)
1729         << error();
1730   } else {
1731     auto cpp_type = field->cpp_type();
1732     // Collapse ENUM to INT32 because they are the same through reflection.
1733     if (cpp_type == field->CPPTYPE_ENUM) cpp_type = field->CPPTYPE_INT32;
1734     ABSL_DCHECK_EQ(+cpp_type, +internal::GetCppType<T>()) << error();
1735 
1736     // Check subfield types for message.
1737     if constexpr (internal::GetCppType<T>() ==
1738                   FieldDescriptor::CPPTYPE_MESSAGE) {
1739       // Singular/oneof messages are by pointer, except non-oneof Lazy.
1740       if (!field->is_repeated() &&
1741           (!IsLazyField(field) || field->real_containing_oneof() != nullptr)) {
1742         ABSL_DCHECK(std::is_pointer_v<T>) << error();
1743       }
1744     }
1745 
1746     // Check subfield types for string.
1747     if constexpr (internal::GetCppType<T>() ==
1748                   FieldDescriptor::CPPTYPE_STRING) {
1749       switch (field->cpp_string_type()) {
1750         case FieldDescriptor::CppStringType::kView:
1751         case FieldDescriptor::CppStringType::kString:
1752           if (IsMicroString(field)) {
1753             ABSL_DCHECK((std::is_same_v<T, internal::MicroString>)) << error();
1754           } else {
1755             ABSL_DCHECK((std::is_same_v<T, internal::ArenaStringPtr> ||
1756                          std::is_same_v<T, RepeatedPtrField<std::string>>))
1757                 << error();
1758           }
1759           break;
1760         case FieldDescriptor::CppStringType::kCord:
1761           if (field->real_containing_oneof() != nullptr) {
1762             ABSL_DCHECK((std::is_same_v<T, absl::Cord*>)) << error();
1763           } else {
1764             ABSL_DCHECK((std::is_same_v<T, absl::Cord> ||
1765                          std::is_same_v<T, RepeatedField<absl::Cord>>))
1766                 << error();
1767           }
1768           break;
1769       }
1770     }
1771   }
1772 }
1773 
1774 template <typename Type>
1775 const Type& Reflection::GetRaw(const Message& message,
1776                                const FieldDescriptor* field) const {
1777   VerifyFieldType<Type>(field);
1778 
1779   const uint32_t field_offset = schema_.GetFieldOffset<Type>(field);
1780 
1781   if (ABSL_PREDICT_FALSE(schema_.IsSplit(field))) {
1782     ABSL_DCHECK(!schema_.InRealOneof(field))
1783         << "Field = " << field->full_name();
1784 
1785     const void* split = GetSplitField(&message);
1786     if (internal::SplitFieldHasExtraIndirectionStatic<Type>(field)) {
1787       return **internal::GetConstPointerAtOffset<Type*>(split, field_offset);
1788     }
1789     return *internal::GetConstPointerAtOffset<Type>(split, field_offset);
1790   }
1791   return internal::GetConstRefAtOffset<Type>(message, field_offset);
1792 }
1793 
1794 template <typename T>
1795 RepeatedFieldRef<T> Reflection::GetRepeatedFieldRef(
1796     const Message& message, const FieldDescriptor* field) const {
1797   ABSL_DCHECK_EQ(message.GetReflection(), this);
1798   return RepeatedFieldRef<T>(message, field);
1799 }
1800 
1801 template <typename T>
1802 MutableRepeatedFieldRef<T> Reflection::GetMutableRepeatedFieldRef(
1803     Message* message, const FieldDescriptor* field) const {
1804   ABSL_DCHECK_EQ(message->GetReflection(), this);
1805   return MutableRepeatedFieldRef<T>(message, field);
1806 }
1807 
1808 template <typename Type>
1809 Type* Reflection::MutableRaw(Message* message,
1810                              const FieldDescriptor* field) const {
1811   VerifyFieldType<Type>(field);
1812 
1813   if (ABSL_PREDICT_FALSE(schema_.IsSplit(field))) {
1814     return reinterpret_cast<Type*>(MutableRawSplitImpl(message, field));
1815   }
1816 
1817   const uint32_t field_offset = schema_.GetFieldOffset<Type>(field);
1818   return internal::GetPointerAtOffset<Type>(message, field_offset);
1819 }
1820 
1821 
1822 }  // namespace protobuf
1823 }  // namespace google
1824 
1825 #include "google/protobuf/port_undef.inc"
1826 
1827 #endif  // GOOGLE_PROTOBUF_MESSAGE_H__