message.h 68 KB

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