1// Protocol Buffers - Google's data interchange format
2// Copyright 2008 Google Inc.  All rights reserved.
3// https://developers.google.com/protocol-buffers/
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
8//
9//     * Redistributions of source code must retain the above copyright
10// notice, this list of conditions and the following disclaimer.
11//     * Redistributions in binary form must reproduce the above
12// copyright notice, this list of conditions and the following disclaimer
13// in the documentation and/or other materials provided with the
14// distribution.
15//     * Neither the name of Google Inc. nor the names of its
16// contributors may be used to endorse or promote products derived from
17// this software without specific prior written permission.
18//
19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31// Author: kenton@google.com (Kenton Varda)
32//  Based on original Protocol Buffers design by
33//  Sanjay Ghemawat, Jeff Dean, and others.
34//
35// Defines Message, the abstract interface implemented by non-lite
36// protocol message objects.  Although it's possible to implement this
37// interface manually, most users will use the protocol compiler to
38// generate implementations.
39//
40// Example usage:
41//
42// Say you have a message defined as:
43//
44//   message Foo {
45//     optional string text = 1;
46//     repeated int32 numbers = 2;
47//   }
48//
49// Then, if you used the protocol compiler to generate a class from the above
50// definition, you could use it like so:
51//
52//   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 != NULL);
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 != NULL);
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 <vector>
116
117#include <google/protobuf/message_lite.h>
118
119#include <google/protobuf/stubs/common.h>
120#include <google/protobuf/descriptor.h>
121
122
123#define GOOGLE_PROTOBUF_HAS_ONEOF
124
125namespace google {
126namespace protobuf {
127
128// Defined in this file.
129class Message;
130class Reflection;
131class MessageFactory;
132
133// Defined in other files.
134class UnknownFieldSet;         // unknown_field_set.h
135namespace io {
136  class ZeroCopyInputStream;   // zero_copy_stream.h
137  class ZeroCopyOutputStream;  // zero_copy_stream.h
138  class CodedInputStream;      // coded_stream.h
139  class CodedOutputStream;     // coded_stream.h
140}
141
142
143template<typename T>
144class RepeatedField;     // repeated_field.h
145
146template<typename T>
147class RepeatedPtrField;  // repeated_field.h
148
149// A container to hold message metadata.
150struct Metadata {
151  const Descriptor* descriptor;
152  const Reflection* reflection;
153};
154
155// Abstract interface for protocol messages.
156//
157// See also MessageLite, which contains most every-day operations.  Message
158// adds descriptors and reflection on top of that.
159//
160// The methods of this class that are virtual but not pure-virtual have
161// default implementations based on reflection.  Message classes which are
162// optimized for speed will want to override these with faster implementations,
163// but classes optimized for code size may be happy with keeping them.  See
164// the optimize_for option in descriptor.proto.
165class LIBPROTOBUF_EXPORT Message : public MessageLite {
166 public:
167  inline Message() {}
168  virtual ~Message();
169
170  // Basic Operations ------------------------------------------------
171
172  // Construct a new instance of the same type.  Ownership is passed to the
173  // caller.  (This is also defined in MessageLite, but is defined again here
174  // for return-type covariance.)
175  virtual Message* New() const = 0;
176
177  // Make this message into a copy of the given message.  The given message
178  // must have the same descriptor, but need not necessarily be the same class.
179  // By default this is just implemented as "Clear(); MergeFrom(from);".
180  virtual void CopyFrom(const Message& from);
181
182  // Merge the fields from the given message into this message.  Singular
183  // fields will be overwritten, if specified in from, except for embedded
184  // messages which will be merged.  Repeated fields will be concatenated.
185  // The given message must be of the same type as this message (i.e. the
186  // exact same class).
187  virtual void MergeFrom(const Message& from);
188
189  // Verifies that IsInitialized() returns true.  GOOGLE_CHECK-fails otherwise, with
190  // a nice error message.
191  void CheckInitialized() const;
192
193  // Slowly build a list of all required fields that are not set.
194  // This is much, much slower than IsInitialized() as it is implemented
195  // purely via reflection.  Generally, you should not call this unless you
196  // have already determined that an error exists by calling IsInitialized().
197  void FindInitializationErrors(std::vector<string>* errors) const;
198
199  // Like FindInitializationErrors, but joins all the strings, delimited by
200  // commas, and returns them.
201  string InitializationErrorString() const;
202
203  // Clears all unknown fields from this message and all embedded messages.
204  // Normally, if unknown tag numbers are encountered when parsing a message,
205  // the tag and value are stored in the message's UnknownFieldSet and
206  // then written back out when the message is serialized.  This allows servers
207  // which simply route messages to other servers to pass through messages
208  // that have new field definitions which they don't yet know about.  However,
209  // this behavior can have security implications.  To avoid it, call this
210  // method after parsing.
211  //
212  // See Reflection::GetUnknownFields() for more on unknown fields.
213  virtual void DiscardUnknownFields();
214
215  // Computes (an estimate of) the total number of bytes currently used for
216  // storing the message in memory.  The default implementation calls the
217  // Reflection object's SpaceUsed() method.
218  virtual int SpaceUsed() const;
219
220  // Debugging & Testing----------------------------------------------
221
222  // Generates a human readable form of this message, useful for debugging
223  // and other purposes.
224  string DebugString() const;
225  // Like DebugString(), but with less whitespace.
226  string ShortDebugString() const;
227  // Like DebugString(), but do not escape UTF-8 byte sequences.
228  string Utf8DebugString() const;
229  // Convenience function useful in GDB.  Prints DebugString() to stdout.
230  void PrintDebugString() const;
231
232  // Heavy I/O -------------------------------------------------------
233  // Additional parsing and serialization methods not implemented by
234  // MessageLite because they are not supported by the lite library.
235
236  // Parse a protocol buffer from a file descriptor.  If successful, the entire
237  // input will be consumed.
238  bool ParseFromFileDescriptor(int file_descriptor);
239  // Like ParseFromFileDescriptor(), but accepts messages that are missing
240  // required fields.
241  bool ParsePartialFromFileDescriptor(int file_descriptor);
242  // Parse a protocol buffer from a C++ istream.  If successful, the entire
243  // input will be consumed.
244  bool ParseFromIstream(istream* input);
245  // Like ParseFromIstream(), but accepts messages that are missing
246  // required fields.
247  bool ParsePartialFromIstream(istream* input);
248
249  // Serialize the message and write it to the given file descriptor.  All
250  // required fields must be set.
251  bool SerializeToFileDescriptor(int file_descriptor) const;
252  // Like SerializeToFileDescriptor(), but allows missing required fields.
253  bool SerializePartialToFileDescriptor(int file_descriptor) const;
254  // Serialize the message and write it to the given C++ ostream.  All
255  // required fields must be set.
256  bool SerializeToOstream(ostream* output) const;
257  // Like SerializeToOstream(), but allows missing required fields.
258  bool SerializePartialToOstream(ostream* output) const;
259
260
261  // Reflection-based methods ----------------------------------------
262  // These methods are pure-virtual in MessageLite, but Message provides
263  // reflection-based default implementations.
264
265  virtual string GetTypeName() const;
266  virtual void Clear();
267  virtual bool IsInitialized() const;
268  virtual void CheckTypeAndMergeFrom(const MessageLite& other);
269  virtual bool MergePartialFromCodedStream(io::CodedInputStream* input);
270  virtual int ByteSize() const;
271  virtual void SerializeWithCachedSizes(io::CodedOutputStream* output) const;
272
273 private:
274  // This is called only by the default implementation of ByteSize(), to
275  // update the cached size.  If you override ByteSize(), you do not need
276  // to override this.  If you do not override ByteSize(), you MUST override
277  // this; the default implementation will crash.
278  //
279  // The method is private because subclasses should never call it; only
280  // override it.  Yes, C++ lets you do that.  Crazy, huh?
281  virtual void SetCachedSize(int size) const;
282
283 public:
284
285  // Introspection ---------------------------------------------------
286
287  // Typedef for backwards-compatibility.
288  typedef google::protobuf::Reflection Reflection;
289
290  // Get a Descriptor for this message's type.  This describes what
291  // fields the message contains, the types of those fields, etc.
292  const Descriptor* GetDescriptor() const { return GetMetadata().descriptor; }
293
294  // Get the Reflection interface for this Message, which can be used to
295  // read and modify the fields of the Message dynamically (in other words,
296  // without knowing the message type at compile time).  This object remains
297  // property of the Message.
298  //
299  // This method remains virtual in case a subclass does not implement
300  // reflection and wants to override the default behavior.
301  virtual const Reflection* GetReflection() const {
302    return GetMetadata().reflection;
303  }
304
305 protected:
306  // Get a struct containing the metadata for the Message. Most subclasses only
307  // need to implement this method, rather than the GetDescriptor() and
308  // GetReflection() wrappers.
309  virtual Metadata GetMetadata() const  = 0;
310
311
312 private:
313  GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Message);
314};
315
316// This interface contains methods that can be used to dynamically access
317// and modify the fields of a protocol message.  Their semantics are
318// similar to the accessors the protocol compiler generates.
319//
320// To get the Reflection for a given Message, call Message::GetReflection().
321//
322// This interface is separate from Message only for efficiency reasons;
323// the vast majority of implementations of Message will share the same
324// implementation of Reflection (GeneratedMessageReflection,
325// defined in generated_message.h), and all Messages of a particular class
326// should share the same Reflection object (though you should not rely on
327// the latter fact).
328//
329// There are several ways that these methods can be used incorrectly.  For
330// example, any of the following conditions will lead to undefined
331// results (probably assertion failures):
332// - The FieldDescriptor is not a field of this message type.
333// - The method called is not appropriate for the field's type.  For
334//   each field type in FieldDescriptor::TYPE_*, there is only one
335//   Get*() method, one Set*() method, and one Add*() method that is
336//   valid for that type.  It should be obvious which (except maybe
337//   for TYPE_BYTES, which are represented using strings in C++).
338// - A Get*() or Set*() method for singular fields is called on a repeated
339//   field.
340// - GetRepeated*(), SetRepeated*(), or Add*() is called on a non-repeated
341//   field.
342// - The Message object passed to any method is not of the right type for
343//   this Reflection object (i.e. message.GetReflection() != reflection).
344//
345// You might wonder why there is not any abstract representation for a field
346// of arbitrary type.  E.g., why isn't there just a "GetField()" method that
347// returns "const Field&", where "Field" is some class with accessors like
348// "GetInt32Value()".  The problem is that someone would have to deal with
349// allocating these Field objects.  For generated message classes, having to
350// allocate space for an additional object to wrap every field would at least
351// double the message's memory footprint, probably worse.  Allocating the
352// objects on-demand, on the other hand, would be expensive and prone to
353// memory leaks.  So, instead we ended up with this flat interface.
354//
355// TODO(kenton):  Create a utility class which callers can use to read and
356//   write fields from a Reflection without paying attention to the type.
357class LIBPROTOBUF_EXPORT Reflection {
358 public:
359  inline Reflection() {}
360  virtual ~Reflection();
361
362  // Get the UnknownFieldSet for the message.  This contains fields which
363  // were seen when the Message was parsed but were not recognized according
364  // to the Message's definition.
365  virtual const UnknownFieldSet& GetUnknownFields(
366      const Message& message) const = 0;
367  // Get a mutable pointer to the UnknownFieldSet for the message.  This
368  // contains fields which were seen when the Message was parsed but were not
369  // recognized according to the Message's definition.
370  virtual UnknownFieldSet* MutableUnknownFields(Message* message) const = 0;
371
372  // Estimate the amount of memory used by the message object.
373  virtual int SpaceUsed(const Message& message) const = 0;
374
375  // Check if the given non-repeated field is set.
376  virtual bool HasField(const Message& message,
377                        const FieldDescriptor* field) const = 0;
378
379  // Get the number of elements of a repeated field.
380  virtual int FieldSize(const Message& message,
381                        const FieldDescriptor* field) const = 0;
382
383  // Clear the value of a field, so that HasField() returns false or
384  // FieldSize() returns zero.
385  virtual void ClearField(Message* message,
386                          const FieldDescriptor* field) const = 0;
387
388  // Check if the oneof is set. Returns ture if any field in oneof
389  // is set, false otherwise.
390  // TODO(jieluo) - make it pure virtual after updating all
391  // the subclasses.
392  virtual bool HasOneof(const Message& /*message*/,
393                        const OneofDescriptor* /*oneof_descriptor*/) const {
394    return false;
395  }
396
397  virtual void ClearOneof(Message* /*message*/,
398                          const OneofDescriptor* /*oneof_descriptor*/) const {}
399
400  // Returns the field descriptor if the oneof is set. NULL otherwise.
401  // TODO(jieluo) - make it pure virtual.
402  virtual const FieldDescriptor* GetOneofFieldDescriptor(
403      const Message& /*message*/,
404      const OneofDescriptor* /*oneof_descriptor*/) const {
405    return NULL;
406  }
407
408  // Removes the last element of a repeated field.
409  // We don't provide a way to remove any element other than the last
410  // because it invites inefficient use, such as O(n^2) filtering loops
411  // that should have been O(n).  If you want to remove an element other
412  // than the last, the best way to do it is to re-arrange the elements
413  // (using Swap()) so that the one you want removed is at the end, then
414  // call RemoveLast().
415  virtual void RemoveLast(Message* message,
416                          const FieldDescriptor* field) const = 0;
417  // Removes the last element of a repeated message field, and returns the
418  // pointer to the caller.  Caller takes ownership of the returned pointer.
419  virtual Message* ReleaseLast(Message* message,
420                               const FieldDescriptor* field) const = 0;
421
422  // Swap the complete contents of two messages.
423  virtual void Swap(Message* message1, Message* message2) const = 0;
424
425  // Swap fields listed in fields vector of two messages.
426  virtual void SwapFields(Message* message1,
427                          Message* message2,
428                          const std::vector<const FieldDescriptor*>& fields)
429      const = 0;
430
431  // Swap two elements of a repeated field.
432  virtual void SwapElements(Message* message,
433                            const FieldDescriptor* field,
434                            int index1,
435                            int index2) const = 0;
436
437  // List all fields of the message which are currently set.  This includes
438  // extensions.  Singular fields will only be listed if HasField(field) would
439  // return true and repeated fields will only be listed if FieldSize(field)
440  // would return non-zero.  Fields (both normal fields and extension fields)
441  // will be listed ordered by field number.
442  virtual void ListFields(const Message& message,
443                          std::vector<const FieldDescriptor*>* output) const = 0;
444
445  // Singular field getters ------------------------------------------
446  // These get the value of a non-repeated field.  They return the default
447  // value for fields that aren't set.
448
449  virtual int32  GetInt32 (const Message& message,
450                           const FieldDescriptor* field) const = 0;
451  virtual int64  GetInt64 (const Message& message,
452                           const FieldDescriptor* field) const = 0;
453  virtual uint32 GetUInt32(const Message& message,
454                           const FieldDescriptor* field) const = 0;
455  virtual uint64 GetUInt64(const Message& message,
456                           const FieldDescriptor* field) const = 0;
457  virtual float  GetFloat (const Message& message,
458                           const FieldDescriptor* field) const = 0;
459  virtual double GetDouble(const Message& message,
460                           const FieldDescriptor* field) const = 0;
461  virtual bool   GetBool  (const Message& message,
462                           const FieldDescriptor* field) const = 0;
463  virtual string GetString(const Message& message,
464                           const FieldDescriptor* field) const = 0;
465  virtual const EnumValueDescriptor* GetEnum(
466      const Message& message, const FieldDescriptor* field) const = 0;
467  // See MutableMessage() for the meaning of the "factory" parameter.
468  virtual const Message& GetMessage(const Message& message,
469                                    const FieldDescriptor* field,
470                                    MessageFactory* factory = NULL) const = 0;
471
472  // Get a string value without copying, if possible.
473  //
474  // GetString() necessarily returns a copy of the string.  This can be
475  // inefficient when the string is already stored in a string object in the
476  // underlying message.  GetStringReference() will return a reference to the
477  // underlying string in this case.  Otherwise, it will copy the string into
478  // *scratch and return that.
479  //
480  // Note:  It is perfectly reasonable and useful to write code like:
481  //     str = reflection->GetStringReference(field, &str);
482  //   This line would ensure that only one copy of the string is made
483  //   regardless of the field's underlying representation.  When initializing
484  //   a newly-constructed string, though, it's just as fast and more readable
485  //   to use code like:
486  //     string str = reflection->GetString(field);
487  virtual const string& GetStringReference(const Message& message,
488                                           const FieldDescriptor* field,
489                                           string* scratch) const = 0;
490
491
492  // Singular field mutators -----------------------------------------
493  // These mutate the value of a non-repeated field.
494
495  virtual void SetInt32 (Message* message,
496                         const FieldDescriptor* field, int32  value) const = 0;
497  virtual void SetInt64 (Message* message,
498                         const FieldDescriptor* field, int64  value) const = 0;
499  virtual void SetUInt32(Message* message,
500                         const FieldDescriptor* field, uint32 value) const = 0;
501  virtual void SetUInt64(Message* message,
502                         const FieldDescriptor* field, uint64 value) const = 0;
503  virtual void SetFloat (Message* message,
504                         const FieldDescriptor* field, float  value) const = 0;
505  virtual void SetDouble(Message* message,
506                         const FieldDescriptor* field, double value) const = 0;
507  virtual void SetBool  (Message* message,
508                         const FieldDescriptor* field, bool   value) const = 0;
509  virtual void SetString(Message* message,
510                         const FieldDescriptor* field,
511                         const string& value) const = 0;
512  virtual void SetEnum  (Message* message,
513                         const FieldDescriptor* field,
514                         const EnumValueDescriptor* value) const = 0;
515  // Get a mutable pointer to a field with a message type.  If a MessageFactory
516  // is provided, it will be used to construct instances of the sub-message;
517  // otherwise, the default factory is used.  If the field is an extension that
518  // does not live in the same pool as the containing message's descriptor (e.g.
519  // it lives in an overlay pool), then a MessageFactory must be provided.
520  // If you have no idea what that meant, then you probably don't need to worry
521  // about it (don't provide a MessageFactory).  WARNING:  If the
522  // FieldDescriptor is for a compiled-in extension, then
523  // factory->GetPrototype(field->message_type() MUST return an instance of the
524  // compiled-in class for this type, NOT DynamicMessage.
525  virtual Message* MutableMessage(Message* message,
526                                  const FieldDescriptor* field,
527                                  MessageFactory* factory = NULL) const = 0;
528  // Replaces the message specified by 'field' with the already-allocated object
529  // sub_message, passing ownership to the message.  If the field contained a
530  // message, that message is deleted.  If sub_message is NULL, the field is
531  // cleared.
532  virtual void SetAllocatedMessage(Message* message,
533                                   Message* sub_message,
534                                   const FieldDescriptor* field) const = 0;
535  // Releases the message specified by 'field' and returns the pointer,
536  // ReleaseMessage() will return the message the message object if it exists.
537  // Otherwise, it may or may not return NULL.  In any case, if the return value
538  // is non-NULL, the caller takes ownership of the pointer.
539  // If the field existed (HasField() is true), then the returned pointer will
540  // be the same as the pointer returned by MutableMessage().
541  // This function has the same effect as ClearField().
542  virtual Message* ReleaseMessage(Message* message,
543                                  const FieldDescriptor* field,
544                                  MessageFactory* factory = NULL) const = 0;
545
546
547  // Repeated field getters ------------------------------------------
548  // These get the value of one element of a repeated field.
549
550  virtual int32  GetRepeatedInt32 (const Message& message,
551                                   const FieldDescriptor* field,
552                                   int index) const = 0;
553  virtual int64  GetRepeatedInt64 (const Message& message,
554                                   const FieldDescriptor* field,
555                                   int index) const = 0;
556  virtual uint32 GetRepeatedUInt32(const Message& message,
557                                   const FieldDescriptor* field,
558                                   int index) const = 0;
559  virtual uint64 GetRepeatedUInt64(const Message& message,
560                                   const FieldDescriptor* field,
561                                   int index) const = 0;
562  virtual float  GetRepeatedFloat (const Message& message,
563                                   const FieldDescriptor* field,
564                                   int index) const = 0;
565  virtual double GetRepeatedDouble(const Message& message,
566                                   const FieldDescriptor* field,
567                                   int index) const = 0;
568  virtual bool   GetRepeatedBool  (const Message& message,
569                                   const FieldDescriptor* field,
570                                   int index) const = 0;
571  virtual string GetRepeatedString(const Message& message,
572                                   const FieldDescriptor* field,
573                                   int index) const = 0;
574  virtual const EnumValueDescriptor* GetRepeatedEnum(
575      const Message& message,
576      const FieldDescriptor* field, int index) const = 0;
577  virtual const Message& GetRepeatedMessage(
578      const Message& message,
579      const FieldDescriptor* field, int index) const = 0;
580
581  // See GetStringReference(), above.
582  virtual const string& GetRepeatedStringReference(
583      const Message& message, const FieldDescriptor* field,
584      int index, string* scratch) const = 0;
585
586
587  // Repeated field mutators -----------------------------------------
588  // These mutate the value of one element of a repeated field.
589
590  virtual void SetRepeatedInt32 (Message* message,
591                                 const FieldDescriptor* field,
592                                 int index, int32  value) const = 0;
593  virtual void SetRepeatedInt64 (Message* message,
594                                 const FieldDescriptor* field,
595                                 int index, int64  value) const = 0;
596  virtual void SetRepeatedUInt32(Message* message,
597                                 const FieldDescriptor* field,
598                                 int index, uint32 value) const = 0;
599  virtual void SetRepeatedUInt64(Message* message,
600                                 const FieldDescriptor* field,
601                                 int index, uint64 value) const = 0;
602  virtual void SetRepeatedFloat (Message* message,
603                                 const FieldDescriptor* field,
604                                 int index, float  value) const = 0;
605  virtual void SetRepeatedDouble(Message* message,
606                                 const FieldDescriptor* field,
607                                 int index, double value) const = 0;
608  virtual void SetRepeatedBool  (Message* message,
609                                 const FieldDescriptor* field,
610                                 int index, bool   value) const = 0;
611  virtual void SetRepeatedString(Message* message,
612                                 const FieldDescriptor* field,
613                                 int index, const string& value) const = 0;
614  virtual void SetRepeatedEnum(Message* message,
615                               const FieldDescriptor* field, int index,
616                               const EnumValueDescriptor* value) const = 0;
617  // Get a mutable pointer to an element of a repeated field with a message
618  // type.
619  virtual Message* MutableRepeatedMessage(
620      Message* message, const FieldDescriptor* field, int index) const = 0;
621
622
623  // Repeated field adders -------------------------------------------
624  // These add an element to a repeated field.
625
626  virtual void AddInt32 (Message* message,
627                         const FieldDescriptor* field, int32  value) const = 0;
628  virtual void AddInt64 (Message* message,
629                         const FieldDescriptor* field, int64  value) const = 0;
630  virtual void AddUInt32(Message* message,
631                         const FieldDescriptor* field, uint32 value) const = 0;
632  virtual void AddUInt64(Message* message,
633                         const FieldDescriptor* field, uint64 value) const = 0;
634  virtual void AddFloat (Message* message,
635                         const FieldDescriptor* field, float  value) const = 0;
636  virtual void AddDouble(Message* message,
637                         const FieldDescriptor* field, double value) const = 0;
638  virtual void AddBool  (Message* message,
639                         const FieldDescriptor* field, bool   value) const = 0;
640  virtual void AddString(Message* message,
641                         const FieldDescriptor* field,
642                         const string& value) const = 0;
643  virtual void AddEnum  (Message* message,
644                         const FieldDescriptor* field,
645                         const EnumValueDescriptor* value) const = 0;
646  // See MutableMessage() for comments on the "factory" parameter.
647  virtual Message* AddMessage(Message* message,
648                              const FieldDescriptor* field,
649                              MessageFactory* factory = NULL) const = 0;
650
651
652  // Repeated field accessors  -------------------------------------------------
653  // The methods above, e.g. GetRepeatedInt32(msg, fd, index), provide singular
654  // access to the data in a RepeatedField.  The methods below provide aggregate
655  // access by exposing the RepeatedField object itself with the Message.
656  // Applying these templates to inappropriate types will lead to an undefined
657  // reference at link time (e.g. GetRepeatedField<***double>), or possibly a
658  // template matching error at compile time (e.g. GetRepeatedPtrField<File>).
659  //
660  // Usage example: my_doubs = refl->GetRepeatedField<double>(msg, fd);
661
662  // for T = Cord and all protobuf scalar types except enums.
663  template<typename T>
664  const RepeatedField<T>& GetRepeatedField(
665      const Message&, const FieldDescriptor*) const;
666
667  // for T = Cord and all protobuf scalar types except enums.
668  template<typename T>
669  RepeatedField<T>* MutableRepeatedField(
670      Message*, const FieldDescriptor*) const;
671
672  // for T = string, google::protobuf::internal::StringPieceField
673  //         google::protobuf::Message & descendants.
674  template<typename T>
675  const RepeatedPtrField<T>& GetRepeatedPtrField(
676      const Message&, const FieldDescriptor*) const;
677
678  // for T = string, google::protobuf::internal::StringPieceField
679  //         google::protobuf::Message & descendants.
680  template<typename T>
681  RepeatedPtrField<T>* MutableRepeatedPtrField(
682      Message*, const FieldDescriptor*) const;
683
684  // Extensions ----------------------------------------------------------------
685
686  // Try to find an extension of this message type by fully-qualified field
687  // name.  Returns NULL if no extension is known for this name or number.
688  virtual const FieldDescriptor* FindKnownExtensionByName(
689      const string& name) const = 0;
690
691  // Try to find an extension of this message type by field number.
692  // Returns NULL if no extension is known for this name or number.
693  virtual const FieldDescriptor* FindKnownExtensionByNumber(
694      int number) const = 0;
695
696  // ---------------------------------------------------------------------------
697
698 protected:
699  // Obtain a pointer to a Repeated Field Structure and do some type checking:
700  //   on field->cpp_type(),
701  //   on field->field_option().ctype() (if ctype >= 0)
702  //   of field->message_type() (if message_type != NULL).
703  // We use 1 routine rather than 4 (const vs mutable) x (scalar vs pointer).
704  virtual void* MutableRawRepeatedField(
705      Message* message, const FieldDescriptor* field, FieldDescriptor::CppType,
706      int ctype, const Descriptor* message_type) const = 0;
707
708 private:
709  // Special version for specialized implementations of string.  We can't call
710  // MutableRawRepeatedField directly here because we don't have access to
711  // FieldOptions::* which are defined in descriptor.pb.h.  Including that
712  // file here is not possible because it would cause a circular include cycle.
713  void* MutableRawRepeatedString(
714      Message* message, const FieldDescriptor* field, bool is_string) const;
715
716  GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Reflection);
717};
718
719// Abstract interface for a factory for message objects.
720class LIBPROTOBUF_EXPORT MessageFactory {
721 public:
722  inline MessageFactory() {}
723  virtual ~MessageFactory();
724
725  // Given a Descriptor, gets or constructs the default (prototype) Message
726  // of that type.  You can then call that message's New() method to construct
727  // a mutable message of that type.
728  //
729  // Calling this method twice with the same Descriptor returns the same
730  // object.  The returned object remains property of the factory.  Also, any
731  // objects created by calling the prototype's New() method share some data
732  // with the prototype, so these must be destroyed before the MessageFactory
733  // is destroyed.
734  //
735  // The given descriptor must outlive the returned message, and hence must
736  // outlive the MessageFactory.
737  //
738  // Some implementations do not support all types.  GetPrototype() will
739  // return NULL if the descriptor passed in is not supported.
740  //
741  // This method may or may not be thread-safe depending on the implementation.
742  // Each implementation should document its own degree thread-safety.
743  virtual const Message* GetPrototype(const Descriptor* type) = 0;
744
745  // Gets a MessageFactory which supports all generated, compiled-in messages.
746  // In other words, for any compiled-in type FooMessage, the following is true:
747  //   MessageFactory::generated_factory()->GetPrototype(
748  //     FooMessage::descriptor()) == FooMessage::default_instance()
749  // This factory supports all types which are found in
750  // DescriptorPool::generated_pool().  If given a descriptor from any other
751  // pool, GetPrototype() will return NULL.  (You can also check if a
752  // descriptor is for a generated message by checking if
753  // descriptor->file()->pool() == DescriptorPool::generated_pool().)
754  //
755  // This factory is 100% thread-safe; calling GetPrototype() does not modify
756  // any shared data.
757  //
758  // This factory is a singleton.  The caller must not delete the object.
759  static MessageFactory* generated_factory();
760
761  // For internal use only:  Registers a .proto file at static initialization
762  // time, to be placed in generated_factory.  The first time GetPrototype()
763  // is called with a descriptor from this file, |register_messages| will be
764  // called, with the file name as the parameter.  It must call
765  // InternalRegisterGeneratedMessage() (below) to register each message type
766  // in the file.  This strange mechanism is necessary because descriptors are
767  // built lazily, so we can't register types by their descriptor until we
768  // know that the descriptor exists.  |filename| must be a permanent string.
769  static void InternalRegisterGeneratedFile(
770      const char* filename, void (*register_messages)(const string&));
771
772  // For internal use only:  Registers a message type.  Called only by the
773  // functions which are registered with InternalRegisterGeneratedFile(),
774  // above.
775  static void InternalRegisterGeneratedMessage(const Descriptor* descriptor,
776                                               const Message* prototype);
777
778
779 private:
780  GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFactory);
781};
782
783#define DECLARE_GET_REPEATED_FIELD(TYPE)                         \
784template<>                                                       \
785LIBPROTOBUF_EXPORT                                               \
786const RepeatedField<TYPE>& Reflection::GetRepeatedField<TYPE>(   \
787    const Message& message, const FieldDescriptor* field) const; \
788                                                                 \
789template<>                                                       \
790RepeatedField<TYPE>* Reflection::MutableRepeatedField<TYPE>(     \
791    Message* message, const FieldDescriptor* field) const;
792
793DECLARE_GET_REPEATED_FIELD(int32)
794DECLARE_GET_REPEATED_FIELD(int64)
795DECLARE_GET_REPEATED_FIELD(uint32)
796DECLARE_GET_REPEATED_FIELD(uint64)
797DECLARE_GET_REPEATED_FIELD(float)
798DECLARE_GET_REPEATED_FIELD(double)
799DECLARE_GET_REPEATED_FIELD(bool)
800
801#undef DECLARE_GET_REPEATED_FIELD
802
803// =============================================================================
804// Implementation details for {Get,Mutable}RawRepeatedPtrField.  We provide
805// specializations for <string>, <StringPieceField> and <Message> and handle
806// everything else with the default template which will match any type having
807// a method with signature "static const google::protobuf::Descriptor* descriptor()".
808// Such a type presumably is a descendant of google::protobuf::Message.
809
810template<>
811inline const RepeatedPtrField<string>& Reflection::GetRepeatedPtrField<string>(
812    const Message& message, const FieldDescriptor* field) const {
813  return *static_cast<RepeatedPtrField<string>* >(
814      MutableRawRepeatedString(const_cast<Message*>(&message), field, true));
815}
816
817template<>
818inline RepeatedPtrField<string>* Reflection::MutableRepeatedPtrField<string>(
819    Message* message, const FieldDescriptor* field) const {
820  return static_cast<RepeatedPtrField<string>* >(
821      MutableRawRepeatedString(message, field, true));
822}
823
824
825// -----
826
827template<>
828inline const RepeatedPtrField<Message>& Reflection::GetRepeatedPtrField(
829    const Message& message, const FieldDescriptor* field) const {
830  return *static_cast<RepeatedPtrField<Message>* >(
831      MutableRawRepeatedField(const_cast<Message*>(&message), field,
832          FieldDescriptor::CPPTYPE_MESSAGE, -1,
833          NULL));
834}
835
836template<>
837inline RepeatedPtrField<Message>* Reflection::MutableRepeatedPtrField(
838    Message* message, const FieldDescriptor* field) const {
839  return static_cast<RepeatedPtrField<Message>* >(
840      MutableRawRepeatedField(message, field,
841          FieldDescriptor::CPPTYPE_MESSAGE, -1,
842          NULL));
843}
844
845template<typename PB>
846inline const RepeatedPtrField<PB>& Reflection::GetRepeatedPtrField(
847    const Message& message, const FieldDescriptor* field) const {
848  return *static_cast<RepeatedPtrField<PB>* >(
849      MutableRawRepeatedField(const_cast<Message*>(&message), field,
850          FieldDescriptor::CPPTYPE_MESSAGE, -1,
851          PB::default_instance().GetDescriptor()));
852}
853
854template<typename PB>
855inline RepeatedPtrField<PB>* Reflection::MutableRepeatedPtrField(
856    Message* message, const FieldDescriptor* field) const {
857  return static_cast<RepeatedPtrField<PB>* >(
858      MutableRawRepeatedField(message, field,
859          FieldDescriptor::CPPTYPE_MESSAGE, -1,
860          PB::default_instance().GetDescriptor()));
861}
862
863}  // namespace protobuf
864
865}  // namespace google
866#endif  // GOOGLE_PROTOBUF_MESSAGE_H__
867