dynamic_message.h 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 an implementation of Message which can emulate types which are not
  35. // known at compile-time.
  36. #ifndef GOOGLE_PROTOBUF_DYNAMIC_MESSAGE_H__
  37. #define GOOGLE_PROTOBUF_DYNAMIC_MESSAGE_H__
  38. #include <algorithm>
  39. #include <memory>
  40. #include <vector>
  41. #include <google/protobuf/message.h>
  42. #include <google/protobuf/repeated_field.h>
  43. #include <google/protobuf/stubs/common.h>
  44. #include <google/protobuf/stubs/mutex.h>
  45. namespace google {
  46. namespace protobuf {
  47. // Defined in other files.
  48. class Descriptor; // descriptor.h
  49. class DescriptorPool; // descriptor.h
  50. // Constructs implementations of Message which can emulate types which are not
  51. // known at compile-time.
  52. //
  53. // Sometimes you want to be able to manipulate protocol types that you don't
  54. // know about at compile time. It would be nice to be able to construct
  55. // a Message object which implements the message type given by any arbitrary
  56. // Descriptor. DynamicMessage provides this.
  57. //
  58. // As it turns out, a DynamicMessage needs to construct extra
  59. // information about its type in order to operate. Most of this information
  60. // can be shared between all DynamicMessages of the same type. But, caching
  61. // this information in some sort of global map would be a bad idea, since
  62. // the cached information for a particular descriptor could outlive the
  63. // descriptor itself. To avoid this problem, DynamicMessageFactory
  64. // encapsulates this "cache". All DynamicMessages of the same type created
  65. // from the same factory will share the same support data. Any Descriptors
  66. // used with a particular factory must outlive the factory.
  67. class LIBPROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory {
  68. public:
  69. // Construct a DynamicMessageFactory that will search for extensions in
  70. // the DescriptorPool in which the extendee is defined.
  71. DynamicMessageFactory();
  72. // Construct a DynamicMessageFactory that will search for extensions in
  73. // the given DescriptorPool.
  74. //
  75. // DEPRECATED: Use CodedInputStream::SetExtensionRegistry() to tell the
  76. // parser to look for extensions in an alternate pool. However, note that
  77. // this is almost never what you want to do. Almost all users should use
  78. // the zero-arg constructor.
  79. DynamicMessageFactory(const DescriptorPool* pool);
  80. ~DynamicMessageFactory();
  81. // Call this to tell the DynamicMessageFactory that if it is given a
  82. // Descriptor d for which:
  83. // d->file()->pool() == DescriptorPool::generated_pool(),
  84. // then it should delegate to MessageFactory::generated_factory() instead
  85. // of constructing a dynamic implementation of the message. In theory there
  86. // is no down side to doing this, so it may become the default in the future.
  87. void SetDelegateToGeneratedFactory(bool enable) {
  88. delegate_to_generated_factory_ = enable;
  89. }
  90. // implements MessageFactory ---------------------------------------
  91. // Given a Descriptor, constructs the default (prototype) Message of that
  92. // type. You can then call that message's New() method to construct a
  93. // mutable message of that type.
  94. //
  95. // Calling this method twice with the same Descriptor returns the same
  96. // object. The returned object remains property of the factory and will
  97. // be destroyed when the factory is destroyed. Also, any objects created
  98. // by calling the prototype's New() method share some data with the
  99. // prototype, so these must be destroyed before the DynamicMessageFactory
  100. // is destroyed.
  101. //
  102. // The given descriptor must outlive the returned message, and hence must
  103. // outlive the DynamicMessageFactory.
  104. //
  105. // The method is thread-safe.
  106. const Message* GetPrototype(const Descriptor* type);
  107. private:
  108. const DescriptorPool* pool_;
  109. bool delegate_to_generated_factory_;
  110. // This struct just contains a hash_map. We can't #include <google/protobuf/stubs/hash.h> from
  111. // this header due to hacks needed for hash_map portability in the open source
  112. // release. Namely, stubs/hash.h, which defines hash_map portably, is not a
  113. // public header (for good reason), but dynamic_message.h is, and public
  114. // headers may only #include other public headers.
  115. struct PrototypeMap;
  116. std::unique_ptr<PrototypeMap> prototypes_;
  117. mutable Mutex prototypes_mutex_;
  118. friend class DynamicMessage;
  119. const Message* GetPrototypeNoLock(const Descriptor* type);
  120. // Construct default oneof instance for reflection usage if oneof
  121. // is defined.
  122. static void ConstructDefaultOneofInstance(const Descriptor* type,
  123. const uint32 offsets[],
  124. void* default_oneof_instance);
  125. // Delete default oneof instance. Called by ~DynamicMessageFactory.
  126. static void DeleteDefaultOneofInstance(const Descriptor* type,
  127. const uint32 offsets[],
  128. const void* default_oneof_instance);
  129. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMessageFactory);
  130. };
  131. // Helper for computing a sorted list of map entries via reflection.
  132. class LIBPROTOBUF_EXPORT DynamicMapSorter {
  133. public:
  134. static std::vector<const Message*> Sort(const Message& message,
  135. int map_size,
  136. const Reflection* reflection,
  137. const FieldDescriptor* field) {
  138. std::vector<const Message*> result(static_cast<size_t>(map_size));
  139. const RepeatedPtrField<Message>& map_field =
  140. reflection->GetRepeatedPtrField<Message>(message, field);
  141. size_t i = 0;
  142. for (RepeatedPtrField<Message>::const_pointer_iterator it =
  143. map_field.pointer_begin(); it != map_field.pointer_end(); ) {
  144. result[i++] = *it++;
  145. }
  146. GOOGLE_DCHECK_EQ(result.size(), i);
  147. MapEntryMessageComparator comparator(field->message_type());
  148. std::stable_sort(result.begin(), result.end(), comparator);
  149. // Complain if the keys aren't in ascending order.
  150. #ifndef NDEBUG
  151. for (size_t j = 1; j < static_cast<size_t>(map_size); j++) {
  152. if (!comparator(result[j - 1], result[j])) {
  153. GOOGLE_LOG(ERROR) << (comparator(result[j], result[j - 1]) ?
  154. "internal error in map key sorting" :
  155. "map keys are not unique");
  156. }
  157. }
  158. #endif
  159. return result;
  160. }
  161. private:
  162. class LIBPROTOBUF_EXPORT MapEntryMessageComparator {
  163. public:
  164. explicit MapEntryMessageComparator(const Descriptor* descriptor)
  165. : field_(descriptor->field(0)) {}
  166. bool operator()(const Message* a, const Message* b) {
  167. const Reflection* reflection = a->GetReflection();
  168. switch (field_->cpp_type()) {
  169. case FieldDescriptor::CPPTYPE_BOOL: {
  170. bool first = reflection->GetBool(*a, field_);
  171. bool second = reflection->GetBool(*b, field_);
  172. return first < second;
  173. }
  174. case FieldDescriptor::CPPTYPE_INT32: {
  175. int32 first = reflection->GetInt32(*a, field_);
  176. int32 second = reflection->GetInt32(*b, field_);
  177. return first < second;
  178. }
  179. case FieldDescriptor::CPPTYPE_INT64: {
  180. int64 first = reflection->GetInt64(*a, field_);
  181. int64 second = reflection->GetInt64(*b, field_);
  182. return first < second;
  183. }
  184. case FieldDescriptor::CPPTYPE_UINT32: {
  185. uint32 first = reflection->GetUInt32(*a, field_);
  186. uint32 second = reflection->GetUInt32(*b, field_);
  187. return first < second;
  188. }
  189. case FieldDescriptor::CPPTYPE_UINT64: {
  190. uint64 first = reflection->GetUInt64(*a, field_);
  191. uint64 second = reflection->GetUInt64(*b, field_);
  192. return first < second;
  193. }
  194. case FieldDescriptor::CPPTYPE_STRING: {
  195. string first = reflection->GetString(*a, field_);
  196. string second = reflection->GetString(*b, field_);
  197. return first < second;
  198. }
  199. default:
  200. GOOGLE_LOG(DFATAL) << "Invalid key for map field.";
  201. return true;
  202. }
  203. }
  204. private:
  205. const FieldDescriptor* field_;
  206. };
  207. };
  208. } // namespace protobuf
  209. } // namespace google
  210. #endif // GOOGLE_PROTOBUF_DYNAMIC_MESSAGE_H__