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 77 kB

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