extension_set.h 72 KB

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