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.

message.h 70 kB

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