You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

extension_set.h 72 kB

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