message.h 72 KB

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