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