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