message.h 39 KB

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