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