message.h 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  1. #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 Google Inc. All rights reserved.
  4. // https://developers.google.com/protocol-buffers/
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. // Author: kenton@google.com (Kenton Varda)
  32. // Based on original Protocol Buffers design by
  33. // Sanjay Ghemawat, Jeff Dean, and others.
  34. //
  35. // Defines Message, the abstract interface implemented by non-lite
  36. // protocol message objects. Although it's possible to implement this
  37. // interface manually, most users will use the protocol compiler to
  38. // generate implementations.
  39. //
  40. // Example usage:
  41. //
  42. // Say you have a message defined as:
  43. //
  44. // message Foo {
  45. // optional string text = 1;
  46. // repeated int32 numbers = 2;
  47. // }
  48. //
  49. // Then, if you used the protocol compiler to generate a class from the above
  50. // definition, you could use it like so:
  51. //
  52. // std::string data; // Will store a serialized version of the message.
  53. //
  54. // {
  55. // // Create a message and serialize it.
  56. // Foo foo;
  57. // foo.set_text("Hello World!");
  58. // foo.add_numbers(1);
  59. // foo.add_numbers(5);
  60. // foo.add_numbers(42);
  61. //
  62. // foo.SerializeToString(&data);
  63. // }
  64. //
  65. // {
  66. // // Parse the serialized message and check that it contains the
  67. // // correct data.
  68. // Foo foo;
  69. // foo.ParseFromString(data);
  70. //
  71. // assert(foo.text() == "Hello World!");
  72. // assert(foo.numbers_size() == 3);
  73. // assert(foo.numbers(0) == 1);
  74. // assert(foo.numbers(1) == 5);
  75. // assert(foo.numbers(2) == 42);
  76. // }
  77. //
  78. // {
  79. // // Same as the last block, but do it dynamically via the Message
  80. // // reflection interface.
  81. // Message* foo = new Foo;
  82. // const Descriptor* descriptor = foo->GetDescriptor();
  83. //
  84. // // Get the descriptors for the fields we're interested in and verify
  85. // // their types.
  86. // const FieldDescriptor* text_field = descriptor->FindFieldByName("text");
  87. // assert(text_field != nullptr);
  88. // assert(text_field->type() == FieldDescriptor::TYPE_STRING);
  89. // assert(text_field->label() == FieldDescriptor::LABEL_OPTIONAL);
  90. // const FieldDescriptor* numbers_field = descriptor->
  91. // FindFieldByName("numbers");
  92. // assert(numbers_field != nullptr);
  93. // assert(numbers_field->type() == FieldDescriptor::TYPE_INT32);
  94. // assert(numbers_field->label() == FieldDescriptor::LABEL_REPEATED);
  95. //
  96. // // Parse the message.
  97. // foo->ParseFromString(data);
  98. //
  99. // // Use the reflection interface to examine the contents.
  100. // const Reflection* reflection = foo->GetReflection();
  101. // assert(reflection->GetString(*foo, text_field) == "Hello World!");
  102. // assert(reflection->FieldSize(*foo, numbers_field) == 3);
  103. // assert(reflection->GetRepeatedInt32(*foo, numbers_field, 0) == 1);
  104. // assert(reflection->GetRepeatedInt32(*foo, numbers_field, 1) == 5);
  105. // assert(reflection->GetRepeatedInt32(*foo, numbers_field, 2) == 42);
  106. //
  107. // delete foo;
  108. // }
  109. #ifndef GOOGLE_PROTOBUF_MESSAGE_H__
  110. #define GOOGLE_PROTOBUF_MESSAGE_H__
  111. #include <iosfwd>
  112. #include <string>
  113. #include <type_traits>
  114. #include <vector>
  115. #include <google/protobuf/stubs/casts.h>
  116. #include <google/protobuf/stubs/common.h>
  117. #include <google/protobuf/arena.h>
  118. #include <google/protobuf/descriptor.h>
  119. #include <google/protobuf/generated_message_reflection.h>
  120. #include <google/protobuf/message_lite.h>
  121. #include <google/protobuf/port.h>
  122. #define GOOGLE_PROTOBUF_HAS_ONEOF
  123. #define GOOGLE_PROTOBUF_HAS_ARENAS
  124. #include <google/protobuf/port_def.inc>
  125. #ifdef SWIG
  126. #error "You cannot SWIG proto headers"
  127. #endif
  128. namespace google {
  129. namespace protobuf {
  130. // Defined in this file.
  131. class Message;
  132. class Reflection;
  133. class MessageFactory;
  134. // Defined in other files.
  135. class AssignDescriptorsHelper;
  136. class DynamicMessageFactory;
  137. class MapKey;
  138. class MapValueRef;
  139. class MapIterator;
  140. class MapReflectionTester;
  141. namespace internal {
  142. struct DescriptorTable;
  143. class MapFieldBase;
  144. }
  145. class UnknownFieldSet; // unknown_field_set.h
  146. namespace io {
  147. class ZeroCopyInputStream; // zero_copy_stream.h
  148. class ZeroCopyOutputStream; // zero_copy_stream.h
  149. class CodedInputStream; // coded_stream.h
  150. class CodedOutputStream; // coded_stream.h
  151. } // namespace io
  152. namespace python {
  153. class MapReflectionFriend; // scalar_map_container.h
  154. }
  155. namespace expr {
  156. class CelMapReflectionFriend; // field_backed_map_impl.cc
  157. }
  158. namespace internal {
  159. class MapFieldPrinterHelper; // text_format.cc
  160. }
  161. namespace internal {
  162. class ReflectionAccessor; // message.cc
  163. class ReflectionOps; // reflection_ops.h
  164. class MapKeySorter; // wire_format.cc
  165. class WireFormat; // wire_format.h
  166. class MapFieldReflectionTest; // map_test.cc
  167. } // namespace internal
  168. template <typename T>
  169. class RepeatedField; // repeated_field.h
  170. template <typename T>
  171. class RepeatedPtrField; // repeated_field.h
  172. // A container to hold message metadata.
  173. struct Metadata {
  174. const Descriptor* descriptor;
  175. const Reflection* reflection;
  176. };
  177. namespace internal {
  178. template <class To>
  179. inline To* GetPointerAtOffset(Message* message, uint32 offset) {
  180. return reinterpret_cast<To*>(reinterpret_cast<char*>(message) + offset);
  181. }
  182. template <class To>
  183. const To* GetConstPointerAtOffset(const Message* message, uint32 offset) {
  184. return reinterpret_cast<const To*>(reinterpret_cast<const char*>(message) +
  185. offset);
  186. }
  187. template <class To>
  188. const To& GetConstRefAtOffset(const Message& message, uint32 offset) {
  189. return *GetConstPointerAtOffset<To>(&message, offset);
  190. }
  191. bool CreateUnknownEnumValues(const FieldDescriptor* field);
  192. } // namespace internal
  193. // Abstract interface for protocol messages.
  194. //
  195. // See also MessageLite, which contains most every-day operations. Message
  196. // adds descriptors and reflection on top of that.
  197. //
  198. // The methods of this class that are virtual but not pure-virtual have
  199. // default implementations based on reflection. Message classes which are
  200. // optimized for speed will want to override these with faster implementations,
  201. // but classes optimized for code size may be happy with keeping them. See
  202. // the optimize_for option in descriptor.proto.
  203. //
  204. // Users must not derive from this class. Only the protocol compiler and
  205. // the internal library are allowed to create subclasses.
  206. class PROTOBUF_EXPORT Message : public MessageLite {
  207. public:
  208. inline Message() {}
  209. // Basic Operations ------------------------------------------------
  210. // Construct a new instance of the same type. Ownership is passed to the
  211. // caller. (This is also defined in MessageLite, but is defined again here
  212. // for return-type covariance.)
  213. Message* New() const override = 0;
  214. // Construct a new instance on the arena. Ownership is passed to the caller
  215. // if arena is a nullptr. Default implementation allows for API compatibility
  216. // during the Arena transition.
  217. Message* New(Arena* arena) const override {
  218. Message* message = New();
  219. if (arena != nullptr) {
  220. arena->Own(message);
  221. }
  222. return message;
  223. }
  224. // Make this message into a copy of the given message. The given message
  225. // must have the same descriptor, but need not necessarily be the same class.
  226. // By default this is just implemented as "Clear(); MergeFrom(from);".
  227. virtual void CopyFrom(const Message& from);
  228. // Merge the fields from the given message into this message. Singular
  229. // fields will be overwritten, if specified in from, except for embedded
  230. // messages which will be merged. Repeated fields will be concatenated.
  231. // The given message must be of the same type as this message (i.e. the
  232. // exact same class).
  233. virtual void MergeFrom(const Message& from);
  234. // Verifies that IsInitialized() returns true. GOOGLE_CHECK-fails otherwise, with
  235. // a nice error message.
  236. void CheckInitialized() const;
  237. // Slowly build a list of all required fields that are not set.
  238. // This is much, much slower than IsInitialized() as it is implemented
  239. // purely via reflection. Generally, you should not call this unless you
  240. // have already determined that an error exists by calling IsInitialized().
  241. void FindInitializationErrors(std::vector<std::string>* errors) const;
  242. // Like FindInitializationErrors, but joins all the strings, delimited by
  243. // commas, and returns them.
  244. std::string InitializationErrorString() const override;
  245. // Clears all unknown fields from this message and all embedded messages.
  246. // Normally, if unknown tag numbers are encountered when parsing a message,
  247. // the tag and value are stored in the message's UnknownFieldSet and
  248. // then written back out when the message is serialized. This allows servers
  249. // which simply route messages to other servers to pass through messages
  250. // that have new field definitions which they don't yet know about. However,
  251. // this behavior can have security implications. To avoid it, call this
  252. // method after parsing.
  253. //
  254. // See Reflection::GetUnknownFields() for more on unknown fields.
  255. virtual void DiscardUnknownFields();
  256. // Computes (an estimate of) the total number of bytes currently used for
  257. // storing the message in memory. The default implementation calls the
  258. // Reflection object's SpaceUsed() method.
  259. //
  260. // SpaceUsed() is noticeably slower than ByteSize(), as it is implemented
  261. // using reflection (rather than the generated code implementation for
  262. // ByteSize()). Like ByteSize(), its CPU time is linear in the number of
  263. // fields defined for the proto.
  264. virtual size_t SpaceUsedLong() const;
  265. PROTOBUF_DEPRECATED_MSG("Please use SpaceUsedLong() instead")
  266. int SpaceUsed() const { return internal::ToIntSize(SpaceUsedLong()); }
  267. // Debugging & Testing----------------------------------------------
  268. // Generates a human readable form of this message, useful for debugging
  269. // and other purposes.
  270. std::string DebugString() const;
  271. // Like DebugString(), but with less whitespace.
  272. std::string ShortDebugString() const;
  273. // Like DebugString(), but do not escape UTF-8 byte sequences.
  274. std::string Utf8DebugString() const;
  275. // Convenience function useful in GDB. Prints DebugString() to stdout.
  276. void PrintDebugString() const;
  277. // Reflection-based methods ----------------------------------------
  278. // These methods are pure-virtual in MessageLite, but Message provides
  279. // reflection-based default implementations.
  280. std::string GetTypeName() const override;
  281. void Clear() override;
  282. // Returns whether all required fields have been set. Note that required
  283. // fields no longer exist starting in proto3.
  284. bool IsInitialized() const override;
  285. void CheckTypeAndMergeFrom(const MessageLite& other) override;
  286. // Reflective parser
  287. const char* _InternalParse(const char* ptr,
  288. internal::ParseContext* ctx) override;
  289. size_t ByteSizeLong() const override;
  290. uint8* _InternalSerialize(uint8* target,
  291. io::EpsCopyOutputStream* stream) const override;
  292. private:
  293. // This is called only by the default implementation of ByteSize(), to
  294. // update the cached size. If you override ByteSize(), you do not need
  295. // to override this. If you do not override ByteSize(), you MUST override
  296. // this; the default implementation will crash.
  297. //
  298. // The method is private because subclasses should never call it; only
  299. // override it. Yes, C++ lets you do that. Crazy, huh?
  300. virtual void SetCachedSize(int size) const;
  301. public:
  302. // Introspection ---------------------------------------------------
  303. // Get a non-owning pointer to a Descriptor for this message's type. This
  304. // describes what fields the message contains, the types of those fields, etc.
  305. // This object remains property of the Message.
  306. const Descriptor* GetDescriptor() const { return GetMetadata().descriptor; }
  307. // Get a non-owning pointer to the Reflection interface for this Message,
  308. // which can be used to read and modify the fields of the Message dynamically
  309. // (in other words, without knowing the message type at compile time). This
  310. // object remains property of the Message.
  311. const Reflection* GetReflection() const { return GetMetadata().reflection; }
  312. protected:
  313. // Get a struct containing the metadata for the Message, which is used in turn
  314. // to implement GetDescriptor() and GetReflection() above.
  315. virtual Metadata GetMetadata() const = 0;
  316. inline explicit Message(Arena* arena) : MessageLite(arena) {}
  317. private:
  318. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Message);
  319. };
  320. namespace internal {
  321. // Forward-declare interfaces used to implement RepeatedFieldRef.
  322. // These are protobuf internals that users shouldn't care about.
  323. class RepeatedFieldAccessor;
  324. } // namespace internal
  325. // Forward-declare RepeatedFieldRef templates. The second type parameter is
  326. // used for SFINAE tricks. Users should ignore it.
  327. template <typename T, typename Enable = void>
  328. class RepeatedFieldRef;
  329. template <typename T, typename Enable = void>
  330. class MutableRepeatedFieldRef;
  331. // This interface contains methods that can be used to dynamically access
  332. // and modify the fields of a protocol message. Their semantics are
  333. // similar to the accessors the protocol compiler generates.
  334. //
  335. // To get the Reflection for a given Message, call Message::GetReflection().
  336. //
  337. // This interface is separate from Message only for efficiency reasons;
  338. // the vast majority of implementations of Message will share the same
  339. // implementation of Reflection (GeneratedMessageReflection,
  340. // defined in generated_message.h), and all Messages of a particular class
  341. // should share the same Reflection object (though you should not rely on
  342. // the latter fact).
  343. //
  344. // There are several ways that these methods can be used incorrectly. For
  345. // example, any of the following conditions will lead to undefined
  346. // results (probably assertion failures):
  347. // - The FieldDescriptor is not a field of this message type.
  348. // - The method called is not appropriate for the field's type. For
  349. // each field type in FieldDescriptor::TYPE_*, there is only one
  350. // Get*() method, one Set*() method, and one Add*() method that is
  351. // valid for that type. It should be obvious which (except maybe
  352. // for TYPE_BYTES, which are represented using strings in C++).
  353. // - A Get*() or Set*() method for singular fields is called on a repeated
  354. // field.
  355. // - GetRepeated*(), SetRepeated*(), or Add*() is called on a non-repeated
  356. // field.
  357. // - The Message object passed to any method is not of the right type for
  358. // this Reflection object (i.e. message.GetReflection() != reflection).
  359. //
  360. // You might wonder why there is not any abstract representation for a field
  361. // of arbitrary type. E.g., why isn't there just a "GetField()" method that
  362. // returns "const Field&", where "Field" is some class with accessors like
  363. // "GetInt32Value()". The problem is that someone would have to deal with
  364. // allocating these Field objects. For generated message classes, having to
  365. // allocate space for an additional object to wrap every field would at least
  366. // double the message's memory footprint, probably worse. Allocating the
  367. // objects on-demand, on the other hand, would be expensive and prone to
  368. // memory leaks. So, instead we ended up with this flat interface.
  369. class PROTOBUF_EXPORT Reflection final {
  370. public:
  371. // Get the UnknownFieldSet for the message. This contains fields which
  372. // were seen when the Message was parsed but were not recognized according
  373. // to the Message's definition.
  374. const UnknownFieldSet& GetUnknownFields(const Message& message) const;
  375. // Get a mutable pointer to the UnknownFieldSet for the message. This
  376. // contains fields which were seen when the Message was parsed but were not
  377. // recognized according to the Message's definition.
  378. UnknownFieldSet* MutableUnknownFields(Message* message) const;
  379. // Estimate the amount of memory used by the message object.
  380. size_t SpaceUsedLong(const Message& message) const;
  381. PROTOBUF_DEPRECATED_MSG("Please use SpaceUsedLong() instead")
  382. int SpaceUsed(const Message& message) const {
  383. return internal::ToIntSize(SpaceUsedLong(message));
  384. }
  385. // Check if the given non-repeated field is set.
  386. bool HasField(const Message& message, const FieldDescriptor* field) const;
  387. // Get the number of elements of a repeated field.
  388. int FieldSize(const Message& message, const FieldDescriptor* field) const;
  389. // Clear the value of a field, so that HasField() returns false or
  390. // FieldSize() returns zero.
  391. void ClearField(Message* message, const FieldDescriptor* field) const;
  392. // Check if the oneof is set. Returns true if any field in oneof
  393. // is set, false otherwise.
  394. bool HasOneof(const Message& message,
  395. const OneofDescriptor* oneof_descriptor) const;
  396. void ClearOneof(Message* message,
  397. const OneofDescriptor* oneof_descriptor) const;
  398. // Returns the field descriptor if the oneof is set. nullptr otherwise.
  399. const FieldDescriptor* GetOneofFieldDescriptor(
  400. const Message& message, const OneofDescriptor* oneof_descriptor) const;
  401. // Removes the last element of a repeated field.
  402. // We don't provide a way to remove any element other than the last
  403. // because it invites inefficient use, such as O(n^2) filtering loops
  404. // that should have been O(n). If you want to remove an element other
  405. // than the last, the best way to do it is to re-arrange the elements
  406. // (using Swap()) so that the one you want removed is at the end, then
  407. // call RemoveLast().
  408. void RemoveLast(Message* message, const FieldDescriptor* field) const;
  409. // Removes the last element of a repeated message field, and returns the
  410. // pointer to the caller. Caller takes ownership of the returned pointer.
  411. Message* ReleaseLast(Message* message, const FieldDescriptor* field) const;
  412. // Swap the complete contents of two messages.
  413. void Swap(Message* message1, Message* message2) const;
  414. // Swap fields listed in fields vector of two messages.
  415. void SwapFields(Message* message1, Message* message2,
  416. const std::vector<const FieldDescriptor*>& fields) const;
  417. // Swap two elements of a repeated field.
  418. void SwapElements(Message* message, const FieldDescriptor* field, int index1,
  419. int index2) const;
  420. // List all fields of the message which are currently set, except for unknown
  421. // fields, but including extension known to the parser (i.e. compiled in).
  422. // Singular fields will only be listed if HasField(field) would return true
  423. // and repeated fields will only be listed if FieldSize(field) would return
  424. // non-zero. Fields (both normal fields and extension fields) will be listed
  425. // ordered by field number.
  426. // Use Reflection::GetUnknownFields() or message.unknown_fields() to also get
  427. // access to fields/extensions unknown to the parser.
  428. void ListFields(const Message& message,
  429. std::vector<const FieldDescriptor*>* output) const;
  430. // Singular field getters ------------------------------------------
  431. // These get the value of a non-repeated field. They return the default
  432. // value for fields that aren't set.
  433. int32 GetInt32(const Message& message, const FieldDescriptor* field) const;
  434. int64 GetInt64(const Message& message, const FieldDescriptor* field) const;
  435. uint32 GetUInt32(const Message& message, const FieldDescriptor* field) const;
  436. uint64 GetUInt64(const Message& message, const FieldDescriptor* field) const;
  437. float GetFloat(const Message& message, const FieldDescriptor* field) const;
  438. double GetDouble(const Message& message, const FieldDescriptor* field) const;
  439. bool GetBool(const Message& message, const FieldDescriptor* field) const;
  440. std::string GetString(const Message& message,
  441. const FieldDescriptor* field) const;
  442. const EnumValueDescriptor* GetEnum(const Message& message,
  443. const FieldDescriptor* field) const;
  444. // GetEnumValue() returns an enum field's value as an integer rather than
  445. // an EnumValueDescriptor*. If the integer value does not correspond to a
  446. // known value descriptor, a new value descriptor is created. (Such a value
  447. // will only be present when the new unknown-enum-value semantics are enabled
  448. // for a message.)
  449. int GetEnumValue(const Message& message, const FieldDescriptor* field) const;
  450. // See MutableMessage() for the meaning of the "factory" parameter.
  451. const Message& GetMessage(const Message& message,
  452. const FieldDescriptor* field,
  453. MessageFactory* factory = nullptr) const;
  454. // Get a string value without copying, if possible.
  455. //
  456. // GetString() necessarily returns a copy of the string. This can be
  457. // inefficient when the std::string is already stored in a std::string object
  458. // in the underlying message. GetStringReference() will return a reference to
  459. // the underlying std::string in this case. Otherwise, it will copy the
  460. // string into *scratch and return that.
  461. //
  462. // Note: It is perfectly reasonable and useful to write code like:
  463. // str = reflection->GetStringReference(message, field, &str);
  464. // This line would ensure that only one copy of the string is made
  465. // regardless of the field's underlying representation. When initializing
  466. // a newly-constructed string, though, it's just as fast and more
  467. // readable to use code like:
  468. // std::string str = reflection->GetString(message, field);
  469. const std::string& GetStringReference(const Message& message,
  470. const FieldDescriptor* field,
  471. std::string* scratch) const;
  472. // Singular field mutators -----------------------------------------
  473. // These mutate the value of a non-repeated field.
  474. void SetInt32(Message* message, const FieldDescriptor* field,
  475. int32 value) const;
  476. void SetInt64(Message* message, const FieldDescriptor* field,
  477. int64 value) const;
  478. void SetUInt32(Message* message, const FieldDescriptor* field,
  479. uint32 value) const;
  480. void SetUInt64(Message* message, const FieldDescriptor* field,
  481. uint64 value) const;
  482. void SetFloat(Message* message, const FieldDescriptor* field,
  483. float value) const;
  484. void SetDouble(Message* message, const FieldDescriptor* field,
  485. double value) const;
  486. void SetBool(Message* message, const FieldDescriptor* field,
  487. bool value) const;
  488. void SetString(Message* message, const FieldDescriptor* field,
  489. std::string value) const;
  490. void SetEnum(Message* message, const FieldDescriptor* field,
  491. const EnumValueDescriptor* value) const;
  492. // Set an enum field's value with an integer rather than EnumValueDescriptor.
  493. // For proto3 this is just setting the enum field to the value specified, for
  494. // proto2 it's more complicated. If value is a known enum value the field is
  495. // set as usual. If the value is unknown then it is added to the unknown field
  496. // set. Note this matches the behavior of parsing unknown enum values.
  497. // If multiple calls with unknown values happen than they are all added to the
  498. // unknown field set in order of the calls.
  499. void SetEnumValue(Message* message, const FieldDescriptor* field,
  500. int value) const;
  501. // Get a mutable pointer to a field with a message type. If a MessageFactory
  502. // is provided, it will be used to construct instances of the sub-message;
  503. // otherwise, the default factory is used. If the field is an extension that
  504. // does not live in the same pool as the containing message's descriptor (e.g.
  505. // it lives in an overlay pool), then a MessageFactory must be provided.
  506. // If you have no idea what that meant, then you probably don't need to worry
  507. // about it (don't provide a MessageFactory). WARNING: If the
  508. // FieldDescriptor is for a compiled-in extension, then
  509. // factory->GetPrototype(field->message_type()) MUST return an instance of
  510. // the compiled-in class for this type, NOT DynamicMessage.
  511. Message* MutableMessage(Message* message, const FieldDescriptor* field,
  512. MessageFactory* factory = nullptr) const;
  513. // Replaces the message specified by 'field' with the already-allocated object
  514. // sub_message, passing ownership to the message. If the field contained a
  515. // message, that message is deleted. If sub_message is nullptr, the field is
  516. // cleared.
  517. void SetAllocatedMessage(Message* message, Message* sub_message,
  518. const FieldDescriptor* field) const;
  519. // Releases the message specified by 'field' and returns the pointer,
  520. // ReleaseMessage() will return the message the message object if it exists.
  521. // Otherwise, it may or may not return nullptr. In any case, if the return
  522. // value is non-null, the caller takes ownership of the pointer.
  523. // If the field existed (HasField() is true), then the returned pointer will
  524. // be the same as the pointer returned by MutableMessage().
  525. // This function has the same effect as ClearField().
  526. Message* ReleaseMessage(Message* message, const FieldDescriptor* field,
  527. MessageFactory* factory = nullptr) const;
  528. // Repeated field getters ------------------------------------------
  529. // These get the value of one element of a repeated field.
  530. int32 GetRepeatedInt32(const Message& message, const FieldDescriptor* field,
  531. int index) const;
  532. int64 GetRepeatedInt64(const Message& message, const FieldDescriptor* field,
  533. int index) const;
  534. uint32 GetRepeatedUInt32(const Message& message, const FieldDescriptor* field,
  535. int index) const;
  536. uint64 GetRepeatedUInt64(const Message& message, const FieldDescriptor* field,
  537. int index) const;
  538. float GetRepeatedFloat(const Message& message, const FieldDescriptor* field,
  539. int index) const;
  540. double GetRepeatedDouble(const Message& message, const FieldDescriptor* field,
  541. int index) const;
  542. bool GetRepeatedBool(const Message& message, const FieldDescriptor* field,
  543. int index) const;
  544. std::string GetRepeatedString(const Message& message,
  545. const FieldDescriptor* field, int index) const;
  546. const EnumValueDescriptor* GetRepeatedEnum(const Message& message,
  547. const FieldDescriptor* field,
  548. int index) const;
  549. // GetRepeatedEnumValue() returns an enum field's value as an integer rather
  550. // than an EnumValueDescriptor*. If the integer value does not correspond to a
  551. // known value descriptor, a new value descriptor is created. (Such a value
  552. // will only be present when the new unknown-enum-value semantics are enabled
  553. // for a message.)
  554. int GetRepeatedEnumValue(const Message& message, const FieldDescriptor* field,
  555. int index) const;
  556. const Message& GetRepeatedMessage(const Message& message,
  557. const FieldDescriptor* field,
  558. int index) const;
  559. // See GetStringReference(), above.
  560. const std::string& GetRepeatedStringReference(const Message& message,
  561. const FieldDescriptor* field,
  562. int index,
  563. std::string* scratch) const;
  564. // Repeated field mutators -----------------------------------------
  565. // These mutate the value of one element of a repeated field.
  566. void SetRepeatedInt32(Message* message, const FieldDescriptor* field,
  567. int index, int32 value) const;
  568. void SetRepeatedInt64(Message* message, const FieldDescriptor* field,
  569. int index, int64 value) const;
  570. void SetRepeatedUInt32(Message* message, const FieldDescriptor* field,
  571. int index, uint32 value) const;
  572. void SetRepeatedUInt64(Message* message, const FieldDescriptor* field,
  573. int index, uint64 value) const;
  574. void SetRepeatedFloat(Message* message, const FieldDescriptor* field,
  575. int index, float value) const;
  576. void SetRepeatedDouble(Message* message, const FieldDescriptor* field,
  577. int index, double value) const;
  578. void SetRepeatedBool(Message* message, const FieldDescriptor* field,
  579. int index, bool value) const;
  580. void SetRepeatedString(Message* message, const FieldDescriptor* field,
  581. int index, std::string value) const;
  582. void SetRepeatedEnum(Message* message, const FieldDescriptor* field,
  583. int index, const EnumValueDescriptor* value) const;
  584. // Set an enum field's value with an integer rather than EnumValueDescriptor.
  585. // For proto3 this is just setting the enum field to the value specified, for
  586. // proto2 it's more complicated. If value is a known enum value the field is
  587. // set as usual. If the value is unknown then it is added to the unknown field
  588. // set. Note this matches the behavior of parsing unknown enum values.
  589. // If multiple calls with unknown values happen than they are all added to the
  590. // unknown field set in order of the calls.
  591. void SetRepeatedEnumValue(Message* message, const FieldDescriptor* field,
  592. int index, int value) const;
  593. // Get a mutable pointer to an element of a repeated field with a message
  594. // type.
  595. Message* MutableRepeatedMessage(Message* message,
  596. const FieldDescriptor* field,
  597. int index) const;
  598. // Repeated field adders -------------------------------------------
  599. // These add an element to a repeated field.
  600. void AddInt32(Message* message, const FieldDescriptor* field,
  601. int32 value) const;
  602. void AddInt64(Message* message, const FieldDescriptor* field,
  603. int64 value) const;
  604. void AddUInt32(Message* message, const FieldDescriptor* field,
  605. uint32 value) const;
  606. void AddUInt64(Message* message, const FieldDescriptor* field,
  607. uint64 value) const;
  608. void AddFloat(Message* message, const FieldDescriptor* field,
  609. float value) const;
  610. void AddDouble(Message* message, const FieldDescriptor* field,
  611. double value) const;
  612. void AddBool(Message* message, const FieldDescriptor* field,
  613. bool value) const;
  614. void AddString(Message* message, const FieldDescriptor* field,
  615. std::string value) const;
  616. void AddEnum(Message* message, const FieldDescriptor* field,
  617. const EnumValueDescriptor* value) const;
  618. // Add an integer value to a repeated enum field rather than
  619. // EnumValueDescriptor. For proto3 this is just setting the enum field to the
  620. // value specified, for proto2 it's more complicated. If value is a known enum
  621. // value the field is set as usual. If the value is unknown then it is added
  622. // to the unknown field set. Note this matches the behavior of parsing unknown
  623. // enum values. If multiple calls with unknown values happen than they are all
  624. // added to the unknown field set in order of the calls.
  625. void AddEnumValue(Message* message, const FieldDescriptor* field,
  626. int value) const;
  627. // See MutableMessage() for comments on the "factory" parameter.
  628. Message* AddMessage(Message* message, const FieldDescriptor* field,
  629. MessageFactory* factory = nullptr) const;
  630. // Appends an already-allocated object 'new_entry' to the repeated field
  631. // specified by 'field' passing ownership to the message.
  632. void AddAllocatedMessage(Message* message, const FieldDescriptor* field,
  633. Message* new_entry) const;
  634. // Get a RepeatedFieldRef object that can be used to read the underlying
  635. // repeated field. The type parameter T must be set according to the
  636. // field's cpp type. The following table shows the mapping from cpp type
  637. // to acceptable T.
  638. //
  639. // field->cpp_type() T
  640. // CPPTYPE_INT32 int32
  641. // CPPTYPE_UINT32 uint32
  642. // CPPTYPE_INT64 int64
  643. // CPPTYPE_UINT64 uint64
  644. // CPPTYPE_DOUBLE double
  645. // CPPTYPE_FLOAT float
  646. // CPPTYPE_BOOL bool
  647. // CPPTYPE_ENUM generated enum type or int32
  648. // CPPTYPE_STRING std::string
  649. // CPPTYPE_MESSAGE generated message type or google::protobuf::Message
  650. //
  651. // A RepeatedFieldRef object can be copied and the resulted object will point
  652. // to the same repeated field in the same message. The object can be used as
  653. // long as the message is not destroyed.
  654. //
  655. // Note that to use this method users need to include the header file
  656. // "reflection.h" (which defines the RepeatedFieldRef class templates).
  657. template <typename T>
  658. RepeatedFieldRef<T> GetRepeatedFieldRef(const Message& message,
  659. const FieldDescriptor* field) const;
  660. // Like GetRepeatedFieldRef() but return an object that can also be used
  661. // manipulate the underlying repeated field.
  662. template <typename T>
  663. MutableRepeatedFieldRef<T> GetMutableRepeatedFieldRef(
  664. Message* message, const FieldDescriptor* field) const;
  665. // DEPRECATED. Please use Get(Mutable)RepeatedFieldRef() for repeated field
  666. // access. The following repeated field accesors will be removed in the
  667. // future.
  668. //
  669. // Repeated field accessors -------------------------------------------------
  670. // The methods above, e.g. GetRepeatedInt32(msg, fd, index), provide singular
  671. // access to the data in a RepeatedField. The methods below provide aggregate
  672. // access by exposing the RepeatedField object itself with the Message.
  673. // Applying these templates to inappropriate types will lead to an undefined
  674. // reference at link time (e.g. GetRepeatedField<***double>), or possibly a
  675. // template matching error at compile time (e.g. GetRepeatedPtrField<File>).
  676. //
  677. // Usage example: my_doubs = refl->GetRepeatedField<double>(msg, fd);
  678. // DEPRECATED. Please use GetRepeatedFieldRef().
  679. //
  680. // for T = Cord and all protobuf scalar types except enums.
  681. template <typename T>
  682. PROTOBUF_DEPRECATED_MSG("Please use GetRepeatedFieldRef() instead")
  683. const RepeatedField<T>& GetRepeatedField(const Message& msg,
  684. const FieldDescriptor* d) const {
  685. return GetRepeatedFieldInternal<T>(msg, d);
  686. }
  687. // DEPRECATED. Please use GetMutableRepeatedFieldRef().
  688. //
  689. // for T = Cord and all protobuf scalar types except enums.
  690. template <typename T>
  691. PROTOBUF_DEPRECATED_MSG("Please use GetMutableRepeatedFieldRef() instead")
  692. RepeatedField<T>* MutableRepeatedField(Message* msg,
  693. const FieldDescriptor* d) const {
  694. return MutableRepeatedFieldInternal<T>(msg, d);
  695. }
  696. // DEPRECATED. Please use GetRepeatedFieldRef().
  697. //
  698. // for T = std::string, google::protobuf::internal::StringPieceField
  699. // google::protobuf::Message & descendants.
  700. template <typename T>
  701. PROTOBUF_DEPRECATED_MSG("Please use GetRepeatedFieldRef() instead")
  702. const RepeatedPtrField<T>& GetRepeatedPtrField(
  703. const Message& msg, const FieldDescriptor* d) const {
  704. return GetRepeatedPtrFieldInternal<T>(msg, d);
  705. }
  706. // DEPRECATED. Please use GetMutableRepeatedFieldRef().
  707. //
  708. // for T = std::string, google::protobuf::internal::StringPieceField
  709. // google::protobuf::Message & descendants.
  710. template <typename T>
  711. PROTOBUF_DEPRECATED_MSG("Please use GetMutableRepeatedFieldRef() instead")
  712. RepeatedPtrField<T>* MutableRepeatedPtrField(Message* msg,
  713. const FieldDescriptor* d) const {
  714. return MutableRepeatedPtrFieldInternal<T>(msg, d);
  715. }
  716. // Extensions ----------------------------------------------------------------
  717. // Try to find an extension of this message type by fully-qualified field
  718. // name. Returns nullptr if no extension is known for this name or number.
  719. const FieldDescriptor* FindKnownExtensionByName(
  720. const std::string& name) const;
  721. // Try to find an extension of this message type by field number.
  722. // Returns nullptr if no extension is known for this name or number.
  723. const FieldDescriptor* FindKnownExtensionByNumber(int number) const;
  724. // Feature Flags -------------------------------------------------------------
  725. // Does this message support storing arbitrary integer values in enum fields?
  726. // If |true|, GetEnumValue/SetEnumValue and associated repeated-field versions
  727. // take arbitrary integer values, and the legacy GetEnum() getter will
  728. // dynamically create an EnumValueDescriptor for any integer value without
  729. // one. If |false|, setting an unknown enum value via the integer-based
  730. // setters results in undefined behavior (in practice, GOOGLE_DCHECK-fails).
  731. //
  732. // Generic code that uses reflection to handle messages with enum fields
  733. // should check this flag before using the integer-based setter, and either
  734. // downgrade to a compatible value or use the UnknownFieldSet if not. For
  735. // example:
  736. //
  737. // int new_value = GetValueFromApplicationLogic();
  738. // if (reflection->SupportsUnknownEnumValues()) {
  739. // reflection->SetEnumValue(message, field, new_value);
  740. // } else {
  741. // if (field_descriptor->enum_type()->
  742. // FindValueByNumber(new_value) != nullptr) {
  743. // reflection->SetEnumValue(message, field, new_value);
  744. // } else if (emit_unknown_enum_values) {
  745. // reflection->MutableUnknownFields(message)->AddVarint(
  746. // field->number(), new_value);
  747. // } else {
  748. // // convert value to a compatible/default value.
  749. // new_value = CompatibleDowngrade(new_value);
  750. // reflection->SetEnumValue(message, field, new_value);
  751. // }
  752. // }
  753. bool SupportsUnknownEnumValues() const;
  754. // Returns the MessageFactory associated with this message. This can be
  755. // useful for determining if a message is a generated message or not, for
  756. // example:
  757. // if (message->GetReflection()->GetMessageFactory() ==
  758. // google::protobuf::MessageFactory::generated_factory()) {
  759. // // This is a generated message.
  760. // }
  761. // It can also be used to create more messages of this type, though
  762. // Message::New() is an easier way to accomplish this.
  763. MessageFactory* GetMessageFactory() const;
  764. private:
  765. template <typename T>
  766. const RepeatedField<T>& GetRepeatedFieldInternal(
  767. const Message& message, const FieldDescriptor* field) const;
  768. template <typename T>
  769. RepeatedField<T>* MutableRepeatedFieldInternal(
  770. Message* message, const FieldDescriptor* field) const;
  771. template <typename T>
  772. const RepeatedPtrField<T>& GetRepeatedPtrFieldInternal(
  773. const Message& message, const FieldDescriptor* field) const;
  774. template <typename T>
  775. RepeatedPtrField<T>* MutableRepeatedPtrFieldInternal(
  776. Message* message, const FieldDescriptor* field) const;
  777. // Obtain a pointer to a Repeated Field Structure and do some type checking:
  778. // on field->cpp_type(),
  779. // on field->field_option().ctype() (if ctype >= 0)
  780. // of field->message_type() (if message_type != nullptr).
  781. // We use 2 routine rather than 4 (const vs mutable) x (scalar vs pointer).
  782. void* MutableRawRepeatedField(Message* message, const FieldDescriptor* field,
  783. FieldDescriptor::CppType, int ctype,
  784. const Descriptor* message_type) const;
  785. const void* GetRawRepeatedField(const Message& message,
  786. const FieldDescriptor* field,
  787. FieldDescriptor::CppType cpptype, int ctype,
  788. const Descriptor* message_type) const;
  789. // The following methods are used to implement (Mutable)RepeatedFieldRef.
  790. // A Ref object will store a raw pointer to the repeated field data (obtained
  791. // from RepeatedFieldData()) and a pointer to a Accessor (obtained from
  792. // RepeatedFieldAccessor) which will be used to access the raw data.
  793. // Returns a raw pointer to the repeated field
  794. //
  795. // "cpp_type" and "message_type" are deduced from the type parameter T passed
  796. // to Get(Mutable)RepeatedFieldRef. If T is a generated message type,
  797. // "message_type" should be set to its descriptor. Otherwise "message_type"
  798. // should be set to nullptr. Implementations of this method should check
  799. // whether "cpp_type"/"message_type" is consistent with the actual type of the
  800. // field. We use 1 routine rather than 2 (const vs mutable) because it is
  801. // protected and it doesn't change the message.
  802. void* RepeatedFieldData(Message* message, const FieldDescriptor* field,
  803. FieldDescriptor::CppType cpp_type,
  804. const Descriptor* message_type) const;
  805. // The returned pointer should point to a singleton instance which implements
  806. // the RepeatedFieldAccessor interface.
  807. const internal::RepeatedFieldAccessor* RepeatedFieldAccessor(
  808. const FieldDescriptor* field) const;
  809. // Lists all fields of the message which are currently set, except for unknown
  810. // fields and stripped fields. See ListFields for details.
  811. void ListFieldsOmitStripped(
  812. const Message& message,
  813. std::vector<const FieldDescriptor*>* output) const;
  814. bool IsMessageStripped(const Descriptor* descriptor) const {
  815. return schema_.IsMessageStripped(descriptor);
  816. }
  817. friend class TextFormat;
  818. void ListFieldsMayFailOnStripped(
  819. const Message& message, bool should_fail,
  820. std::vector<const FieldDescriptor*>* output) const;
  821. const Descriptor* const descriptor_;
  822. const internal::ReflectionSchema schema_;
  823. const DescriptorPool* const descriptor_pool_;
  824. MessageFactory* const message_factory_;
  825. // Last non weak field index. This is an optimization when most weak fields
  826. // are at the end of the containing message. If a message proto doesn't
  827. // contain weak fields, then this field equals descriptor_->field_count().
  828. int last_non_weak_field_index_;
  829. template <typename T, typename Enable>
  830. friend class RepeatedFieldRef;
  831. template <typename T, typename Enable>
  832. friend class MutableRepeatedFieldRef;
  833. friend class ::PROTOBUF_NAMESPACE_ID::MessageLayoutInspector;
  834. friend class ::PROTOBUF_NAMESPACE_ID::AssignDescriptorsHelper;
  835. friend class DynamicMessageFactory;
  836. friend class python::MapReflectionFriend;
  837. #define GOOGLE_PROTOBUF_HAS_CEL_MAP_REFLECTION_FRIEND
  838. friend class expr::CelMapReflectionFriend;
  839. friend class internal::MapFieldReflectionTest;
  840. friend class internal::MapKeySorter;
  841. friend class internal::WireFormat;
  842. friend class internal::ReflectionOps;
  843. // Needed for implementing text format for map.
  844. friend class internal::MapFieldPrinterHelper;
  845. Reflection(const Descriptor* descriptor,
  846. const internal::ReflectionSchema& schema,
  847. const DescriptorPool* pool, MessageFactory* factory);
  848. // Special version for specialized implementations of string. We can't
  849. // call MutableRawRepeatedField directly here because we don't have access to
  850. // FieldOptions::* which are defined in descriptor.pb.h. Including that
  851. // file here is not possible because it would cause a circular include cycle.
  852. // We use 1 routine rather than 2 (const vs mutable) because it is private
  853. // and mutable a repeated string field doesn't change the message.
  854. void* MutableRawRepeatedString(Message* message, const FieldDescriptor* field,
  855. bool is_string) const;
  856. friend class MapReflectionTester;
  857. // Returns true if key is in map. Returns false if key is not in map field.
  858. bool ContainsMapKey(const Message& message, const FieldDescriptor* field,
  859. const MapKey& key) const;
  860. // If key is in map field: Saves the value pointer to val and returns
  861. // false. If key in not in map field: Insert the key into map, saves
  862. // value pointer to val and returns true.
  863. bool InsertOrLookupMapValue(Message* message, const FieldDescriptor* field,
  864. const MapKey& key, MapValueRef* val) const;
  865. // Delete and returns true if key is in the map field. Returns false
  866. // otherwise.
  867. bool DeleteMapValue(Message* message, const FieldDescriptor* field,
  868. const MapKey& key) const;
  869. // Returns a MapIterator referring to the first element in the map field.
  870. // If the map field is empty, this function returns the same as
  871. // reflection::MapEnd. Mutation to the field may invalidate the iterator.
  872. MapIterator MapBegin(Message* message, const FieldDescriptor* field) const;
  873. // Returns a MapIterator referring to the theoretical element that would
  874. // follow the last element in the map field. It does not point to any
  875. // real element. Mutation to the field may invalidate the iterator.
  876. MapIterator MapEnd(Message* message, const FieldDescriptor* field) const;
  877. // Get the number of <key, value> pair of a map field. The result may be
  878. // different from FieldSize which can have duplicate keys.
  879. int MapSize(const Message& message, const FieldDescriptor* field) const;
  880. // Help method for MapIterator.
  881. friend class MapIterator;
  882. friend class WireFormatForMapFieldTest;
  883. internal::MapFieldBase* MutableMapData(Message* message,
  884. const FieldDescriptor* field) const;
  885. const internal::MapFieldBase* GetMapData(const Message& message,
  886. const FieldDescriptor* field) const;
  887. template <class T>
  888. const T& GetRawNonOneof(const Message& message,
  889. const FieldDescriptor* field) const;
  890. template <class T>
  891. T* MutableRawNonOneof(Message* message, const FieldDescriptor* field) const;
  892. template <typename Type>
  893. const Type& GetRaw(const Message& message,
  894. const FieldDescriptor* field) const;
  895. template <typename Type>
  896. inline Type* MutableRaw(Message* message, const FieldDescriptor* field) const;
  897. template <typename Type>
  898. const Type& DefaultRaw(const FieldDescriptor* field) const;
  899. inline const uint32* GetHasBits(const Message& message) const;
  900. inline uint32* MutableHasBits(Message* message) const;
  901. inline uint32 GetOneofCase(const Message& message,
  902. const OneofDescriptor* oneof_descriptor) const;
  903. inline uint32* MutableOneofCase(
  904. Message* message, const OneofDescriptor* oneof_descriptor) const;
  905. inline bool HasExtensionSet(const Message& message) const {
  906. return schema_.HasExtensionSet();
  907. }
  908. const internal::ExtensionSet& GetExtensionSet(const Message& message) const;
  909. internal::ExtensionSet* MutableExtensionSet(Message* message) const;
  910. inline Arena* GetArena(Message* message) const;
  911. inline const internal::InternalMetadata& GetInternalMetadata(
  912. const Message& message) const;
  913. internal::InternalMetadata* MutableInternalMetadata(Message* message) const;
  914. inline bool IsInlined(const FieldDescriptor* field) const;
  915. inline bool HasBit(const Message& message,
  916. const FieldDescriptor* field) const;
  917. inline void SetBit(Message* message, const FieldDescriptor* field) const;
  918. inline void ClearBit(Message* message, const FieldDescriptor* field) const;
  919. inline void SwapBit(Message* message1, Message* message2,
  920. const FieldDescriptor* field) const;
  921. // This function only swaps the field. Should swap corresponding has_bit
  922. // before or after using this function.
  923. void SwapField(Message* message1, Message* message2,
  924. const FieldDescriptor* field) const;
  925. void SwapOneofField(Message* message1, Message* message2,
  926. const OneofDescriptor* oneof_descriptor) const;
  927. inline bool HasOneofField(const Message& message,
  928. const FieldDescriptor* field) const;
  929. inline void SetOneofCase(Message* message,
  930. const FieldDescriptor* field) const;
  931. inline void ClearOneofField(Message* message,
  932. const FieldDescriptor* field) const;
  933. template <typename Type>
  934. inline const Type& GetField(const Message& message,
  935. const FieldDescriptor* field) const;
  936. template <typename Type>
  937. inline void SetField(Message* message, const FieldDescriptor* field,
  938. const Type& value) const;
  939. template <typename Type>
  940. inline Type* MutableField(Message* message,
  941. const FieldDescriptor* field) const;
  942. template <typename Type>
  943. inline const Type& GetRepeatedField(const Message& message,
  944. const FieldDescriptor* field,
  945. int index) const;
  946. template <typename Type>
  947. inline const Type& GetRepeatedPtrField(const Message& message,
  948. const FieldDescriptor* field,
  949. int index) const;
  950. template <typename Type>
  951. inline void SetRepeatedField(Message* message, const FieldDescriptor* field,
  952. int index, Type value) const;
  953. template <typename Type>
  954. inline Type* MutableRepeatedField(Message* message,
  955. const FieldDescriptor* field,
  956. int index) const;
  957. template <typename Type>
  958. inline void AddField(Message* message, const FieldDescriptor* field,
  959. const Type& value) const;
  960. template <typename Type>
  961. inline Type* AddField(Message* message, const FieldDescriptor* field) const;
  962. int GetExtensionNumberOrDie(const Descriptor* type) const;
  963. // Internal versions of EnumValue API perform no checking. Called after checks
  964. // by public methods.
  965. void SetEnumValueInternal(Message* message, const FieldDescriptor* field,
  966. int value) const;
  967. void SetRepeatedEnumValueInternal(Message* message,
  968. const FieldDescriptor* field, int index,
  969. int value) const;
  970. void AddEnumValueInternal(Message* message, const FieldDescriptor* field,
  971. int value) const;
  972. Message* UnsafeArenaReleaseMessage(Message* message,
  973. const FieldDescriptor* field,
  974. MessageFactory* factory = nullptr) const;
  975. void UnsafeArenaSetAllocatedMessage(Message* message, Message* sub_message,
  976. const FieldDescriptor* field) const;
  977. friend inline // inline so nobody can call this function.
  978. void
  979. RegisterAllTypesInternal(const Metadata* file_level_metadata, int size);
  980. friend inline const char* ParseLenDelim(int field_number,
  981. const FieldDescriptor* field,
  982. Message* msg,
  983. const Reflection* reflection,
  984. const char* ptr,
  985. internal::ParseContext* ctx);
  986. friend inline const char* ParsePackedField(const FieldDescriptor* field,
  987. Message* msg,
  988. const Reflection* reflection,
  989. const char* ptr,
  990. internal::ParseContext* ctx);
  991. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Reflection);
  992. };
  993. // Abstract interface for a factory for message objects.
  994. class PROTOBUF_EXPORT MessageFactory {
  995. public:
  996. inline MessageFactory() {}
  997. virtual ~MessageFactory();
  998. // Given a Descriptor, gets or constructs the default (prototype) Message
  999. // of that type. You can then call that message's New() method to construct
  1000. // a mutable message of that type.
  1001. //
  1002. // Calling this method twice with the same Descriptor returns the same
  1003. // object. The returned object remains property of the factory. Also, any
  1004. // objects created by calling the prototype's New() method share some data
  1005. // with the prototype, so these must be destroyed before the MessageFactory
  1006. // is destroyed.
  1007. //
  1008. // The given descriptor must outlive the returned message, and hence must
  1009. // outlive the MessageFactory.
  1010. //
  1011. // Some implementations do not support all types. GetPrototype() will
  1012. // return nullptr if the descriptor passed in is not supported.
  1013. //
  1014. // This method may or may not be thread-safe depending on the implementation.
  1015. // Each implementation should document its own degree thread-safety.
  1016. virtual const Message* GetPrototype(const Descriptor* type) = 0;
  1017. // Gets a MessageFactory which supports all generated, compiled-in messages.
  1018. // In other words, for any compiled-in type FooMessage, the following is true:
  1019. // MessageFactory::generated_factory()->GetPrototype(
  1020. // FooMessage::descriptor()) == FooMessage::default_instance()
  1021. // This factory supports all types which are found in
  1022. // DescriptorPool::generated_pool(). If given a descriptor from any other
  1023. // pool, GetPrototype() will return nullptr. (You can also check if a
  1024. // descriptor is for a generated message by checking if
  1025. // descriptor->file()->pool() == DescriptorPool::generated_pool().)
  1026. //
  1027. // This factory is 100% thread-safe; calling GetPrototype() does not modify
  1028. // any shared data.
  1029. //
  1030. // This factory is a singleton. The caller must not delete the object.
  1031. static MessageFactory* generated_factory();
  1032. // For internal use only: Registers a .proto file at static initialization
  1033. // time, to be placed in generated_factory. The first time GetPrototype()
  1034. // is called with a descriptor from this file, |register_messages| will be
  1035. // called, with the file name as the parameter. It must call
  1036. // InternalRegisterGeneratedMessage() (below) to register each message type
  1037. // in the file. This strange mechanism is necessary because descriptors are
  1038. // built lazily, so we can't register types by their descriptor until we
  1039. // know that the descriptor exists. |filename| must be a permanent string.
  1040. static void InternalRegisterGeneratedFile(
  1041. const google::protobuf::internal::DescriptorTable* table);
  1042. // For internal use only: Registers a message type. Called only by the
  1043. // functions which are registered with InternalRegisterGeneratedFile(),
  1044. // above.
  1045. static void InternalRegisterGeneratedMessage(const Descriptor* descriptor,
  1046. const Message* prototype);
  1047. private:
  1048. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFactory);
  1049. };
  1050. #define DECLARE_GET_REPEATED_FIELD(TYPE) \
  1051. template <> \
  1052. PROTOBUF_EXPORT const RepeatedField<TYPE>& \
  1053. Reflection::GetRepeatedFieldInternal<TYPE>( \
  1054. const Message& message, const FieldDescriptor* field) const; \
  1055. \
  1056. template <> \
  1057. PROTOBUF_EXPORT RepeatedField<TYPE>* \
  1058. Reflection::MutableRepeatedFieldInternal<TYPE>( \
  1059. Message * message, const FieldDescriptor* field) const;
  1060. DECLARE_GET_REPEATED_FIELD(int32)
  1061. DECLARE_GET_REPEATED_FIELD(int64)
  1062. DECLARE_GET_REPEATED_FIELD(uint32)
  1063. DECLARE_GET_REPEATED_FIELD(uint64)
  1064. DECLARE_GET_REPEATED_FIELD(float)
  1065. DECLARE_GET_REPEATED_FIELD(double)
  1066. DECLARE_GET_REPEATED_FIELD(bool)
  1067. #undef DECLARE_GET_REPEATED_FIELD
  1068. // Tries to downcast this message to a generated message type. Returns nullptr
  1069. // if this class is not an instance of T. This works even if RTTI is disabled.
  1070. //
  1071. // This also has the effect of creating a strong reference to T that will
  1072. // prevent the linker from stripping it out at link time. This can be important
  1073. // if you are using a DynamicMessageFactory that delegates to the generated
  1074. // factory.
  1075. template <typename T>
  1076. const T* DynamicCastToGenerated(const Message* from) {
  1077. // Compile-time assert that T is a generated type that has a
  1078. // default_instance() accessor, but avoid actually calling it.
  1079. const T& (*get_default_instance)() = &T::default_instance;
  1080. (void)get_default_instance;
  1081. // Compile-time assert that T is a subclass of google::protobuf::Message.
  1082. const Message* unused = static_cast<T*>(nullptr);
  1083. (void)unused;
  1084. #if PROTOBUF_RTTI
  1085. return dynamic_cast<const T*>(from);
  1086. #else
  1087. bool ok = T::default_instance().GetReflection() == from->GetReflection();
  1088. return ok ? down_cast<const T*>(from) : nullptr;
  1089. #endif
  1090. }
  1091. template <typename T>
  1092. T* DynamicCastToGenerated(Message* from) {
  1093. const Message* message_const = from;
  1094. return const_cast<T*>(DynamicCastToGenerated<T>(message_const));
  1095. }
  1096. // Call this function to ensure that this message's reflection is linked into
  1097. // the binary:
  1098. //
  1099. // google::protobuf::LinkMessageReflection<FooMessage>();
  1100. //
  1101. // This will ensure that the following lookup will succeed:
  1102. //
  1103. // DescriptorPool::generated_pool()->FindMessageTypeByName("FooMessage");
  1104. //
  1105. // As a side-effect, it will also guarantee that anything else from the same
  1106. // .proto file will also be available for lookup in the generated pool.
  1107. //
  1108. // This function does not actually register the message, so it does not need
  1109. // to be called before the lookup. However it does need to occur in a function
  1110. // that cannot be stripped from the binary (ie. it must be reachable from main).
  1111. //
  1112. // Best practice is to call this function as close as possible to where the
  1113. // reflection is actually needed. This function is very cheap to call, so you
  1114. // should not need to worry about its runtime overhead except in the tightest
  1115. // of loops (on x86-64 it compiles into two "mov" instructions).
  1116. template <typename T>
  1117. void LinkMessageReflection() {
  1118. internal::StrongReference(T::default_instance);
  1119. }
  1120. // =============================================================================
  1121. // Implementation details for {Get,Mutable}RawRepeatedPtrField. We provide
  1122. // specializations for <std::string>, <StringPieceField> and <Message> and
  1123. // handle everything else with the default template which will match any type
  1124. // having a method with signature "static const google::protobuf::Descriptor*
  1125. // descriptor()". Such a type presumably is a descendant of google::protobuf::Message.
  1126. template <>
  1127. inline const RepeatedPtrField<std::string>&
  1128. Reflection::GetRepeatedPtrFieldInternal<std::string>(
  1129. const Message& message, const FieldDescriptor* field) const {
  1130. return *static_cast<RepeatedPtrField<std::string>*>(
  1131. MutableRawRepeatedString(const_cast<Message*>(&message), field, true));
  1132. }
  1133. template <>
  1134. inline RepeatedPtrField<std::string>*
  1135. Reflection::MutableRepeatedPtrFieldInternal<std::string>(
  1136. Message* message, const FieldDescriptor* field) const {
  1137. return static_cast<RepeatedPtrField<std::string>*>(
  1138. MutableRawRepeatedString(message, field, true));
  1139. }
  1140. // -----
  1141. template <>
  1142. inline const RepeatedPtrField<Message>& Reflection::GetRepeatedPtrFieldInternal(
  1143. const Message& message, const FieldDescriptor* field) const {
  1144. return *static_cast<const RepeatedPtrField<Message>*>(GetRawRepeatedField(
  1145. message, field, FieldDescriptor::CPPTYPE_MESSAGE, -1, nullptr));
  1146. }
  1147. template <>
  1148. inline RepeatedPtrField<Message>* Reflection::MutableRepeatedPtrFieldInternal(
  1149. Message* message, const FieldDescriptor* field) const {
  1150. return static_cast<RepeatedPtrField<Message>*>(MutableRawRepeatedField(
  1151. message, field, FieldDescriptor::CPPTYPE_MESSAGE, -1, nullptr));
  1152. }
  1153. template <typename PB>
  1154. inline const RepeatedPtrField<PB>& Reflection::GetRepeatedPtrFieldInternal(
  1155. const Message& message, const FieldDescriptor* field) const {
  1156. return *static_cast<const RepeatedPtrField<PB>*>(
  1157. GetRawRepeatedField(message, field, FieldDescriptor::CPPTYPE_MESSAGE, -1,
  1158. PB::default_instance().GetDescriptor()));
  1159. }
  1160. template <typename PB>
  1161. inline RepeatedPtrField<PB>* Reflection::MutableRepeatedPtrFieldInternal(
  1162. Message* message, const FieldDescriptor* field) const {
  1163. return static_cast<RepeatedPtrField<PB>*>(
  1164. MutableRawRepeatedField(message, field, FieldDescriptor::CPPTYPE_MESSAGE,
  1165. -1, PB::default_instance().GetDescriptor()));
  1166. }
  1167. template <typename Type>
  1168. const Type& Reflection::DefaultRaw(const FieldDescriptor* field) const {
  1169. return *reinterpret_cast<const Type*>(schema_.GetFieldDefault(field));
  1170. }
  1171. } // namespace protobuf
  1172. } // namespace google
  1173. #include <google/protobuf/port_undef.inc>
  1174. #endif // GOOGLE_PROTOBUF_MESSAGE_H__
  1175. #else
  1176. #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
  1177. #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)