message.h 65 KB

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