• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 // Author: kenton@google.com (Kenton Varda)
32 //  Based on original Protocol Buffers design by
33 //  Sanjay Ghemawat, Jeff Dean, and others.
34 //
35 // This header is logically internal, but is made public because it is used
36 // from protocol-compiler-generated code, which may reside in other components.
37 
38 #ifndef GOOGLE_PROTOBUF_EXTENSION_SET_H__
39 #define GOOGLE_PROTOBUF_EXTENSION_SET_H__
40 
41 #include <algorithm>
42 #include <cassert>
43 #include <map>
44 #include <string>
45 #include <utility>
46 #include <vector>
47 
48 #include <google/protobuf/stubs/common.h>
49 #include <google/protobuf/stubs/logging.h>
50 #include <google/protobuf/parse_context.h>
51 #include <google/protobuf/io/coded_stream.h>
52 #include <google/protobuf/port.h>
53 #include <google/protobuf/repeated_field.h>
54 #include <google/protobuf/wire_format_lite.h>
55 
56 #include <google/protobuf/port_def.inc>
57 
58 #ifdef SWIG
59 #error "You cannot SWIG proto headers"
60 #endif
61 
62 namespace google {
63 namespace protobuf {
64 class Arena;
65 class Descriptor;       // descriptor.h
66 class FieldDescriptor;  // descriptor.h
67 class DescriptorPool;   // descriptor.h
68 class MessageLite;      // message_lite.h
69 class Message;          // message.h
70 class MessageFactory;   // message.h
71 class UnknownFieldSet;  // unknown_field_set.h
72 namespace internal {
73 class FieldSkipper;  // wire_format_lite.h
74 }  // namespace internal
75 }  // namespace protobuf
76 }  // namespace google
77 
78 namespace google {
79 namespace protobuf {
80 namespace internal {
81 
82 class InternalMetadata;
83 
84 // Used to store values of type WireFormatLite::FieldType without having to
85 // #include wire_format_lite.h.  Also, ensures that we use only one byte to
86 // store these values, which is important to keep the layout of
87 // ExtensionSet::Extension small.
88 typedef uint8 FieldType;
89 
90 // A function which, given an integer value, returns true if the number
91 // matches one of the defined values for the corresponding enum type.  This
92 // is used with RegisterEnumExtension, below.
93 typedef bool EnumValidityFunc(int number);
94 
95 // Version of the above which takes an argument.  This is needed to deal with
96 // extensions that are not compiled in.
97 typedef bool EnumValidityFuncWithArg(const void* arg, int number);
98 
99 // Information about a registered extension.
100 struct ExtensionInfo {
ExtensionInfoExtensionInfo101   inline ExtensionInfo() {}
ExtensionInfoExtensionInfo102   inline ExtensionInfo(FieldType type_param, bool isrepeated, bool ispacked)
103       : type(type_param),
104         is_repeated(isrepeated),
105         is_packed(ispacked),
106         descriptor(NULL) {}
107 
108   FieldType type;
109   bool is_repeated;
110   bool is_packed;
111 
112   struct EnumValidityCheck {
113     EnumValidityFuncWithArg* func;
114     const void* arg;
115   };
116 
117   struct MessageInfo {
118     const MessageLite* prototype;
119   };
120 
121   union {
122     EnumValidityCheck enum_validity_check;
123     MessageInfo message_info;
124   };
125 
126   // The descriptor for this extension, if one exists and is known.  May be
127   // NULL.  Must not be NULL if the descriptor for the extension does not
128   // live in the same pool as the descriptor for the containing type.
129   const FieldDescriptor* descriptor;
130 };
131 
132 // Abstract interface for an object which looks up extension definitions.  Used
133 // when parsing.
134 class PROTOBUF_EXPORT ExtensionFinder {
135  public:
136   virtual ~ExtensionFinder();
137 
138   // Find the extension with the given containing type and number.
139   virtual bool Find(int number, ExtensionInfo* output) = 0;
140 };
141 
142 // Implementation of ExtensionFinder which finds extensions defined in .proto
143 // files which have been compiled into the binary.
144 class PROTOBUF_EXPORT GeneratedExtensionFinder : public ExtensionFinder {
145  public:
GeneratedExtensionFinder(const MessageLite * containing_type)146   GeneratedExtensionFinder(const MessageLite* containing_type)
147       : containing_type_(containing_type) {}
~GeneratedExtensionFinder()148   ~GeneratedExtensionFinder() override {}
149 
150   // Returns true and fills in *output if found, otherwise returns false.
151   bool Find(int number, ExtensionInfo* output) override;
152 
153  private:
154   const MessageLite* containing_type_;
155 };
156 
157 // A FieldSkipper used for parsing MessageSet.
158 class MessageSetFieldSkipper;
159 
160 // Note:  extension_set_heavy.cc defines DescriptorPoolExtensionFinder for
161 // finding extensions from a DescriptorPool.
162 
163 // This is an internal helper class intended for use within the protocol buffer
164 // library and generated classes.  Clients should not use it directly.  Instead,
165 // use the generated accessors such as GetExtension() of the class being
166 // extended.
167 //
168 // This class manages extensions for a protocol message object.  The
169 // message's HasExtension(), GetExtension(), MutableExtension(), and
170 // ClearExtension() methods are just thin wrappers around the embedded
171 // ExtensionSet.  When parsing, if a tag number is encountered which is
172 // inside one of the message type's extension ranges, the tag is passed
173 // off to the ExtensionSet for parsing.  Etc.
174 class PROTOBUF_EXPORT ExtensionSet {
175  public:
176   ExtensionSet();
177   explicit ExtensionSet(Arena* arena);
178   ~ExtensionSet();
179 
180   // These are called at startup by protocol-compiler-generated code to
181   // register known extensions.  The registrations are used by ParseField()
182   // to look up extensions for parsed field numbers.  Note that dynamic parsing
183   // does not use ParseField(); only protocol-compiler-generated parsing
184   // methods do.
185   static void RegisterExtension(const MessageLite* containing_type, int number,
186                                 FieldType type, bool is_repeated,
187                                 bool is_packed);
188   static void RegisterEnumExtension(const MessageLite* containing_type,
189                                     int number, FieldType type,
190                                     bool is_repeated, bool is_packed,
191                                     EnumValidityFunc* is_valid);
192   static void RegisterMessageExtension(const MessageLite* containing_type,
193                                        int number, FieldType type,
194                                        bool is_repeated, bool is_packed,
195                                        const MessageLite* prototype);
196 
197   // =================================================================
198 
199   // Add all fields which are currently present to the given vector.  This
200   // is useful to implement Reflection::ListFields().
201   void AppendToList(const Descriptor* containing_type,
202                     const DescriptorPool* pool,
203                     std::vector<const FieldDescriptor*>* output) const;
204 
205   // =================================================================
206   // Accessors
207   //
208   // Generated message classes include type-safe templated wrappers around
209   // these methods.  Generally you should use those rather than call these
210   // directly, unless you are doing low-level memory management.
211   //
212   // When calling any of these accessors, the extension number requested
213   // MUST exist in the DescriptorPool provided to the constructor.  Otherwise,
214   // the method will fail an assert.  Normally, though, you would not call
215   // these directly; you would either call the generated accessors of your
216   // message class (e.g. GetExtension()) or you would call the accessors
217   // of the reflection interface.  In both cases, it is impossible to
218   // trigger this assert failure:  the generated accessors only accept
219   // linked-in extension types as parameters, while the Reflection interface
220   // requires you to provide the FieldDescriptor describing the extension.
221   //
222   // When calling any of these accessors, a protocol-compiler-generated
223   // implementation of the extension corresponding to the number MUST
224   // be linked in, and the FieldDescriptor used to refer to it MUST be
225   // the one generated by that linked-in code.  Otherwise, the method will
226   // die on an assert failure.  The message objects returned by the message
227   // accessors are guaranteed to be of the correct linked-in type.
228   //
229   // These methods pretty much match Reflection except that:
230   // - They're not virtual.
231   // - They identify fields by number rather than FieldDescriptors.
232   // - They identify enum values using integers rather than descriptors.
233   // - Strings provide Mutable() in addition to Set() accessors.
234 
235   bool Has(int number) const;
236   int ExtensionSize(int number) const;  // Size of a repeated extension.
237   int NumExtensions() const;            // The number of extensions
238   FieldType ExtensionType(int number) const;
239   void ClearExtension(int number);
240 
241   // singular fields -------------------------------------------------
242 
243   int32 GetInt32(int number, int32 default_value) const;
244   int64 GetInt64(int number, int64 default_value) const;
245   uint32 GetUInt32(int number, uint32 default_value) const;
246   uint64 GetUInt64(int number, uint64 default_value) const;
247   float GetFloat(int number, float default_value) const;
248   double GetDouble(int number, double default_value) const;
249   bool GetBool(int number, bool default_value) const;
250   int GetEnum(int number, int default_value) const;
251   const std::string& GetString(int number,
252                                const std::string& default_value) const;
253   const MessageLite& GetMessage(int number,
254                                 const MessageLite& default_value) const;
255   const MessageLite& GetMessage(int number, const Descriptor* message_type,
256                                 MessageFactory* factory) const;
257 
258   // |descriptor| may be NULL so long as it is known that the descriptor for
259   // the extension lives in the same pool as the descriptor for the containing
260   // type.
261 #define desc const FieldDescriptor* descriptor  // avoid line wrapping
262   void SetInt32(int number, FieldType type, int32 value, desc);
263   void SetInt64(int number, FieldType type, int64 value, desc);
264   void SetUInt32(int number, FieldType type, uint32 value, desc);
265   void SetUInt64(int number, FieldType type, uint64 value, desc);
266   void SetFloat(int number, FieldType type, float value, desc);
267   void SetDouble(int number, FieldType type, double value, desc);
268   void SetBool(int number, FieldType type, bool value, desc);
269   void SetEnum(int number, FieldType type, int value, desc);
270   void SetString(int number, FieldType type, std::string value, desc);
271   std::string* MutableString(int number, FieldType type, desc);
272   MessageLite* MutableMessage(int number, FieldType type,
273                               const MessageLite& prototype, desc);
274   MessageLite* MutableMessage(const FieldDescriptor* descriptor,
275                               MessageFactory* factory);
276   // Adds the given message to the ExtensionSet, taking ownership of the
277   // message object. Existing message with the same number will be deleted.
278   // If "message" is NULL, this is equivalent to "ClearExtension(number)".
279   void SetAllocatedMessage(int number, FieldType type,
280                            const FieldDescriptor* descriptor,
281                            MessageLite* message);
282   void UnsafeArenaSetAllocatedMessage(int number, FieldType type,
283                                       const FieldDescriptor* descriptor,
284                                       MessageLite* message);
285   MessageLite* ReleaseMessage(int number, const MessageLite& prototype);
286   MessageLite* UnsafeArenaReleaseMessage(int number,
287                                          const MessageLite& prototype);
288 
289   MessageLite* ReleaseMessage(const FieldDescriptor* descriptor,
290                               MessageFactory* factory);
291   MessageLite* UnsafeArenaReleaseMessage(const FieldDescriptor* descriptor,
292                                          MessageFactory* factory);
293 #undef desc
GetArena()294   Arena* GetArena() const { return arena_; }
295 
296   // repeated fields -------------------------------------------------
297 
298   // Fetches a RepeatedField extension by number; returns |default_value|
299   // if no such extension exists. User should not touch this directly; it is
300   // used by the GetRepeatedExtension() method.
301   const void* GetRawRepeatedField(int number, const void* default_value) const;
302   // Fetches a mutable version of a RepeatedField extension by number,
303   // instantiating one if none exists. Similar to above, user should not use
304   // this directly; it underlies MutableRepeatedExtension().
305   void* MutableRawRepeatedField(int number, FieldType field_type, bool packed,
306                                 const FieldDescriptor* desc);
307 
308   // This is an overload of MutableRawRepeatedField to maintain compatibility
309   // with old code using a previous API. This version of
310   // MutableRawRepeatedField() will GOOGLE_CHECK-fail on a missing extension.
311   // (E.g.: borg/clients/internal/proto1/proto2_reflection.cc.)
312   void* MutableRawRepeatedField(int number);
313 
314   int32 GetRepeatedInt32(int number, int index) const;
315   int64 GetRepeatedInt64(int number, int index) const;
316   uint32 GetRepeatedUInt32(int number, int index) const;
317   uint64 GetRepeatedUInt64(int number, int index) const;
318   float GetRepeatedFloat(int number, int index) const;
319   double GetRepeatedDouble(int number, int index) const;
320   bool GetRepeatedBool(int number, int index) const;
321   int GetRepeatedEnum(int number, int index) const;
322   const std::string& GetRepeatedString(int number, int index) const;
323   const MessageLite& GetRepeatedMessage(int number, int index) const;
324 
325   void SetRepeatedInt32(int number, int index, int32 value);
326   void SetRepeatedInt64(int number, int index, int64 value);
327   void SetRepeatedUInt32(int number, int index, uint32 value);
328   void SetRepeatedUInt64(int number, int index, uint64 value);
329   void SetRepeatedFloat(int number, int index, float value);
330   void SetRepeatedDouble(int number, int index, double value);
331   void SetRepeatedBool(int number, int index, bool value);
332   void SetRepeatedEnum(int number, int index, int value);
333   void SetRepeatedString(int number, int index, std::string value);
334   std::string* MutableRepeatedString(int number, int index);
335   MessageLite* MutableRepeatedMessage(int number, int index);
336 
337 #define desc const FieldDescriptor* descriptor  // avoid line wrapping
338   void AddInt32(int number, FieldType type, bool packed, int32 value, desc);
339   void AddInt64(int number, FieldType type, bool packed, int64 value, desc);
340   void AddUInt32(int number, FieldType type, bool packed, uint32 value, desc);
341   void AddUInt64(int number, FieldType type, bool packed, uint64 value, desc);
342   void AddFloat(int number, FieldType type, bool packed, float value, desc);
343   void AddDouble(int number, FieldType type, bool packed, double value, desc);
344   void AddBool(int number, FieldType type, bool packed, bool value, desc);
345   void AddEnum(int number, FieldType type, bool packed, int value, desc);
346   void AddString(int number, FieldType type, std::string value, desc);
347   std::string* AddString(int number, FieldType type, desc);
348   MessageLite* AddMessage(int number, FieldType type,
349                           const MessageLite& prototype, desc);
350   MessageLite* AddMessage(const FieldDescriptor* descriptor,
351                           MessageFactory* factory);
352   void AddAllocatedMessage(const FieldDescriptor* descriptor,
353                            MessageLite* new_entry);
354 #undef desc
355 
356   void RemoveLast(int number);
357   MessageLite* ReleaseLast(int number);
358   void SwapElements(int number, int index1, int index2);
359 
360   // -----------------------------------------------------------------
361   // TODO(kenton):  Hardcore memory management accessors
362 
363   // =================================================================
364   // convenience methods for implementing methods of Message
365   //
366   // These could all be implemented in terms of the other methods of this
367   // class, but providing them here helps keep the generated code size down.
368 
369   void Clear();
370   void MergeFrom(const ExtensionSet& other);
371   void Swap(ExtensionSet* other);
372   void SwapExtension(ExtensionSet* other, int number);
373   bool IsInitialized() const;
374 
375   // Parses a single extension from the input. The input should start out
376   // positioned immediately after the tag.
377   bool ParseField(uint32 tag, io::CodedInputStream* input,
378                   ExtensionFinder* extension_finder,
379                   FieldSkipper* field_skipper);
380 
381   // Specific versions for lite or full messages (constructs the appropriate
382   // FieldSkipper automatically).  |containing_type| is the default
383   // instance for the containing message; it is used only to look up the
384   // extension by number.  See RegisterExtension(), above.  Unlike the other
385   // methods of ExtensionSet, this only works for generated message types --
386   // it looks up extensions registered using RegisterExtension().
387   bool ParseField(uint32 tag, io::CodedInputStream* input,
388                   const MessageLite* containing_type);
389   bool ParseField(uint32 tag, io::CodedInputStream* input,
390                   const Message* containing_type,
391                   UnknownFieldSet* unknown_fields);
392   bool ParseField(uint32 tag, io::CodedInputStream* input,
393                   const MessageLite* containing_type,
394                   io::CodedOutputStream* unknown_fields);
395 
396   // Lite parser
397   const char* ParseField(uint64 tag, const char* ptr,
398                          const MessageLite* containing_type,
399                          internal::InternalMetadata* metadata,
400                          internal::ParseContext* ctx);
401   // Full parser
402   const char* ParseField(uint64 tag, const char* ptr,
403                          const Message* containing_type,
404                          internal::InternalMetadata* metadata,
405                          internal::ParseContext* ctx);
406   template <typename Msg>
ParseMessageSet(const char * ptr,const Msg * containing_type,InternalMetadata * metadata,internal::ParseContext * ctx)407   const char* ParseMessageSet(const char* ptr, const Msg* containing_type,
408                               InternalMetadata* metadata,
409                               internal::ParseContext* ctx) {
410     struct MessageSetItem {
411       const char* _InternalParse(const char* ptr, ParseContext* ctx) {
412         return me->ParseMessageSetItem(ptr, containing_type, metadata, ctx);
413       }
414       ExtensionSet* me;
415       const Msg* containing_type;
416       InternalMetadata* metadata;
417     } item{this, containing_type, metadata};
418     while (!ctx->Done(&ptr)) {
419       uint32 tag;
420       ptr = ReadTag(ptr, &tag);
421       GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
422       if (tag == WireFormatLite::kMessageSetItemStartTag) {
423         ptr = ctx->ParseGroup(&item, ptr, tag);
424         GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
425       } else {
426         if (tag == 0 || (tag & 7) == 4) {
427           ctx->SetLastTag(tag);
428           return ptr;
429         }
430         ptr = ParseField(tag, ptr, containing_type, metadata, ctx);
431         GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
432       }
433     }
434     return ptr;
435   }
436 
437   // Parse an entire message in MessageSet format.  Such messages have no
438   // fields, only extensions.
439   bool ParseMessageSetLite(io::CodedInputStream* input,
440                            ExtensionFinder* extension_finder,
441                            FieldSkipper* field_skipper);
442   bool ParseMessageSet(io::CodedInputStream* input,
443                        ExtensionFinder* extension_finder,
444                        MessageSetFieldSkipper* field_skipper);
445 
446   // Specific versions for lite or full messages (constructs the appropriate
447   // FieldSkipper automatically).
448   bool ParseMessageSet(io::CodedInputStream* input,
449                        const MessageLite* containing_type,
450                        std::string* unknown_fields);
451   bool ParseMessageSet(io::CodedInputStream* input,
452                        const Message* containing_type,
453                        UnknownFieldSet* unknown_fields);
454 
455   // Write all extension fields with field numbers in the range
456   //   [start_field_number, end_field_number)
457   // to the output stream, using the cached sizes computed when ByteSize() was
458   // last called.  Note that the range bounds are inclusive-exclusive.
SerializeWithCachedSizes(int start_field_number,int end_field_number,io::CodedOutputStream * output)459   void SerializeWithCachedSizes(int start_field_number, int end_field_number,
460                                 io::CodedOutputStream* output) const {
461     output->SetCur(_InternalSerialize(start_field_number, end_field_number,
462                                       output->Cur(), output->EpsCopy()));
463   }
464 
465   // Same as SerializeWithCachedSizes, but without any bounds checking.
466   // The caller must ensure that target has sufficient capacity for the
467   // serialized extensions.
468   //
469   // Returns a pointer past the last written byte.
470   uint8* _InternalSerialize(int start_field_number, int end_field_number,
471                             uint8* target,
472                             io::EpsCopyOutputStream* stream) const;
473 
474   // Like above but serializes in MessageSet format.
SerializeMessageSetWithCachedSizes(io::CodedOutputStream * output)475   void SerializeMessageSetWithCachedSizes(io::CodedOutputStream* output) const {
476     output->SetCur(InternalSerializeMessageSetWithCachedSizesToArray(
477         output->Cur(), output->EpsCopy()));
478   }
479   uint8* InternalSerializeMessageSetWithCachedSizesToArray(
480       uint8* target, io::EpsCopyOutputStream* stream) const;
481 
482   // For backward-compatibility, versions of two of the above methods that
483   // serialize deterministically iff SetDefaultSerializationDeterministic()
484   // has been called.
485   uint8* SerializeWithCachedSizesToArray(int start_field_number,
486                                          int end_field_number,
487                                          uint8* target) const;
488   uint8* SerializeMessageSetWithCachedSizesToArray(uint8* target) const;
489 
490   // Returns the total serialized size of all the extensions.
491   size_t ByteSize() const;
492 
493   // Like ByteSize() but uses MessageSet format.
494   size_t MessageSetByteSize() const;
495 
496   // Returns (an estimate of) the total number of bytes used for storing the
497   // extensions in memory, excluding sizeof(*this).  If the ExtensionSet is
498   // for a lite message (and thus possibly contains lite messages), the results
499   // are undefined (might work, might crash, might corrupt data, might not even
500   // be linked in).  It's up to the protocol compiler to avoid calling this on
501   // such ExtensionSets (easy enough since lite messages don't implement
502   // SpaceUsed()).
503   size_t SpaceUsedExcludingSelfLong() const;
504 
505   // This method just calls SpaceUsedExcludingSelfLong() but it can not be
506   // inlined because the definition of SpaceUsedExcludingSelfLong() is not
507   // included in lite runtime and when an inline method refers to it MSVC
508   // will complain about unresolved symbols when building the lite runtime
509   // as .dll.
510   int SpaceUsedExcludingSelf() const;
511 
512  private:
513   // Interface of a lazily parsed singular message extension.
514   class PROTOBUF_EXPORT LazyMessageExtension {
515    public:
LazyMessageExtension()516     LazyMessageExtension() {}
~LazyMessageExtension()517     virtual ~LazyMessageExtension() {}
518 
519     virtual LazyMessageExtension* New(Arena* arena) const = 0;
520     virtual const MessageLite& GetMessage(
521         const MessageLite& prototype) const = 0;
522     virtual MessageLite* MutableMessage(const MessageLite& prototype) = 0;
523     virtual void SetAllocatedMessage(MessageLite* message) = 0;
524     virtual void UnsafeArenaSetAllocatedMessage(MessageLite* message) = 0;
525     virtual MessageLite* ReleaseMessage(const MessageLite& prototype) = 0;
526     virtual MessageLite* UnsafeArenaReleaseMessage(
527         const MessageLite& prototype) = 0;
528 
529     virtual bool IsInitialized() const = 0;
530 
531     PROTOBUF_DEPRECATED_MSG("Please use ByteSizeLong() instead")
ByteSize()532     virtual int ByteSize() const { return internal::ToIntSize(ByteSizeLong()); }
533     virtual size_t ByteSizeLong() const = 0;
534     virtual size_t SpaceUsedLong() const = 0;
535 
536     virtual void MergeFrom(const LazyMessageExtension& other) = 0;
537     virtual void Clear() = 0;
538 
539     virtual bool ReadMessage(const MessageLite& prototype,
540                              io::CodedInputStream* input) = 0;
541     virtual const char* _InternalParse(const char* ptr, ParseContext* ctx) = 0;
542     virtual uint8* WriteMessageToArray(
543         int number, uint8* target, io::EpsCopyOutputStream* stream) const = 0;
544 
545    private:
546     virtual void UnusedKeyMethod();  // Dummy key method to avoid weak vtable.
547 
548     GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(LazyMessageExtension);
549   };
550   struct Extension {
551     // The order of these fields packs Extension into 24 bytes when using 8
552     // byte alignment. Consider this when adding or removing fields here.
553     union {
554       int32 int32_value;
555       int64 int64_value;
556       uint32 uint32_value;
557       uint64 uint64_value;
558       float float_value;
559       double double_value;
560       bool bool_value;
561       int enum_value;
562       std::string* string_value;
563       MessageLite* message_value;
564       LazyMessageExtension* lazymessage_value;
565 
566       RepeatedField<int32>* repeated_int32_value;
567       RepeatedField<int64>* repeated_int64_value;
568       RepeatedField<uint32>* repeated_uint32_value;
569       RepeatedField<uint64>* repeated_uint64_value;
570       RepeatedField<float>* repeated_float_value;
571       RepeatedField<double>* repeated_double_value;
572       RepeatedField<bool>* repeated_bool_value;
573       RepeatedField<int>* repeated_enum_value;
574       RepeatedPtrField<std::string>* repeated_string_value;
575       RepeatedPtrField<MessageLite>* repeated_message_value;
576     };
577 
578     FieldType type;
579     bool is_repeated;
580 
581     // For singular types, indicates if the extension is "cleared".  This
582     // happens when an extension is set and then later cleared by the caller.
583     // We want to keep the Extension object around for reuse, so instead of
584     // removing it from the map, we just set is_cleared = true.  This has no
585     // meaning for repeated types; for those, the size of the RepeatedField
586     // simply becomes zero when cleared.
587     bool is_cleared : 4;
588 
589     // For singular message types, indicates whether lazy parsing is enabled
590     // for this extension. This field is only valid when type == TYPE_MESSAGE
591     // and !is_repeated because we only support lazy parsing for singular
592     // message types currently. If is_lazy = true, the extension is stored in
593     // lazymessage_value. Otherwise, the extension will be message_value.
594     bool is_lazy : 4;
595 
596     // For repeated types, this indicates if the [packed=true] option is set.
597     bool is_packed;
598 
599     // For packed fields, the size of the packed data is recorded here when
600     // ByteSize() is called then used during serialization.
601     // TODO(kenton):  Use atomic<int> when C++ supports it.
602     mutable int cached_size;
603 
604     // The descriptor for this extension, if one exists and is known.  May be
605     // NULL.  Must not be NULL if the descriptor for the extension does not
606     // live in the same pool as the descriptor for the containing type.
607     const FieldDescriptor* descriptor;
608 
609     // Some helper methods for operations on a single Extension.
610     uint8* InternalSerializeFieldWithCachedSizesToArray(
611         int number, uint8* target, io::EpsCopyOutputStream* stream) const;
612     uint8* InternalSerializeMessageSetItemWithCachedSizesToArray(
613         int number, uint8* target, io::EpsCopyOutputStream* stream) const;
614     size_t ByteSize(int number) const;
615     size_t MessageSetItemByteSize(int number) const;
616     void Clear();
617     int GetSize() const;
618     void Free();
619     size_t SpaceUsedExcludingSelfLong() const;
620     bool IsInitialized() const;
621   };
622 
623   // The Extension struct is small enough to be passed by value, so we use it
624   // directly as the value type in mappings rather than use pointers.  We use
625   // sorted maps rather than hash-maps because we expect most ExtensionSets will
626   // only contain a small number of extension.  Also, we want AppendToList and
627   // deterministic serialization to order fields by field number.
628 
629   struct KeyValue {
630     int first;
631     Extension second;
632 
633     struct FirstComparator {
operatorKeyValue::FirstComparator634       bool operator()(const KeyValue& lhs, const KeyValue& rhs) const {
635         return lhs.first < rhs.first;
636       }
operatorKeyValue::FirstComparator637       bool operator()(const KeyValue& lhs, int key) const {
638         return lhs.first < key;
639       }
operatorKeyValue::FirstComparator640       bool operator()(int key, const KeyValue& rhs) const {
641         return key < rhs.first;
642       }
643     };
644   };
645 
646   typedef std::map<int, Extension> LargeMap;
647 
648   // Wrapper API that switches between flat-map and LargeMap.
649 
650   // Finds a key (if present) in the ExtensionSet.
651   const Extension* FindOrNull(int key) const;
652   Extension* FindOrNull(int key);
653 
654   // Helper-functions that only inspect the LargeMap.
655   const Extension* FindOrNullInLargeMap(int key) const;
656   Extension* FindOrNullInLargeMap(int key);
657 
658   // Inserts a new (key, Extension) into the ExtensionSet (and returns true), or
659   // finds the already-existing Extension for that key (returns false).
660   // The Extension* will point to the new-or-found Extension.
661   std::pair<Extension*, bool> Insert(int key);
662 
663   // Grows the flat_capacity_.
664   // If flat_capacity_ > kMaximumFlatCapacity, converts to LargeMap.
665   void GrowCapacity(size_t minimum_new_capacity);
666   static constexpr uint16 kMaximumFlatCapacity = 256;
is_large()667   bool is_large() const { return flat_capacity_ > kMaximumFlatCapacity; }
668 
669   // Removes a key from the ExtensionSet.
670   void Erase(int key);
671 
Size()672   size_t Size() const {
673     return PROTOBUF_PREDICT_FALSE(is_large()) ? map_.large->size() : flat_size_;
674   }
675 
676   // Similar to std::for_each.
677   // Each Iterator is decomposed into ->first and ->second fields, so
678   // that the KeyValueFunctor can be agnostic vis-a-vis KeyValue-vs-std::pair.
679   template <typename Iterator, typename KeyValueFunctor>
ForEach(Iterator begin,Iterator end,KeyValueFunctor func)680   static KeyValueFunctor ForEach(Iterator begin, Iterator end,
681                                  KeyValueFunctor func) {
682     for (Iterator it = begin; it != end; ++it) func(it->first, it->second);
683     return std::move(func);
684   }
685 
686   // Applies a functor to the <int, Extension&> pairs in sorted order.
687   template <typename KeyValueFunctor>
ForEach(KeyValueFunctor func)688   KeyValueFunctor ForEach(KeyValueFunctor func) {
689     if (PROTOBUF_PREDICT_FALSE(is_large())) {
690       return ForEach(map_.large->begin(), map_.large->end(), std::move(func));
691     }
692     return ForEach(flat_begin(), flat_end(), std::move(func));
693   }
694 
695   // Applies a functor to the <int, const Extension&> pairs in sorted order.
696   template <typename KeyValueFunctor>
ForEach(KeyValueFunctor func)697   KeyValueFunctor ForEach(KeyValueFunctor func) const {
698     if (PROTOBUF_PREDICT_FALSE(is_large())) {
699       return ForEach(map_.large->begin(), map_.large->end(), std::move(func));
700     }
701     return ForEach(flat_begin(), flat_end(), std::move(func));
702   }
703 
704   // Merges existing Extension from other_extension
705   void InternalExtensionMergeFrom(int number, const Extension& other_extension);
706 
707   // Returns true and fills field_number and extension if extension is found.
708   // Note to support packed repeated field compatibility, it also fills whether
709   // the tag on wire is packed, which can be different from
710   // extension->is_packed (whether packed=true is specified).
711   bool FindExtensionInfoFromTag(uint32 tag, ExtensionFinder* extension_finder,
712                                 int* field_number, ExtensionInfo* extension,
713                                 bool* was_packed_on_wire);
714 
715   // Returns true and fills extension if extension is found.
716   // Note to support packed repeated field compatibility, it also fills whether
717   // the tag on wire is packed, which can be different from
718   // extension->is_packed (whether packed=true is specified).
719   bool FindExtensionInfoFromFieldNumber(int wire_type, int field_number,
720                                         ExtensionFinder* extension_finder,
721                                         ExtensionInfo* extension,
722                                         bool* was_packed_on_wire);
723 
724   // Parses a single extension from the input. The input should start out
725   // positioned immediately after the wire tag. This method is called in
726   // ParseField() after field number and was_packed_on_wire is extracted from
727   // the wire tag and ExtensionInfo is found by the field number.
728   bool ParseFieldWithExtensionInfo(int field_number, bool was_packed_on_wire,
729                                    const ExtensionInfo& extension,
730                                    io::CodedInputStream* input,
731                                    FieldSkipper* field_skipper);
732 
733   // Like ParseField(), but this method may parse singular message extensions
734   // lazily depending on the value of FLAGS_eagerly_parse_message_sets.
735   bool ParseFieldMaybeLazily(int wire_type, int field_number,
736                              io::CodedInputStream* input,
737                              ExtensionFinder* extension_finder,
738                              MessageSetFieldSkipper* field_skipper);
739 
740   // Gets the extension with the given number, creating it if it does not
741   // already exist.  Returns true if the extension did not already exist.
742   bool MaybeNewExtension(int number, const FieldDescriptor* descriptor,
743                          Extension** result);
744 
745   // Gets the repeated extension for the given descriptor, creating it if
746   // it does not exist.
747   Extension* MaybeNewRepeatedExtension(const FieldDescriptor* descriptor);
748 
749   // Parse a single MessageSet item -- called just after the item group start
750   // tag has been read.
751   bool ParseMessageSetItemLite(io::CodedInputStream* input,
752                                ExtensionFinder* extension_finder,
753                                FieldSkipper* field_skipper);
754   // Parse a single MessageSet item -- called just after the item group start
755   // tag has been read.
756   bool ParseMessageSetItem(io::CodedInputStream* input,
757                            ExtensionFinder* extension_finder,
758                            MessageSetFieldSkipper* field_skipper);
759 
FindExtension(int wire_type,uint32 field,const MessageLite * containing_type,const internal::ParseContext *,ExtensionInfo * extension,bool * was_packed_on_wire)760   bool FindExtension(int wire_type, uint32 field,
761                      const MessageLite* containing_type,
762                      const internal::ParseContext* /*ctx*/,
763                      ExtensionInfo* extension, bool* was_packed_on_wire) {
764     GeneratedExtensionFinder finder(containing_type);
765     return FindExtensionInfoFromFieldNumber(wire_type, field, &finder,
766                                             extension, was_packed_on_wire);
767   }
768   inline bool FindExtension(int wire_type, uint32 field,
769                             const Message* containing_type,
770                             const internal::ParseContext* ctx,
771                             ExtensionInfo* extension, bool* was_packed_on_wire);
772   // Used for MessageSet only
ParseFieldMaybeLazily(uint64 tag,const char * ptr,const MessageLite * containing_type,internal::InternalMetadata * metadata,internal::ParseContext * ctx)773   const char* ParseFieldMaybeLazily(uint64 tag, const char* ptr,
774                                     const MessageLite* containing_type,
775                                     internal::InternalMetadata* metadata,
776                                     internal::ParseContext* ctx) {
777     // Lite MessageSet doesn't implement lazy.
778     return ParseField(tag, ptr, containing_type, metadata, ctx);
779   }
780   const char* ParseFieldMaybeLazily(uint64 tag, const char* ptr,
781                                     const Message* containing_type,
782                                     internal::InternalMetadata* metadata,
783                                     internal::ParseContext* ctx);
784   const char* ParseMessageSetItem(const char* ptr,
785                                   const MessageLite* containing_type,
786                                   internal::InternalMetadata* metadata,
787                                   internal::ParseContext* ctx);
788   const char* ParseMessageSetItem(const char* ptr,
789                                   const Message* containing_type,
790                                   internal::InternalMetadata* metadata,
791                                   internal::ParseContext* ctx);
792 
793   // Implemented in extension_set_inl.h to keep code out of the header file.
794   template <typename T>
795   const char* ParseFieldWithExtensionInfo(int number, bool was_packed_on_wire,
796                                           const ExtensionInfo& info,
797                                           internal::InternalMetadata* metadata,
798                                           const char* ptr,
799                                           internal::ParseContext* ctx);
800   template <typename Msg, typename T>
801   const char* ParseMessageSetItemTmpl(const char* ptr,
802                                       const Msg* containing_type,
803                                       internal::InternalMetadata* metadata,
804                                       internal::ParseContext* ctx);
805 
806   // Hack:  RepeatedPtrFieldBase declares ExtensionSet as a friend.  This
807   //   friendship should automatically extend to ExtensionSet::Extension, but
808   //   unfortunately some older compilers (e.g. GCC 3.4.4) do not implement this
809   //   correctly.  So, we must provide helpers for calling methods of that
810   //   class.
811 
812   // Defined in extension_set_heavy.cc.
813   static inline size_t RepeatedMessage_SpaceUsedExcludingSelfLong(
814       RepeatedPtrFieldBase* field);
815 
flat_begin()816   KeyValue* flat_begin() {
817     assert(!is_large());
818     return map_.flat;
819   }
flat_begin()820   const KeyValue* flat_begin() const {
821     assert(!is_large());
822     return map_.flat;
823   }
flat_end()824   KeyValue* flat_end() {
825     assert(!is_large());
826     return map_.flat + flat_size_;
827   }
flat_end()828   const KeyValue* flat_end() const {
829     assert(!is_large());
830     return map_.flat + flat_size_;
831   }
832 
833   Arena* arena_;
834 
835   // Manual memory-management:
836   // map_.flat is an allocated array of flat_capacity_ elements.
837   // [map_.flat, map_.flat + flat_size_) is the currently-in-use prefix.
838   uint16 flat_capacity_;
839   uint16 flat_size_;
840   union AllocatedData {
841     KeyValue* flat;
842 
843     // If flat_capacity_ > kMaximumFlatCapacity, switch to LargeMap,
844     // which guarantees O(n lg n) CPU but larger constant factors.
845     LargeMap* large;
846   } map_;
847 
848   static void DeleteFlatMap(const KeyValue* flat, uint16 flat_capacity);
849 
850   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionSet);
851 };
852 
853 // These are just for convenience...
SetString(int number,FieldType type,std::string value,const FieldDescriptor * descriptor)854 inline void ExtensionSet::SetString(int number, FieldType type,
855                                     std::string value,
856                                     const FieldDescriptor* descriptor) {
857   MutableString(number, type, descriptor)->assign(std::move(value));
858 }
SetRepeatedString(int number,int index,std::string value)859 inline void ExtensionSet::SetRepeatedString(int number, int index,
860                                             std::string value) {
861   MutableRepeatedString(number, index)->assign(std::move(value));
862 }
AddString(int number,FieldType type,std::string value,const FieldDescriptor * descriptor)863 inline void ExtensionSet::AddString(int number, FieldType type,
864                                     std::string value,
865                                     const FieldDescriptor* descriptor) {
866   AddString(number, type, descriptor)->assign(std::move(value));
867 }
868 // ===================================================================
869 // Glue for generated extension accessors
870 
871 // -------------------------------------------------------------------
872 // Template magic
873 
874 // First we have a set of classes representing "type traits" for different
875 // field types.  A type traits class knows how to implement basic accessors
876 // for extensions of a particular type given an ExtensionSet.  The signature
877 // for a type traits class looks like this:
878 //
879 //   class TypeTraits {
880 //    public:
881 //     typedef ? ConstType;
882 //     typedef ? MutableType;
883 //     // TypeTraits for singular fields and repeated fields will define the
884 //     // symbol "Singular" or "Repeated" respectively. These two symbols will
885 //     // be used in extension accessors to distinguish between singular
886 //     // extensions and repeated extensions. If the TypeTraits for the passed
887 //     // in extension doesn't have the expected symbol defined, it means the
888 //     // user is passing a repeated extension to a singular accessor, or the
889 //     // opposite. In that case the C++ compiler will generate an error
890 //     // message "no matching member function" to inform the user.
891 //     typedef ? Singular
892 //     typedef ? Repeated
893 //
894 //     static inline ConstType Get(int number, const ExtensionSet& set);
895 //     static inline void Set(int number, ConstType value, ExtensionSet* set);
896 //     static inline MutableType Mutable(int number, ExtensionSet* set);
897 //
898 //     // Variants for repeated fields.
899 //     static inline ConstType Get(int number, const ExtensionSet& set,
900 //                                 int index);
901 //     static inline void Set(int number, int index,
902 //                            ConstType value, ExtensionSet* set);
903 //     static inline MutableType Mutable(int number, int index,
904 //                                       ExtensionSet* set);
905 //     static inline void Add(int number, ConstType value, ExtensionSet* set);
906 //     static inline MutableType Add(int number, ExtensionSet* set);
907 //     This is used by the ExtensionIdentifier constructor to register
908 //     the extension at dynamic initialization.
909 //     template <typename ExtendeeT>
910 //     static void Register(int number, FieldType type, bool is_packed);
911 //   };
912 //
913 // Not all of these methods make sense for all field types.  For example, the
914 // "Mutable" methods only make sense for strings and messages, and the
915 // repeated methods only make sense for repeated types.  So, each type
916 // traits class implements only the set of methods from this signature that it
917 // actually supports.  This will cause a compiler error if the user tries to
918 // access an extension using a method that doesn't make sense for its type.
919 // For example, if "foo" is an extension of type "optional int32", then if you
920 // try to write code like:
921 //   my_message.MutableExtension(foo)
922 // you will get a compile error because PrimitiveTypeTraits<int32> does not
923 // have a "Mutable()" method.
924 
925 // -------------------------------------------------------------------
926 // PrimitiveTypeTraits
927 
928 // Since the ExtensionSet has different methods for each primitive type,
929 // we must explicitly define the methods of the type traits class for each
930 // known type.
931 template <typename Type>
932 class PrimitiveTypeTraits {
933  public:
934   typedef Type ConstType;
935   typedef Type MutableType;
936   typedef PrimitiveTypeTraits<Type> Singular;
937 
938   static inline ConstType Get(int number, const ExtensionSet& set,
939                               ConstType default_value);
940   static inline void Set(int number, FieldType field_type, ConstType value,
941                          ExtensionSet* set);
942   template <typename ExtendeeT>
Register(int number,FieldType type,bool is_packed)943   static void Register(int number, FieldType type, bool is_packed) {
944     ExtensionSet::RegisterExtension(&ExtendeeT::default_instance(), number,
945                                     type, false, is_packed);
946   }
947 };
948 
949 template <typename Type>
950 class RepeatedPrimitiveTypeTraits {
951  public:
952   typedef Type ConstType;
953   typedef Type MutableType;
954   typedef RepeatedPrimitiveTypeTraits<Type> Repeated;
955 
956   typedef RepeatedField<Type> RepeatedFieldType;
957 
958   static inline Type Get(int number, const ExtensionSet& set, int index);
959   static inline void Set(int number, int index, Type value, ExtensionSet* set);
960   static inline void Add(int number, FieldType field_type, bool is_packed,
961                          Type value, ExtensionSet* set);
962 
963   static inline const RepeatedField<ConstType>& GetRepeated(
964       int number, const ExtensionSet& set);
965   static inline RepeatedField<Type>* MutableRepeated(int number,
966                                                      FieldType field_type,
967                                                      bool is_packed,
968                                                      ExtensionSet* set);
969 
970   static const RepeatedFieldType* GetDefaultRepeatedField();
971   template <typename ExtendeeT>
Register(int number,FieldType type,bool is_packed)972   static void Register(int number, FieldType type, bool is_packed) {
973     ExtensionSet::RegisterExtension(&ExtendeeT::default_instance(), number,
974                                     type, true, is_packed);
975   }
976 };
977 
978 class PROTOBUF_EXPORT RepeatedPrimitiveDefaults {
979  private:
980   template <typename Type>
981   friend class RepeatedPrimitiveTypeTraits;
982   static const RepeatedPrimitiveDefaults* default_instance();
983   RepeatedField<int32> default_repeated_field_int32_;
984   RepeatedField<int64> default_repeated_field_int64_;
985   RepeatedField<uint32> default_repeated_field_uint32_;
986   RepeatedField<uint64> default_repeated_field_uint64_;
987   RepeatedField<double> default_repeated_field_double_;
988   RepeatedField<float> default_repeated_field_float_;
989   RepeatedField<bool> default_repeated_field_bool_;
990 };
991 
992 #define PROTOBUF_DEFINE_PRIMITIVE_TYPE(TYPE, METHOD)                           \
993   template <>                                                                  \
994   inline TYPE PrimitiveTypeTraits<TYPE>::Get(                                  \
995       int number, const ExtensionSet& set, TYPE default_value) {               \
996     return set.Get##METHOD(number, default_value);                             \
997   }                                                                            \
998   template <>                                                                  \
999   inline void PrimitiveTypeTraits<TYPE>::Set(int number, FieldType field_type, \
1000                                              TYPE value, ExtensionSet* set) {  \
1001     set->Set##METHOD(number, field_type, value, NULL);                         \
1002   }                                                                            \
1003                                                                                \
1004   template <>                                                                  \
1005   inline TYPE RepeatedPrimitiveTypeTraits<TYPE>::Get(                          \
1006       int number, const ExtensionSet& set, int index) {                        \
1007     return set.GetRepeated##METHOD(number, index);                             \
1008   }                                                                            \
1009   template <>                                                                  \
1010   inline void RepeatedPrimitiveTypeTraits<TYPE>::Set(                          \
1011       int number, int index, TYPE value, ExtensionSet* set) {                  \
1012     set->SetRepeated##METHOD(number, index, value);                            \
1013   }                                                                            \
1014   template <>                                                                  \
1015   inline void RepeatedPrimitiveTypeTraits<TYPE>::Add(                          \
1016       int number, FieldType field_type, bool is_packed, TYPE value,            \
1017       ExtensionSet* set) {                                                     \
1018     set->Add##METHOD(number, field_type, is_packed, value, NULL);              \
1019   }                                                                            \
1020   template <>                                                                  \
1021   inline const RepeatedField<TYPE>*                                            \
1022   RepeatedPrimitiveTypeTraits<TYPE>::GetDefaultRepeatedField() {               \
1023     return &RepeatedPrimitiveDefaults::default_instance()                      \
1024                 ->default_repeated_field_##TYPE##_;                            \
1025   }                                                                            \
1026   template <>                                                                  \
1027   inline const RepeatedField<TYPE>&                                            \
1028   RepeatedPrimitiveTypeTraits<TYPE>::GetRepeated(int number,                   \
1029                                                  const ExtensionSet& set) {    \
1030     return *reinterpret_cast<const RepeatedField<TYPE>*>(                      \
1031         set.GetRawRepeatedField(number, GetDefaultRepeatedField()));           \
1032   }                                                                            \
1033   template <>                                                                  \
1034   inline RepeatedField<TYPE>*                                                  \
1035   RepeatedPrimitiveTypeTraits<TYPE>::MutableRepeated(                          \
1036       int number, FieldType field_type, bool is_packed, ExtensionSet* set) {   \
1037     return reinterpret_cast<RepeatedField<TYPE>*>(                             \
1038         set->MutableRawRepeatedField(number, field_type, is_packed, NULL));    \
1039   }
1040 
PROTOBUF_DEFINE_PRIMITIVE_TYPE(int32,Int32)1041 PROTOBUF_DEFINE_PRIMITIVE_TYPE(int32, Int32)
1042 PROTOBUF_DEFINE_PRIMITIVE_TYPE(int64, Int64)
1043 PROTOBUF_DEFINE_PRIMITIVE_TYPE(uint32, UInt32)
1044 PROTOBUF_DEFINE_PRIMITIVE_TYPE(uint64, UInt64)
1045 PROTOBUF_DEFINE_PRIMITIVE_TYPE(float, Float)
1046 PROTOBUF_DEFINE_PRIMITIVE_TYPE(double, Double)
1047 PROTOBUF_DEFINE_PRIMITIVE_TYPE(bool, Bool)
1048 
1049 #undef PROTOBUF_DEFINE_PRIMITIVE_TYPE
1050 
1051 // -------------------------------------------------------------------
1052 // StringTypeTraits
1053 
1054 // Strings support both Set() and Mutable().
1055 class PROTOBUF_EXPORT StringTypeTraits {
1056  public:
1057   typedef const std::string& ConstType;
1058   typedef std::string* MutableType;
1059   typedef StringTypeTraits Singular;
1060 
1061   static inline const std::string& Get(int number, const ExtensionSet& set,
1062                                        ConstType default_value) {
1063     return set.GetString(number, default_value);
1064   }
1065   static inline void Set(int number, FieldType field_type,
1066                          const std::string& value, ExtensionSet* set) {
1067     set->SetString(number, field_type, value, NULL);
1068   }
1069   static inline std::string* Mutable(int number, FieldType field_type,
1070                                      ExtensionSet* set) {
1071     return set->MutableString(number, field_type, NULL);
1072   }
1073   template <typename ExtendeeT>
1074   static void Register(int number, FieldType type, bool is_packed) {
1075     ExtensionSet::RegisterExtension(&ExtendeeT::default_instance(), number,
1076                                     type, false, is_packed);
1077   }
1078 };
1079 
1080 class PROTOBUF_EXPORT RepeatedStringTypeTraits {
1081  public:
1082   typedef const std::string& ConstType;
1083   typedef std::string* MutableType;
1084   typedef RepeatedStringTypeTraits Repeated;
1085 
1086   typedef RepeatedPtrField<std::string> RepeatedFieldType;
1087 
Get(int number,const ExtensionSet & set,int index)1088   static inline const std::string& Get(int number, const ExtensionSet& set,
1089                                        int index) {
1090     return set.GetRepeatedString(number, index);
1091   }
Set(int number,int index,const std::string & value,ExtensionSet * set)1092   static inline void Set(int number, int index, const std::string& value,
1093                          ExtensionSet* set) {
1094     set->SetRepeatedString(number, index, value);
1095   }
Mutable(int number,int index,ExtensionSet * set)1096   static inline std::string* Mutable(int number, int index, ExtensionSet* set) {
1097     return set->MutableRepeatedString(number, index);
1098   }
Add(int number,FieldType field_type,bool,const std::string & value,ExtensionSet * set)1099   static inline void Add(int number, FieldType field_type, bool /*is_packed*/,
1100                          const std::string& value, ExtensionSet* set) {
1101     set->AddString(number, field_type, value, NULL);
1102   }
Add(int number,FieldType field_type,ExtensionSet * set)1103   static inline std::string* Add(int number, FieldType field_type,
1104                                  ExtensionSet* set) {
1105     return set->AddString(number, field_type, NULL);
1106   }
GetRepeated(int number,const ExtensionSet & set)1107   static inline const RepeatedPtrField<std::string>& GetRepeated(
1108       int number, const ExtensionSet& set) {
1109     return *reinterpret_cast<const RepeatedPtrField<std::string>*>(
1110         set.GetRawRepeatedField(number, GetDefaultRepeatedField()));
1111   }
1112 
MutableRepeated(int number,FieldType field_type,bool is_packed,ExtensionSet * set)1113   static inline RepeatedPtrField<std::string>* MutableRepeated(
1114       int number, FieldType field_type, bool is_packed, ExtensionSet* set) {
1115     return reinterpret_cast<RepeatedPtrField<std::string>*>(
1116         set->MutableRawRepeatedField(number, field_type, is_packed, NULL));
1117   }
1118 
1119   static const RepeatedFieldType* GetDefaultRepeatedField();
1120 
1121   template <typename ExtendeeT>
Register(int number,FieldType type,bool is_packed)1122   static void Register(int number, FieldType type, bool is_packed) {
1123     ExtensionSet::RegisterExtension(&ExtendeeT::default_instance(), number,
1124                                     type, true, is_packed);
1125   }
1126 
1127  private:
1128   static void InitializeDefaultRepeatedFields();
1129   static void DestroyDefaultRepeatedFields();
1130 };
1131 
1132 // -------------------------------------------------------------------
1133 // EnumTypeTraits
1134 
1135 // ExtensionSet represents enums using integers internally, so we have to
1136 // static_cast around.
1137 template <typename Type, bool IsValid(int)>
1138 class EnumTypeTraits {
1139  public:
1140   typedef Type ConstType;
1141   typedef Type MutableType;
1142   typedef EnumTypeTraits<Type, IsValid> Singular;
1143 
Get(int number,const ExtensionSet & set,ConstType default_value)1144   static inline ConstType Get(int number, const ExtensionSet& set,
1145                               ConstType default_value) {
1146     return static_cast<Type>(set.GetEnum(number, default_value));
1147   }
Set(int number,FieldType field_type,ConstType value,ExtensionSet * set)1148   static inline void Set(int number, FieldType field_type, ConstType value,
1149                          ExtensionSet* set) {
1150     GOOGLE_DCHECK(IsValid(value));
1151     set->SetEnum(number, field_type, value, NULL);
1152   }
1153   template <typename ExtendeeT>
Register(int number,FieldType type,bool is_packed)1154   static void Register(int number, FieldType type, bool is_packed) {
1155     ExtensionSet::RegisterEnumExtension(&ExtendeeT::default_instance(), number,
1156                                         type, false, is_packed, IsValid);
1157   }
1158 };
1159 
1160 template <typename Type, bool IsValid(int)>
1161 class RepeatedEnumTypeTraits {
1162  public:
1163   typedef Type ConstType;
1164   typedef Type MutableType;
1165   typedef RepeatedEnumTypeTraits<Type, IsValid> Repeated;
1166 
1167   typedef RepeatedField<Type> RepeatedFieldType;
1168 
Get(int number,const ExtensionSet & set,int index)1169   static inline ConstType Get(int number, const ExtensionSet& set, int index) {
1170     return static_cast<Type>(set.GetRepeatedEnum(number, index));
1171   }
Set(int number,int index,ConstType value,ExtensionSet * set)1172   static inline void Set(int number, int index, ConstType value,
1173                          ExtensionSet* set) {
1174     GOOGLE_DCHECK(IsValid(value));
1175     set->SetRepeatedEnum(number, index, value);
1176   }
Add(int number,FieldType field_type,bool is_packed,ConstType value,ExtensionSet * set)1177   static inline void Add(int number, FieldType field_type, bool is_packed,
1178                          ConstType value, ExtensionSet* set) {
1179     GOOGLE_DCHECK(IsValid(value));
1180     set->AddEnum(number, field_type, is_packed, value, NULL);
1181   }
GetRepeated(int number,const ExtensionSet & set)1182   static inline const RepeatedField<Type>& GetRepeated(
1183       int number, const ExtensionSet& set) {
1184     // Hack: the `Extension` struct stores a RepeatedField<int> for enums.
1185     // RepeatedField<int> cannot implicitly convert to RepeatedField<EnumType>
1186     // so we need to do some casting magic. See message.h for similar
1187     // contortions for non-extension fields.
1188     return *reinterpret_cast<const RepeatedField<Type>*>(
1189         set.GetRawRepeatedField(number, GetDefaultRepeatedField()));
1190   }
1191 
MutableRepeated(int number,FieldType field_type,bool is_packed,ExtensionSet * set)1192   static inline RepeatedField<Type>* MutableRepeated(int number,
1193                                                      FieldType field_type,
1194                                                      bool is_packed,
1195                                                      ExtensionSet* set) {
1196     return reinterpret_cast<RepeatedField<Type>*>(
1197         set->MutableRawRepeatedField(number, field_type, is_packed, NULL));
1198   }
1199 
GetDefaultRepeatedField()1200   static const RepeatedFieldType* GetDefaultRepeatedField() {
1201     // Hack: as noted above, repeated enum fields are internally stored as a
1202     // RepeatedField<int>. We need to be able to instantiate global static
1203     // objects to return as default (empty) repeated fields on non-existent
1204     // extensions. We would not be able to know a-priori all of the enum types
1205     // (values of |Type|) to instantiate all of these, so we just re-use int32's
1206     // default repeated field object.
1207     return reinterpret_cast<const RepeatedField<Type>*>(
1208         RepeatedPrimitiveTypeTraits<int32>::GetDefaultRepeatedField());
1209   }
1210   template <typename ExtendeeT>
Register(int number,FieldType type,bool is_packed)1211   static void Register(int number, FieldType type, bool is_packed) {
1212     ExtensionSet::RegisterEnumExtension(&ExtendeeT::default_instance(), number,
1213                                         type, true, is_packed, IsValid);
1214   }
1215 };
1216 
1217 // -------------------------------------------------------------------
1218 // MessageTypeTraits
1219 
1220 // ExtensionSet guarantees that when manipulating extensions with message
1221 // types, the implementation used will be the compiled-in class representing
1222 // that type.  So, we can static_cast down to the exact type we expect.
1223 template <typename Type>
1224 class MessageTypeTraits {
1225  public:
1226   typedef const Type& ConstType;
1227   typedef Type* MutableType;
1228   typedef MessageTypeTraits<Type> Singular;
1229 
Get(int number,const ExtensionSet & set,ConstType default_value)1230   static inline ConstType Get(int number, const ExtensionSet& set,
1231                               ConstType default_value) {
1232     return static_cast<const Type&>(set.GetMessage(number, default_value));
1233   }
Mutable(int number,FieldType field_type,ExtensionSet * set)1234   static inline MutableType Mutable(int number, FieldType field_type,
1235                                     ExtensionSet* set) {
1236     return static_cast<Type*>(set->MutableMessage(
1237         number, field_type, Type::default_instance(), NULL));
1238   }
SetAllocated(int number,FieldType field_type,MutableType message,ExtensionSet * set)1239   static inline void SetAllocated(int number, FieldType field_type,
1240                                   MutableType message, ExtensionSet* set) {
1241     set->SetAllocatedMessage(number, field_type, NULL, message);
1242   }
UnsafeArenaSetAllocated(int number,FieldType field_type,MutableType message,ExtensionSet * set)1243   static inline void UnsafeArenaSetAllocated(int number, FieldType field_type,
1244                                              MutableType message,
1245                                              ExtensionSet* set) {
1246     set->UnsafeArenaSetAllocatedMessage(number, field_type, NULL, message);
1247   }
Release(int number,FieldType,ExtensionSet * set)1248   static inline MutableType Release(int number, FieldType /* field_type */,
1249                                     ExtensionSet* set) {
1250     return static_cast<Type*>(
1251         set->ReleaseMessage(number, Type::default_instance()));
1252   }
UnsafeArenaRelease(int number,FieldType,ExtensionSet * set)1253   static inline MutableType UnsafeArenaRelease(int number,
1254                                                FieldType /* field_type */,
1255                                                ExtensionSet* set) {
1256     return static_cast<Type*>(
1257         set->UnsafeArenaReleaseMessage(number, Type::default_instance()));
1258   }
1259   template <typename ExtendeeT>
Register(int number,FieldType type,bool is_packed)1260   static void Register(int number, FieldType type, bool is_packed) {
1261     ExtensionSet::RegisterMessageExtension(&ExtendeeT::default_instance(),
1262                                            number, type, false, is_packed,
1263                                            &Type::default_instance());
1264   }
1265 };
1266 
1267 // forward declaration
1268 class RepeatedMessageGenericTypeTraits;
1269 
1270 template <typename Type>
1271 class RepeatedMessageTypeTraits {
1272  public:
1273   typedef const Type& ConstType;
1274   typedef Type* MutableType;
1275   typedef RepeatedMessageTypeTraits<Type> Repeated;
1276 
1277   typedef RepeatedPtrField<Type> RepeatedFieldType;
1278 
Get(int number,const ExtensionSet & set,int index)1279   static inline ConstType Get(int number, const ExtensionSet& set, int index) {
1280     return static_cast<const Type&>(set.GetRepeatedMessage(number, index));
1281   }
Mutable(int number,int index,ExtensionSet * set)1282   static inline MutableType Mutable(int number, int index, ExtensionSet* set) {
1283     return static_cast<Type*>(set->MutableRepeatedMessage(number, index));
1284   }
Add(int number,FieldType field_type,ExtensionSet * set)1285   static inline MutableType Add(int number, FieldType field_type,
1286                                 ExtensionSet* set) {
1287     return static_cast<Type*>(
1288         set->AddMessage(number, field_type, Type::default_instance(), NULL));
1289   }
GetRepeated(int number,const ExtensionSet & set)1290   static inline const RepeatedPtrField<Type>& GetRepeated(
1291       int number, const ExtensionSet& set) {
1292     // See notes above in RepeatedEnumTypeTraits::GetRepeated(): same
1293     // casting hack applies here, because a RepeatedPtrField<MessageLite>
1294     // cannot naturally become a RepeatedPtrType<Type> even though Type is
1295     // presumably a message. google::protobuf::Message goes through similar contortions
1296     // with a reinterpret_cast<>.
1297     return *reinterpret_cast<const RepeatedPtrField<Type>*>(
1298         set.GetRawRepeatedField(number, GetDefaultRepeatedField()));
1299   }
MutableRepeated(int number,FieldType field_type,bool is_packed,ExtensionSet * set)1300   static inline RepeatedPtrField<Type>* MutableRepeated(int number,
1301                                                         FieldType field_type,
1302                                                         bool is_packed,
1303                                                         ExtensionSet* set) {
1304     return reinterpret_cast<RepeatedPtrField<Type>*>(
1305         set->MutableRawRepeatedField(number, field_type, is_packed, NULL));
1306   }
1307 
1308   static const RepeatedFieldType* GetDefaultRepeatedField();
1309   template <typename ExtendeeT>
Register(int number,FieldType type,bool is_packed)1310   static void Register(int number, FieldType type, bool is_packed) {
1311     ExtensionSet::RegisterMessageExtension(&ExtendeeT::default_instance(),
1312                                            number, type, true, is_packed,
1313                                            &Type::default_instance());
1314   }
1315 };
1316 
1317 template <typename Type>
1318 inline const typename RepeatedMessageTypeTraits<Type>::RepeatedFieldType*
GetDefaultRepeatedField()1319 RepeatedMessageTypeTraits<Type>::GetDefaultRepeatedField() {
1320   static auto instance = OnShutdownDelete(new RepeatedFieldType);
1321   return instance;
1322 }
1323 
1324 // -------------------------------------------------------------------
1325 // ExtensionIdentifier
1326 
1327 // This is the type of actual extension objects.  E.g. if you have:
1328 //   extends Foo with optional int32 bar = 1234;
1329 // then "bar" will be defined in C++ as:
1330 //   ExtensionIdentifier<Foo, PrimitiveTypeTraits<int32>, 5, false> bar(1234);
1331 //
1332 // Note that we could, in theory, supply the field number as a template
1333 // parameter, and thus make an instance of ExtensionIdentifier have no
1334 // actual contents.  However, if we did that, then using an extension
1335 // identifier would not necessarily cause the compiler to output any sort
1336 // of reference to any symbol defined in the extension's .pb.o file.  Some
1337 // linkers will actually drop object files that are not explicitly referenced,
1338 // but that would be bad because it would cause this extension to not be
1339 // registered at static initialization, and therefore using it would crash.
1340 
1341 template <typename ExtendeeType, typename TypeTraitsType, FieldType field_type,
1342           bool is_packed>
1343 class ExtensionIdentifier {
1344  public:
1345   typedef TypeTraitsType TypeTraits;
1346   typedef ExtendeeType Extendee;
1347 
ExtensionIdentifier(int number,typename TypeTraits::ConstType default_value)1348   ExtensionIdentifier(int number, typename TypeTraits::ConstType default_value)
1349       : number_(number), default_value_(default_value) {
1350     Register(number);
1351   }
number()1352   inline int number() const { return number_; }
default_value()1353   typename TypeTraits::ConstType default_value() const {
1354     return default_value_;
1355   }
1356 
Register(int number)1357   static void Register(int number) {
1358     TypeTraits::template Register<ExtendeeType>(number, field_type, is_packed);
1359   }
1360 
1361  private:
1362   const int number_;
1363   typename TypeTraits::ConstType default_value_;
1364 };
1365 
1366 // -------------------------------------------------------------------
1367 // Generated accessors
1368 
1369 // This macro should be expanded in the context of a generated type which
1370 // has extensions.
1371 //
1372 // We use "_proto_TypeTraits" as a type name below because "TypeTraits"
1373 // causes problems if the class has a nested message or enum type with that
1374 // name and "_TypeTraits" is technically reserved for the C++ library since
1375 // it starts with an underscore followed by a capital letter.
1376 //
1377 // For similar reason, we use "_field_type" and "_is_packed" as parameter names
1378 // below, so that "field_type" and "is_packed" can be used as field names.
1379 #define GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(CLASSNAME)                       \
1380   /* Has, Size, Clear */                                                      \
1381   template <typename _proto_TypeTraits,                                       \
1382             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1383             bool _is_packed>                                                  \
1384   inline bool HasExtension(                                                   \
1385       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1386           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \
1387     return _extensions_.Has(id.number());                                     \
1388   }                                                                           \
1389                                                                               \
1390   template <typename _proto_TypeTraits,                                       \
1391             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1392             bool _is_packed>                                                  \
1393   inline void ClearExtension(                                                 \
1394       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1395           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) {       \
1396     _extensions_.ClearExtension(id.number());                                 \
1397   }                                                                           \
1398                                                                               \
1399   template <typename _proto_TypeTraits,                                       \
1400             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1401             bool _is_packed>                                                  \
1402   inline int ExtensionSize(                                                   \
1403       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1404           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \
1405     return _extensions_.ExtensionSize(id.number());                           \
1406   }                                                                           \
1407                                                                               \
1408   /* Singular accessors */                                                    \
1409   template <typename _proto_TypeTraits,                                       \
1410             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1411             bool _is_packed>                                                  \
1412   inline typename _proto_TypeTraits::Singular::ConstType GetExtension(        \
1413       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1414           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \
1415     return _proto_TypeTraits::Get(id.number(), _extensions_,                  \
1416                                   id.default_value());                        \
1417   }                                                                           \
1418                                                                               \
1419   template <typename _proto_TypeTraits,                                       \
1420             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1421             bool _is_packed>                                                  \
1422   inline typename _proto_TypeTraits::Singular::MutableType MutableExtension(  \
1423       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1424           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) {       \
1425     return _proto_TypeTraits::Mutable(id.number(), _field_type,               \
1426                                       &_extensions_);                         \
1427   }                                                                           \
1428                                                                               \
1429   template <typename _proto_TypeTraits,                                       \
1430             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1431             bool _is_packed>                                                  \
1432   inline void SetExtension(                                                   \
1433       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1434           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id,         \
1435       typename _proto_TypeTraits::Singular::ConstType value) {                \
1436     _proto_TypeTraits::Set(id.number(), _field_type, value, &_extensions_);   \
1437   }                                                                           \
1438                                                                               \
1439   template <typename _proto_TypeTraits,                                       \
1440             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1441             bool _is_packed>                                                  \
1442   inline void SetAllocatedExtension(                                          \
1443       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1444           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id,         \
1445       typename _proto_TypeTraits::Singular::MutableType value) {              \
1446     _proto_TypeTraits::SetAllocated(id.number(), _field_type, value,          \
1447                                     &_extensions_);                           \
1448   }                                                                           \
1449   template <typename _proto_TypeTraits,                                       \
1450             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1451             bool _is_packed>                                                  \
1452   inline void UnsafeArenaSetAllocatedExtension(                               \
1453       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1454           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id,         \
1455       typename _proto_TypeTraits::Singular::MutableType value) {              \
1456     _proto_TypeTraits::UnsafeArenaSetAllocated(id.number(), _field_type,      \
1457                                                value, &_extensions_);         \
1458   }                                                                           \
1459   template <typename _proto_TypeTraits,                                       \
1460             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1461             bool _is_packed>                                                  \
1462   inline typename _proto_TypeTraits::Singular::MutableType ReleaseExtension(  \
1463       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1464           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) {       \
1465     return _proto_TypeTraits::Release(id.number(), _field_type,               \
1466                                       &_extensions_);                         \
1467   }                                                                           \
1468   template <typename _proto_TypeTraits,                                       \
1469             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1470             bool _is_packed>                                                  \
1471   inline typename _proto_TypeTraits::Singular::MutableType                    \
1472   UnsafeArenaReleaseExtension(                                                \
1473       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1474           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) {       \
1475     return _proto_TypeTraits::UnsafeArenaRelease(id.number(), _field_type,    \
1476                                                  &_extensions_);              \
1477   }                                                                           \
1478                                                                               \
1479   /* Repeated accessors */                                                    \
1480   template <typename _proto_TypeTraits,                                       \
1481             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1482             bool _is_packed>                                                  \
1483   inline typename _proto_TypeTraits::Repeated::ConstType GetExtension(        \
1484       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1485           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id,         \
1486       int index) const {                                                      \
1487     return _proto_TypeTraits::Get(id.number(), _extensions_, index);          \
1488   }                                                                           \
1489                                                                               \
1490   template <typename _proto_TypeTraits,                                       \
1491             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1492             bool _is_packed>                                                  \
1493   inline typename _proto_TypeTraits::Repeated::MutableType MutableExtension(  \
1494       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1495           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id,         \
1496       int index) {                                                            \
1497     return _proto_TypeTraits::Mutable(id.number(), index, &_extensions_);     \
1498   }                                                                           \
1499                                                                               \
1500   template <typename _proto_TypeTraits,                                       \
1501             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1502             bool _is_packed>                                                  \
1503   inline void SetExtension(                                                   \
1504       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1505           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id,         \
1506       int index, typename _proto_TypeTraits::Repeated::ConstType value) {     \
1507     _proto_TypeTraits::Set(id.number(), index, value, &_extensions_);         \
1508   }                                                                           \
1509                                                                               \
1510   template <typename _proto_TypeTraits,                                       \
1511             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1512             bool _is_packed>                                                  \
1513   inline typename _proto_TypeTraits::Repeated::MutableType AddExtension(      \
1514       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1515           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) {       \
1516     return _proto_TypeTraits::Add(id.number(), _field_type, &_extensions_);   \
1517   }                                                                           \
1518                                                                               \
1519   template <typename _proto_TypeTraits,                                       \
1520             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1521             bool _is_packed>                                                  \
1522   inline void AddExtension(                                                   \
1523       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1524           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id,         \
1525       typename _proto_TypeTraits::Repeated::ConstType value) {                \
1526     _proto_TypeTraits::Add(id.number(), _field_type, _is_packed, value,       \
1527                            &_extensions_);                                    \
1528   }                                                                           \
1529                                                                               \
1530   template <typename _proto_TypeTraits,                                       \
1531             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1532             bool _is_packed>                                                  \
1533   inline const typename _proto_TypeTraits::Repeated::RepeatedFieldType&       \
1534   GetRepeatedExtension(                                                       \
1535       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1536           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \
1537     return _proto_TypeTraits::GetRepeated(id.number(), _extensions_);         \
1538   }                                                                           \
1539                                                                               \
1540   template <typename _proto_TypeTraits,                                       \
1541             ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type,         \
1542             bool _is_packed>                                                  \
1543   inline typename _proto_TypeTraits::Repeated::RepeatedFieldType*             \
1544   MutableRepeatedExtension(                                                   \
1545       const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier<           \
1546           CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) {       \
1547     return _proto_TypeTraits::MutableRepeated(id.number(), _field_type,       \
1548                                               _is_packed, &_extensions_);     \
1549   }
1550 
1551 }  // namespace internal
1552 
1553 // Call this function to ensure that this extensions's reflection is linked into
1554 // the binary:
1555 //
1556 //   google::protobuf::LinkExtensionReflection(Foo::my_extension);
1557 //
1558 // This will ensure that the following lookup will succeed:
1559 //
1560 //   DescriptorPool::generated_pool()->FindExtensionByName("Foo.my_extension");
1561 //
1562 // This is often relevant for parsing extensions in text mode.
1563 //
1564 // As a side-effect, it will also guarantee that anything else from the same
1565 // .proto file will also be available for lookup in the generated pool.
1566 //
1567 // This function does not actually register the extension, so it does not need
1568 // to be called before the lookup.  However it does need to occur in a function
1569 // that cannot be stripped from the binary (ie. it must be reachable from main).
1570 //
1571 // Best practice is to call this function as close as possible to where the
1572 // reflection is actually needed.  This function is very cheap to call, so you
1573 // should not need to worry about its runtime overhead except in tight loops (on
1574 // x86-64 it compiles into two "mov" instructions).
1575 template <typename ExtendeeType, typename TypeTraitsType,
1576           internal::FieldType field_type, bool is_packed>
LinkExtensionReflection(const google::protobuf::internal::ExtensionIdentifier<ExtendeeType,TypeTraitsType,field_type,is_packed> & extension)1577 void LinkExtensionReflection(
1578     const google::protobuf::internal::ExtensionIdentifier<
1579         ExtendeeType, TypeTraitsType, field_type, is_packed>& extension) {
1580   internal::StrongReference(extension);
1581 }
1582 
1583 }  // namespace protobuf
1584 }  // namespace google
1585 
1586 #include <google/protobuf/port_undef.inc>
1587 
1588 #endif  // GOOGLE_PROTOBUF_EXTENSION_SET_H__
1589