message.h 68 KB

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