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