Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-09-25 09:15:31

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 // This header is logically internal, but is made public because it is used
0013 // from protocol-compiler-generated code, which may reside in other components.
0014 
0015 #ifndef GOOGLE_PROTOBUF_EXTENSION_SET_H__
0016 #define GOOGLE_PROTOBUF_EXTENSION_SET_H__
0017 
0018 #include <algorithm>
0019 #include <atomic>
0020 #include <cassert>
0021 #include <cstddef>
0022 #include <cstdint>
0023 #include <initializer_list>
0024 #include <string>
0025 #include <tuple>
0026 #include <type_traits>
0027 #include <utility>
0028 #include <variant>
0029 #include <vector>
0030 
0031 #include "google/protobuf/stubs/common.h"
0032 #include "absl/base/casts.h"
0033 #include "absl/base/prefetch.h"
0034 #include "absl/container/btree_map.h"
0035 #include "absl/log/absl_check.h"
0036 #include "absl/strings/string_view.h"
0037 #include "google/protobuf/generated_enum_util.h"
0038 #include "google/protobuf/generated_message_tctable_decl.h"
0039 #include "google/protobuf/internal_visibility.h"
0040 #include "google/protobuf/port.h"
0041 #include "google/protobuf/io/coded_stream.h"
0042 #include "google/protobuf/message_lite.h"
0043 #include "google/protobuf/parse_context.h"
0044 #include "google/protobuf/repeated_field.h"
0045 #include "google/protobuf/repeated_ptr_field.h"
0046 #include "google/protobuf/wire_format_lite.h"
0047 
0048 // clang-format off
0049 #include "google/protobuf/port_def.inc"  // Must be last
0050 // clang-format on
0051 
0052 #ifdef SWIG
0053 #error "You cannot SWIG proto headers"
0054 #endif
0055 
0056 
0057 namespace google {
0058 namespace protobuf {
0059 class Arena;
0060 class Descriptor;       // descriptor.h
0061 class FieldDescriptor;  // descriptor.h
0062 class DescriptorPool;   // descriptor.h
0063 class MessageLite;      // message_lite.h
0064 class Message;          // message.h
0065 class MessageFactory;   // message.h
0066 class Reflection;       // message.h
0067 class UnknownFieldSet;  // unknown_field_set.h
0068 class FeatureSet;
0069 namespace internal {
0070 struct DescriptorTable;
0071 class FieldSkipper;     // wire_format_lite.h
0072 class ReflectionVisit;  // message_reflection_util.h
0073 class WireFormat;
0074 struct DynamicExtensionInfoHelper;
0075 void InitializeLazyExtensionSet();
0076 }  // namespace internal
0077 }  // namespace protobuf
0078 }  // namespace google
0079 namespace pb {
0080 class CppFeatures;
0081 namespace internal {
0082 // Forward-declares the function for FeatureSet extensions to make it visible
0083 // to the internal feature helper. It should hold and return serialized
0084 // FeatureSetDefaults data.
0085 template <class T>
0086 inline ::absl::string_view GetFeatureSetDefaultsData();
0087 }  // namespace internal
0088 }  // namespace pb
0089 
0090 namespace google {
0091 namespace protobuf {
0092 namespace internal {
0093 
0094 class InternalMetadata;
0095 
0096 namespace v2 {
0097 class TableDrivenMessage;
0098 }  // namespace v2
0099 
0100 // Used to store values of type WireFormatLite::FieldType without having to
0101 // #include wire_format_lite.h.  Also, ensures that we use only one byte to
0102 // store these values, which is important to keep the layout of
0103 // ExtensionSet::Extension small.
0104 typedef uint8_t FieldType;
0105 
0106 // Version of the above which takes an argument.  This is needed to deal with
0107 // extensions that are not compiled in.
0108 typedef bool EnumValidityFuncWithArg(const void* arg, int number);
0109 
0110 enum class LazyAnnotation : int8_t {
0111   kUndefined = 0,
0112   kLazy = 1,
0113   kEager = 2,
0114 };
0115 
0116 // Information about a registered extension.
0117 struct ExtensionInfo {
0118   constexpr ExtensionInfo() : enum_validity_check() {}
0119   constexpr ExtensionInfo(const MessageLite* extendee, int param_number,
0120                           FieldType type_param, bool isrepeated, bool ispacked)
0121       : message(extendee),
0122         number(param_number),
0123         type(type_param),
0124         is_repeated(isrepeated),
0125         is_packed(ispacked),
0126         enum_validity_check() {}
0127   constexpr ExtensionInfo(const MessageLite* extendee, int param_number,
0128                           FieldType type_param, bool isrepeated, bool ispacked,
0129                           LazyEagerVerifyFnType verify_func,
0130                           LazyAnnotation islazy = LazyAnnotation::kUndefined)
0131       : message(extendee),
0132         number(param_number),
0133         type(type_param),
0134         is_repeated(isrepeated),
0135         is_packed(ispacked),
0136         is_lazy(islazy),
0137         enum_validity_check(),
0138         lazy_eager_verify_func(verify_func) {}
0139 
0140   const MessageLite* message = nullptr;
0141   int number = 0;
0142 
0143   FieldType type = 0;
0144   bool is_repeated = false;
0145   bool is_packed = false;
0146   LazyAnnotation is_lazy = LazyAnnotation::kUndefined;
0147 
0148   struct EnumValidityCheck {
0149     // TODO: Fully remove the function pointer approach.
0150     EnumValidityFuncWithArg* func;
0151     const void* arg;
0152 
0153     bool IsValid(int value) const {
0154       return func != nullptr ? func(arg, value)
0155                              : internal::ValidateEnum(
0156                                    value, static_cast<const uint32_t*>(arg));
0157     }
0158   };
0159 
0160   struct MessageInfo {
0161     const MessageLite* prototype = nullptr;
0162     // The TcParse table used for this object.
0163     // Never null. (except in platforms that don't constant initialize default
0164     // instances)
0165     const internal::TcParseTableBase* tc_table = nullptr;
0166 
0167     const ClassData* GetClassData() const {
0168 #ifdef PROTOBUF_CONSTINIT_DEFAULT_INSTANCES
0169       return tc_table->class_data;
0170 #else
0171       return google::protobuf::internal::GetClassData(*prototype);
0172 #endif
0173     }
0174   };
0175 
0176   union {
0177     EnumValidityCheck enum_validity_check;
0178     MessageInfo message_info;
0179   };
0180 
0181   // The descriptor for this extension, if one exists and is known.  May be
0182   // nullptr.  Must not be nullptr if the descriptor for the extension does not
0183   // live in the same pool as the descriptor for the containing type.
0184   const FieldDescriptor* descriptor = nullptr;
0185 
0186   // If this field is potentially lazy this function can be used as a cheap
0187   // verification of the raw bytes.
0188   // If nullptr then no verification is performed.
0189   LazyEagerVerifyFnType lazy_eager_verify_func = nullptr;
0190 };
0191 
0192 
0193 // An ExtensionFinder is an object which looks up extension definitions.  It
0194 // must implement this method:
0195 //
0196 // bool Find(int number, ExtensionInfo* output);
0197 
0198 // GeneratedExtensionFinder is an ExtensionFinder which finds extensions
0199 // defined in .proto files which have been compiled into the binary.
0200 class PROTOBUF_EXPORT GeneratedExtensionFinder {
0201  public:
0202   explicit GeneratedExtensionFinder(const MessageLite* extendee)
0203       : extendee_(extendee) {}
0204 
0205   // Returns true and fills in *output if found, otherwise returns false.
0206   bool Find(int number, ExtensionInfo* output);
0207 
0208  private:
0209   const MessageLite* extendee_;
0210 };
0211 
0212 // Note:  extension_set_heavy.cc defines DescriptorPoolExtensionFinder for
0213 // finding extensions from a DescriptorPool.
0214 
0215 // This is an internal helper class intended for use within the protocol buffer
0216 // library and generated classes.  Clients should not use it directly.  Instead,
0217 // use the generated accessors such as GetExtension() of the class being
0218 // extended.
0219 //
0220 // This class manages extensions for a protocol message object.  The
0221 // message's HasExtension(), GetExtension(), MutableExtension(), and
0222 // ClearExtension() methods are just thin wrappers around the embedded
0223 // ExtensionSet.  When parsing, if a tag number is encountered which is
0224 // inside one of the message type's extension ranges, the tag is passed
0225 // off to the ExtensionSet for parsing.  Etc.
0226 class PROTOBUF_EXPORT ExtensionSet {
0227  public:
0228   constexpr ExtensionSet() : ExtensionSet(nullptr) {}
0229   ExtensionSet(const ExtensionSet& rhs) = delete;
0230 
0231   // Arena enabled constructors: for internal use only.
0232   ExtensionSet(internal::InternalVisibility, Arena* arena)
0233       : ExtensionSet(arena) {}
0234 
0235   // TODO: make constructor private, and migrate `ArenaInitialized`
0236   // to `InternalVisibility` overloaded constructor(s).
0237   explicit constexpr ExtensionSet(Arena* arena);
0238   ExtensionSet(ArenaInitialized, Arena* arena) : ExtensionSet(arena) {}
0239 
0240   ExtensionSet& operator=(const ExtensionSet&) = delete;
0241   ~ExtensionSet();
0242 
0243   // These are called at startup by protocol-compiler-generated code to
0244   // register known extensions.  The registrations are used by ParseField()
0245   // to look up extensions for parsed field numbers.  Note that dynamic parsing
0246   // does not use ParseField(); only protocol-compiler-generated parsing
0247   // methods do.
0248   static void RegisterExtension(const MessageLite* extendee, int number,
0249                                 FieldType type, bool is_repeated,
0250                                 bool is_packed);
0251   static void RegisterEnumExtension(const MessageLite* extendee, int number,
0252                                     FieldType type, bool is_repeated,
0253                                     bool is_packed,
0254                                     const uint32_t* validation_data);
0255   static void RegisterMessageExtension(const MessageLite* extendee, int number,
0256                                        FieldType type, bool is_repeated,
0257                                        bool is_packed,
0258                                        const MessageLite* prototype,
0259                                        LazyEagerVerifyFnType verify_func,
0260                                        LazyAnnotation is_lazy);
0261 
0262   // In weak descriptor mode we register extensions in two phases.
0263   // This function determines if it is the right time to register a particular
0264   // extension.
0265   // During "preregistration" we only register extensions that have all their
0266   // types linked in.
0267   struct WeakPrototypeRef {
0268     const internal::DescriptorTable* table;
0269     int index;
0270   };
0271   static bool ShouldRegisterAtThisTime(
0272       std::initializer_list<WeakPrototypeRef> messages,
0273       bool is_preregistration);
0274 
0275   // =================================================================
0276 
0277   // Add all fields which are currently present to the given vector.  This
0278   // is useful to implement Reflection::ListFields(). Descriptors are appended
0279   // in increasing tag order.
0280   void AppendToList(const Descriptor* extendee, const DescriptorPool* pool,
0281                     std::vector<const FieldDescriptor*>* output) const;
0282 
0283   // =================================================================
0284   // Accessors
0285   //
0286   // Generated message classes include type-safe templated wrappers around
0287   // these methods.  Generally you should use those rather than call these
0288   // directly, unless you are doing low-level memory management.
0289   //
0290   // When calling any of these accessors, the extension number requested
0291   // MUST exist in the DescriptorPool provided to the constructor.  Otherwise,
0292   // the method will fail an assert.  Normally, though, you would not call
0293   // these directly; you would either call the generated accessors of your
0294   // message class (e.g. GetExtension()) or you would call the accessors
0295   // of the reflection interface.  In both cases, it is impossible to
0296   // trigger this assert failure:  the generated accessors only accept
0297   // linked-in extension types as parameters, while the Reflection interface
0298   // requires you to provide the FieldDescriptor describing the extension.
0299   //
0300   // When calling any of these accessors, a protocol-compiler-generated
0301   // implementation of the extension corresponding to the number MUST
0302   // be linked in, and the FieldDescriptor used to refer to it MUST be
0303   // the one generated by that linked-in code.  Otherwise, the method will
0304   // die on an assert failure.  The message objects returned by the message
0305   // accessors are guaranteed to be of the correct linked-in type.
0306   //
0307   // These methods pretty much match Reflection except that:
0308   // - They're not virtual.
0309   // - They identify fields by number rather than FieldDescriptors.
0310   // - They identify enum values using integers rather than descriptors.
0311   // - Strings provide Mutable() in addition to Set() accessors.
0312 
0313   bool Has(int number) const;
0314   int ExtensionSize(int number) const;  // Size of a repeated extension.
0315   int NumExtensions() const;            // The number of extensions
0316   FieldType ExtensionType(int number) const;
0317   void ClearExtension(int number);
0318 
0319   // singular fields -------------------------------------------------
0320 
0321   template <typename T>
0322   const T& Get(int number,
0323                const internal::type_identity_t<T>& default_value) const {
0324     const Extension* extension = FindOrNull(number);
0325     if (extension == nullptr || extension->is_cleared) {
0326       return default_value;
0327     } else {
0328       return extension->Get<T>();
0329     }
0330   }
0331 
0332   template <typename T, typename U>
0333   void Set(int number, FieldType type, U&& value,
0334            const FieldDescriptor* descriptor) {
0335     if constexpr (Extension::kUsesPointer<T>) {
0336       Extension& extension =
0337           FindOrCreate(number, type, false, false, descriptor, CreateImpl<T>);
0338       *extension.Mutable<T>() = std::forward<U>(value);
0339     } else {
0340       FindOrCreate(number, type, false, false, descriptor, nullptr)
0341           .Mutable<T>() = std::forward<U>(value);
0342     }
0343   }
0344 
0345   const MessageLite& GetMessage(int number,
0346                                 const MessageLite& default_value) const;
0347   const MessageLite& GetMessage(int number, const Descriptor* message_type,
0348                                 MessageFactory* factory) const;
0349 
0350   // |descriptor| may be nullptr so long as it is known that the descriptor for
0351   // the extension lives in the same pool as the descriptor for the containing
0352   // type.
0353 #define desc const FieldDescriptor* descriptor  // avoid line wrapping
0354   std::string* MutableString(int number, FieldType type, desc);
0355   MessageLite* MutableMessage(int number, FieldType type,
0356                               const MessageLite& prototype, desc);
0357   MessageLite* MutableMessage(const FieldDescriptor* descriptor,
0358                               MessageFactory* factory);
0359   // Adds the given message to the ExtensionSet, taking ownership of the
0360   // message object. Existing message with the same number will be deleted.
0361   // If "message" is nullptr, this is equivalent to "ClearExtension(number)".
0362   void SetAllocatedMessage(int number, FieldType type,
0363                            const FieldDescriptor* descriptor,
0364                            MessageLite* message);
0365   void UnsafeArenaSetAllocatedMessage(int number, FieldType type,
0366                                       const FieldDescriptor* descriptor,
0367                                       MessageLite* message);
0368   [[nodiscard]] MessageLite* ReleaseMessage(int number,
0369                                             const MessageLite& prototype);
0370   MessageLite* UnsafeArenaReleaseMessage(int number,
0371                                          const MessageLite& prototype);
0372 
0373   [[nodiscard]] MessageLite* ReleaseMessage(const FieldDescriptor* descriptor,
0374                                             MessageFactory* factory);
0375   MessageLite* UnsafeArenaReleaseMessage(const FieldDescriptor* descriptor,
0376                                          MessageFactory* factory);
0377 #undef desc
0378   Arena* GetArena() const { return arena_; }
0379 
0380   // repeated fields -------------------------------------------------
0381 
0382   // Fetches a RepeatedField extension by number; returns |default_value|
0383   // if no such extension exists. User should not touch this directly; it is
0384   // used by the GetRepeatedExtension() method.
0385   const void* GetRawRepeatedField(int number, const void* default_value) const;
0386   // Fetches a mutable version of a RepeatedField extension by number,
0387   // instantiating one if none exists. Similar to above, user should not use
0388   // this directly; it underlies MutableRepeatedExtension().
0389   void* MutableRawRepeatedField(int number, FieldType field_type, bool packed,
0390                                 const FieldDescriptor* desc);
0391 
0392   // This is an overload of MutableRawRepeatedField to maintain compatibility
0393   // with old code using a previous API. This version of
0394   // MutableRawRepeatedField() will ABSL_CHECK-fail on a missing extension.
0395   // (E.g.: borg/clients/internal/proto1/proto2_reflection.cc.)
0396   void* MutableRawRepeatedField(int number);
0397 
0398   template <typename T>
0399   const T& GetRepeated(int number, int index) const {
0400     const Extension* extension = FindOrNull(number);
0401     ABSL_CHECK(extension != nullptr) << "Index out-of-bounds (field is empty).";
0402     return extension->Get<RepFor<T>>().Get(index);
0403   }
0404 
0405   template <typename T, typename U>
0406   void SetRepeated(int number, int index, U&& value) {
0407     Extension* extension = FindOrNull(number);
0408     ABSL_CHECK(extension != nullptr) << "Index out-of-bounds (field is empty).";
0409     (*extension->Mutable<RepFor<T>>())[index] = std::forward<U>(value);
0410   }
0411 
0412   template <typename T>
0413   auto& Add(int number, FieldType type, const FieldDescriptor* descriptor) {
0414     static_assert(std::is_class_v<T>);
0415     Extension& ext = FindOrCreate(number, type, true, false, descriptor,
0416                                   &CreateImpl<RepFor<T>>);
0417     return *ext.Mutable<RepFor<T>>()->Add();
0418   }
0419 
0420   template <typename T>
0421   void Add(int number, FieldType type, bool packed, T value,
0422            const FieldDescriptor* descriptor) {
0423     static_assert(std::is_arithmetic_v<T>,
0424                   "Only arithmetic types take `packed`");
0425     Extension& ext = FindOrCreate(number, type, true, packed, descriptor,
0426                                   &CreateImpl<RepFor<T>>);
0427     ext.Mutable<RepFor<T>>()->Add(value);
0428   }
0429 
0430   const MessageLite& GetRepeatedMessage(int number, int index) const;
0431   std::string* MutableRepeatedString(int number, int index);
0432   MessageLite* MutableRepeatedMessage(int number, int index);
0433 
0434 #define desc const FieldDescriptor* descriptor  // avoid line wrapping
0435   std::string* AddString(int number, FieldType type, desc);
0436   MessageLite* AddMessage(int number, FieldType type,
0437                           const ClassData* class_data, desc);
0438   MessageLite* AddMessage(const FieldDescriptor* descriptor,
0439                           MessageFactory* factory);
0440   void AddAllocatedMessage(const FieldDescriptor* descriptor,
0441                            MessageLite* new_entry);
0442   void UnsafeArenaAddAllocatedMessage(const FieldDescriptor* descriptor,
0443                                       MessageLite* new_entry);
0444 #undef desc
0445 
0446   void RemoveLast(int number);
0447   [[nodiscard]] MessageLite* ReleaseLast(int number);
0448   MessageLite* UnsafeArenaReleaseLast(int number);
0449   void SwapElements(int number, int index1, int index2);
0450 
0451   // =================================================================
0452   // convenience methods for implementing methods of Message
0453   //
0454   // These could all be implemented in terms of the other methods of this
0455   // class, but providing them here helps keep the generated code size down.
0456 
0457   void Clear();
0458   void MergeFrom(const MessageLite* extendee, const ExtensionSet& other);
0459   void Swap(const MessageLite* extendee, ExtensionSet* other);
0460   void InternalSwap(ExtensionSet* other);
0461   void SwapExtension(const MessageLite* extendee, ExtensionSet* other,
0462                      int number);
0463   void UnsafeShallowSwapExtension(ExtensionSet* other, int number);
0464   bool IsInitialized(const MessageLite* extendee) const;
0465 
0466   // Lite parser
0467   const char* ParseField(uint64_t tag, const char* ptr,
0468                          const MessageLite* extendee,
0469                          internal::InternalMetadata* metadata,
0470                          internal::ParseContext* ctx);
0471   // Full parser
0472   const char* ParseField(uint64_t tag, const char* ptr, const Message* extendee,
0473                          internal::InternalMetadata* metadata,
0474                          internal::ParseContext* ctx);
0475   template <typename Msg>
0476   const char* ParseMessageSet(const char* ptr, const Msg* extendee,
0477                               InternalMetadata* metadata,
0478                               internal::ParseContext* ctx) {
0479     while (!ctx->Done(&ptr)) {
0480       uint32_t tag;
0481       ptr = ReadTag(ptr, &tag);
0482       GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
0483       if (tag == WireFormatLite::kMessageSetItemStartTag) {
0484         ptr = ctx->ParseGroupInlined(ptr, tag, [&](const char* ptr) {
0485           return ParseMessageSetItem(ptr, extendee, metadata, ctx);
0486         });
0487         GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
0488       } else {
0489         if (tag == 0 || (tag & 7) == 4) {
0490           ctx->SetLastTag(tag);
0491           return ptr;
0492         }
0493         ptr = ParseField(tag, ptr, extendee, metadata, ctx);
0494         GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
0495       }
0496     }
0497     return ptr;
0498   }
0499 
0500   // Write all extension fields with field numbers in the range
0501   //   [start_field_number, end_field_number)
0502   // to the output stream, using the cached sizes computed when ByteSize() was
0503   // last called.  Note that the range bounds are inclusive-exclusive.
0504   void SerializeWithCachedSizes(const MessageLite* extendee,
0505                                 int start_field_number, int end_field_number,
0506                                 io::CodedOutputStream* output) const {
0507     output->SetCur(_InternalSerialize(extendee, start_field_number,
0508                                       end_field_number, output->Cur(),
0509                                       output->EpsCopy()));
0510   }
0511 
0512   // Same as SerializeWithCachedSizes, but without any bounds checking.
0513   // The caller must ensure that target has sufficient capacity for the
0514   // serialized extensions.
0515   //
0516   // Returns a pointer past the last written byte.
0517   uint8_t* _InternalSerialize(const MessageLite* extendee,
0518                               int start_field_number, int end_field_number,
0519                               uint8_t* target,
0520                               io::EpsCopyOutputStream* stream) const {
0521     if (flat_size_ == 0) {
0522       assert(!is_large());
0523       return target;
0524     }
0525     return _InternalSerializeImpl(extendee, start_field_number,
0526                                   end_field_number, target, stream);
0527   }
0528 
0529   // Same as _InternalSerialize, but do not verify the range of field numbers.
0530   uint8_t* _InternalSerializeAll(const MessageLite* extendee, uint8_t* target,
0531                                  io::EpsCopyOutputStream* stream) const {
0532     if (flat_size_ == 0) {
0533       assert(!is_large());
0534       return target;
0535     }
0536     return _InternalSerializeAllImpl(extendee, target, stream);
0537   }
0538 
0539   // Like above but serializes in MessageSet format.
0540   void SerializeMessageSetWithCachedSizes(const MessageLite* extendee,
0541                                           io::CodedOutputStream* output) const {
0542     output->SetCur(InternalSerializeMessageSetWithCachedSizesToArray(
0543         extendee, output->Cur(), output->EpsCopy()));
0544   }
0545   uint8_t* InternalSerializeMessageSetWithCachedSizesToArray(
0546       const MessageLite* extendee, uint8_t* target,
0547       io::EpsCopyOutputStream* stream) const;
0548 
0549   // For backward-compatibility, versions of two of the above methods that
0550   // serialize deterministically iff SetDefaultSerializationDeterministic()
0551   // has been called.
0552   uint8_t* SerializeWithCachedSizesToArray(int start_field_number,
0553                                            int end_field_number,
0554                                            uint8_t* target) const;
0555   uint8_t* SerializeMessageSetWithCachedSizesToArray(
0556       const MessageLite* extendee, uint8_t* target) const;
0557 
0558   // Returns the total serialized size of all the extensions.
0559   size_t ByteSize() const;
0560 
0561   // Like ByteSize() but uses MessageSet format.
0562   size_t MessageSetByteSize() const;
0563 
0564   // Returns (an estimate of) the total number of bytes used for storing the
0565   // extensions in memory, excluding sizeof(*this).  If the ExtensionSet is
0566   // for a lite message (and thus possibly contains lite messages), the results
0567   // are undefined (might work, might crash, might corrupt data, might not even
0568   // be linked in).  It's up to the protocol compiler to avoid calling this on
0569   // such ExtensionSets (easy enough since lite messages don't implement
0570   // SpaceUsed()).
0571   size_t SpaceUsedExcludingSelfLong() const;
0572 
0573   // This method just calls SpaceUsedExcludingSelfLong() but it can not be
0574   // inlined because the definition of SpaceUsedExcludingSelfLong() is not
0575   // included in lite runtime and when an inline method refers to it MSVC
0576   // will complain about unresolved symbols when building the lite runtime
0577   // as .dll.
0578   int SpaceUsedExcludingSelf() const;
0579 
0580   static constexpr size_t InternalGetArenaOffset(internal::InternalVisibility) {
0581     return PROTOBUF_FIELD_OFFSET(ExtensionSet, arena_);
0582   }
0583 
0584  private:
0585   template <typename Type>
0586   friend class PrimitiveTypeTraits;
0587 
0588   template <typename Type>
0589   friend class RepeatedPrimitiveTypeTraits;
0590 
0591   template <typename Type>
0592   friend class EnumTypeTraits;
0593 
0594   template <typename Type>
0595   friend class RepeatedEnumTypeTraits;
0596 
0597   friend class google::protobuf::Reflection;
0598   friend class google::protobuf::internal::ReflectionVisit;
0599   friend struct google::protobuf::internal::DynamicExtensionInfoHelper;
0600   friend class google::protobuf::internal::WireFormat;
0601   friend class google::protobuf::internal::v2::TableDrivenMessage;
0602 
0603   friend void internal::InitializeLazyExtensionSet();
0604 
0605   // The repeated field type for T.
0606   template <typename T>
0607   using RepFor = std::conditional_t<std::is_arithmetic_v<T>,
0608                                     RepeatedField<std::decay_t<T>>,
0609                                     RepeatedPtrField<std::decay_t<T>>>;
0610 
0611   static bool FieldTypeIsPointer(FieldType type);
0612 
0613   size_t GetMessageByteSizeLong(int number) const;
0614   uint8_t* InternalSerializeMessage(int number, const MessageLite* prototype,
0615                                     uint8_t* target,
0616                                     io::EpsCopyOutputStream* stream) const;
0617 
0618   // Implementation of _InternalSerialize for non-empty map_.
0619   uint8_t* _InternalSerializeImpl(const MessageLite* extendee,
0620                                   int start_field_number, int end_field_number,
0621                                   uint8_t* target,
0622                                   io::EpsCopyOutputStream* stream) const;
0623   // Implementation of _InternalSerializeAll for non-empty map_.
0624   uint8_t* _InternalSerializeAllImpl(const MessageLite* extendee,
0625                                      uint8_t* target,
0626                                      io::EpsCopyOutputStream* stream) const;
0627   // Implementation of _InternalSerialize for large map_.
0628   // Extracted as a separate method to avoid inlining and to reuse in
0629   // _InternalSerializeAllImpl.
0630   uint8_t* _InternalSerializeImplLarge(const MessageLite* extendee,
0631                                        int start_field_number,
0632                                        int end_field_number, uint8_t* target,
0633                                        io::EpsCopyOutputStream* stream) const;
0634   // Interface of a lazily parsed singular message extension.
0635   class PROTOBUF_EXPORT LazyMessageExtension {
0636    public:
0637     LazyMessageExtension() = default;
0638     LazyMessageExtension(const LazyMessageExtension&) = delete;
0639     LazyMessageExtension& operator=(const LazyMessageExtension&) = delete;
0640     virtual ~LazyMessageExtension() = default;
0641 
0642     virtual LazyMessageExtension* Clone(Arena* arena,
0643                                         const LazyMessageExtension& other,
0644                                         Arena* other_arena) const = 0;
0645     virtual const MessageLite& GetMessage(const MessageLite& prototype,
0646                                           Arena* arena) const = 0;
0647     virtual const MessageLite& GetMessageIgnoreUnparsed(
0648         const MessageLite& prototype, Arena* arena) const = 0;
0649     virtual MessageLite* MutableMessage(const MessageLite& prototype,
0650                                         Arena* arena) = 0;
0651     virtual void SetAllocatedMessage(MessageLite* message, Arena* arena) = 0;
0652     virtual void UnsafeArenaSetAllocatedMessage(MessageLite* message,
0653                                                 Arena* arena) = 0;
0654     [[nodiscard]] virtual MessageLite* ReleaseMessage(
0655         const MessageLite& prototype, Arena* arena) = 0;
0656     virtual MessageLite* UnsafeArenaReleaseMessage(const MessageLite& prototype,
0657                                                    Arena* arena) = 0;
0658 
0659     virtual bool IsInitialized(const MessageLite* prototype,
0660                                Arena* arena) const = 0;
0661     virtual bool IsEagerSerializeSafe(const MessageLite* prototype,
0662                                       Arena* arena) const = 0;
0663 
0664     [[deprecated("Please use ByteSizeLong() instead")]] virtual int ByteSize()
0665         const {
0666       return internal::ToIntSize(ByteSizeLong());
0667     }
0668     virtual size_t ByteSizeLong() const = 0;
0669     virtual size_t SpaceUsedLong() const = 0;
0670 
0671     virtual std::variant<size_t, const MessageLite*> UnparsedSizeOrMessage()
0672         const = 0;
0673 
0674     virtual void MergeFrom(const MessageLite* prototype,
0675                            const LazyMessageExtension& other, Arena* arena,
0676                            Arena* other_arena) = 0;
0677     virtual void MergeFromMessage(const MessageLite& msg, Arena* arena) = 0;
0678     virtual void Clear() = 0;
0679 
0680     virtual const char* _InternalParse(const MessageLite& prototype,
0681                                        Arena* arena, const char* ptr,
0682                                        ParseContext* ctx) = 0;
0683     virtual uint8_t* WriteMessageToArray(
0684         const MessageLite* prototype, int number, uint8_t* target,
0685         io::EpsCopyOutputStream* stream) const = 0;
0686 
0687 
0688    private:
0689     virtual void UnusedKeyMethod();  // Dummy key method to avoid weak vtable.
0690   };
0691   // Give access to function defined below to see LazyMessageExtension.
0692   static LazyMessageExtension* MaybeCreateLazyExtensionImpl(Arena* arena);
0693   static LazyMessageExtension* MaybeCreateLazyExtension(Arena* arena) {
0694     auto* f = maybe_create_lazy_extension_.load(std::memory_order_relaxed);
0695     return f != nullptr ? f(arena) : nullptr;
0696   }
0697   static std::atomic<LazyMessageExtension* (*)(Arena* arena)>
0698       maybe_create_lazy_extension_;
0699 
0700   // We can't directly use std::atomic for Extension::cached_size because
0701   // Extension needs to be trivially copyable.
0702   class TrivialAtomicInt {
0703    public:
0704     int operator()() const {
0705       return reinterpret_cast<const AtomicT*>(int_)->load(
0706           std::memory_order_relaxed);
0707     }
0708     void set(int v) {
0709       reinterpret_cast<AtomicT*>(int_)->store(v, std::memory_order_relaxed);
0710     }
0711 
0712    private:
0713     using AtomicT = std::atomic<int>;
0714     alignas(AtomicT) char int_[sizeof(AtomicT)];
0715   };
0716 
0717   struct Extension {
0718     // Some helper methods for operations on a single Extension.
0719     uint8_t* InternalSerializeFieldWithCachedSizesToArray(
0720         const MessageLite* extendee, const ExtensionSet* extension_set,
0721         int number, uint8_t* target, io::EpsCopyOutputStream* stream) const;
0722     uint8_t* InternalSerializeMessageSetItemWithCachedSizesToArray(
0723         const MessageLite* extendee, const ExtensionSet* extension_set,
0724         int number, uint8_t* target, io::EpsCopyOutputStream* stream) const;
0725     size_t ByteSize(int number) const;
0726     size_t MessageSetItemByteSize(int number) const;
0727     void Clear();
0728     int GetSize() const;
0729     void Free();
0730     size_t SpaceUsedExcludingSelfLong() const;
0731     bool IsInitialized(const ExtensionSet* ext_set, const MessageLite* extendee,
0732                        int number, Arena* arena) const;
0733     const void* PrefetchPtr() const {
0734       ABSL_DCHECK_EQ(is_pointer, is_repeated || FieldTypeIsPointer(type));
0735       // We don't want to prefetch invalid/null pointers so if there isn't a
0736       // pointer to prefetch, then return `this`.
0737       return is_pointer ? raw_ptr() : this;
0738     }
0739 
0740     // The order of these fields packs Extension into 24 bytes when using 8
0741     // byte alignment. Consider this when adding or removing fields here.
0742 
0743     // We need a separate named union for pointer values to allow for
0744     // prefetching the pointer without undefined behavior.
0745     union Pointer {
0746       std::string* string_value;
0747       MessageLite* message_value;
0748       LazyMessageExtension* lazymessage_value;
0749 
0750       RepeatedField<int32_t>* repeated_int32_t_value;
0751       RepeatedField<int64_t>* repeated_int64_t_value;
0752       RepeatedField<uint32_t>* repeated_uint32_t_value;
0753       RepeatedField<uint64_t>* repeated_uint64_t_value;
0754       RepeatedField<float>* repeated_float_value;
0755       RepeatedField<double>* repeated_double_value;
0756       RepeatedField<bool>* repeated_bool_value;
0757       RepeatedPtrField<std::string>* repeated_string_value;
0758       RepeatedPtrField<MessageLite>* repeated_message_value;
0759     };
0760 
0761     union {
0762       int32_t int32_t_value;
0763       int64_t int64_t_value;
0764       uint32_t uint32_t_value;
0765       uint64_t uint64_t_value;
0766       float float_value;
0767       double double_value;
0768       bool bool_value;
0769       Pointer ptr;
0770     };
0771 
0772     template <typename T>
0773     static inline constexpr auto kUnionMember = std::get<T Extension::*>(
0774         std::tuple{&Extension::int32_t_value, &Extension::int64_t_value,
0775                    &Extension::uint32_t_value, &Extension::uint64_t_value,
0776                    &Extension::float_value, &Extension::double_value,
0777                    &Extension::bool_value});
0778 
0779     template <typename T>
0780     static inline constexpr auto kPtrUnionMember =
0781         std::get<T Pointer::*>(std::tuple{
0782             // we omit message fields because those have custom behavior.
0783             &Pointer::string_value, &Pointer::repeated_int32_t_value,
0784             &Pointer::repeated_int64_t_value, &Pointer::repeated_uint32_t_value,
0785             &Pointer::repeated_uint64_t_value, &Pointer::repeated_float_value,
0786             &Pointer::repeated_double_value, &Pointer::repeated_bool_value,
0787             &Pointer::repeated_string_value, &Pointer::repeated_message_value});
0788 
0789     void* raw_ptr() const { return absl::bit_cast<void*>(ptr); }
0790 
0791     template <typename T>
0792     static inline constexpr bool kUsesPointer = !std::is_arithmetic_v<T>;
0793 
0794     template <typename T>
0795     void VerifyType() const {
0796       ABSL_DCHECK_EQ(is_repeated || FieldTypeIsPointer(type), kUsesPointer<T>);
0797       constexpr auto expected_cpp_type = WireFormatLite::CppTypeFor<T>();
0798       ABSL_DCHECK_EQ(
0799           +expected_cpp_type,
0800           +(type == WireFormatLite::TYPE_ENUM
0801                 ? WireFormatLite::CPPTYPE_INT32
0802                 : WireFormatLite::FieldTypeToCppType(
0803                       static_cast<WireFormatLite::FieldType>(type))));
0804     }
0805 
0806     // Returns a reference to the union member for T.
0807     // For pointer-stored types, follow the pointer.
0808     template <typename T>
0809     const T& Get() const {
0810       VerifyType<T>();
0811       if constexpr (kUsesPointer<T>) {
0812         return *(ptr.*kPtrUnionMember<T*>);
0813       } else {
0814         return this->*kUnionMember<T>;
0815       }
0816     }
0817 
0818     // Returns a reference to the union member for T.
0819     // For pointer-stored types, return a reference to the pointer.
0820     template <typename T>
0821     auto& Mutable() {
0822       VerifyType<T>();
0823       if constexpr (kUsesPointer<T>) {
0824         return ptr.*kPtrUnionMember<T*>;
0825       } else {
0826         return this->*kUnionMember<T>;
0827       }
0828     }
0829 
0830     FieldType type;
0831     bool is_repeated;
0832 
0833     // Whether the extension is a pointer. This is used for prefetching.
0834     bool is_pointer : 1;
0835 
0836     // For singular types, indicates if the extension is "cleared".  This
0837     // happens when an extension is set and then later cleared by the caller.
0838     // We want to keep the Extension object around for reuse, so instead of
0839     // removing it from the map, we just set is_cleared = true.
0840     //
0841     // This is always set to false for repeated types.
0842     // The size of the RepeatedField simply becomes zero when cleared.
0843     bool is_cleared : 1;
0844 
0845     // For singular message types, indicates whether lazy parsing is enabled
0846     // for this extension. This field is only valid when type == TYPE_MESSAGE
0847     // and !is_repeated because we only support lazy parsing for singular
0848     // message types currently. If is_lazy = true, the extension is stored in
0849     // lazymessage_value. Otherwise, the extension will be message_value.
0850     bool is_lazy : 1;
0851 
0852     // For repeated types, this indicates if the [packed=true] option is set.
0853     bool is_packed;
0854 
0855     // For packed fields, the size of the packed data is recorded here when
0856     // ByteSize() is called then used during serialization.
0857     mutable TrivialAtomicInt cached_size;
0858 
0859     // The descriptor for this extension, if one exists and is known.  May be
0860     // nullptr.  Must not be nullptr if the descriptor for the extension does
0861     // not live in the same pool as the descriptor for the containing type.
0862     const FieldDescriptor* descriptor;
0863   };
0864 
0865   // The Extension struct is small enough to be passed by value so we use it
0866   // directly as the value type in mappings rather than use pointers. We use
0867   // sorted maps rather than hash-maps because we expect most ExtensionSets will
0868   // only contain a small number of extensions, and we want AppendToList and
0869   // deterministic serialization to order fields by field number. In flat mode,
0870   // the number of elements is small enough that linear search is faster than
0871   // binary search.
0872 
0873   struct KeyValue {
0874     int first;
0875     Extension second;
0876   };
0877 
0878   using LargeMap = absl::btree_map<int, Extension>;
0879 
0880   // Wrapper API that switches between flat-map and LargeMap.
0881 
0882   // Finds a key (if present) in the ExtensionSet.
0883   const Extension* FindOrNull(int key) const;
0884   Extension* FindOrNull(int key);
0885 
0886   // Helper-functions that only inspect the LargeMap.
0887   const Extension* FindOrNullInLargeMap(int key) const;
0888   Extension* FindOrNullInLargeMap(int key);
0889 
0890   // Inserts a new (key, Extension) into the ExtensionSet (and returns true), or
0891   // finds the already-existing Extension for that key (returns false).
0892   // The Extension* will point to the new-or-found Extension.
0893   std::pair<Extension*, bool> Insert(int key);
0894   // Same as insert for the large map.
0895   std::pair<Extension*, bool> InternalInsertIntoLargeMap(int key);
0896 
0897   // Grows the flat_capacity_.
0898   // If flat_capacity_ > kMaximumFlatCapacity, converts to LargeMap.
0899   void GrowCapacity(size_t minimum_new_capacity);
0900 
0901   static constexpr uint16_t kMaximumFlatCapacity = 256;
0902 
0903   // Reserves capacity for the flat_capacity_ when the ExtensionSet is
0904   // IsCompletelyEmpty.
0905   // minimum_new_capacity must be <= kMaximumFlatCapacity.
0906   void InternalReserveSmallCapacityFromEmpty(size_t minimum_new_capacity);
0907 
0908   bool is_large() const { return static_cast<int16_t>(flat_size_) < 0; }
0909 
0910   // Removes a key from the ExtensionSet.
0911   void Erase(int key);
0912 
0913   // Returns the number of elements in the ExtensionSet, including cleared
0914   // extensions.
0915   size_t Size() const {
0916     return ABSL_PREDICT_FALSE(is_large()) ? map_.large->size() : flat_size_;
0917   }
0918 
0919   // For use as `PrefetchFunctor`s in `ForEach`.
0920   struct Prefetch {
0921     void operator()(const void* ptr) const { absl::PrefetchToLocalCache(ptr); }
0922   };
0923   struct PrefetchNta {
0924     void operator()(const void* ptr) const {
0925       absl::PrefetchToLocalCacheNta(ptr);
0926     }
0927   };
0928 
0929   template <typename Iterator, typename KeyValueFunctor,
0930             typename PrefetchFunctor>
0931   static void ForEachPrefetchImpl(Iterator it, Iterator end,
0932                                   KeyValueFunctor func,
0933                                   PrefetchFunctor prefetch_func) {
0934     // Note: based on arena's ChunkList::Cleanup().
0935     // Prefetch distance 16 performs better than 8 in load tests.
0936     constexpr int kPrefetchDistance = 16;
0937     Iterator prefetch = it;
0938     // Prefetch the first kPrefetchDistance extensions.
0939     for (int i = 0; prefetch != end && i < kPrefetchDistance; ++prefetch, ++i) {
0940       prefetch_func(prefetch->second.PrefetchPtr());
0941     }
0942     // For the middle extensions, call func and then prefetch the extension
0943     // kPrefetchDistance after the current one.
0944     for (; prefetch != end; ++it, ++prefetch) {
0945       func(it->first, it->second);
0946       prefetch_func(prefetch->second.PrefetchPtr());
0947     }
0948     // Call func on the rest without prefetching.
0949     for (; it != end; ++it) func(it->first, it->second);
0950   }
0951 
0952   // Similar to std::for_each, but returning void.
0953   // Each Iterator is decomposed into ->first and ->second fields, so
0954   // that the KeyValueFunctor can be agnostic vis-a-vis KeyValue-vs-std::pair.
0955   // Applies a functor to the <int, Extension&> pairs in sorted order and
0956   // prefetches ahead.
0957   template <typename KeyValueFunctor, typename PrefetchFunctor>
0958   void ForEach(KeyValueFunctor func, PrefetchFunctor prefetch_func) {
0959     if (ABSL_PREDICT_FALSE(is_large())) {
0960       ForEachPrefetchImpl(map_.large->begin(), map_.large->end(),
0961                           std::move(func), std::move(prefetch_func));
0962       return;
0963     }
0964     ForEachPrefetchImpl(flat_begin(), flat_end(), std::move(func),
0965                         std::move(prefetch_func));
0966   }
0967   // As above, but const.
0968   template <typename KeyValueFunctor, typename PrefetchFunctor>
0969   void ForEach(KeyValueFunctor func, PrefetchFunctor prefetch_func) const {
0970     if (ABSL_PREDICT_FALSE(is_large())) {
0971       ForEachPrefetchImpl(map_.large->begin(), map_.large->end(),
0972                           std::move(func), std::move(prefetch_func));
0973       return;
0974     }
0975     ForEachPrefetchImpl(flat_begin(), flat_end(), std::move(func),
0976                         std::move(prefetch_func));
0977   }
0978 
0979   // As above, but without prefetching. This is for use in cases where we never
0980   // use the pointed-to extension values in `func`.
0981   template <typename Iterator, typename KeyValueFunctor>
0982   static void ForEachNoPrefetch(Iterator begin, Iterator end,
0983                                 KeyValueFunctor func) {
0984     for (Iterator it = begin; it != end; ++it) func(it->first, it->second);
0985   }
0986 
0987   // Applies a functor to the <int, Extension&> pairs in sorted order.
0988   template <typename KeyValueFunctor>
0989   void ForEachNoPrefetch(KeyValueFunctor func) {
0990     if (ABSL_PREDICT_FALSE(is_large())) {
0991       ForEachNoPrefetch(map_.large->begin(), map_.large->end(),
0992                         std::move(func));
0993       return;
0994     }
0995     ForEachNoPrefetch(flat_begin(), flat_end(), std::move(func));
0996   }
0997 
0998   // As above, but const.
0999   template <typename KeyValueFunctor>
1000   void ForEachNoPrefetch(KeyValueFunctor func) const {
1001     if (ABSL_PREDICT_FALSE(is_large())) {
1002       ForEachNoPrefetch(map_.large->begin(), map_.large->end(),
1003                         std::move(func));
1004       return;
1005     }
1006     ForEachNoPrefetch(flat_begin(), flat_end(), std::move(func));
1007   }
1008 
1009   // Returns true if nothing is allocated in the ExtensionSet.
1010   bool IsCompletelyEmpty() const {
1011     return flat_size_ == 0 && flat_capacity_ == 0;
1012   }
1013 
1014   // Implementation of MergeFrom into the empty ExtensionSet from a small
1015   // `other`.
1016   // This is used in all types of copy.
1017   // PRECONDITIONs:
1018   // 1. `this.IsCompletelyEmpty()`.
1019   // 2. `other` is small (!other.is_large()).
1020   void InternalMergeFromSmallToEmpty(const MessageLite* extendee,
1021                                      const ExtensionSet& other);
1022   // Implementation of MergeFrom for general case.
1023   void InternalMergeFromSlow(const MessageLite* extendee,
1024                              const ExtensionSet& other);
1025   // Merges new or existing Extension from other_extension.
1026   void InternalExtensionMergeFrom(const MessageLite* extendee, int number,
1027                                   const Extension& other_extension,
1028                                   Arena* other_arena);
1029   // Merges newly created uninitialized Extension from other_extension.
1030   void InternalExtensionMergeFromIntoUninitializedExtension(
1031       Extension& dst_extension, const MessageLite* extendee, int number,
1032       const Extension& other_extension, Arena* other_arena);
1033 
1034   inline static bool is_packable(WireFormatLite::WireType type) {
1035     switch (type) {
1036       case WireFormatLite::WIRETYPE_VARINT:
1037       case WireFormatLite::WIRETYPE_FIXED64:
1038       case WireFormatLite::WIRETYPE_FIXED32:
1039         return true;
1040       case WireFormatLite::WIRETYPE_LENGTH_DELIMITED:
1041       case WireFormatLite::WIRETYPE_START_GROUP:
1042       case WireFormatLite::WIRETYPE_END_GROUP:
1043         return false;
1044 
1045         // Do not add a default statement. Let the compiler complain when
1046         // someone
1047         // adds a new wire type.
1048     }
1049     Unreachable();  // switch handles all possible enum values
1050     return false;
1051   }
1052 
1053   // Returns true and fills field_number and extension if extension is found.
1054   // Note to support packed repeated field compatibility, it also fills whether
1055   // the tag on wire is packed, which can be different from
1056   // extension->is_packed (whether packed=true is specified).
1057   template <typename ExtensionFinder>
1058   bool FindExtensionInfoFromTag(uint32_t tag, ExtensionFinder* extension_finder,
1059                                 int* field_number, ExtensionInfo* extension,
1060                                 bool* was_packed_on_wire) {
1061     *field_number = WireFormatLite::GetTagFieldNumber(tag);
1062     WireFormatLite::WireType wire_type = WireFormatLite::GetTagWireType(tag);
1063     return FindExtensionInfoFromFieldNumber(wire_type, *field_number,
1064                                             extension_finder, extension,
1065                                             was_packed_on_wire);
1066   }
1067 
1068   // Returns true and fills extension if extension is found.
1069   // Note to support packed repeated field compatibility, it also fills whether
1070   // the tag on wire is packed, which can be different from
1071   // extension->is_packed (whether packed=true is specified).
1072   template <typename ExtensionFinder>
1073   bool FindExtensionInfoFromFieldNumber(int wire_type, int field_number,
1074                                         ExtensionFinder* extension_finder,
1075                                         ExtensionInfo* extension,
1076                                         bool* was_packed_on_wire) const {
1077     if (!extension_finder->Find(field_number, extension)) {
1078       return false;
1079     }
1080 
1081     ABSL_DCHECK(extension->type > 0 &&
1082                 extension->type <= WireFormatLite::MAX_FIELD_TYPE);
1083     auto real_type = static_cast<WireFormatLite::FieldType>(extension->type);
1084 
1085     WireFormatLite::WireType expected_wire_type =
1086         WireFormatLite::WireTypeForFieldType(real_type);
1087 
1088     // Check if this is a packed field.
1089     *was_packed_on_wire = false;
1090     if (extension->is_repeated &&
1091         wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED &&
1092         is_packable(expected_wire_type)) {
1093       *was_packed_on_wire = true;
1094       return true;
1095     }
1096     // Otherwise the wire type must match.
1097     return expected_wire_type == wire_type;
1098   }
1099 
1100   // Find the prototype for a LazyMessage from the extension registry. Returns
1101   // null if the extension is not found.
1102   const MessageLite* GetPrototypeForLazyMessage(const MessageLite* extendee,
1103                                                 int number) const;
1104 
1105   // Returns true if extension is present and lazy.
1106   bool HasLazy(int number) const;
1107 
1108   // Gets the extension with the given number, creating it if it does not
1109   // already exist.  Returns true if the extension did not already exist.
1110   bool MaybeNewExtension(int number, const FieldDescriptor* descriptor,
1111                          Extension** result);
1112 
1113   // Gets the repeated extension for the given descriptor, creating it if
1114   // it does not exist.
1115   Extension* MaybeNewRepeatedExtension(const FieldDescriptor* descriptor);
1116 
1117   // If the extension exists, return it. Otherwise, create it first.
1118   // If `pointer_creator` is not null, it is called on creation.
1119   Extension& FindOrCreate(int number, FieldType type, bool repeated,
1120                           bool packed, const FieldDescriptor* descriptor,
1121                           Extension& (*pointer_creator)(Extension& ext,
1122                                                         Arena* arena));
1123 
1124   template <typename T>
1125   static Extension& CreateImpl(Extension& ext, Arena* arena) {
1126     ext.Mutable<T>() = Arena::Create<T>(arena);
1127     return ext;
1128   }
1129 
1130   bool FindExtension(int wire_type, uint32_t field, const MessageLite* extendee,
1131                      const internal::ParseContext* /*ctx*/,
1132                      ExtensionInfo* extension, bool* was_packed_on_wire) {
1133     GeneratedExtensionFinder finder(extendee);
1134     return FindExtensionInfoFromFieldNumber(wire_type, field, &finder,
1135                                             extension, was_packed_on_wire);
1136   }
1137   inline bool FindExtension(int wire_type, uint32_t field,
1138                             const Message* extendee,
1139                             const internal::ParseContext* ctx,
1140                             ExtensionInfo* extension, bool* was_packed_on_wire);
1141   // Used for MessageSet only
1142   const char* ParseFieldMaybeLazily(uint64_t tag, const char* ptr,
1143                                     const MessageLite* extendee,
1144                                     internal::InternalMetadata* metadata,
1145                                     internal::ParseContext* ctx) {
1146     // Lite MessageSet doesn't implement lazy.
1147     return ParseField(tag, ptr, extendee, metadata, ctx);
1148   }
1149   const char* ParseFieldMaybeLazily(uint64_t tag, const char* ptr,
1150                                     const Message* extendee,
1151                                     internal::InternalMetadata* metadata,
1152                                     internal::ParseContext* ctx);
1153   const char* ParseMessageSetItem(const char* ptr, const MessageLite* extendee,
1154                                   internal::InternalMetadata* metadata,
1155                                   internal::ParseContext* ctx);
1156   const char* ParseMessageSetItem(const char* ptr, const Message* extendee,
1157                                   internal::InternalMetadata* metadata,
1158                                   internal::ParseContext* ctx);
1159 
1160   // Implemented in extension_set_inl.h to keep code out of the header file.
1161   template <typename T>
1162   const char* ParseFieldWithExtensionInfo(int number, bool was_packed_on_wire,
1163                                           const ExtensionInfo& info,
1164                                           internal::InternalMetadata* metadata,
1165                                           const char* ptr,
1166                                           internal::ParseContext* ctx);
1167   template <typename Msg, typename T>
1168   const char* ParseMessageSetItemTmpl(const char* ptr, const Msg* extendee,
1169                                       internal::InternalMetadata* metadata,
1170                                       internal::ParseContext* ctx);
1171 
1172   // Hack:  RepeatedPtrFieldBase declares ExtensionSet as a friend.  This
1173   //   friendship should automatically extend to ExtensionSet::Extension, but
1174   //   unfortunately some older compilers (e.g. GCC 3.4.4) do not implement this
1175   //   correctly.  So, we must provide helpers for calling methods of that
1176   //   class.
1177 
1178   // Defined in extension_set_heavy.cc.
1179   static inline size_t RepeatedMessage_SpaceUsedExcludingSelfLong(
1180       RepeatedPtrFieldBase* field);
1181 
1182   KeyValue* flat_begin() {
1183     assert(!is_large());
1184     return map_.flat;
1185   }
1186   const KeyValue* flat_begin() const {
1187     assert(!is_large());
1188     return map_.flat;
1189   }
1190   KeyValue* flat_end() {
1191     assert(!is_large());
1192     return map_.flat + flat_size_;
1193   }
1194   const KeyValue* flat_end() const {
1195     assert(!is_large());
1196     return map_.flat + flat_size_;
1197   }
1198 
1199   static KeyValue* AllocateFlatMap(Arena* arena,
1200                                    uint16_t powerof2_flat_capacity);
1201   static void DeleteFlatMap(const KeyValue* flat, uint16_t flat_capacity);
1202 
1203   Arena* arena_;
1204 
1205   // Manual memory-management:
1206   // map_.flat is an allocated array of flat_capacity_ elements.
1207   // [map_.flat, map_.flat + flat_size_) is the currently-in-use prefix.
1208   uint16_t flat_capacity_;
1209   uint16_t flat_size_;  // negative int16_t(flat_size_) indicates is_large()
1210   union AllocatedData {
1211     KeyValue* flat;
1212 
1213     // If flat_capacity_ > kMaximumFlatCapacity, switch to LargeMap,
1214     // which guarantees O(n lg n) CPU but larger constant factors.
1215     LargeMap* large;
1216   } map_;
1217 };
1218 
1219 constexpr ExtensionSet::ExtensionSet(Arena* arena)
1220     : arena_(arena), flat_capacity_(0), flat_size_(0), map_{nullptr} {}
1221 
1222 // ===================================================================
1223 // Glue for generated extension accessors
1224 
1225 // -------------------------------------------------------------------
1226 // Template magic
1227 
1228 // First we have a set of classes representing "type traits" for different
1229 // field types.  A type traits class knows how to implement basic accessors
1230 // for extensions of a particular type given an ExtensionSet.  The signature
1231 // for a type traits class looks like this:
1232 //
1233 //   class TypeTraits {
1234 //    public:
1235 //     typedef ? ConstType;
1236 //     typedef ? MutableType;
1237 //     // TypeTraits for singular fields and repeated fields will define the
1238 //     // symbol "Singular" or "Repeated" respectively. These two symbols will
1239 //     // be used in extension accessors to distinguish between singular
1240 //     // extensions and repeated extensions. If the TypeTraits for the passed
1241 //     // in extension doesn't have the expected symbol defined, it means the
1242 //     // user is passing a repeated extension to a singular accessor, or the
1243 //     // opposite. In that case the C++ compiler will generate an error
1244 //     // message "no matching member function" to inform the user.
1245 //     typedef ? Singular
1246 //     typedef ? Repeated
1247 //
1248 //     static inline ConstType Get(int number, const ExtensionSet& set);
1249 //     static inline void Set(int number, ConstType value, ExtensionSet* set);
1250 //     static inline MutableType Mutable(int number, ExtensionSet* set);
1251 //
1252 //     // Variants for repeated fields.
1253 //     static inline ConstType Get(int number, const ExtensionSet& set,
1254 //                                 int index);
1255 //     static inline void Set(int number, int index,
1256 //                            ConstType value, ExtensionSet* set);
1257 //     static inline MutableType Mutable(int number, int index,
1258 //                                       ExtensionSet* set);
1259 //     static inline void Add(int number, ConstType value, ExtensionSet* set);
1260 //     static inline MutableType Add(int number, ExtensionSet* set);
1261 //     This is used by the ExtensionIdentifier constructor to register
1262 //     the extension at dynamic initialization.
1263 //   };
1264 //
1265 // Not all of these methods make sense for all field types.  For example, the
1266 // "Mutable" methods only make sense for strings and messages, and the
1267 // repeated methods only make sense for repeated types.  So, each type
1268 // traits class implements only the set of methods from this signature that it
1269 // actually supports.  This will cause a compiler error if the user tries to
1270 // access an extension using a method that doesn't make sense for its type.
1271 // For example, if "foo" is an extension of type "optional int32", then if you
1272 // try to write code like:
1273 //   my_message.MutableExtension(foo)
1274 // you will get a compile error because PrimitiveTypeTraits<int32_t> does not
1275 // have a "Mutable()" method.
1276 
1277 // -------------------------------------------------------------------
1278 // PrimitiveTypeTraits
1279 
1280 // Since the ExtensionSet has different methods for each primitive type,
1281 // we must explicitly define the methods of the type traits class for each
1282 // known type.
1283 template <typename Type>
1284 class PrimitiveTypeTraits {
1285  public:
1286   typedef Type ConstType;
1287   typedef Type MutableType;
1288   using InitType = ConstType;
1289   static const ConstType& FromInitType(const InitType& v) { return v; }
1290   typedef PrimitiveTypeTraits<Type> Singular;
1291   static constexpr bool kLifetimeBound = false;
1292 
1293   static inline ConstType Get(int number, const ExtensionSet& set,
1294                               ConstType default_value) {
1295     return set.Get<Type>(number, default_value);
1296   }
1297 
1298   static inline const ConstType* GetPtr(int number, const ExtensionSet& set,
1299                                         const ConstType& default_value) {
1300     return &set.Get<Type>(number, default_value);
1301   }
1302   static inline void Set(int number, FieldType field_type, ConstType value,
1303                          ExtensionSet* set) {
1304     set->Set<Type>(number, field_type, value, nullptr);
1305   }
1306 };
1307 
1308 template <typename Type>
1309 class RepeatedPrimitiveTypeTraits {
1310  public:
1311   typedef Type ConstType;
1312   typedef Type MutableType;
1313   using InitType = ConstType;
1314   static const ConstType& FromInitType(const InitType& v) { return v; }
1315   typedef RepeatedPrimitiveTypeTraits<Type> Repeated;
1316   static constexpr bool kLifetimeBound = false;
1317 
1318   typedef RepeatedField<Type> RepeatedFieldType;
1319 
1320   static inline Type Get(int number, const ExtensionSet& set, int index) {
1321     return set.GetRepeated<Type>(number, index);
1322   }
1323   static inline const Type* GetPtr(int number, const ExtensionSet& set,
1324                                    int index) {
1325     return &set.GetRepeated<Type>(number, index);
1326   }
1327   static inline const RepeatedField<ConstType>* GetRepeatedPtr(
1328       int number, const ExtensionSet& set);
1329   static inline void Set(int number, int index, Type value, ExtensionSet* set) {
1330     set->SetRepeated<Type>(number, index, value);
1331   }
1332   static inline void Add(int number, FieldType field_type, bool is_packed,
1333                          Type value, ExtensionSet* set) {
1334     set->Add<Type>(number, field_type, is_packed, value, nullptr);
1335   }
1336 
1337   static inline const RepeatedField<ConstType>& GetRepeated(
1338       int number, const ExtensionSet& set);
1339   static inline RepeatedField<Type>* MutableRepeated(int number,
1340                                                      FieldType field_type,
1341                                                      bool is_packed,
1342                                                      ExtensionSet* set);
1343 
1344   static const RepeatedFieldType* GetDefaultRepeatedField();
1345 };
1346 
1347 class PROTOBUF_EXPORT RepeatedPrimitiveDefaults {
1348  private:
1349   template <typename Type>
1350   friend class RepeatedPrimitiveTypeTraits;
1351   static const RepeatedPrimitiveDefaults* default_instance();
1352   RepeatedField<int32_t> default_repeated_field_int32_t_;
1353   RepeatedField<int64_t> default_repeated_field_int64_t_;
1354   RepeatedField<uint32_t> default_repeated_field_uint32_t_;
1355   RepeatedField<uint64_t> default_repeated_field_uint64_t_;
1356   RepeatedField<double> default_repeated_field_double_;
1357   RepeatedField<float> default_repeated_field_float_;
1358   RepeatedField<bool> default_repeated_field_bool_;
1359 };
1360 
1361 #define PROTOBUF_DEFINE_PRIMITIVE_TYPE(TYPE, METHOD)                           \
1362   template <>                                                                  \
1363   inline const RepeatedField<TYPE>*                                            \
1364   RepeatedPrimitiveTypeTraits<TYPE>::GetDefaultRepeatedField() {               \
1365     return &RepeatedPrimitiveDefaults::default_instance()                      \
1366                 ->default_repeated_field_##TYPE##_;                            \
1367   }                                                                            \
1368   template <>                                                                  \
1369   inline const RepeatedField<TYPE>&                                            \
1370   RepeatedPrimitiveTypeTraits<TYPE>::GetRepeated(int number,                   \
1371                                                  const ExtensionSet& set) {    \
1372     return *reinterpret_cast<const RepeatedField<TYPE>*>(                      \
1373         set.GetRawRepeatedField(number, GetDefaultRepeatedField()));           \
1374   }                                                                            \
1375   template <>                                                                  \
1376   inline const RepeatedField<TYPE>*                                            \
1377   RepeatedPrimitiveTypeTraits<TYPE>::GetRepeatedPtr(int number,                \
1378                                                     const ExtensionSet& set) { \
1379     return &GetRepeated(number, set);                                          \
1380   }                                                                            \
1381   template <>                                                                  \
1382   inline RepeatedField<TYPE>*                                                  \
1383   RepeatedPrimitiveTypeTraits<TYPE>::MutableRepeated(                          \
1384       int number, FieldType field_type, bool is_packed, ExtensionSet* set) {   \
1385     return reinterpret_cast<RepeatedField<TYPE>*>(                             \
1386         set->MutableRawRepeatedField(number, field_type, is_packed, nullptr)); \
1387   }
1388 
1389 PROTOBUF_DEFINE_PRIMITIVE_TYPE(int32_t, Int32)
1390 PROTOBUF_DEFINE_PRIMITIVE_TYPE(int64_t, Int64)
1391 PROTOBUF_DEFINE_PRIMITIVE_TYPE(uint32_t, UInt32)
1392 PROTOBUF_DEFINE_PRIMITIVE_TYPE(uint64_t, UInt64)
1393 PROTOBUF_DEFINE_PRIMITIVE_TYPE(float, Float)
1394 PROTOBUF_DEFINE_PRIMITIVE_TYPE(double, Double)
1395 PROTOBUF_DEFINE_PRIMITIVE_TYPE(bool, Bool)
1396 
1397 #undef PROTOBUF_DEFINE_PRIMITIVE_TYPE
1398 
1399 // -------------------------------------------------------------------
1400 // StringTypeTraits
1401 
1402 // Strings support both Set() and Mutable().
1403 class PROTOBUF_EXPORT StringTypeTraits {
1404  public:
1405   typedef const std::string& ConstType;
1406   typedef std::string* MutableType;
1407   using InitType = ConstType;
1408   static ConstType FromInitType(InitType v) { return v; }
1409   typedef StringTypeTraits Singular;
1410   static constexpr bool kLifetimeBound = true;
1411 
1412   static inline const std::string& Get(int number, const ExtensionSet& set,
1413                                        ConstType default_value) {
1414     return set.Get<std::string>(number, default_value);
1415   }
1416   static inline const std::string* GetPtr(int number, const ExtensionSet& set,
1417                                           ConstType default_value) {
1418     return &Get(number, set, default_value);
1419   }
1420   static inline void Set(int number, FieldType field_type,
1421                          const std::string& value, ExtensionSet* set) {
1422     set->Set<std::string>(number, field_type, value, nullptr);
1423   }
1424   static inline std::string* Mutable(int number, FieldType field_type,
1425                                      ExtensionSet* set) {
1426     return set->MutableString(number, field_type, nullptr);
1427   }
1428 };
1429 
1430 class PROTOBUF_EXPORT RepeatedStringTypeTraits {
1431  public:
1432   typedef const std::string& ConstType;
1433   typedef std::string* MutableType;
1434   using InitType = ConstType;
1435   static ConstType FromInitType(InitType v) { return v; }
1436   typedef RepeatedStringTypeTraits Repeated;
1437   static constexpr bool kLifetimeBound = true;
1438 
1439   typedef RepeatedPtrField<std::string> RepeatedFieldType;
1440 
1441   static inline const std::string& Get(int number, const ExtensionSet& set,
1442                                        int index) {
1443     return set.GetRepeated<std::string>(number, index);
1444   }
1445   static inline const std::string* GetPtr(int number, const ExtensionSet& set,
1446                                           int index) {
1447     return &Get(number, set, index);
1448   }
1449   static inline const RepeatedPtrField<std::string>* GetRepeatedPtr(
1450       int number, const ExtensionSet& set) {
1451     return &GetRepeated(number, set);
1452   }
1453   static inline void Set(int number, int index, const std::string& value,
1454                          ExtensionSet* set) {
1455     set->SetRepeated<std::string>(number, index, value);
1456   }
1457   static inline std::string* Mutable(int number, int index, ExtensionSet* set) {
1458     return set->MutableRepeatedString(number, index);
1459   }
1460   static inline void Add(int number, FieldType field_type, bool /*is_packed*/,
1461                          const std::string& value, ExtensionSet* set) {
1462     set->Add<std::string>(number, field_type, nullptr) = value;
1463   }
1464   static inline std::string* Add(int number, FieldType field_type,
1465                                  ExtensionSet* set) {
1466     return &set->Add<std::string>(number, field_type, nullptr);
1467   }
1468 
1469   static inline const RepeatedPtrField<std::string>& GetRepeated(
1470       int number, const ExtensionSet& set) {
1471     return *reinterpret_cast<const RepeatedPtrField<std::string>*>(
1472         set.GetRawRepeatedField(number, GetDefaultRepeatedField()));
1473   }
1474 
1475   static inline RepeatedPtrField<std::string>* MutableRepeated(
1476       int number, FieldType field_type, bool is_packed, ExtensionSet* set) {
1477     return reinterpret_cast<RepeatedPtrField<std::string>*>(
1478         set->MutableRawRepeatedField(number, field_type, is_packed, nullptr));
1479   }
1480 
1481   static const RepeatedFieldType* GetDefaultRepeatedField();
1482 
1483  private:
1484   static void InitializeDefaultRepeatedFields();
1485   static void DestroyDefaultRepeatedFields();
1486 };
1487 
1488 // -------------------------------------------------------------------
1489 // EnumTypeTraits
1490 
1491 // ExtensionSet represents enums using integers internally, so we have to
1492 // static_cast around.
1493 template <typename Type>
1494 class EnumTypeTraits {
1495  public:
1496   typedef Type ConstType;
1497   typedef Type MutableType;
1498   using InitType = ConstType;
1499   static const ConstType& FromInitType(const InitType& v) { return v; }
1500   typedef EnumTypeTraits<Type> Singular;
1501   static constexpr bool kLifetimeBound = false;
1502 
1503   static inline ConstType Get(int number, const ExtensionSet& set,
1504                               ConstType default_value) {
1505     return static_cast<Type>(set.Get<int>(number, default_value));
1506   }
1507   static inline const ConstType* GetPtr(int number, const ExtensionSet& set,
1508                                         const ConstType& default_value) {
1509     return reinterpret_cast<const Type*>(&set.Get<int>(number, default_value));
1510   }
1511   static inline void Set(int number, FieldType field_type, ConstType value,
1512                          ExtensionSet* set) {
1513     ABSL_DCHECK(
1514         internal::ValidateEnum(value, EnumTraits<Type>::validation_data()));
1515     set->Set<int>(number, field_type, value, nullptr);
1516   }
1517 };
1518 
1519 template <typename Type>
1520 class RepeatedEnumTypeTraits {
1521  public:
1522   typedef Type ConstType;
1523   typedef Type MutableType;
1524   using InitType = ConstType;
1525   static const ConstType& FromInitType(const InitType& v) { return v; }
1526   typedef RepeatedEnumTypeTraits<Type> Repeated;
1527   static constexpr bool kLifetimeBound = false;
1528 
1529   typedef RepeatedField<Type> RepeatedFieldType;
1530 
1531   static inline ConstType Get(int number, const ExtensionSet& set, int index) {
1532     return static_cast<Type>(set.GetRepeated<int>(number, index));
1533   }
1534   static inline const ConstType* GetPtr(int number, const ExtensionSet& set,
1535                                         int index) {
1536     return reinterpret_cast<const Type*>(&set.GetRepeated<int>(number, index));
1537   }
1538   static inline void Set(int number, int index, ConstType value,
1539                          ExtensionSet* set) {
1540     ABSL_DCHECK(
1541         internal::ValidateEnum(value, EnumTraits<Type>::validation_data()));
1542     set->SetRepeated<int>(number, index, value);
1543   }
1544   static inline void Add(int number, FieldType field_type, bool is_packed,
1545                          ConstType value, ExtensionSet* set) {
1546     ABSL_DCHECK(
1547         internal::ValidateEnum(value, EnumTraits<Type>::validation_data()));
1548     set->Add<int>(number, field_type, is_packed, value, nullptr);
1549   }
1550   static inline const RepeatedField<Type>& GetRepeated(
1551       int number, const ExtensionSet& set) {
1552     // Hack: the `Extension` struct stores a RepeatedField<int> for enums.
1553     // RepeatedField<int> cannot implicitly convert to RepeatedField<EnumType>
1554     // so we need to do some casting magic. See message.h for similar
1555     // contortions for non-extension fields.
1556     return *reinterpret_cast<const RepeatedField<Type>*>(
1557         set.GetRawRepeatedField(number, GetDefaultRepeatedField()));
1558   }
1559   static inline const RepeatedField<Type>* GetRepeatedPtr(
1560       int number, const ExtensionSet& set) {
1561     return &GetRepeated(number, set);
1562   }
1563   static inline RepeatedField<Type>* MutableRepeated(int number,
1564                                                      FieldType field_type,
1565                                                      bool is_packed,
1566                                                      ExtensionSet* set) {
1567     return reinterpret_cast<RepeatedField<Type>*>(
1568         set->MutableRawRepeatedField(number, field_type, is_packed, nullptr));
1569   }
1570 
1571   static const RepeatedFieldType* GetDefaultRepeatedField() {
1572     // Hack: as noted above, repeated enum fields are internally stored as a
1573     // RepeatedField<int>. We need to be able to instantiate global static
1574     // objects to return as default (empty) repeated fields on non-existent
1575     // extensions. We would not be able to know a-priori all of the enum types
1576     // (values of |Type|) to instantiate all of these, so we just re-use
1577     // int32_t's default repeated field object.
1578     return reinterpret_cast<const RepeatedField<Type>*>(
1579         RepeatedPrimitiveTypeTraits<int32_t>::GetDefaultRepeatedField());
1580   }
1581 };
1582 
1583 // -------------------------------------------------------------------
1584 // MessageTypeTraits
1585 
1586 // ExtensionSet guarantees that when manipulating extensions with message
1587 // types, the implementation used will be the compiled-in class representing
1588 // that type.  So, we can static_cast down to the exact type we expect.
1589 template <typename Type>
1590 class MessageTypeTraits {
1591  public:
1592   typedef const Type& ConstType;
1593   typedef Type* MutableType;
1594   using InitType = const void*;
1595   static ConstType FromInitType(InitType v) {
1596     return *static_cast<const Type*>(v);
1597   }
1598   typedef MessageTypeTraits<Type> Singular;
1599   static constexpr bool kLifetimeBound = true;
1600 
1601   static inline ConstType Get(int number, const ExtensionSet& set,
1602                               ConstType default_value) {
1603     return static_cast<const Type&>(set.GetMessage(number, default_value));
1604   }
1605   static inline std::nullptr_t GetPtr(int /* number */,
1606                                       const ExtensionSet& /* set */,
1607                                       ConstType /* default_value */) {
1608     // Cannot be implemented because of forward declared messages?
1609     return nullptr;
1610   }
1611   static inline MutableType Mutable(int number, FieldType field_type,
1612                                     ExtensionSet* set) {
1613     return static_cast<Type*>(set->MutableMessage(
1614         number, field_type, Type::default_instance(), nullptr));
1615   }
1616   static inline void SetAllocated(int number, FieldType field_type,
1617                                   MutableType message, ExtensionSet* set) {
1618     set->SetAllocatedMessage(number, field_type, nullptr, message);
1619   }
1620   static inline void UnsafeArenaSetAllocated(int number, FieldType field_type,
1621                                              MutableType message,
1622                                              ExtensionSet* set) {
1623     set->UnsafeArenaSetAllocatedMessage(number, field_type, nullptr, message);
1624   }
1625   [[nodiscard]] static inline MutableType Release(int number,
1626                                                   FieldType /* field_type */,
1627                                                   ExtensionSet* set) {
1628     return static_cast<Type*>(
1629         set->ReleaseMessage(number, Type::default_instance()));
1630   }
1631   static inline MutableType UnsafeArenaRelease(int number,
1632                                                FieldType /* field_type */,
1633                                                ExtensionSet* set) {
1634     return static_cast<Type*>(
1635         set->UnsafeArenaReleaseMessage(number, Type::default_instance()));
1636   }
1637 };
1638 
1639 // Used by WireFormatVerify to extract the verify function from the registry.
1640 LazyEagerVerifyFnType FindExtensionLazyEagerVerifyFn(
1641     const MessageLite* extendee, int number);
1642 
1643 // forward declaration.
1644 class RepeatedMessageGenericTypeTraits;
1645 
1646 template <typename Type>
1647 class RepeatedMessageTypeTraits {
1648  public:
1649   typedef const Type& ConstType;
1650   typedef Type* MutableType;
1651   using InitType = const void*;
1652   static ConstType FromInitType(InitType v) {
1653     return *static_cast<const Type*>(v);
1654   }
1655   typedef RepeatedMessageTypeTraits<Type> Repeated;
1656   static constexpr bool kLifetimeBound = true;
1657 
1658   typedef RepeatedPtrField<Type> RepeatedFieldType;
1659 
1660   static inline ConstType Get(int number, const ExtensionSet& set, int index) {
1661     return static_cast<const Type&>(set.GetRepeatedMessage(number, index));
1662   }
1663   static inline std::nullptr_t GetPtr(int /* number */,
1664                                       const ExtensionSet& /* set */,
1665                                       int /* index */) {
1666     // Cannot be implemented because of forward declared messages?
1667     return nullptr;
1668   }
1669   static inline std::nullptr_t GetRepeatedPtr(int /* number */,
1670                                               const ExtensionSet& /* set */) {
1671     // Cannot be implemented because of forward declared messages?
1672     return nullptr;
1673   }
1674   static inline MutableType Mutable(int number, int index, ExtensionSet* set) {
1675     return static_cast<Type*>(set->MutableRepeatedMessage(number, index));
1676   }
1677   static inline MutableType Add(int number, FieldType field_type,
1678                                 ExtensionSet* set) {
1679     static const ClassData* class_data = MessageTraits<Type>::class_data();
1680     return static_cast<Type*>(
1681         set->AddMessage(number, field_type, class_data, nullptr));
1682   }
1683   static inline const RepeatedPtrField<Type>& GetRepeated(
1684       int number, const ExtensionSet& set) {
1685     // See notes above in RepeatedEnumTypeTraits::GetRepeated(): same
1686     // casting hack applies here, because a RepeatedPtrField<MessageLite>
1687     // cannot naturally become a RepeatedPtrType<Type> even though Type is
1688     // presumably a message. google::protobuf::Message goes through similar contortions
1689     // with a reinterpret_cast<>.
1690     return *reinterpret_cast<const RepeatedPtrField<Type>*>(
1691         set.GetRawRepeatedField(number, GetDefaultRepeatedField()));
1692   }
1693   static inline RepeatedPtrField<Type>* MutableRepeated(int number,
1694                                                         FieldType field_type,
1695                                                         bool is_packed,
1696                                                         ExtensionSet* set) {
1697     return reinterpret_cast<RepeatedPtrField<Type>*>(
1698         set->MutableRawRepeatedField(number, field_type, is_packed, nullptr));
1699   }
1700 
1701   static const RepeatedFieldType* GetDefaultRepeatedField();
1702 };
1703 
1704 template <typename Type>
1705 inline const typename RepeatedMessageTypeTraits<Type>::RepeatedFieldType*
1706 RepeatedMessageTypeTraits<Type>::GetDefaultRepeatedField() {
1707   static auto instance = OnShutdownDelete(new RepeatedFieldType);
1708   return instance;
1709 }
1710 
1711 // -------------------------------------------------------------------
1712 // ExtensionIdentifier
1713 
1714 // This is the type of actual extension objects.  E.g. if you have:
1715 //   extend Foo {
1716 //     optional int32 bar = 1234;
1717 //   }
1718 // then "bar" will be defined in C++ as:
1719 //   ExtensionIdentifier<Foo, PrimitiveTypeTraits<int32_t>, 5, false> bar(1234);
1720 //
1721 // Note that we could, in theory, supply the field number as a template
1722 // parameter, and thus make an instance of ExtensionIdentifier have no
1723 // actual contents.  However, if we did that, then using an extension
1724 // identifier would not necessarily cause the compiler to output any sort
1725 // of reference to any symbol defined in the extension's .pb.o file.  Some
1726 // linkers will actually drop object files that are not explicitly referenced,
1727 // but that would be bad because it would cause this extension to not be
1728 // registered at static initialization, and therefore using it would crash.
1729 
1730 template <typename ExtendeeType, typename TypeTraitsType, FieldType field_type,
1731           bool is_packed>
1732 class ExtensionIdentifier {
1733  public:
1734   typedef TypeTraitsType TypeTraits;
1735   typedef ExtendeeType Extendee;
1736 
1737   constexpr ExtensionIdentifier(int number,
1738                                 typename TypeTraits::InitType default_value)
1739       : number_(number), default_value_(default_value) {}
1740 
1741   inline int number() const { return number_; }
1742   typename TypeTraits::ConstType default_value() const {
1743     return TypeTraits::FromInitType(default_value_);
1744   }
1745 
1746   typename TypeTraits::ConstType const& default_value_ref() const {
1747     return TypeTraits::FromInitType(default_value_);
1748   }
1749 
1750  private:
1751   const int number_;
1752   typename TypeTraits::InitType default_value_;
1753 };
1754 
1755 // -------------------------------------------------------------------
1756 // Generated accessors
1757 
1758 
1759 }  // namespace internal
1760 
1761 // Call this function to ensure that this extensions's reflection is linked into
1762 // the binary:
1763 //
1764 //   google::protobuf::LinkExtensionReflection(Foo::my_extension);
1765 //
1766 // This will ensure that the following lookup will succeed:
1767 //
1768 //   DescriptorPool::generated_pool()->FindExtensionByName("Foo.my_extension");
1769 //
1770 // This is often relevant for parsing extensions in text mode.
1771 //
1772 // As a side-effect, it will also guarantee that anything else from the same
1773 // .proto file will also be available for lookup in the generated pool.
1774 //
1775 // This function does not actually register the extension, so it does not need
1776 // to be called before the lookup.  However it does need to occur in a function
1777 // that cannot be stripped from the binary (ie. it must be reachable from main).
1778 //
1779 // Best practice is to call this function as close as possible to where the
1780 // reflection is actually needed.  This function is very cheap to call, so you
1781 // should not need to worry about its runtime overhead except in tight loops (on
1782 // x86-64 it compiles into two "mov" instructions).
1783 template <typename ExtendeeType, typename TypeTraitsType,
1784           internal::FieldType field_type, bool is_packed>
1785 void LinkExtensionReflection(
1786     const google::protobuf::internal::ExtensionIdentifier<
1787         ExtendeeType, TypeTraitsType, field_type, is_packed>& extension) {
1788   internal::StrongReference(extension);
1789 }
1790 
1791 // Returns the field descriptor for a generated extension identifier.  This is
1792 // useful when doing reflection over generated extensions.
1793 template <typename ExtendeeType, typename TypeTraitsType,
1794           internal::FieldType field_type, bool is_packed,
1795           typename PoolType = DescriptorPool>
1796 const FieldDescriptor* GetExtensionReflection(
1797     const google::protobuf::internal::ExtensionIdentifier<
1798         ExtendeeType, TypeTraitsType, field_type, is_packed>& extension) {
1799   return PoolType::generated_pool()->FindExtensionByNumber(
1800       google::protobuf::internal::ExtensionIdentifier<ExtendeeType, TypeTraitsType,
1801                                             field_type,
1802                                             is_packed>::Extendee::descriptor(),
1803       extension.number());
1804 }
1805 
1806 }  // namespace protobuf
1807 }  // namespace google
1808 
1809 #include "google/protobuf/port_undef.inc"
1810 
1811 #endif  // GOOGLE_PROTOBUF_EXTENSION_SET_H__