1// Protocol Buffers - Google's data interchange format
2// Copyright 2008 Google Inc.  All rights reserved.
3// http://code.google.com/p/protobuf/
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//     Descriptor* descriptor = foo->GetDescriptor();
83//
84//     // Get the descriptors for the fields we're interested in and verify
85//     // their types.
86//     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::TYPE_OPTIONAL);
90//     FieldDescriptor* numbers_field = descriptor->FindFieldByName("numbers");
91//     assert(numbers_field != NULL);
92//     assert(numbers_field->type() == FieldDescriptor::TYPE_INT32);
93//     assert(numbers_field->label() == FieldDescriptor::TYPE_REPEATED);
94//
95//     // Parse the message.
96//     foo->ParseFromString(data);
97//
98//     // Use the reflection interface to examine the contents.
99//     const Reflection* reflection = foo->GetReflection();
100//     assert(reflection->GetString(foo, text_field) == "Hello World!");
101//     assert(reflection->FieldSize(foo, numbers_field) == 3);
102//     assert(reflection->GetRepeatedInt32(foo, numbers_field, 0) == 1);
103//     assert(reflection->GetRepeatedInt32(foo, numbers_field, 1) == 5);
104//     assert(reflection->GetRepeatedInt32(foo, numbers_field, 2) == 42);
105//
106//     delete foo;
107//   }
108
109#ifndef GOOGLE_PROTOBUF_MESSAGE_H__
110#define GOOGLE_PROTOBUF_MESSAGE_H__
111
112#include <vector>
113#include <string>
114
115#ifdef __DECCXX
116// HP C++'s iosfwd doesn't work.
117#include <iostream>
118#else
119#include <iosfwd>
120#endif
121
122#include <google/protobuf/message_lite.h>
123
124#include <google/protobuf/stubs/common.h>
125
126#if defined(_WIN32) && defined(GetMessage)
127// windows.h defines GetMessage() as a macro.  Let's re-define it as an inline
128// function.  This is necessary because Reflection has a method called
129// GetMessage() which we don't want overridden.  The inline function should be
130// equivalent for C++ users.
131inline BOOL GetMessage_Win32(
132    LPMSG lpMsg, HWND hWnd,
133    UINT wMsgFilterMin, UINT wMsgFilterMax) {
134  return GetMessage(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax);
135}
136#undef GetMessage
137inline BOOL GetMessage(
138    LPMSG lpMsg, HWND hWnd,
139    UINT wMsgFilterMin, UINT wMsgFilterMax) {
140  return GetMessage_Win32(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax);
141}
142#endif
143
144
145namespace google {
146namespace protobuf {
147
148// Defined in this file.
149class Message;
150class Reflection;
151class MessageFactory;
152
153// Defined in other files.
154class Descriptor;            // descriptor.h
155class FieldDescriptor;       // descriptor.h
156class EnumDescriptor;        // descriptor.h
157class EnumValueDescriptor;   // descriptor.h
158namespace io {
159  class ZeroCopyInputStream;   // zero_copy_stream.h
160  class ZeroCopyOutputStream;  // zero_copy_stream.h
161  class CodedInputStream;      // coded_stream.h
162  class CodedOutputStream;     // coded_stream.h
163}
164class UnknownFieldSet;       // unknown_field_set.h
165
166// A container to hold message metadata.
167struct Metadata {
168  const Descriptor* descriptor;
169  const Reflection* reflection;
170};
171
172// Returns the EnumDescriptor for enum type E, which must be a
173// proto-declared enum type.  Code generated by the protocol compiler
174// will include specializations of this template for each enum type declared.
175template <typename E>
176const EnumDescriptor* GetEnumDescriptor();
177
178// Abstract interface for protocol messages.
179//
180// See also MessageLite, which contains most every-day operations.  Message
181// adds descriptors and reflection on top of that.
182//
183// The methods of this class that are virtual but not pure-virtual have
184// default implementations based on reflection.  Message classes which are
185// optimized for speed will want to override these with faster implementations,
186// but classes optimized for code size may be happy with keeping them.  See
187// the optimize_for option in descriptor.proto.
188class LIBPROTOBUF_EXPORT Message : public MessageLite {
189 public:
190  inline Message() {}
191  virtual ~Message();
192
193  // Basic Operations ------------------------------------------------
194
195  // Construct a new instance of the same type.  Ownership is passed to the
196  // caller.  (This is also defined in MessageLite, but is defined again here
197  // for return-type covariance.)
198  virtual Message* New() const = 0;
199
200  // Make this message into a copy of the given message.  The given message
201  // must have the same descriptor, but need not necessarily be the same class.
202  // By default this is just implemented as "Clear(); MergeFrom(from);".
203  virtual void CopyFrom(const Message& from);
204
205  // Merge the fields from the given message into this message.  Singular
206  // fields will be overwritten, except for embedded messages which will
207  // be merged.  Repeated fields will be concatenated.  The given message
208  // must be of the same type as this message (i.e. the exact same class).
209  virtual void MergeFrom(const Message& from);
210
211  // Verifies that IsInitialized() returns true.  GOOGLE_CHECK-fails otherwise, with
212  // a nice error message.
213  void CheckInitialized() const;
214
215  // Slowly build a list of all required fields that are not set.
216  // This is much, much slower than IsInitialized() as it is implemented
217  // purely via reflection.  Generally, you should not call this unless you
218  // have already determined that an error exists by calling IsInitialized().
219  void FindInitializationErrors(vector<string>* errors) const;
220
221  // Like FindInitializationErrors, but joins all the strings, delimited by
222  // commas, and returns them.
223  string InitializationErrorString() const;
224
225  // Clears all unknown fields from this message and all embedded messages.
226  // Normally, if unknown tag numbers are encountered when parsing a message,
227  // the tag and value are stored in the message's UnknownFieldSet and
228  // then written back out when the message is serialized.  This allows servers
229  // which simply route messages to other servers to pass through messages
230  // that have new field definitions which they don't yet know about.  However,
231  // this behavior can have security implications.  To avoid it, call this
232  // method after parsing.
233  //
234  // See Reflection::GetUnknownFields() for more on unknown fields.
235  virtual void DiscardUnknownFields();
236
237  // Computes (an estimate of) the total number of bytes currently used for
238  // storing the message in memory.  The default implementation calls the
239  // Reflection object's SpaceUsed() method.
240  virtual int SpaceUsed() const;
241
242  // Debugging & Testing----------------------------------------------
243
244  // Generates a human readable form of this message, useful for debugging
245  // and other purposes.
246  string DebugString() const;
247  // Like DebugString(), but with less whitespace.
248  string ShortDebugString() const;
249  // Like DebugString(), but do not escape UTF-8 byte sequences.
250  string Utf8DebugString() const;
251  // Convenience function useful in GDB.  Prints DebugString() to stdout.
252  void PrintDebugString() const;
253
254  // Heavy I/O -------------------------------------------------------
255  // Additional parsing and serialization methods not implemented by
256  // MessageLite because they are not supported by the lite library.
257
258  // Parse a protocol buffer from a file descriptor.  If successful, the entire
259  // input will be consumed.
260  bool ParseFromFileDescriptor(int file_descriptor);
261  // Like ParseFromFileDescriptor(), but accepts messages that are missing
262  // required fields.
263  bool ParsePartialFromFileDescriptor(int file_descriptor);
264  // Parse a protocol buffer from a C++ istream.  If successful, the entire
265  // input will be consumed.
266  bool ParseFromIstream(istream* input);
267  // Like ParseFromIstream(), but accepts messages that are missing
268  // required fields.
269  bool ParsePartialFromIstream(istream* input);
270
271  // Serialize the message and write it to the given file descriptor.  All
272  // required fields must be set.
273  bool SerializeToFileDescriptor(int file_descriptor) const;
274  // Like SerializeToFileDescriptor(), but allows missing required fields.
275  bool SerializePartialToFileDescriptor(int file_descriptor) const;
276  // Serialize the message and write it to the given C++ ostream.  All
277  // required fields must be set.
278  bool SerializeToOstream(ostream* output) const;
279  // Like SerializeToOstream(), but allows missing required fields.
280  bool SerializePartialToOstream(ostream* output) const;
281
282
283  // Reflection-based methods ----------------------------------------
284  // These methods are pure-virtual in MessageLite, but Message provides
285  // reflection-based default implementations.
286
287  virtual string GetTypeName() const;
288  virtual void Clear();
289  virtual bool IsInitialized() const;
290  virtual void CheckTypeAndMergeFrom(const MessageLite& other);
291  virtual bool MergePartialFromCodedStream(io::CodedInputStream* input);
292  virtual int ByteSize() const;
293  virtual void SerializeWithCachedSizes(io::CodedOutputStream* output) const;
294
295 private:
296  // This is called only by the default implementation of ByteSize(), to
297  // update the cached size.  If you override ByteSize(), you do not need
298  // to override this.  If you do not override ByteSize(), you MUST override
299  // this; the default implementation will crash.
300  //
301  // The method is private because subclasses should never call it; only
302  // override it.  Yes, C++ lets you do that.  Crazy, huh?
303  virtual void SetCachedSize(int size) const;
304
305 public:
306
307  // Introspection ---------------------------------------------------
308
309  // Typedef for backwards-compatibility.
310  typedef google::protobuf::Reflection Reflection;
311
312  // Get a Descriptor for this message's type.  This describes what
313  // fields the message contains, the types of those fields, etc.
314  const Descriptor* GetDescriptor() const { return GetMetadata().descriptor; }
315
316  // Get the Reflection interface for this Message, which can be used to
317  // read and modify the fields of the Message dynamically (in other words,
318  // without knowing the message type at compile time).  This object remains
319  // property of the Message.
320  //
321  // This method remains virtual in case a subclass does not implement
322  // reflection and wants to override the default behavior.
323  virtual const Reflection* GetReflection() const {
324    return GetMetadata().reflection;
325  }
326
327 protected:
328  // Get a struct containing the metadata for the Message. Most subclasses only
329  // need to implement this method, rather than the GetDescriptor() and
330  // GetReflection() wrappers.
331  virtual Metadata GetMetadata() const  = 0;
332
333
334 private:
335  GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Message);
336};
337
338// This interface contains methods that can be used to dynamically access
339// and modify the fields of a protocol message.  Their semantics are
340// similar to the accessors the protocol compiler generates.
341//
342// To get the Reflection for a given Message, call Message::GetReflection().
343//
344// This interface is separate from Message only for efficiency reasons;
345// the vast majority of implementations of Message will share the same
346// implementation of Reflection (GeneratedMessageReflection,
347// defined in generated_message.h), and all Messages of a particular class
348// should share the same Reflection object (though you should not rely on
349// the latter fact).
350//
351// There are several ways that these methods can be used incorrectly.  For
352// example, any of the following conditions will lead to undefined
353// results (probably assertion failures):
354// - The FieldDescriptor is not a field of this message type.
355// - The method called is not appropriate for the field's type.  For
356//   each field type in FieldDescriptor::TYPE_*, there is only one
357//   Get*() method, one Set*() method, and one Add*() method that is
358//   valid for that type.  It should be obvious which (except maybe
359//   for TYPE_BYTES, which are represented using strings in C++).
360// - A Get*() or Set*() method for singular fields is called on a repeated
361//   field.
362// - GetRepeated*(), SetRepeated*(), or Add*() is called on a non-repeated
363//   field.
364// - The Message object passed to any method is not of the right type for
365//   this Reflection object (i.e. message.GetReflection() != reflection).
366//
367// You might wonder why there is not any abstract representation for a field
368// of arbitrary type.  E.g., why isn't there just a "GetField()" method that
369// returns "const Field&", where "Field" is some class with accessors like
370// "GetInt32Value()".  The problem is that someone would have to deal with
371// allocating these Field objects.  For generated message classes, having to
372// allocate space for an additional object to wrap every field would at least
373// double the message's memory footprint, probably worse.  Allocating the
374// objects on-demand, on the other hand, would be expensive and prone to
375// memory leaks.  So, instead we ended up with this flat interface.
376//
377// TODO(kenton):  Create a utility class which callers can use to read and
378//   write fields from a Reflection without paying attention to the type.
379class LIBPROTOBUF_EXPORT Reflection {
380 public:
381  // TODO(kenton):  Remove parameter.
382  inline Reflection() {}
383  virtual ~Reflection();
384
385  // Get the UnknownFieldSet for the message.  This contains fields which
386  // were seen when the Message was parsed but were not recognized according
387  // to the Message's definition.
388  virtual const UnknownFieldSet& GetUnknownFields(
389      const Message& message) const = 0;
390  // Get a mutable pointer to the UnknownFieldSet for the message.  This
391  // contains fields which were seen when the Message was parsed but were not
392  // recognized according to the Message's definition.
393  virtual UnknownFieldSet* MutableUnknownFields(Message* message) const = 0;
394
395  // Estimate the amount of memory used by the message object.
396  virtual int SpaceUsed(const Message& message) const = 0;
397
398  // Check if the given non-repeated field is set.
399  virtual bool HasField(const Message& message,
400                        const FieldDescriptor* field) const = 0;
401
402  // Get the number of elements of a repeated field.
403  virtual int FieldSize(const Message& message,
404                        const FieldDescriptor* field) const = 0;
405
406  // Clear the value of a field, so that HasField() returns false or
407  // FieldSize() returns zero.
408  virtual void ClearField(Message* message,
409                          const FieldDescriptor* field) const = 0;
410
411  // Remove the last element of a repeated field.
412  // We don't provide a way to remove any element other than the last
413  // because it invites inefficient use, such as O(n^2) filtering loops
414  // that should have been O(n).  If you want to remove an element other
415  // than the last, the best way to do it is to re-arrange the elements
416  // (using Swap()) so that the one you want removed is at the end, then
417  // call RemoveLast().
418  virtual void RemoveLast(Message* message,
419                          const FieldDescriptor* field) const = 0;
420
421  // Swap the complete contents of two messages.
422  virtual void Swap(Message* message1, Message* message2) const = 0;
423
424  // Swap two elements of a repeated field.
425  virtual void SwapElements(Message* message,
426                    const FieldDescriptor* field,
427                    int index1,
428                    int index2) const = 0;
429
430  // List all fields of the message which are currently set.  This includes
431  // extensions.  Singular fields will only be listed if HasField(field) would
432  // return true and repeated fields will only be listed if FieldSize(field)
433  // would return non-zero.  Fields (both normal fields and extension fields)
434  // will be listed ordered by field number.
435  virtual void ListFields(const Message& message,
436                          vector<const FieldDescriptor*>* output) const = 0;
437
438  // Singular field getters ------------------------------------------
439  // These get the value of a non-repeated field.  They return the default
440  // value for fields that aren't set.
441
442  virtual int32  GetInt32 (const Message& message,
443                           const FieldDescriptor* field) const = 0;
444  virtual int64  GetInt64 (const Message& message,
445                           const FieldDescriptor* field) const = 0;
446  virtual uint32 GetUInt32(const Message& message,
447                           const FieldDescriptor* field) const = 0;
448  virtual uint64 GetUInt64(const Message& message,
449                           const FieldDescriptor* field) const = 0;
450  virtual float  GetFloat (const Message& message,
451                           const FieldDescriptor* field) const = 0;
452  virtual double GetDouble(const Message& message,
453                           const FieldDescriptor* field) const = 0;
454  virtual bool   GetBool  (const Message& message,
455                           const FieldDescriptor* field) const = 0;
456  virtual string GetString(const Message& message,
457                           const FieldDescriptor* field) const = 0;
458  virtual const EnumValueDescriptor* GetEnum(
459      const Message& message, const FieldDescriptor* field) const = 0;
460  // See MutableMessage() for the meaning of the "factory" parameter.
461  virtual const Message& GetMessage(const Message& message,
462                                    const FieldDescriptor* field,
463                                    MessageFactory* factory = NULL) const = 0;
464
465  // Get a string value without copying, if possible.
466  //
467  // GetString() necessarily returns a copy of the string.  This can be
468  // inefficient when the string is already stored in a string object in the
469  // underlying message.  GetStringReference() will return a reference to the
470  // underlying string in this case.  Otherwise, it will copy the string into
471  // *scratch and return that.
472  //
473  // Note:  It is perfectly reasonable and useful to write code like:
474  //     str = reflection->GetStringReference(field, &str);
475  //   This line would ensure that only one copy of the string is made
476  //   regardless of the field's underlying representation.  When initializing
477  //   a newly-constructed string, though, it's just as fast and more readable
478  //   to use code like:
479  //     string str = reflection->GetString(field);
480  virtual const string& GetStringReference(const Message& message,
481                                           const FieldDescriptor* field,
482                                           string* scratch) const = 0;
483
484
485  // Singular field mutators -----------------------------------------
486  // These mutate the value of a non-repeated field.
487
488  virtual void SetInt32 (Message* message,
489                         const FieldDescriptor* field, int32  value) const = 0;
490  virtual void SetInt64 (Message* message,
491                         const FieldDescriptor* field, int64  value) const = 0;
492  virtual void SetUInt32(Message* message,
493                         const FieldDescriptor* field, uint32 value) const = 0;
494  virtual void SetUInt64(Message* message,
495                         const FieldDescriptor* field, uint64 value) const = 0;
496  virtual void SetFloat (Message* message,
497                         const FieldDescriptor* field, float  value) const = 0;
498  virtual void SetDouble(Message* message,
499                         const FieldDescriptor* field, double value) const = 0;
500  virtual void SetBool  (Message* message,
501                         const FieldDescriptor* field, bool   value) const = 0;
502  virtual void SetString(Message* message,
503                         const FieldDescriptor* field,
504                         const string& value) const = 0;
505  virtual void SetEnum  (Message* message,
506                         const FieldDescriptor* field,
507                         const EnumValueDescriptor* value) const = 0;
508  // Get a mutable pointer to a field with a message type.  If a MessageFactory
509  // is provided, it will be used to construct instances of the sub-message;
510  // otherwise, the default factory is used.  If the field is an extension that
511  // does not live in the same pool as the containing message's descriptor (e.g.
512  // it lives in an overlay pool), then a MessageFactory must be provided.
513  // If you have no idea what that meant, then you probably don't need to worry
514  // about it (don't provide a MessageFactory).  WARNING:  If the
515  // FieldDescriptor is for a compiled-in extension, then
516  // factory->GetPrototype(field->message_type() MUST return an instance of the
517  // compiled-in class for this type, NOT DynamicMessage.
518  virtual Message* MutableMessage(Message* message,
519                                  const FieldDescriptor* field,
520                                  MessageFactory* factory = NULL) const = 0;
521
522
523  // Repeated field getters ------------------------------------------
524  // These get the value of one element of a repeated field.
525
526  virtual int32  GetRepeatedInt32 (const Message& message,
527                                   const FieldDescriptor* field,
528                                   int index) const = 0;
529  virtual int64  GetRepeatedInt64 (const Message& message,
530                                   const FieldDescriptor* field,
531                                   int index) const = 0;
532  virtual uint32 GetRepeatedUInt32(const Message& message,
533                                   const FieldDescriptor* field,
534                                   int index) const = 0;
535  virtual uint64 GetRepeatedUInt64(const Message& message,
536                                   const FieldDescriptor* field,
537                                   int index) const = 0;
538  virtual float  GetRepeatedFloat (const Message& message,
539                                   const FieldDescriptor* field,
540                                   int index) const = 0;
541  virtual double GetRepeatedDouble(const Message& message,
542                                   const FieldDescriptor* field,
543                                   int index) const = 0;
544  virtual bool   GetRepeatedBool  (const Message& message,
545                                   const FieldDescriptor* field,
546                                   int index) const = 0;
547  virtual string GetRepeatedString(const Message& message,
548                                   const FieldDescriptor* field,
549                                   int index) const = 0;
550  virtual const EnumValueDescriptor* GetRepeatedEnum(
551      const Message& message,
552      const FieldDescriptor* field, int index) const = 0;
553  virtual const Message& GetRepeatedMessage(
554      const Message& message,
555      const FieldDescriptor* field, int index) const = 0;
556
557  // See GetStringReference(), above.
558  virtual const string& GetRepeatedStringReference(
559      const Message& message, const FieldDescriptor* field,
560      int index, string* scratch) const = 0;
561
562
563  // Repeated field mutators -----------------------------------------
564  // These mutate the value of one element of a repeated field.
565
566  virtual void SetRepeatedInt32 (Message* message,
567                                 const FieldDescriptor* field,
568                                 int index, int32  value) const = 0;
569  virtual void SetRepeatedInt64 (Message* message,
570                                 const FieldDescriptor* field,
571                                 int index, int64  value) const = 0;
572  virtual void SetRepeatedUInt32(Message* message,
573                                 const FieldDescriptor* field,
574                                 int index, uint32 value) const = 0;
575  virtual void SetRepeatedUInt64(Message* message,
576                                 const FieldDescriptor* field,
577                                 int index, uint64 value) const = 0;
578  virtual void SetRepeatedFloat (Message* message,
579                                 const FieldDescriptor* field,
580                                 int index, float  value) const = 0;
581  virtual void SetRepeatedDouble(Message* message,
582                                 const FieldDescriptor* field,
583                                 int index, double value) const = 0;
584  virtual void SetRepeatedBool  (Message* message,
585                                 const FieldDescriptor* field,
586                                 int index, bool   value) const = 0;
587  virtual void SetRepeatedString(Message* message,
588                                 const FieldDescriptor* field,
589                                 int index, const string& value) const = 0;
590  virtual void SetRepeatedEnum(Message* message,
591                               const FieldDescriptor* field, int index,
592                               const EnumValueDescriptor* value) const = 0;
593  // Get a mutable pointer to an element of a repeated field with a message
594  // type.
595  virtual Message* MutableRepeatedMessage(
596      Message* message, const FieldDescriptor* field, int index) const = 0;
597
598
599  // Repeated field adders -------------------------------------------
600  // These add an element to a repeated field.
601
602  virtual void AddInt32 (Message* message,
603                         const FieldDescriptor* field, int32  value) const = 0;
604  virtual void AddInt64 (Message* message,
605                         const FieldDescriptor* field, int64  value) const = 0;
606  virtual void AddUInt32(Message* message,
607                         const FieldDescriptor* field, uint32 value) const = 0;
608  virtual void AddUInt64(Message* message,
609                         const FieldDescriptor* field, uint64 value) const = 0;
610  virtual void AddFloat (Message* message,
611                         const FieldDescriptor* field, float  value) const = 0;
612  virtual void AddDouble(Message* message,
613                         const FieldDescriptor* field, double value) const = 0;
614  virtual void AddBool  (Message* message,
615                         const FieldDescriptor* field, bool   value) const = 0;
616  virtual void AddString(Message* message,
617                         const FieldDescriptor* field,
618                         const string& value) const = 0;
619  virtual void AddEnum  (Message* message,
620                         const FieldDescriptor* field,
621                         const EnumValueDescriptor* value) const = 0;
622  // See MutableMessage() for comments on the "factory" parameter.
623  virtual Message* AddMessage(Message* message,
624                              const FieldDescriptor* field,
625                              MessageFactory* factory = NULL) const = 0;
626
627
628  // Extensions ------------------------------------------------------
629
630  // Try to find an extension of this message type by fully-qualified field
631  // name.  Returns NULL if no extension is known for this name or number.
632  virtual const FieldDescriptor* FindKnownExtensionByName(
633      const string& name) const = 0;
634
635  // Try to find an extension of this message type by field number.
636  // Returns NULL if no extension is known for this name or number.
637  virtual const FieldDescriptor* FindKnownExtensionByNumber(
638      int number) const = 0;
639
640 private:
641  GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Reflection);
642};
643
644// Abstract interface for a factory for message objects.
645class LIBPROTOBUF_EXPORT MessageFactory {
646 public:
647  inline MessageFactory() {}
648  virtual ~MessageFactory();
649
650  // Given a Descriptor, gets or constructs the default (prototype) Message
651  // of that type.  You can then call that message's New() method to construct
652  // a mutable message of that type.
653  //
654  // Calling this method twice with the same Descriptor returns the same
655  // object.  The returned object remains property of the factory.  Also, any
656  // objects created by calling the prototype's New() method share some data
657  // with the prototype, so these must be destoyed before the MessageFactory
658  // is destroyed.
659  //
660  // The given descriptor must outlive the returned message, and hence must
661  // outlive the MessageFactory.
662  //
663  // Some implementations do not support all types.  GetPrototype() will
664  // return NULL if the descriptor passed in is not supported.
665  //
666  // This method may or may not be thread-safe depending on the implementation.
667  // Each implementation should document its own degree thread-safety.
668  virtual const Message* GetPrototype(const Descriptor* type) = 0;
669
670  // Gets a MessageFactory which supports all generated, compiled-in messages.
671  // In other words, for any compiled-in type FooMessage, the following is true:
672  //   MessageFactory::generated_factory()->GetPrototype(
673  //     FooMessage::descriptor()) == FooMessage::default_instance()
674  // This factory supports all types which are found in
675  // DescriptorPool::generated_pool().  If given a descriptor from any other
676  // pool, GetPrototype() will return NULL.  (You can also check if a
677  // descriptor is for a generated message by checking if
678  // descriptor->file()->pool() == DescriptorPool::generated_pool().)
679  //
680  // This factory is 100% thread-safe; calling GetPrototype() does not modify
681  // any shared data.
682  //
683  // This factory is a singleton.  The caller must not delete the object.
684  static MessageFactory* generated_factory();
685
686  // For internal use only:  Registers a .proto file at static initialization
687  // time, to be placed in generated_factory.  The first time GetPrototype()
688  // is called with a descriptor from this file, |register_messages| will be
689  // called, with the file name as the parameter.  It must call
690  // InternalRegisterGeneratedMessage() (below) to register each message type
691  // in the file.  This strange mechanism is necessary because descriptors are
692  // built lazily, so we can't register types by their descriptor until we
693  // know that the descriptor exists.  |filename| must be a permanent string.
694  static void InternalRegisterGeneratedFile(
695      const char* filename, void (*register_messages)(const string&));
696
697  // For internal use only:  Registers a message type.  Called only by the
698  // functions which are registered with InternalRegisterGeneratedFile(),
699  // above.
700  static void InternalRegisterGeneratedMessage(const Descriptor* descriptor,
701                                               const Message* prototype);
702
703 private:
704  GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFactory);
705};
706
707}  // namespace protobuf
708
709}  // namespace google
710#endif  // GOOGLE_PROTOBUF_MESSAGE_H__
711