• Home
  • History
  • Annotate
  • 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 <vector>
42 #include <map>
43 #include <utility>
44 #include <string>
45 
46 
47 #include <google/protobuf/stubs/common.h>
48 #include <google/protobuf/stubs/logging.h>
49 #include <google/protobuf/stubs/once.h>
50 
51 #include <google/protobuf/repeated_field.h>
52 
53 namespace google {
54 
55 namespace protobuf {
56   class Arena;
57   class Descriptor;                                    // descriptor.h
58   class FieldDescriptor;                               // descriptor.h
59   class DescriptorPool;                                // descriptor.h
60   class MessageLite;                                   // message_lite.h
61   class Message;                                       // message.h
62   class MessageFactory;                                // message.h
63   class UnknownFieldSet;                               // unknown_field_set.h
64   namespace io {
65     class CodedInputStream;                              // coded_stream.h
66     class CodedOutputStream;                             // coded_stream.h
67   }
68   namespace internal {
69     class FieldSkipper;                                  // wire_format_lite.h
70   }
71 }
72 
73 namespace protobuf {
74 namespace internal {
75 
76 // Used to store values of type WireFormatLite::FieldType without having to
77 // #include wire_format_lite.h.  Also, ensures that we use only one byte to
78 // store these values, which is important to keep the layout of
79 // ExtensionSet::Extension small.
80 typedef uint8 FieldType;
81 
82 // A function which, given an integer value, returns true if the number
83 // matches one of the defined values for the corresponding enum type.  This
84 // is used with RegisterEnumExtension, below.
85 typedef bool EnumValidityFunc(int number);
86 
87 // Version of the above which takes an argument.  This is needed to deal with
88 // extensions that are not compiled in.
89 typedef bool EnumValidityFuncWithArg(const void* arg, int number);
90 
91 // Information about a registered extension.
92 struct ExtensionInfo {
ExtensionInfoExtensionInfo93   inline ExtensionInfo() {}
ExtensionInfoExtensionInfo94   inline ExtensionInfo(FieldType type_param, bool isrepeated, bool ispacked)
95       : type(type_param), is_repeated(isrepeated), is_packed(ispacked),
96         descriptor(NULL) {}
97 
98   FieldType type;
99   bool is_repeated;
100   bool is_packed;
101 
102   struct EnumValidityCheck {
103     EnumValidityFuncWithArg* func;
104     const void* arg;
105   };
106 
107   union {
108     EnumValidityCheck enum_validity_check;
109     const MessageLite* message_prototype;
110   };
111 
112   // The descriptor for this extension, if one exists and is known.  May be
113   // NULL.  Must not be NULL if the descriptor for the extension does not
114   // live in the same pool as the descriptor for the containing type.
115   const FieldDescriptor* descriptor;
116 };
117 
118 // Abstract interface for an object which looks up extension definitions.  Used
119 // when parsing.
120 class LIBPROTOBUF_EXPORT ExtensionFinder {
121  public:
122   virtual ~ExtensionFinder();
123 
124   // Find the extension with the given containing type and number.
125   virtual bool Find(int number, ExtensionInfo* output) = 0;
126 };
127 
128 // Implementation of ExtensionFinder which finds extensions defined in .proto
129 // files which have been compiled into the binary.
130 class LIBPROTOBUF_EXPORT GeneratedExtensionFinder : public ExtensionFinder {
131  public:
GeneratedExtensionFinder(const MessageLite * containing_type)132   GeneratedExtensionFinder(const MessageLite* containing_type)
133       : containing_type_(containing_type) {}
~GeneratedExtensionFinder()134   virtual ~GeneratedExtensionFinder() {}
135 
136   // Returns true and fills in *output if found, otherwise returns false.
137   virtual bool Find(int number, ExtensionInfo* output);
138 
139  private:
140   const MessageLite* containing_type_;
141 };
142 
143 // A FieldSkipper used for parsing MessageSet.
144 class MessageSetFieldSkipper;
145 
146 // Note:  extension_set_heavy.cc defines DescriptorPoolExtensionFinder for
147 // finding extensions from a DescriptorPool.
148 
149 // This is an internal helper class intended for use within the protocol buffer
150 // library and generated classes.  Clients should not use it directly.  Instead,
151 // use the generated accessors such as GetExtension() of the class being
152 // extended.
153 //
154 // This class manages extensions for a protocol message object.  The
155 // message's HasExtension(), GetExtension(), MutableExtension(), and
156 // ClearExtension() methods are just thin wrappers around the embedded
157 // ExtensionSet.  When parsing, if a tag number is encountered which is
158 // inside one of the message type's extension ranges, the tag is passed
159 // off to the ExtensionSet for parsing.  Etc.
160 class LIBPROTOBUF_EXPORT ExtensionSet {
161  public:
162   ExtensionSet();
163   explicit ExtensionSet(::google::protobuf::Arena* arena);
164   ~ExtensionSet();
165 
166   // These are called at startup by protocol-compiler-generated code to
167   // register known extensions.  The registrations are used by ParseField()
168   // to look up extensions for parsed field numbers.  Note that dynamic parsing
169   // does not use ParseField(); only protocol-compiler-generated parsing
170   // methods do.
171   static void RegisterExtension(const MessageLite* containing_type,
172                                 int number, FieldType type,
173                                 bool is_repeated, bool is_packed);
174   static void RegisterEnumExtension(const MessageLite* containing_type,
175                                     int number, FieldType type,
176                                     bool is_repeated, bool is_packed,
177                                     EnumValidityFunc* is_valid);
178   static void RegisterMessageExtension(const MessageLite* containing_type,
179                                        int number, FieldType type,
180                                        bool is_repeated, bool is_packed,
181                                        const MessageLite* prototype);
182 
183   // =================================================================
184 
185   // Add all fields which are currently present to the given vector.  This
186   // is useful to implement Reflection::ListFields().
187   void AppendToList(const Descriptor* containing_type,
188                     const DescriptorPool* pool,
189                     std::vector<const FieldDescriptor*>* output) const;
190 
191   // =================================================================
192   // Accessors
193   //
194   // Generated message classes include type-safe templated wrappers around
195   // these methods.  Generally you should use those rather than call these
196   // directly, unless you are doing low-level memory management.
197   //
198   // When calling any of these accessors, the extension number requested
199   // MUST exist in the DescriptorPool provided to the constructor.  Otherwise,
200   // the method will fail an assert.  Normally, though, you would not call
201   // these directly; you would either call the generated accessors of your
202   // message class (e.g. GetExtension()) or you would call the accessors
203   // of the reflection interface.  In both cases, it is impossible to
204   // trigger this assert failure:  the generated accessors only accept
205   // linked-in extension types as parameters, while the Reflection interface
206   // requires you to provide the FieldDescriptor describing the extension.
207   //
208   // When calling any of these accessors, a protocol-compiler-generated
209   // implementation of the extension corresponding to the number MUST
210   // be linked in, and the FieldDescriptor used to refer to it MUST be
211   // the one generated by that linked-in code.  Otherwise, the method will
212   // die on an assert failure.  The message objects returned by the message
213   // accessors are guaranteed to be of the correct linked-in type.
214   //
215   // These methods pretty much match Reflection except that:
216   // - They're not virtual.
217   // - They identify fields by number rather than FieldDescriptors.
218   // - They identify enum values using integers rather than descriptors.
219   // - Strings provide Mutable() in addition to Set() accessors.
220 
221   bool Has(int number) const;
222   int ExtensionSize(int number) const;   // Size of a repeated extension.
223   int NumExtensions() const;  // The number of extensions
224   FieldType ExtensionType(int number) const;
225   void ClearExtension(int number);
226 
227   // singular fields -------------------------------------------------
228 
229   int32  GetInt32 (int number, int32  default_value) const;
230   int64  GetInt64 (int number, int64  default_value) const;
231   uint32 GetUInt32(int number, uint32 default_value) const;
232   uint64 GetUInt64(int number, uint64 default_value) const;
233   float  GetFloat (int number, float  default_value) const;
234   double GetDouble(int number, double default_value) const;
235   bool   GetBool  (int number, bool   default_value) const;
236   int    GetEnum  (int number, int    default_value) const;
237   const string & GetString (int number, const string&  default_value) const;
238   const MessageLite& GetMessage(int number,
239                                 const MessageLite& default_value) const;
240   const MessageLite& GetMessage(int number, const Descriptor* message_type,
241                                 MessageFactory* factory) const;
242 
243   // |descriptor| may be NULL so long as it is known that the descriptor for
244   // the extension lives in the same pool as the descriptor for the containing
245   // type.
246 #define desc const FieldDescriptor* descriptor  // avoid line wrapping
247   void SetInt32 (int number, FieldType type, int32  value, desc);
248   void SetInt64 (int number, FieldType type, int64  value, desc);
249   void SetUInt32(int number, FieldType type, uint32 value, desc);
250   void SetUInt64(int number, FieldType type, uint64 value, desc);
251   void SetFloat (int number, FieldType type, float  value, desc);
252   void SetDouble(int number, FieldType type, double value, desc);
253   void SetBool  (int number, FieldType type, bool   value, desc);
254   void SetEnum  (int number, FieldType type, int    value, desc);
255   void SetString(int number, FieldType type, const string& value, desc);
256   string * MutableString (int number, FieldType type, desc);
257   MessageLite* MutableMessage(int number, FieldType type,
258                               const MessageLite& prototype, desc);
259   MessageLite* MutableMessage(const FieldDescriptor* decsriptor,
260                               MessageFactory* factory);
261   // Adds the given message to the ExtensionSet, taking ownership of the
262   // message object. Existing message with the same number will be deleted.
263   // If "message" is NULL, this is equivalent to "ClearExtension(number)".
264   void SetAllocatedMessage(int number, FieldType type,
265                            const FieldDescriptor* descriptor,
266                            MessageLite* message);
267   void UnsafeArenaSetAllocatedMessage(int number, FieldType type,
268                                       const FieldDescriptor* descriptor,
269                                       MessageLite* message);
270   MessageLite* ReleaseMessage(int number, const MessageLite& prototype);
271   MessageLite* UnsafeArenaReleaseMessage(
272       int number, const MessageLite& prototype);
273 
274   MessageLite* ReleaseMessage(const FieldDescriptor* descriptor,
275                               MessageFactory* factory);
276   MessageLite* UnsafeArenaReleaseMessage(const FieldDescriptor* descriptor,
277                                          MessageFactory* factory);
278 #undef desc
GetArenaNoVirtual()279   ::google::protobuf::Arena* GetArenaNoVirtual() const { return arena_; }
280 
281   // repeated fields -------------------------------------------------
282 
283   // Fetches a RepeatedField extension by number; returns |default_value|
284   // if no such extension exists. User should not touch this directly; it is
285   // used by the GetRepeatedExtension() method.
286   const void* GetRawRepeatedField(int number, const void* default_value) const;
287   // Fetches a mutable version of a RepeatedField extension by number,
288   // instantiating one if none exists. Similar to above, user should not use
289   // this directly; it underlies MutableRepeatedExtension().
290   void* MutableRawRepeatedField(int number, FieldType field_type,
291                                 bool packed, const FieldDescriptor* desc);
292 
293   // This is an overload of MutableRawRepeatedField to maintain compatibility
294   // with old code using a previous API. This version of
295   // MutableRawRepeatedField() will GOOGLE_CHECK-fail on a missing extension.
296   // (E.g.: borg/clients/internal/proto1/proto2_reflection.cc.)
297   void* MutableRawRepeatedField(int number);
298 
299   int32  GetRepeatedInt32 (int number, int index) const;
300   int64  GetRepeatedInt64 (int number, int index) const;
301   uint32 GetRepeatedUInt32(int number, int index) const;
302   uint64 GetRepeatedUInt64(int number, int index) const;
303   float  GetRepeatedFloat (int number, int index) const;
304   double GetRepeatedDouble(int number, int index) const;
305   bool   GetRepeatedBool  (int number, int index) const;
306   int    GetRepeatedEnum  (int number, int index) const;
307   const string & GetRepeatedString (int number, int index) const;
308   const MessageLite& GetRepeatedMessage(int number, int index) const;
309 
310   void SetRepeatedInt32 (int number, int index, int32  value);
311   void SetRepeatedInt64 (int number, int index, int64  value);
312   void SetRepeatedUInt32(int number, int index, uint32 value);
313   void SetRepeatedUInt64(int number, int index, uint64 value);
314   void SetRepeatedFloat (int number, int index, float  value);
315   void SetRepeatedDouble(int number, int index, double value);
316   void SetRepeatedBool  (int number, int index, bool   value);
317   void SetRepeatedEnum  (int number, int index, int    value);
318   void SetRepeatedString(int number, int index, const string& value);
319   string * MutableRepeatedString (int number, int index);
320   MessageLite* MutableRepeatedMessage(int number, int index);
321 
322 #define desc const FieldDescriptor* descriptor  // avoid line wrapping
323   void AddInt32 (int number, FieldType type, bool packed, int32  value, desc);
324   void AddInt64 (int number, FieldType type, bool packed, int64  value, desc);
325   void AddUInt32(int number, FieldType type, bool packed, uint32 value, desc);
326   void AddUInt64(int number, FieldType type, bool packed, uint64 value, desc);
327   void AddFloat (int number, FieldType type, bool packed, float  value, desc);
328   void AddDouble(int number, FieldType type, bool packed, double value, desc);
329   void AddBool  (int number, FieldType type, bool packed, bool   value, desc);
330   void AddEnum  (int number, FieldType type, bool packed, int    value, desc);
331   void AddString(int number, FieldType type, const string& value, desc);
332   string * AddString (int number, FieldType type, desc);
333   MessageLite* AddMessage(int number, FieldType type,
334                           const MessageLite& prototype, desc);
335   MessageLite* AddMessage(const FieldDescriptor* descriptor,
336                           MessageFactory* factory);
337   void AddAllocatedMessage(const FieldDescriptor* descriptor,
338                            MessageLite* new_entry);
339 #undef desc
340 
341   void RemoveLast(int number);
342   MessageLite* ReleaseLast(int number);
343   void SwapElements(int number, int index1, int index2);
344 
345   // -----------------------------------------------------------------
346   // TODO(kenton):  Hardcore memory management accessors
347 
348   // =================================================================
349   // convenience methods for implementing methods of Message
350   //
351   // These could all be implemented in terms of the other methods of this
352   // class, but providing them here helps keep the generated code size down.
353 
354   void Clear();
355   void MergeFrom(const ExtensionSet& other);
356   void Swap(ExtensionSet* other);
357   void SwapExtension(ExtensionSet* other, int number);
358   bool IsInitialized() const;
359 
360   // Parses a single extension from the input. The input should start out
361   // positioned immediately after the tag.
362   bool ParseField(uint32 tag, io::CodedInputStream* input,
363                   ExtensionFinder* extension_finder,
364                   FieldSkipper* field_skipper);
365 
366   // Specific versions for lite or full messages (constructs the appropriate
367   // FieldSkipper automatically).  |containing_type| is the default
368   // instance for the containing message; it is used only to look up the
369   // extension by number.  See RegisterExtension(), above.  Unlike the other
370   // methods of ExtensionSet, this only works for generated message types --
371   // it looks up extensions registered using RegisterExtension().
372   bool ParseField(uint32 tag, io::CodedInputStream* input,
373                   const MessageLite* containing_type);
374   bool ParseField(uint32 tag, io::CodedInputStream* input,
375                   const Message* containing_type,
376                   UnknownFieldSet* unknown_fields);
377   bool ParseField(uint32 tag, io::CodedInputStream* input,
378                   const MessageLite* containing_type,
379                   io::CodedOutputStream* unknown_fields);
380 
381   // Parse an entire message in MessageSet format.  Such messages have no
382   // fields, only extensions.
383   bool ParseMessageSet(io::CodedInputStream* input,
384                        ExtensionFinder* extension_finder,
385                        MessageSetFieldSkipper* field_skipper);
386 
387   // Specific versions for lite or full messages (constructs the appropriate
388   // FieldSkipper automatically).
389   bool ParseMessageSet(io::CodedInputStream* input,
390                        const MessageLite* containing_type);
391   bool ParseMessageSet(io::CodedInputStream* input,
392                        const Message* containing_type,
393                        UnknownFieldSet* unknown_fields);
394 
395   // Write all extension fields with field numbers in the range
396   //   [start_field_number, end_field_number)
397   // to the output stream, using the cached sizes computed when ByteSize() was
398   // last called.  Note that the range bounds are inclusive-exclusive.
399   void SerializeWithCachedSizes(int start_field_number,
400                                 int end_field_number,
401                                 io::CodedOutputStream* output) const;
402 
403   // Same as SerializeWithCachedSizes, but without any bounds checking.
404   // The caller must ensure that target has sufficient capacity for the
405   // serialized extensions.
406   //
407   // Returns a pointer past the last written byte.
408   uint8* InternalSerializeWithCachedSizesToArray(int start_field_number,
409                                                  int end_field_number,
410                                                  bool deterministic,
411                                                  uint8* target) const;
412 
413   // Like above but serializes in MessageSet format.
414   void SerializeMessageSetWithCachedSizes(io::CodedOutputStream* output) const;
415   uint8* InternalSerializeMessageSetWithCachedSizesToArray(bool deterministic,
416                                                            uint8* target) const;
417 
418   // For backward-compatibility, versions of two of the above methods that
419   // are never forced to serialize deterministically.
420   uint8* SerializeWithCachedSizesToArray(int start_field_number,
421                                          int end_field_number,
422                                          uint8* target) const;
423   uint8* SerializeMessageSetWithCachedSizesToArray(uint8* target) const;
424 
425   // Returns the total serialized size of all the extensions.
426   int ByteSize() const;
427 
428   // Like ByteSize() but uses MessageSet format.
429   int MessageSetByteSize() const;
430 
431   // Returns (an estimate of) the total number of bytes used for storing the
432   // extensions in memory, excluding sizeof(*this).  If the ExtensionSet is
433   // for a lite message (and thus possibly contains lite messages), the results
434   // are undefined (might work, might crash, might corrupt data, might not even
435   // be linked in).  It's up to the protocol compiler to avoid calling this on
436   // such ExtensionSets (easy enough since lite messages don't implement
437   // SpaceUsed()).
438   int SpaceUsedExcludingSelf() const;
439 
440  private:
441 
442   // Interface of a lazily parsed singular message extension.
443   class LIBPROTOBUF_EXPORT LazyMessageExtension {
444    public:
LazyMessageExtension()445     LazyMessageExtension() {}
~LazyMessageExtension()446     virtual ~LazyMessageExtension() {}
447 
448     virtual LazyMessageExtension* New(::google::protobuf::Arena* arena) const = 0;
449     virtual const MessageLite& GetMessage(
450         const MessageLite& prototype) const = 0;
451     virtual MessageLite* MutableMessage(const MessageLite& prototype) = 0;
452     virtual void SetAllocatedMessage(MessageLite *message) = 0;
453     virtual void UnsafeArenaSetAllocatedMessage(MessageLite *message) = 0;
454     virtual MessageLite* ReleaseMessage(const MessageLite& prototype) = 0;
455     virtual MessageLite* UnsafeArenaReleaseMessage(
456         const MessageLite& prototype) = 0;
457 
458     virtual bool IsInitialized() const = 0;
459     virtual int ByteSize() const = 0;
460     virtual int SpaceUsed() const = 0;
461 
462     virtual void MergeFrom(const LazyMessageExtension& other) = 0;
463     virtual void Clear() = 0;
464 
465     virtual bool ReadMessage(const MessageLite& prototype,
466                              io::CodedInputStream* input) = 0;
467     virtual void WriteMessage(int number,
468                               io::CodedOutputStream* output) const = 0;
469     virtual uint8* WriteMessageToArray(int number, uint8* target) const = 0;
InternalWriteMessageToArray(int number,bool,uint8 * target)470     virtual uint8* InternalWriteMessageToArray(int number, bool,
471                                                uint8* target) const {
472       // TODO(gpike): make this pure virtual. This is a placeholder because we
473       // need to update third_party/upb, for example.
474       return WriteMessageToArray(number, target);
475     }
476 
477    private:
478     GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(LazyMessageExtension);
479   };
480   struct Extension {
481     // The order of these fields packs Extension into 24 bytes when using 8
482     // byte alignment. Consider this when adding or removing fields here.
483     union {
484       int32                 int32_value;
485       int64                 int64_value;
486       uint32                uint32_value;
487       uint64                uint64_value;
488       float                 float_value;
489       double                double_value;
490       bool                  bool_value;
491       int                   enum_value;
492       string*               string_value;
493       MessageLite*          message_value;
494       LazyMessageExtension* lazymessage_value;
495 
496       RepeatedField   <int32      >* repeated_int32_value;
497       RepeatedField   <int64      >* repeated_int64_value;
498       RepeatedField   <uint32     >* repeated_uint32_value;
499       RepeatedField   <uint64     >* repeated_uint64_value;
500       RepeatedField   <float      >* repeated_float_value;
501       RepeatedField   <double     >* repeated_double_value;
502       RepeatedField   <bool       >* repeated_bool_value;
503       RepeatedField   <int        >* repeated_enum_value;
504       RepeatedPtrField<string     >* repeated_string_value;
505       RepeatedPtrField<MessageLite>* repeated_message_value;
506     };
507 
508     FieldType type;
509     bool is_repeated;
510 
511     // For singular types, indicates if the extension is "cleared".  This
512     // happens when an extension is set and then later cleared by the caller.
513     // We want to keep the Extension object around for reuse, so instead of
514     // removing it from the map, we just set is_cleared = true.  This has no
515     // meaning for repeated types; for those, the size of the RepeatedField
516     // simply becomes zero when cleared.
517     bool is_cleared : 4;
518 
519     // For singular message types, indicates whether lazy parsing is enabled
520     // for this extension. This field is only valid when type == TYPE_MESSAGE
521     // and !is_repeated because we only support lazy parsing for singular
522     // message types currently. If is_lazy = true, the extension is stored in
523     // lazymessage_value. Otherwise, the extension will be message_value.
524     bool is_lazy : 4;
525 
526     // For repeated types, this indicates if the [packed=true] option is set.
527     bool is_packed;
528 
529     // For packed fields, the size of the packed data is recorded here when
530     // ByteSize() is called then used during serialization.
531     // TODO(kenton):  Use atomic<int> when C++ supports it.
532     mutable int cached_size;
533 
534     // The descriptor for this extension, if one exists and is known.  May be
535     // NULL.  Must not be NULL if the descriptor for the extension does not
536     // live in the same pool as the descriptor for the containing type.
537     const FieldDescriptor* descriptor;
538 
539     // Some helper methods for operations on a single Extension.
540     void SerializeFieldWithCachedSizes(
541         int number,
542         io::CodedOutputStream* output) const;
543     uint8* InternalSerializeFieldWithCachedSizesToArray(
544         int number,
545         bool deterministic,
546         uint8* target) const;
547     void SerializeMessageSetItemWithCachedSizes(
548         int number,
549         io::CodedOutputStream* output) const;
550     uint8* InternalSerializeMessageSetItemWithCachedSizesToArray(
551         int number,
552         bool deterministic,
553         uint8* target) const;
554     int ByteSize(int number) const;
555     int MessageSetItemByteSize(int number) const;
556     void Clear();
557     int GetSize() const;
558     void Free();
559     int SpaceUsedExcludingSelf() const;
560   };
561   typedef std::map<int, Extension> ExtensionMap;
562 
563 
564   // Merges existing Extension from other_extension
565   void InternalExtensionMergeFrom(int number, const Extension& other_extension);
566 
567   // Returns true and fills field_number and extension if extension is found.
568   // Note to support packed repeated field compatibility, it also fills whether
569   // the tag on wire is packed, which can be different from
570   // extension->is_packed (whether packed=true is specified).
571   bool FindExtensionInfoFromTag(uint32 tag, ExtensionFinder* extension_finder,
572                                 int* field_number, ExtensionInfo* extension,
573                                 bool* was_packed_on_wire);
574 
575   // Returns true and fills extension if extension is found.
576   // Note to support packed repeated field compatibility, it also fills whether
577   // the tag on wire is packed, which can be different from
578   // extension->is_packed (whether packed=true is specified).
579   bool FindExtensionInfoFromFieldNumber(int wire_type, int field_number,
580                                         ExtensionFinder* extension_finder,
581                                         ExtensionInfo* extension,
582                                         bool* was_packed_on_wire);
583 
584   // Parses a single extension from the input. The input should start out
585   // positioned immediately after the wire tag. This method is called in
586   // ParseField() after field number and was_packed_on_wire is extracted from
587   // the wire tag and ExtensionInfo is found by the field number.
588   bool ParseFieldWithExtensionInfo(int field_number,
589                                    bool was_packed_on_wire,
590                                    const ExtensionInfo& extension,
591                                    io::CodedInputStream* input,
592                                    FieldSkipper* field_skipper);
593 
594   // Like ParseField(), but this method may parse singular message extensions
595   // lazily depending on the value of FLAGS_eagerly_parse_message_sets.
596   bool ParseFieldMaybeLazily(int wire_type, int field_number,
597                              io::CodedInputStream* input,
598                              ExtensionFinder* extension_finder,
599                              MessageSetFieldSkipper* field_skipper);
600 
601   // Gets the extension with the given number, creating it if it does not
602   // already exist.  Returns true if the extension did not already exist.
603   bool MaybeNewExtension(int number, const FieldDescriptor* descriptor,
604                          Extension** result);
605 
606   // Gets the repeated extension for the given descriptor, creating it if
607   // it does not exist.
608   Extension* MaybeNewRepeatedExtension(const FieldDescriptor* descriptor);
609 
610   // Parse a single MessageSet item -- called just after the item group start
611   // tag has been read.
612   bool ParseMessageSetItem(io::CodedInputStream* input,
613                            ExtensionFinder* extension_finder,
614                            MessageSetFieldSkipper* field_skipper);
615 
616   // Hack:  RepeatedPtrFieldBase declares ExtensionSet as a friend.  This
617   //   friendship should automatically extend to ExtensionSet::Extension, but
618   //   unfortunately some older compilers (e.g. GCC 3.4.4) do not implement this
619   //   correctly.  So, we must provide helpers for calling methods of that
620   //   class.
621 
622   // Defined in extension_set_heavy.cc.
623   static inline int RepeatedMessage_SpaceUsedExcludingSelf(
624       RepeatedPtrFieldBase* field);
625 
626   // The Extension struct is small enough to be passed by value, so we use it
627   // directly as the value type in the map rather than use pointers.  We use
628   // a map rather than hash_map here because we expect most ExtensionSets will
629   // only contain a small number of extensions whereas hash_map is optimized
630   // for 100 elements or more.  Also, we want AppendToList() to order fields
631   // by field number.
632   ExtensionMap extensions_;
633   ::google::protobuf::Arena* arena_;
634   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionSet);
635 };
636 
637 // These are just for convenience...
SetString(int number,FieldType type,const string & value,const FieldDescriptor * descriptor)638 inline void ExtensionSet::SetString(int number, FieldType type,
639                                     const string& value,
640                                     const FieldDescriptor* descriptor) {
641   MutableString(number, type, descriptor)->assign(value);
642 }
SetRepeatedString(int number,int index,const string & value)643 inline void ExtensionSet::SetRepeatedString(int number, int index,
644                                             const string& value) {
645   MutableRepeatedString(number, index)->assign(value);
646 }
AddString(int number,FieldType type,const string & value,const FieldDescriptor * descriptor)647 inline void ExtensionSet::AddString(int number, FieldType type,
648                                     const string& value,
649                                     const FieldDescriptor* descriptor) {
650   AddString(number, type, descriptor)->assign(value);
651 }
652 
653 // ===================================================================
654 // Glue for generated extension accessors
655 
656 // -------------------------------------------------------------------
657 // Template magic
658 
659 // First we have a set of classes representing "type traits" for different
660 // field types.  A type traits class knows how to implement basic accessors
661 // for extensions of a particular type given an ExtensionSet.  The signature
662 // for a type traits class looks like this:
663 //
664 //   class TypeTraits {
665 //    public:
666 //     typedef ? ConstType;
667 //     typedef ? MutableType;
668 //     // TypeTraits for singular fields and repeated fields will define the
669 //     // symbol "Singular" or "Repeated" respectively. These two symbols will
670 //     // be used in extension accessors to distinguish between singular
671 //     // extensions and repeated extensions. If the TypeTraits for the passed
672 //     // in extension doesn't have the expected symbol defined, it means the
673 //     // user is passing a repeated extension to a singular accessor, or the
674 //     // opposite. In that case the C++ compiler will generate an error
675 //     // message "no matching member function" to inform the user.
676 //     typedef ? Singular
677 //     typedef ? Repeated
678 //
679 //     static inline ConstType Get(int number, const ExtensionSet& set);
680 //     static inline void Set(int number, ConstType value, ExtensionSet* set);
681 //     static inline MutableType Mutable(int number, ExtensionSet* set);
682 //
683 //     // Variants for repeated fields.
684 //     static inline ConstType Get(int number, const ExtensionSet& set,
685 //                                 int index);
686 //     static inline void Set(int number, int index,
687 //                            ConstType value, ExtensionSet* set);
688 //     static inline MutableType Mutable(int number, int index,
689 //                                       ExtensionSet* set);
690 //     static inline void Add(int number, ConstType value, ExtensionSet* set);
691 //     static inline MutableType Add(int number, ExtensionSet* set);
692 //   };
693 //
694 // Not all of these methods make sense for all field types.  For example, the
695 // "Mutable" methods only make sense for strings and messages, and the
696 // repeated methods only make sense for repeated types.  So, each type
697 // traits class implements only the set of methods from this signature that it
698 // actually supports.  This will cause a compiler error if the user tries to
699 // access an extension using a method that doesn't make sense for its type.
700 // For example, if "foo" is an extension of type "optional int32", then if you
701 // try to write code like:
702 //   my_message.MutableExtension(foo)
703 // you will get a compile error because PrimitiveTypeTraits<int32> does not
704 // have a "Mutable()" method.
705 
706 // -------------------------------------------------------------------
707 // PrimitiveTypeTraits
708 
709 // Since the ExtensionSet has different methods for each primitive type,
710 // we must explicitly define the methods of the type traits class for each
711 // known type.
712 template <typename Type>
713 class PrimitiveTypeTraits {
714  public:
715   typedef Type ConstType;
716   typedef Type MutableType;
717   typedef PrimitiveTypeTraits<Type> Singular;
718 
719   static inline ConstType Get(int number, const ExtensionSet& set,
720                               ConstType default_value);
721   static inline void Set(int number, FieldType field_type,
722                          ConstType value, ExtensionSet* set);
723 };
724 
725 template <typename Type>
726 class RepeatedPrimitiveTypeTraits {
727  public:
728   typedef Type ConstType;
729   typedef Type MutableType;
730   typedef RepeatedPrimitiveTypeTraits<Type> Repeated;
731 
732   typedef RepeatedField<Type> RepeatedFieldType;
733 
734   static inline Type Get(int number, const ExtensionSet& set, int index);
735   static inline void Set(int number, int index, Type value, ExtensionSet* set);
736   static inline void Add(int number, FieldType field_type,
737                          bool is_packed, Type value, ExtensionSet* set);
738 
739   static inline const RepeatedField<ConstType>&
740       GetRepeated(int number, const ExtensionSet& set);
741   static inline RepeatedField<Type>*
742       MutableRepeated(int number, FieldType field_type,
743                       bool is_packed, ExtensionSet* set);
744 
745   static const RepeatedFieldType* GetDefaultRepeatedField();
746 };
747 
748 LIBPROTOBUF_EXPORT extern ProtobufOnceType repeated_primitive_generic_type_traits_once_init_;
749 
750 class LIBPROTOBUF_EXPORT RepeatedPrimitiveGenericTypeTraits {
751  private:
752   template<typename Type> friend class RepeatedPrimitiveTypeTraits;
753   static void InitializeDefaultRepeatedFields();
754   static void DestroyDefaultRepeatedFields();
755   static const RepeatedField<int32>* default_repeated_field_int32_;
756   static const RepeatedField<int64>* default_repeated_field_int64_;
757   static const RepeatedField<uint32>* default_repeated_field_uint32_;
758   static const RepeatedField<uint64>* default_repeated_field_uint64_;
759   static const RepeatedField<double>* default_repeated_field_double_;
760   static const RepeatedField<float>* default_repeated_field_float_;
761   static const RepeatedField<bool>* default_repeated_field_bool_;
762 };
763 
764 #define PROTOBUF_DEFINE_PRIMITIVE_TYPE(TYPE, METHOD)                       \
765 template<> inline TYPE PrimitiveTypeTraits<TYPE>::Get(                     \
766     int number, const ExtensionSet& set, TYPE default_value) {             \
767   return set.Get##METHOD(number, default_value);                           \
768 }                                                                          \
769 template<> inline void PrimitiveTypeTraits<TYPE>::Set(                     \
770     int number, FieldType field_type, TYPE value, ExtensionSet* set) {     \
771   set->Set##METHOD(number, field_type, value, NULL);                       \
772 }                                                                          \
773                                                                            \
774 template<> inline TYPE RepeatedPrimitiveTypeTraits<TYPE>::Get(             \
775     int number, const ExtensionSet& set, int index) {                      \
776   return set.GetRepeated##METHOD(number, index);                           \
777 }                                                                          \
778 template<> inline void RepeatedPrimitiveTypeTraits<TYPE>::Set(             \
779     int number, int index, TYPE value, ExtensionSet* set) {                \
780   set->SetRepeated##METHOD(number, index, value);                          \
781 }                                                                          \
782 template<> inline void RepeatedPrimitiveTypeTraits<TYPE>::Add(             \
783     int number, FieldType field_type, bool is_packed,                      \
784     TYPE value, ExtensionSet* set) {                                       \
785   set->Add##METHOD(number, field_type, is_packed, value, NULL);            \
786 }                                                                          \
787 template<> inline const RepeatedField<TYPE>*                               \
788     RepeatedPrimitiveTypeTraits<TYPE>::GetDefaultRepeatedField() {         \
789   ::google::protobuf::GoogleOnceInit(                                                          \
790       &repeated_primitive_generic_type_traits_once_init_,                  \
791       &RepeatedPrimitiveGenericTypeTraits::InitializeDefaultRepeatedFields); \
792   return RepeatedPrimitiveGenericTypeTraits::                              \
793       default_repeated_field_##TYPE##_;                                    \
794 }                                                                          \
795 template<> inline const RepeatedField<TYPE>&                               \
796     RepeatedPrimitiveTypeTraits<TYPE>::GetRepeated(int number,             \
797                                                const ExtensionSet& set) {  \
798   return *reinterpret_cast<const RepeatedField<TYPE>*>(                    \
799                             set.GetRawRepeatedField(                       \
800                                 number, GetDefaultRepeatedField()));       \
801 }                                                                          \
802 template<> inline RepeatedField<TYPE>*                                     \
803     RepeatedPrimitiveTypeTraits<TYPE>::MutableRepeated(int number,         \
804                                                    FieldType field_type,   \
805                                                    bool is_packed,         \
806                                                    ExtensionSet* set) {    \
807   return reinterpret_cast<RepeatedField<TYPE>*>(                           \
808       set->MutableRawRepeatedField(number, field_type, is_packed, NULL));  \
809 }
810 
PROTOBUF_DEFINE_PRIMITIVE_TYPE(int32,Int32)811 PROTOBUF_DEFINE_PRIMITIVE_TYPE( int32,  Int32)
812 PROTOBUF_DEFINE_PRIMITIVE_TYPE( int64,  Int64)
813 PROTOBUF_DEFINE_PRIMITIVE_TYPE(uint32, UInt32)
814 PROTOBUF_DEFINE_PRIMITIVE_TYPE(uint64, UInt64)
815 PROTOBUF_DEFINE_PRIMITIVE_TYPE( float,  Float)
816 PROTOBUF_DEFINE_PRIMITIVE_TYPE(double, Double)
817 PROTOBUF_DEFINE_PRIMITIVE_TYPE(  bool,   Bool)
818 
819 #undef PROTOBUF_DEFINE_PRIMITIVE_TYPE
820 
821 // -------------------------------------------------------------------
822 // StringTypeTraits
823 
824 // Strings support both Set() and Mutable().
825 class LIBPROTOBUF_EXPORT StringTypeTraits {
826  public:
827   typedef const string& ConstType;
828   typedef string* MutableType;
829   typedef StringTypeTraits Singular;
830 
831   static inline const string& Get(int number, const ExtensionSet& set,
832                                   ConstType default_value) {
833     return set.GetString(number, default_value);
834   }
835   static inline void Set(int number, FieldType field_type,
836                          const string& value, ExtensionSet* set) {
837     set->SetString(number, field_type, value, NULL);
838   }
839   static inline string* Mutable(int number, FieldType field_type,
840                                 ExtensionSet* set) {
841     return set->MutableString(number, field_type, NULL);
842   }
843 };
844 
845 LIBPROTOBUF_EXPORT extern ProtobufOnceType repeated_string_type_traits_once_init_;
846 
847 class LIBPROTOBUF_EXPORT RepeatedStringTypeTraits {
848  public:
849   typedef const string& ConstType;
850   typedef string* MutableType;
851   typedef RepeatedStringTypeTraits Repeated;
852 
853   typedef RepeatedPtrField<string> RepeatedFieldType;
854 
Get(int number,const ExtensionSet & set,int index)855   static inline const string& Get(int number, const ExtensionSet& set,
856                                   int index) {
857     return set.GetRepeatedString(number, index);
858   }
Set(int number,int index,const string & value,ExtensionSet * set)859   static inline void Set(int number, int index,
860                          const string& value, ExtensionSet* set) {
861     set->SetRepeatedString(number, index, value);
862   }
Mutable(int number,int index,ExtensionSet * set)863   static inline string* Mutable(int number, int index, ExtensionSet* set) {
864     return set->MutableRepeatedString(number, index);
865   }
Add(int number,FieldType field_type,bool,const string & value,ExtensionSet * set)866   static inline void Add(int number, FieldType field_type,
867                          bool /*is_packed*/, const string& value,
868                          ExtensionSet* set) {
869     set->AddString(number, field_type, value, NULL);
870   }
Add(int number,FieldType field_type,ExtensionSet * set)871   static inline string* Add(int number, FieldType field_type,
872                             ExtensionSet* set) {
873     return set->AddString(number, field_type, NULL);
874   }
875   static inline const RepeatedPtrField<string>&
GetRepeated(int number,const ExtensionSet & set)876       GetRepeated(int number, const ExtensionSet& set) {
877     return *reinterpret_cast<const RepeatedPtrField<string>*>(
878         set.GetRawRepeatedField(number, GetDefaultRepeatedField()));
879   }
880 
881   static inline RepeatedPtrField<string>*
MutableRepeated(int number,FieldType field_type,bool is_packed,ExtensionSet * set)882       MutableRepeated(int number, FieldType field_type,
883                       bool is_packed, ExtensionSet* set) {
884     return reinterpret_cast<RepeatedPtrField<string>*>(
885         set->MutableRawRepeatedField(number, field_type,
886                                      is_packed, NULL));
887   }
888 
GetDefaultRepeatedField()889   static const RepeatedFieldType* GetDefaultRepeatedField() {
890     ::google::protobuf::GoogleOnceInit(&repeated_string_type_traits_once_init_,
891                    &InitializeDefaultRepeatedFields);
892     return default_repeated_field_;
893   }
894 
895  private:
896   static void InitializeDefaultRepeatedFields();
897   static void DestroyDefaultRepeatedFields();
898   static const RepeatedFieldType *default_repeated_field_;
899 };
900 
901 // -------------------------------------------------------------------
902 // EnumTypeTraits
903 
904 // ExtensionSet represents enums using integers internally, so we have to
905 // static_cast around.
906 template <typename Type, bool IsValid(int)>
907 class EnumTypeTraits {
908  public:
909   typedef Type ConstType;
910   typedef Type MutableType;
911   typedef EnumTypeTraits<Type, IsValid> Singular;
912 
Get(int number,const ExtensionSet & set,ConstType default_value)913   static inline ConstType Get(int number, const ExtensionSet& set,
914                               ConstType default_value) {
915     return static_cast<Type>(set.GetEnum(number, default_value));
916   }
Set(int number,FieldType field_type,ConstType value,ExtensionSet * set)917   static inline void Set(int number, FieldType field_type,
918                          ConstType value, ExtensionSet* set) {
919     GOOGLE_DCHECK(IsValid(value));
920     set->SetEnum(number, field_type, value, NULL);
921   }
922 };
923 
924 template <typename Type, bool IsValid(int)>
925 class RepeatedEnumTypeTraits {
926  public:
927   typedef Type ConstType;
928   typedef Type MutableType;
929   typedef RepeatedEnumTypeTraits<Type, IsValid> Repeated;
930 
931   typedef RepeatedField<Type> RepeatedFieldType;
932 
Get(int number,const ExtensionSet & set,int index)933   static inline ConstType Get(int number, const ExtensionSet& set, int index) {
934     return static_cast<Type>(set.GetRepeatedEnum(number, index));
935   }
Set(int number,int index,ConstType value,ExtensionSet * set)936   static inline void Set(int number, int index,
937                          ConstType value, ExtensionSet* set) {
938     GOOGLE_DCHECK(IsValid(value));
939     set->SetRepeatedEnum(number, index, value);
940   }
Add(int number,FieldType field_type,bool is_packed,ConstType value,ExtensionSet * set)941   static inline void Add(int number, FieldType field_type,
942                          bool is_packed, ConstType value, ExtensionSet* set) {
943     GOOGLE_DCHECK(IsValid(value));
944     set->AddEnum(number, field_type, is_packed, value, NULL);
945   }
GetRepeated(int number,const ExtensionSet & set)946   static inline const RepeatedField<Type>& GetRepeated(int number,
947                                                        const ExtensionSet&
948                                                        set) {
949     // Hack: the `Extension` struct stores a RepeatedField<int> for enums.
950     // RepeatedField<int> cannot implicitly convert to RepeatedField<EnumType>
951     // so we need to do some casting magic. See message.h for similar
952     // contortions for non-extension fields.
953     return *reinterpret_cast<const RepeatedField<Type>*>(
954         set.GetRawRepeatedField(number, GetDefaultRepeatedField()));
955   }
956 
MutableRepeated(int number,FieldType field_type,bool is_packed,ExtensionSet * set)957   static inline RepeatedField<Type>* MutableRepeated(int number,
958                                                      FieldType field_type,
959                                                      bool is_packed,
960                                                      ExtensionSet* set) {
961     return reinterpret_cast<RepeatedField<Type>*>(
962         set->MutableRawRepeatedField(number, field_type, is_packed, NULL));
963   }
964 
GetDefaultRepeatedField()965   static const RepeatedFieldType* GetDefaultRepeatedField() {
966     // Hack: as noted above, repeated enum fields are internally stored as a
967     // RepeatedField<int>. We need to be able to instantiate global static
968     // objects to return as default (empty) repeated fields on non-existent
969     // extensions. We would not be able to know a-priori all of the enum types
970     // (values of |Type|) to instantiate all of these, so we just re-use int32's
971     // default repeated field object.
972     return reinterpret_cast<const RepeatedField<Type>*>(
973         RepeatedPrimitiveTypeTraits<int32>::GetDefaultRepeatedField());
974   }
975 };
976 
977 // -------------------------------------------------------------------
978 // MessageTypeTraits
979 
980 // ExtensionSet guarantees that when manipulating extensions with message
981 // types, the implementation used will be the compiled-in class representing
982 // that type.  So, we can static_cast down to the exact type we expect.
983 template <typename Type>
984 class MessageTypeTraits {
985  public:
986   typedef const Type& ConstType;
987   typedef Type* MutableType;
988   typedef MessageTypeTraits<Type> Singular;
989 
Get(int number,const ExtensionSet & set,ConstType default_value)990   static inline ConstType Get(int number, const ExtensionSet& set,
991                               ConstType default_value) {
992     return static_cast<const Type&>(
993         set.GetMessage(number, default_value));
994   }
Mutable(int number,FieldType field_type,ExtensionSet * set)995   static inline MutableType Mutable(int number, FieldType field_type,
996                                     ExtensionSet* set) {
997     return static_cast<Type*>(
998       set->MutableMessage(number, field_type, Type::default_instance(), NULL));
999   }
SetAllocated(int number,FieldType field_type,MutableType message,ExtensionSet * set)1000   static inline void SetAllocated(int number, FieldType field_type,
1001                                   MutableType message, ExtensionSet* set) {
1002     set->SetAllocatedMessage(number, field_type, NULL, message);
1003   }
UnsafeArenaSetAllocated(int number,FieldType field_type,MutableType message,ExtensionSet * set)1004   static inline void UnsafeArenaSetAllocated(int number, FieldType field_type,
1005                                              MutableType message,
1006                                              ExtensionSet* set) {
1007     set->UnsafeArenaSetAllocatedMessage(number, field_type, NULL, message);
1008   }
Release(int number,FieldType,ExtensionSet * set)1009   static inline MutableType Release(int number, FieldType /* field_type */,
1010                                     ExtensionSet* set) {
1011     return static_cast<Type*>(set->ReleaseMessage(
1012         number, Type::default_instance()));
1013   }
UnsafeArenaRelease(int number,FieldType,ExtensionSet * set)1014   static inline MutableType UnsafeArenaRelease(int number,
1015                                                FieldType /* field_type */,
1016                                                ExtensionSet* set) {
1017     return static_cast<Type*>(set->UnsafeArenaReleaseMessage(
1018         number, Type::default_instance()));
1019   }
1020 };
1021 
1022 // forward declaration
1023 class RepeatedMessageGenericTypeTraits;
1024 
1025 template <typename Type>
1026 class RepeatedMessageTypeTraits {
1027  public:
1028   typedef const Type& ConstType;
1029   typedef Type* MutableType;
1030   typedef RepeatedMessageTypeTraits<Type> Repeated;
1031 
1032   typedef RepeatedPtrField<Type> RepeatedFieldType;
1033 
Get(int number,const ExtensionSet & set,int index)1034   static inline ConstType Get(int number, const ExtensionSet& set, int index) {
1035     return static_cast<const Type&>(set.GetRepeatedMessage(number, index));
1036   }
Mutable(int number,int index,ExtensionSet * set)1037   static inline MutableType Mutable(int number, int index, ExtensionSet* set) {
1038     return static_cast<Type*>(set->MutableRepeatedMessage(number, index));
1039   }
Add(int number,FieldType field_type,ExtensionSet * set)1040   static inline MutableType Add(int number, FieldType field_type,
1041                                 ExtensionSet* set) {
1042     return static_cast<Type*>(
1043         set->AddMessage(number, field_type, Type::default_instance(), NULL));
1044   }
GetRepeated(int number,const ExtensionSet & set)1045   static inline const RepeatedPtrField<Type>& GetRepeated(int number,
1046                                                           const ExtensionSet&
1047                                                           set) {
1048     // See notes above in RepeatedEnumTypeTraits::GetRepeated(): same
1049     // casting hack applies here, because a RepeatedPtrField<MessageLite>
1050     // cannot naturally become a RepeatedPtrType<Type> even though Type is
1051     // presumably a message. google::protobuf::Message goes through similar contortions
1052     // with a reinterpret_cast<>.
1053     return *reinterpret_cast<const RepeatedPtrField<Type>*>(
1054         set.GetRawRepeatedField(number, GetDefaultRepeatedField()));
1055   }
MutableRepeated(int number,FieldType field_type,bool is_packed,ExtensionSet * set)1056   static inline RepeatedPtrField<Type>* MutableRepeated(int number,
1057                                                         FieldType field_type,
1058                                                         bool is_packed,
1059                                                         ExtensionSet* set) {
1060     return reinterpret_cast<RepeatedPtrField<Type>*>(
1061         set->MutableRawRepeatedField(number, field_type, is_packed, NULL));
1062   }
1063 
1064   static const RepeatedFieldType* GetDefaultRepeatedField();
1065 };
1066 
1067 LIBPROTOBUF_EXPORT extern ProtobufOnceType repeated_message_generic_type_traits_once_init_;
1068 
1069 // This class exists only to hold a generic default empty repeated field for all
1070 // message-type repeated field extensions.
1071 class LIBPROTOBUF_EXPORT RepeatedMessageGenericTypeTraits {
1072  public:
1073   typedef RepeatedPtrField< ::google::protobuf::MessageLite*> RepeatedFieldType;
1074  private:
1075   template<typename Type> friend class RepeatedMessageTypeTraits;
1076   static void InitializeDefaultRepeatedFields();
1077   static void DestroyDefaultRepeatedFields();
1078   static const RepeatedFieldType* default_repeated_field_;
1079 };
1080 
1081 template<typename Type> inline
1082     const typename RepeatedMessageTypeTraits<Type>::RepeatedFieldType*
GetDefaultRepeatedField()1083     RepeatedMessageTypeTraits<Type>::GetDefaultRepeatedField() {
1084   ::google::protobuf::GoogleOnceInit(
1085       &repeated_message_generic_type_traits_once_init_,
1086       &RepeatedMessageGenericTypeTraits::InitializeDefaultRepeatedFields);
1087   return reinterpret_cast<const RepeatedFieldType*>(
1088       RepeatedMessageGenericTypeTraits::default_repeated_field_);
1089 }
1090 
1091 // -------------------------------------------------------------------
1092 // ExtensionIdentifier
1093 
1094 // This is the type of actual extension objects.  E.g. if you have:
1095 //   extends Foo with optional int32 bar = 1234;
1096 // then "bar" will be defined in C++ as:
1097 //   ExtensionIdentifier<Foo, PrimitiveTypeTraits<int32>, 1, false> bar(1234);
1098 //
1099 // Note that we could, in theory, supply the field number as a template
1100 // parameter, and thus make an instance of ExtensionIdentifier have no
1101 // actual contents.  However, if we did that, then using at extension
1102 // identifier would not necessarily cause the compiler to output any sort
1103 // of reference to any simple defined in the extension's .pb.o file.  Some
1104 // linkers will actually drop object files that are not explicitly referenced,
1105 // but that would be bad because it would cause this extension to not be
1106 // registered at static initialization, and therefore using it would crash.
1107 
1108 template <typename ExtendeeType, typename TypeTraitsType,
1109           FieldType field_type, bool is_packed>
1110 class ExtensionIdentifier {
1111  public:
1112   typedef TypeTraitsType TypeTraits;
1113   typedef ExtendeeType Extendee;
1114 
ExtensionIdentifier(int number,typename TypeTraits::ConstType default_value)1115   ExtensionIdentifier(int number, typename TypeTraits::ConstType default_value)
1116       : number_(number), default_value_(default_value) {}
number()1117   inline int number() const { return number_; }
default_value()1118   typename TypeTraits::ConstType default_value() const {
1119     return default_value_;
1120   }
1121 
1122  private:
1123   const int number_;
1124   typename TypeTraits::ConstType default_value_;
1125 };
1126 
1127 // -------------------------------------------------------------------
1128 // Generated accessors
1129 
1130 // This macro should be expanded in the context of a generated type which
1131 // has extensions.
1132 //
1133 // We use "_proto_TypeTraits" as a type name below because "TypeTraits"
1134 // causes problems if the class has a nested message or enum type with that
1135 // name and "_TypeTraits" is technically reserved for the C++ library since
1136 // it starts with an underscore followed by a capital letter.
1137 //
1138 // For similar reason, we use "_field_type" and "_is_packed" as parameter names
1139 // below, so that "field_type" and "is_packed" can be used as field names.
1140 #define GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(CLASSNAME)                        \
1141   /* Has, Size, Clear */                                                      \
1142   template <typename _proto_TypeTraits,                                       \
1143             ::google::protobuf::internal::FieldType _field_type,                        \
1144             bool _is_packed>                                                  \
1145   inline bool HasExtension(                                                   \
1146       const ::google::protobuf::internal::ExtensionIdentifier<                          \
1147         CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const {   \
1148     return _extensions_.Has(id.number());                                     \
1149   }                                                                           \
1150                                                                               \
1151   template <typename _proto_TypeTraits,                                       \
1152             ::google::protobuf::internal::FieldType _field_type,                        \
1153             bool _is_packed>                                                  \
1154   inline void ClearExtension(                                                 \
1155       const ::google::protobuf::internal::ExtensionIdentifier<                          \
1156         CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) {         \
1157     _extensions_.ClearExtension(id.number());                                 \
1158   }                                                                           \
1159                                                                               \
1160   template <typename _proto_TypeTraits,                                       \
1161             ::google::protobuf::internal::FieldType _field_type,                        \
1162             bool _is_packed>                                                  \
1163   inline int ExtensionSize(                                                   \
1164       const ::google::protobuf::internal::ExtensionIdentifier<                          \
1165         CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const {   \
1166     return _extensions_.ExtensionSize(id.number());                           \
1167   }                                                                           \
1168                                                                               \
1169   /* Singular accessors */                                                    \
1170   template <typename _proto_TypeTraits,                                       \
1171             ::google::protobuf::internal::FieldType _field_type,                        \
1172             bool _is_packed>                                                  \
1173   inline typename _proto_TypeTraits::Singular::ConstType GetExtension(        \
1174       const ::google::protobuf::internal::ExtensionIdentifier<                          \
1175         CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const {   \
1176     return _proto_TypeTraits::Get(id.number(), _extensions_,                  \
1177                                   id.default_value());                        \
1178   }                                                                           \
1179                                                                               \
1180   template <typename _proto_TypeTraits,                                       \
1181             ::google::protobuf::internal::FieldType _field_type,                        \
1182             bool _is_packed>                                                  \
1183   inline typename _proto_TypeTraits::Singular::MutableType MutableExtension(  \
1184       const ::google::protobuf::internal::ExtensionIdentifier<                          \
1185         CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) {         \
1186     return _proto_TypeTraits::Mutable(id.number(), _field_type,               \
1187                                       &_extensions_);                         \
1188   }                                                                           \
1189                                                                               \
1190   template <typename _proto_TypeTraits,                                       \
1191             ::google::protobuf::internal::FieldType _field_type,                        \
1192             bool _is_packed>                                                  \
1193   inline void SetExtension(                                                   \
1194       const ::google::protobuf::internal::ExtensionIdentifier<                          \
1195         CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id,           \
1196       typename _proto_TypeTraits::Singular::ConstType value) {                \
1197     _proto_TypeTraits::Set(id.number(), _field_type, value, &_extensions_);   \
1198   }                                                                           \
1199                                                                               \
1200   template <typename _proto_TypeTraits,                                       \
1201             ::google::protobuf::internal::FieldType _field_type,                        \
1202             bool _is_packed>                                                  \
1203   inline void SetAllocatedExtension(                                          \
1204       const ::google::protobuf::internal::ExtensionIdentifier<                          \
1205         CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id,           \
1206       typename _proto_TypeTraits::Singular::MutableType value) {              \
1207     _proto_TypeTraits::SetAllocated(id.number(), _field_type,                 \
1208                                     value, &_extensions_);                    \
1209   }                                                                           \
1210   template <typename _proto_TypeTraits,                                       \
1211             ::google::protobuf::internal::FieldType _field_type,                        \
1212             bool _is_packed>                                                  \
1213   inline void UnsafeArenaSetAllocatedExtension(                               \
1214       const ::google::protobuf::internal::ExtensionIdentifier<                          \
1215         CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id,           \
1216       typename _proto_TypeTraits::Singular::MutableType value) {              \
1217     _proto_TypeTraits::UnsafeArenaSetAllocated(id.number(), _field_type,      \
1218                                                value, &_extensions_);         \
1219   }                                                                           \
1220   template <typename _proto_TypeTraits,                                       \
1221             ::google::protobuf::internal::FieldType _field_type,                        \
1222             bool _is_packed>                                                  \
1223   inline typename _proto_TypeTraits::Singular::MutableType ReleaseExtension(  \
1224       const ::google::protobuf::internal::ExtensionIdentifier<                          \
1225         CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) {         \
1226     return _proto_TypeTraits::Release(id.number(), _field_type,               \
1227                                       &_extensions_);                         \
1228   }                                                                           \
1229   template <typename _proto_TypeTraits,                                       \
1230             ::google::protobuf::internal::FieldType _field_type,                        \
1231             bool _is_packed>                                                  \
1232   inline typename _proto_TypeTraits::Singular::MutableType                    \
1233       UnsafeArenaReleaseExtension(                                            \
1234           const ::google::protobuf::internal::ExtensionIdentifier<                      \
1235             CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) {     \
1236     return _proto_TypeTraits::UnsafeArenaRelease(id.number(), _field_type,    \
1237                                                  &_extensions_);              \
1238   }                                                                           \
1239                                                                               \
1240   /* Repeated accessors */                                                    \
1241   template <typename _proto_TypeTraits,                                       \
1242             ::google::protobuf::internal::FieldType _field_type,                        \
1243             bool _is_packed>                                                  \
1244   inline typename _proto_TypeTraits::Repeated::ConstType GetExtension(        \
1245       const ::google::protobuf::internal::ExtensionIdentifier<                          \
1246         CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id,           \
1247       int index) const {                                                      \
1248     return _proto_TypeTraits::Get(id.number(), _extensions_, index);          \
1249   }                                                                           \
1250                                                                               \
1251   template <typename _proto_TypeTraits,                                       \
1252             ::google::protobuf::internal::FieldType _field_type,                        \
1253             bool _is_packed>                                                  \
1254   inline typename _proto_TypeTraits::Repeated::MutableType MutableExtension(  \
1255       const ::google::protobuf::internal::ExtensionIdentifier<                          \
1256         CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id,           \
1257       int index) {                                                            \
1258     return _proto_TypeTraits::Mutable(id.number(), index, &_extensions_);     \
1259   }                                                                           \
1260                                                                               \
1261   template <typename _proto_TypeTraits,                                       \
1262             ::google::protobuf::internal::FieldType _field_type,                        \
1263             bool _is_packed>                                                  \
1264   inline void SetExtension(                                                   \
1265       const ::google::protobuf::internal::ExtensionIdentifier<                          \
1266         CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id,           \
1267       int index, typename _proto_TypeTraits::Repeated::ConstType value) {     \
1268     _proto_TypeTraits::Set(id.number(), index, value, &_extensions_);         \
1269   }                                                                           \
1270                                                                               \
1271   template <typename _proto_TypeTraits,                                       \
1272             ::google::protobuf::internal::FieldType _field_type,                        \
1273             bool _is_packed>                                                  \
1274   inline typename _proto_TypeTraits::Repeated::MutableType AddExtension(      \
1275       const ::google::protobuf::internal::ExtensionIdentifier<                          \
1276         CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) {         \
1277     return _proto_TypeTraits::Add(id.number(), _field_type, &_extensions_);   \
1278   }                                                                           \
1279                                                                               \
1280   template <typename _proto_TypeTraits,                                       \
1281             ::google::protobuf::internal::FieldType _field_type,                        \
1282             bool _is_packed>                                                  \
1283   inline void AddExtension(                                                   \
1284       const ::google::protobuf::internal::ExtensionIdentifier<                          \
1285         CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id,           \
1286       typename _proto_TypeTraits::Repeated::ConstType value) {                \
1287     _proto_TypeTraits::Add(id.number(), _field_type, _is_packed,              \
1288                            value, &_extensions_);                             \
1289   }                                                                           \
1290                                                                               \
1291   template <typename _proto_TypeTraits,                                       \
1292             ::google::protobuf::internal::FieldType _field_type,                        \
1293             bool _is_packed>                                                  \
1294   inline const typename _proto_TypeTraits::Repeated::RepeatedFieldType&       \
1295       GetRepeatedExtension(                                                   \
1296           const ::google::protobuf::internal::ExtensionIdentifier<                      \
1297             CLASSNAME, _proto_TypeTraits, _field_type,                        \
1298             _is_packed>& id) const {                                          \
1299     return _proto_TypeTraits::GetRepeated(id.number(), _extensions_);         \
1300   }                                                                           \
1301                                                                               \
1302   template <typename _proto_TypeTraits,                                       \
1303             ::google::protobuf::internal::FieldType _field_type,                        \
1304             bool _is_packed>                                                  \
1305   inline typename _proto_TypeTraits::Repeated::RepeatedFieldType*             \
1306       MutableRepeatedExtension(                                               \
1307           const ::google::protobuf::internal::ExtensionIdentifier<                      \
1308               CLASSNAME, _proto_TypeTraits, _field_type,                      \
1309               _is_packed>& id) {                                              \
1310     return _proto_TypeTraits::MutableRepeated(id.number(), _field_type,       \
1311                                               _is_packed, &_extensions_);     \
1312   }
1313 
1314 }  // namespace internal
1315 }  // namespace protobuf
1316 
1317 }  // namespace google
1318 #endif  // GOOGLE_PROTOBUF_EXTENSION_SET_H__
1319