1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 // Author: kenton@google.com (Kenton Varda)
32 //  Based on original Protocol Buffers design by
33 //  Sanjay Ghemawat, Jeff Dean, and others.
34 //
35 // Defines an implementation of Message which can emulate types which are not
36 // known at compile-time.
37 
38 #ifndef GOOGLE_PROTOBUF_DYNAMIC_MESSAGE_H__
39 #define GOOGLE_PROTOBUF_DYNAMIC_MESSAGE_H__
40 
41 #include <algorithm>
42 #include <memory>
43 #include <unordered_map>
44 #include <vector>
45 
46 #include <google/protobuf/stubs/common.h>
47 #include <google/protobuf/message.h>
48 #include <google/protobuf/stubs/mutex.h>
49 #include <google/protobuf/reflection.h>
50 #include <google/protobuf/repeated_field.h>
51 
52 #ifdef SWIG
53 #error "You cannot SWIG proto headers"
54 #endif
55 
56 #include <google/protobuf/port_def.inc>
57 
58 namespace google {
59 namespace protobuf {
60 
61 // Defined in other files.
62 class Descriptor;      // descriptor.h
63 class DescriptorPool;  // descriptor.h
64 
65 // Constructs implementations of Message which can emulate types which are not
66 // known at compile-time.
67 //
68 // Sometimes you want to be able to manipulate protocol types that you don't
69 // know about at compile time.  It would be nice to be able to construct
70 // a Message object which implements the message type given by any arbitrary
71 // Descriptor.  DynamicMessage provides this.
72 //
73 // As it turns out, a DynamicMessage needs to construct extra
74 // information about its type in order to operate.  Most of this information
75 // can be shared between all DynamicMessages of the same type.  But, caching
76 // this information in some sort of global map would be a bad idea, since
77 // the cached information for a particular descriptor could outlive the
78 // descriptor itself.  To avoid this problem, DynamicMessageFactory
79 // encapsulates this "cache".  All DynamicMessages of the same type created
80 // from the same factory will share the same support data.  Any Descriptors
81 // used with a particular factory must outlive the factory.
82 class PROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory {
83  public:
84   // Construct a DynamicMessageFactory that will search for extensions in
85   // the DescriptorPool in which the extendee is defined.
86   DynamicMessageFactory();
87 
88   // Construct a DynamicMessageFactory that will search for extensions in
89   // the given DescriptorPool.
90   //
91   // DEPRECATED:  Use CodedInputStream::SetExtensionRegistry() to tell the
92   //   parser to look for extensions in an alternate pool.  However, note that
93   //   this is almost never what you want to do.  Almost all users should use
94   //   the zero-arg constructor.
95   DynamicMessageFactory(const DescriptorPool* pool);
96 
97   ~DynamicMessageFactory();
98 
99   // Call this to tell the DynamicMessageFactory that if it is given a
100   // Descriptor d for which:
101   //   d->file()->pool() == DescriptorPool::generated_pool(),
102   // then it should delegate to MessageFactory::generated_factory() instead
103   // of constructing a dynamic implementation of the message.  In theory there
104   // is no down side to doing this, so it may become the default in the future.
SetDelegateToGeneratedFactory(bool enable)105   void SetDelegateToGeneratedFactory(bool enable) {
106     delegate_to_generated_factory_ = enable;
107   }
108 
109   // implements MessageFactory ---------------------------------------
110 
111   // Given a Descriptor, constructs the default (prototype) Message of that
112   // type.  You can then call that message's New() method to construct a
113   // mutable message of that type.
114   //
115   // Calling this method twice with the same Descriptor returns the same
116   // object.  The returned object remains property of the factory and will
117   // be destroyed when the factory is destroyed.  Also, any objects created
118   // by calling the prototype's New() method share some data with the
119   // prototype, so these must be destroyed before the DynamicMessageFactory
120   // is destroyed.
121   //
122   // The given descriptor must outlive the returned message, and hence must
123   // outlive the DynamicMessageFactory.
124   //
125   // The method is thread-safe.
126   const Message* GetPrototype(const Descriptor* type) override;
127 
128  private:
129   const DescriptorPool* pool_;
130   bool delegate_to_generated_factory_;
131 
132   struct TypeInfo;
133   std::unordered_map<const Descriptor*, const TypeInfo*> prototypes_;
134   mutable internal::WrappedMutex prototypes_mutex_;
135 
136   friend class DynamicMessage;
137   const Message* GetPrototypeNoLock(const Descriptor* type);
138 
139   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMessageFactory);
140 };
141 
142 // Helper for computing a sorted list of map entries via reflection.
143 class PROTOBUF_EXPORT DynamicMapSorter {
144  public:
Sort(const Message & message,int map_size,const Reflection * reflection,const FieldDescriptor * field)145   static std::vector<const Message*> Sort(const Message& message, int map_size,
146                                           const Reflection* reflection,
147                                           const FieldDescriptor* field) {
148     std::vector<const Message*> result;
149     result.reserve(map_size);
150     RepeatedFieldRef<Message> map_field =
151         reflection->GetRepeatedFieldRef<Message>(message, field);
152     for (auto it = map_field.begin(); it != map_field.end(); ++it) {
153       result.push_back(&*it);
154     }
155     MapEntryMessageComparator comparator(field->message_type());
156     std::stable_sort(result.begin(), result.end(), comparator);
157     // Complain if the keys aren't in ascending order.
158 #ifndef NDEBUG
159     for (size_t j = 1; j < static_cast<size_t>(map_size); j++) {
160       if (!comparator(result[j - 1], result[j])) {
161         GOOGLE_LOG(ERROR) << (comparator(result[j], result[j - 1])
162                            ? "internal error in map key sorting"
163                            : "map keys are not unique");
164       }
165     }
166 #endif
167     return result;
168   }
169 
170  private:
171   class PROTOBUF_EXPORT MapEntryMessageComparator {
172    public:
MapEntryMessageComparator(const Descriptor * descriptor)173     explicit MapEntryMessageComparator(const Descriptor* descriptor)
174         : field_(descriptor->field(0)) {}
175 
operator()176     bool operator()(const Message* a, const Message* b) {
177       const Reflection* reflection = a->GetReflection();
178       switch (field_->cpp_type()) {
179         case FieldDescriptor::CPPTYPE_BOOL: {
180           bool first = reflection->GetBool(*a, field_);
181           bool second = reflection->GetBool(*b, field_);
182           return first < second;
183         }
184         case FieldDescriptor::CPPTYPE_INT32: {
185           int32 first = reflection->GetInt32(*a, field_);
186           int32 second = reflection->GetInt32(*b, field_);
187           return first < second;
188         }
189         case FieldDescriptor::CPPTYPE_INT64: {
190           int64 first = reflection->GetInt64(*a, field_);
191           int64 second = reflection->GetInt64(*b, field_);
192           return first < second;
193         }
194         case FieldDescriptor::CPPTYPE_UINT32: {
195           uint32 first = reflection->GetUInt32(*a, field_);
196           uint32 second = reflection->GetUInt32(*b, field_);
197           return first < second;
198         }
199         case FieldDescriptor::CPPTYPE_UINT64: {
200           uint64 first = reflection->GetUInt64(*a, field_);
201           uint64 second = reflection->GetUInt64(*b, field_);
202           return first < second;
203         }
204         case FieldDescriptor::CPPTYPE_STRING: {
205           std::string first = reflection->GetString(*a, field_);
206           std::string second = reflection->GetString(*b, field_);
207           return first < second;
208         }
209         default:
210           GOOGLE_LOG(DFATAL) << "Invalid key for map field.";
211           return true;
212       }
213     }
214 
215    private:
216     const FieldDescriptor* field_;
217   };
218 };
219 
220 }  // namespace protobuf
221 }  // namespace google
222 
223 #include <google/protobuf/port_undef.inc>
224 
225 #endif  // GOOGLE_PROTOBUF_DYNAMIC_MESSAGE_H__
226