message.h 61 KB

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