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 #include <algorithm>
36 #include <set>
37 
38 #include <google/protobuf/stubs/logging.h>
39 #include <google/protobuf/stubs/common.h>
40 #include <google/protobuf/descriptor.pb.h>
41 #include <google/protobuf/descriptor.h>
42 #include <google/protobuf/extension_set.h>
43 #include <google/protobuf/generated_message_reflection.h>
44 #include <google/protobuf/generated_message_util.h>
45 #include <google/protobuf/map_field.h>
46 #include <google/protobuf/repeated_field.h>
47 
48 
49 #define GOOGLE_PROTOBUF_HAS_ONEOF
50 
51 namespace google {
52 namespace protobuf {
53 namespace internal {
54 
55 namespace {
IsMapFieldInApi(const FieldDescriptor * field)56 bool IsMapFieldInApi(const FieldDescriptor* field) {
57   return field->is_map();
58 }
59 }  // anonymous namespace
60 
ParseNamedEnum(const EnumDescriptor * descriptor,const string & name,int * value)61 bool ParseNamedEnum(const EnumDescriptor* descriptor,
62                     const string& name,
63                     int* value) {
64   const EnumValueDescriptor* d = descriptor->FindValueByName(name);
65   if (d == NULL) return false;
66   *value = d->number();
67   return true;
68 }
69 
NameOfEnum(const EnumDescriptor * descriptor,int value)70 const string& NameOfEnum(const EnumDescriptor* descriptor, int value) {
71   const EnumValueDescriptor* d = descriptor->FindValueByNumber(value);
72   return (d == NULL ? GetEmptyString() : d->name());
73 }
74 
75 namespace {
SupportsArenas(const Descriptor * descriptor)76 inline bool SupportsArenas(const Descriptor* descriptor) {
77   return descriptor->file()->options().cc_enable_arenas();
78 }
79 }  // anonymous namespace
80 
81 // ===================================================================
82 // Helpers for reporting usage errors (e.g. trying to use GetInt32() on
83 // a string field).
84 
85 namespace {
86 
ReportReflectionUsageError(const Descriptor * descriptor,const FieldDescriptor * field,const char * method,const char * description)87 void ReportReflectionUsageError(
88     const Descriptor* descriptor, const FieldDescriptor* field,
89     const char* method, const char* description) {
90   GOOGLE_LOG(FATAL)
91     << "Protocol Buffer reflection usage error:\n"
92        "  Method      : google::protobuf::Reflection::" << method << "\n"
93        "  Message type: " << descriptor->full_name() << "\n"
94        "  Field       : " << field->full_name() << "\n"
95        "  Problem     : " << description;
96 }
97 
98 const char* cpptype_names_[FieldDescriptor::MAX_CPPTYPE + 1] = {
99   "INVALID_CPPTYPE",
100   "CPPTYPE_INT32",
101   "CPPTYPE_INT64",
102   "CPPTYPE_UINT32",
103   "CPPTYPE_UINT64",
104   "CPPTYPE_DOUBLE",
105   "CPPTYPE_FLOAT",
106   "CPPTYPE_BOOL",
107   "CPPTYPE_ENUM",
108   "CPPTYPE_STRING",
109   "CPPTYPE_MESSAGE"
110 };
111 
ReportReflectionUsageTypeError(const Descriptor * descriptor,const FieldDescriptor * field,const char * method,FieldDescriptor::CppType expected_type)112 static void ReportReflectionUsageTypeError(
113     const Descriptor* descriptor, const FieldDescriptor* field,
114     const char* method,
115     FieldDescriptor::CppType expected_type) {
116   GOOGLE_LOG(FATAL)
117     << "Protocol Buffer reflection usage error:\n"
118        "  Method      : google::protobuf::Reflection::" << method << "\n"
119        "  Message type: " << descriptor->full_name() << "\n"
120        "  Field       : " << field->full_name() << "\n"
121        "  Problem     : Field is not the right type for this message:\n"
122        "    Expected  : " << cpptype_names_[expected_type] << "\n"
123        "    Field type: " << cpptype_names_[field->cpp_type()];
124 }
125 
ReportReflectionUsageEnumTypeError(const Descriptor * descriptor,const FieldDescriptor * field,const char * method,const EnumValueDescriptor * value)126 static void ReportReflectionUsageEnumTypeError(
127     const Descriptor* descriptor, const FieldDescriptor* field,
128     const char* method, const EnumValueDescriptor* value) {
129   GOOGLE_LOG(FATAL)
130     << "Protocol Buffer reflection usage error:\n"
131        "  Method      : google::protobuf::Reflection::" << method << "\n"
132        "  Message type: " << descriptor->full_name() << "\n"
133        "  Field       : " << field->full_name() << "\n"
134        "  Problem     : Enum value did not match field type:\n"
135        "    Expected  : " << field->enum_type()->full_name() << "\n"
136        "    Actual    : " << value->full_name();
137 }
138 
139 #define USAGE_CHECK(CONDITION, METHOD, ERROR_DESCRIPTION)                      \
140   if (!(CONDITION))                                                            \
141     ReportReflectionUsageError(descriptor_, field, #METHOD, ERROR_DESCRIPTION)
142 #define USAGE_CHECK_EQ(A, B, METHOD, ERROR_DESCRIPTION)                        \
143   USAGE_CHECK((A) == (B), METHOD, ERROR_DESCRIPTION)
144 #define USAGE_CHECK_NE(A, B, METHOD, ERROR_DESCRIPTION)                        \
145   USAGE_CHECK((A) != (B), METHOD, ERROR_DESCRIPTION)
146 
147 #define USAGE_CHECK_TYPE(METHOD, CPPTYPE)                                      \
148   if (field->cpp_type() != FieldDescriptor::CPPTYPE_##CPPTYPE)                 \
149     ReportReflectionUsageTypeError(descriptor_, field, #METHOD,                \
150                                    FieldDescriptor::CPPTYPE_##CPPTYPE)
151 
152 #define USAGE_CHECK_ENUM_VALUE(METHOD)                                         \
153   if (value->type() != field->enum_type())                                     \
154     ReportReflectionUsageEnumTypeError(descriptor_, field, #METHOD, value)
155 
156 #define USAGE_CHECK_MESSAGE_TYPE(METHOD)                                       \
157   USAGE_CHECK_EQ(field->containing_type(), descriptor_,                        \
158                  METHOD, "Field does not match message type.");
159 #define USAGE_CHECK_SINGULAR(METHOD)                                           \
160   USAGE_CHECK_NE(field->label(), FieldDescriptor::LABEL_REPEATED, METHOD,      \
161                  "Field is repeated; the method requires a singular field.")
162 #define USAGE_CHECK_REPEATED(METHOD)                                           \
163   USAGE_CHECK_EQ(field->label(), FieldDescriptor::LABEL_REPEATED, METHOD,      \
164                  "Field is singular; the method requires a repeated field.")
165 
166 #define USAGE_CHECK_ALL(METHOD, LABEL, CPPTYPE)                       \
167     USAGE_CHECK_MESSAGE_TYPE(METHOD);                                 \
168     USAGE_CHECK_##LABEL(METHOD);                                      \
169     USAGE_CHECK_TYPE(METHOD, CPPTYPE)
170 
171 }  // namespace
172 
173 // ===================================================================
174 
GeneratedMessageReflection(const Descriptor * descriptor,const Message * default_instance,const int offsets[],int has_bits_offset,int unknown_fields_offset,int extensions_offset,const DescriptorPool * descriptor_pool,MessageFactory * factory,int object_size,int arena_offset,int is_default_instance_offset)175 GeneratedMessageReflection::GeneratedMessageReflection(
176     const Descriptor* descriptor,
177     const Message* default_instance,
178     const int offsets[],
179     int has_bits_offset,
180     int unknown_fields_offset,
181     int extensions_offset,
182     const DescriptorPool* descriptor_pool,
183     MessageFactory* factory,
184     int object_size,
185     int arena_offset,
186     int is_default_instance_offset)
187   : descriptor_       (descriptor),
188     default_instance_ (default_instance),
189     offsets_          (offsets),
190     has_bits_offset_  (has_bits_offset),
191     unknown_fields_offset_(unknown_fields_offset),
192     extensions_offset_(extensions_offset),
193     arena_offset_     (arena_offset),
194     is_default_instance_offset_(is_default_instance_offset),
195     object_size_      (object_size),
196     descriptor_pool_  ((descriptor_pool == NULL) ?
197                          DescriptorPool::generated_pool() :
198                          descriptor_pool),
199     message_factory_  (factory) {
200 }
201 
GeneratedMessageReflection(const Descriptor * descriptor,const Message * default_instance,const int offsets[],int has_bits_offset,int unknown_fields_offset,int extensions_offset,const void * default_oneof_instance,int oneof_case_offset,const DescriptorPool * descriptor_pool,MessageFactory * factory,int object_size,int arena_offset,int is_default_instance_offset)202 GeneratedMessageReflection::GeneratedMessageReflection(
203     const Descriptor* descriptor,
204     const Message* default_instance,
205     const int offsets[],
206     int has_bits_offset,
207     int unknown_fields_offset,
208     int extensions_offset,
209     const void* default_oneof_instance,
210     int oneof_case_offset,
211     const DescriptorPool* descriptor_pool,
212     MessageFactory* factory,
213     int object_size,
214     int arena_offset,
215     int is_default_instance_offset)
216   : descriptor_       (descriptor),
217     default_instance_ (default_instance),
218     default_oneof_instance_ (default_oneof_instance),
219     offsets_          (offsets),
220     has_bits_offset_  (has_bits_offset),
221     oneof_case_offset_(oneof_case_offset),
222     unknown_fields_offset_(unknown_fields_offset),
223     extensions_offset_(extensions_offset),
224     arena_offset_     (arena_offset),
225     is_default_instance_offset_(is_default_instance_offset),
226     object_size_      (object_size),
227     descriptor_pool_  ((descriptor_pool == NULL) ?
228                          DescriptorPool::generated_pool() :
229                          descriptor_pool),
230     message_factory_  (factory) {
231 }
232 
~GeneratedMessageReflection()233 GeneratedMessageReflection::~GeneratedMessageReflection() {}
234 
235 namespace {
236 UnknownFieldSet* empty_unknown_field_set_ = NULL;
237 GOOGLE_PROTOBUF_DECLARE_ONCE(empty_unknown_field_set_once_);
238 
DeleteEmptyUnknownFieldSet()239 void DeleteEmptyUnknownFieldSet() {
240   delete empty_unknown_field_set_;
241   empty_unknown_field_set_ = NULL;
242 }
243 
InitEmptyUnknownFieldSet()244 void InitEmptyUnknownFieldSet() {
245   empty_unknown_field_set_ = new UnknownFieldSet;
246   internal::OnShutdown(&DeleteEmptyUnknownFieldSet);
247 }
248 
GetEmptyUnknownFieldSet()249 const UnknownFieldSet& GetEmptyUnknownFieldSet() {
250   ::google::protobuf::GoogleOnceInit(&empty_unknown_field_set_once_, &InitEmptyUnknownFieldSet);
251   return *empty_unknown_field_set_;
252 }
253 }  // namespace
254 
GetUnknownFields(const Message & message) const255 const UnknownFieldSet& GeneratedMessageReflection::GetUnknownFields(
256     const Message& message) const {
257   if (descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
258     return GetEmptyUnknownFieldSet();
259   }
260   if (unknown_fields_offset_ == kUnknownFieldSetInMetadata) {
261     return GetInternalMetadataWithArena(message).unknown_fields();
262   }
263   const void* ptr = reinterpret_cast<const uint8*>(&message) +
264                     unknown_fields_offset_;
265   return *reinterpret_cast<const UnknownFieldSet*>(ptr);
266 }
267 
MutableUnknownFields(Message * message) const268 UnknownFieldSet* GeneratedMessageReflection::MutableUnknownFields(
269     Message* message) const {
270   if (unknown_fields_offset_ == kUnknownFieldSetInMetadata) {
271     return MutableInternalMetadataWithArena(message)->
272         mutable_unknown_fields();
273   }
274   void* ptr = reinterpret_cast<uint8*>(message) + unknown_fields_offset_;
275   return reinterpret_cast<UnknownFieldSet*>(ptr);
276 }
277 
SpaceUsed(const Message & message) const278 int GeneratedMessageReflection::SpaceUsed(const Message& message) const {
279   // object_size_ already includes the in-memory representation of each field
280   // in the message, so we only need to account for additional memory used by
281   // the fields.
282   int total_size = object_size_;
283 
284   total_size += GetUnknownFields(message).SpaceUsedExcludingSelf();
285 
286   if (extensions_offset_ != -1) {
287     total_size += GetExtensionSet(message).SpaceUsedExcludingSelf();
288   }
289 
290   for (int i = 0; i < descriptor_->field_count(); i++) {
291     const FieldDescriptor* field = descriptor_->field(i);
292 
293     if (field->is_repeated()) {
294       switch (field->cpp_type()) {
295 #define HANDLE_TYPE(UPPERCASE, LOWERCASE)                                     \
296         case FieldDescriptor::CPPTYPE_##UPPERCASE :                           \
297           total_size += GetRaw<RepeatedField<LOWERCASE> >(message, field)     \
298                           .SpaceUsedExcludingSelf();                          \
299           break
300 
301         HANDLE_TYPE( INT32,  int32);
302         HANDLE_TYPE( INT64,  int64);
303         HANDLE_TYPE(UINT32, uint32);
304         HANDLE_TYPE(UINT64, uint64);
305         HANDLE_TYPE(DOUBLE, double);
306         HANDLE_TYPE( FLOAT,  float);
307         HANDLE_TYPE(  BOOL,   bool);
308         HANDLE_TYPE(  ENUM,    int);
309 #undef HANDLE_TYPE
310 
311         case FieldDescriptor::CPPTYPE_STRING:
312           switch (field->options().ctype()) {
313             default:  // TODO(kenton):  Support other string reps.
314             case FieldOptions::STRING:
315               total_size += GetRaw<RepeatedPtrField<string> >(message, field)
316                               .SpaceUsedExcludingSelf();
317               break;
318           }
319           break;
320 
321         case FieldDescriptor::CPPTYPE_MESSAGE:
322           if (IsMapFieldInApi(field)) {
323             total_size +=
324                 GetRaw<MapFieldBase>(message, field).SpaceUsedExcludingSelf();
325           } else {
326             // We don't know which subclass of RepeatedPtrFieldBase the type is,
327             // so we use RepeatedPtrFieldBase directly.
328             total_size +=
329                 GetRaw<RepeatedPtrFieldBase>(message, field)
330                   .SpaceUsedExcludingSelf<GenericTypeHandler<Message> >();
331           }
332 
333           break;
334       }
335     } else {
336       if (field->containing_oneof() && !HasOneofField(message, field)) {
337         continue;
338       }
339       switch (field->cpp_type()) {
340         case FieldDescriptor::CPPTYPE_INT32 :
341         case FieldDescriptor::CPPTYPE_INT64 :
342         case FieldDescriptor::CPPTYPE_UINT32:
343         case FieldDescriptor::CPPTYPE_UINT64:
344         case FieldDescriptor::CPPTYPE_DOUBLE:
345         case FieldDescriptor::CPPTYPE_FLOAT :
346         case FieldDescriptor::CPPTYPE_BOOL  :
347         case FieldDescriptor::CPPTYPE_ENUM  :
348           // Field is inline, so we've already counted it.
349           break;
350 
351         case FieldDescriptor::CPPTYPE_STRING: {
352           switch (field->options().ctype()) {
353             default:  // TODO(kenton):  Support other string reps.
354             case FieldOptions::STRING: {
355               // Initially, the string points to the default value stored in
356               // the prototype. Only count the string if it has been changed
357               // from the default value.
358               const string* default_ptr =
359                   &DefaultRaw<ArenaStringPtr>(field).Get(NULL);
360               const string* ptr =
361                   &GetField<ArenaStringPtr>(message, field).Get(default_ptr);
362 
363               if (ptr != default_ptr) {
364                 // string fields are represented by just a pointer, so also
365                 // include sizeof(string) as well.
366                 total_size += sizeof(*ptr) + StringSpaceUsedExcludingSelf(*ptr);
367               }
368               break;
369             }
370           }
371           break;
372         }
373 
374         case FieldDescriptor::CPPTYPE_MESSAGE:
375           if (&message == default_instance_) {
376             // For singular fields, the prototype just stores a pointer to the
377             // external type's prototype, so there is no extra memory usage.
378           } else {
379             const Message* sub_message = GetRaw<const Message*>(message, field);
380             if (sub_message != NULL) {
381               total_size += sub_message->SpaceUsed();
382             }
383           }
384           break;
385       }
386     }
387   }
388 
389   return total_size;
390 }
391 
SwapField(Message * message1,Message * message2,const FieldDescriptor * field) const392 void GeneratedMessageReflection::SwapField(
393     Message* message1,
394     Message* message2,
395     const FieldDescriptor* field) const {
396   if (field->is_repeated()) {
397     switch (field->cpp_type()) {
398 #define SWAP_ARRAYS(CPPTYPE, TYPE)                                      \
399       case FieldDescriptor::CPPTYPE_##CPPTYPE:                          \
400         MutableRaw<RepeatedField<TYPE> >(message1, field)->Swap(        \
401             MutableRaw<RepeatedField<TYPE> >(message2, field));         \
402         break;
403 
404       SWAP_ARRAYS(INT32 , int32 );
405       SWAP_ARRAYS(INT64 , int64 );
406       SWAP_ARRAYS(UINT32, uint32);
407       SWAP_ARRAYS(UINT64, uint64);
408       SWAP_ARRAYS(FLOAT , float );
409       SWAP_ARRAYS(DOUBLE, double);
410       SWAP_ARRAYS(BOOL  , bool  );
411       SWAP_ARRAYS(ENUM  , int   );
412 #undef SWAP_ARRAYS
413 
414       case FieldDescriptor::CPPTYPE_STRING:
415         switch (field->options().ctype()) {
416           default:  // TODO(kenton):  Support other string reps.
417           case FieldOptions::STRING:
418             MutableRaw<RepeatedPtrFieldBase>(message1, field)->
419                 Swap<GenericTypeHandler<string> >(
420                     MutableRaw<RepeatedPtrFieldBase>(message2, field));
421             break;
422         }
423         break;
424       case FieldDescriptor::CPPTYPE_MESSAGE:
425         if (IsMapFieldInApi(field)) {
426           MutableRaw<MapFieldBase>(message1, field)->
427             MutableRepeatedField()->
428               Swap<GenericTypeHandler<google::protobuf::Message> >(
429                 MutableRaw<MapFieldBase>(message2, field)->
430                   MutableRepeatedField());
431         } else {
432           MutableRaw<RepeatedPtrFieldBase>(message1, field)->
433             Swap<GenericTypeHandler<google::protobuf::Message> >(
434               MutableRaw<RepeatedPtrFieldBase>(message2, field));
435         }
436         break;
437 
438       default:
439         GOOGLE_LOG(FATAL) << "Unimplemented type: " << field->cpp_type();
440     }
441   } else {
442     switch (field->cpp_type()) {
443 #define SWAP_VALUES(CPPTYPE, TYPE)                                      \
444       case FieldDescriptor::CPPTYPE_##CPPTYPE:                          \
445         std::swap(*MutableRaw<TYPE>(message1, field),                   \
446                   *MutableRaw<TYPE>(message2, field));                  \
447         break;
448 
449       SWAP_VALUES(INT32 , int32 );
450       SWAP_VALUES(INT64 , int64 );
451       SWAP_VALUES(UINT32, uint32);
452       SWAP_VALUES(UINT64, uint64);
453       SWAP_VALUES(FLOAT , float );
454       SWAP_VALUES(DOUBLE, double);
455       SWAP_VALUES(BOOL  , bool  );
456       SWAP_VALUES(ENUM  , int   );
457 #undef SWAP_VALUES
458       case FieldDescriptor::CPPTYPE_MESSAGE:
459         if (GetArena(message1) == GetArena(message2)) {
460           std::swap(*MutableRaw<Message*>(message1, field),
461                     *MutableRaw<Message*>(message2, field));
462         } else {
463           Message** sub_msg1 = MutableRaw<Message*>(message1, field);
464           Message** sub_msg2 = MutableRaw<Message*>(message2, field);
465           if (*sub_msg1 == NULL && *sub_msg2 == NULL) break;
466           if (*sub_msg1 && *sub_msg2) {
467             (*sub_msg1)->GetReflection()->Swap(*sub_msg1, *sub_msg2);
468             break;
469           }
470           if (*sub_msg1 == NULL) {
471             *sub_msg1 = (*sub_msg2)->New(message1->GetArena());
472             (*sub_msg1)->CopyFrom(**sub_msg2);
473             ClearField(message2, field);
474           } else {
475             *sub_msg2 = (*sub_msg1)->New(message2->GetArena());
476             (*sub_msg2)->CopyFrom(**sub_msg1);
477             ClearField(message1, field);
478           }
479         }
480         break;
481 
482       case FieldDescriptor::CPPTYPE_STRING:
483         switch (field->options().ctype()) {
484           default:  // TODO(kenton):  Support other string reps.
485           case FieldOptions::STRING:
486             {
487               Arena* arena1 = GetArena(message1);
488               Arena* arena2 = GetArena(message2);
489               ArenaStringPtr* string1 =
490                   MutableRaw<ArenaStringPtr>(message1, field);
491               ArenaStringPtr* string2 =
492                   MutableRaw<ArenaStringPtr>(message2, field);
493               if (arena1 == arena2) {
494                 string1->Swap(string2);
495               } else {
496                 const string* default_ptr =
497                     &DefaultRaw<ArenaStringPtr>(field).Get(NULL);
498                 const string temp = string1->Get(default_ptr);
499                 string1->Set(default_ptr, string2->Get(default_ptr), arena1);
500                 string2->Set(default_ptr, temp, arena2);
501               }
502             }
503             break;
504         }
505         break;
506 
507       default:
508         GOOGLE_LOG(FATAL) << "Unimplemented type: " << field->cpp_type();
509     }
510   }
511 }
512 
SwapOneofField(Message * message1,Message * message2,const OneofDescriptor * oneof_descriptor) const513 void GeneratedMessageReflection::SwapOneofField(
514     Message* message1,
515     Message* message2,
516     const OneofDescriptor* oneof_descriptor) const {
517   uint32 oneof_case1 = GetOneofCase(*message1, oneof_descriptor);
518   uint32 oneof_case2 = GetOneofCase(*message2, oneof_descriptor);
519 
520   int32 temp_int32;
521   int64 temp_int64;
522   uint32 temp_uint32;
523   uint64 temp_uint64;
524   float temp_float;
525   double temp_double;
526   bool temp_bool;
527   int temp_int;
528   Message* temp_message = NULL;
529   string temp_string;
530 
531   // Stores message1's oneof field to a temp variable.
532   const FieldDescriptor* field1 = NULL;
533   if (oneof_case1 > 0) {
534     field1 = descriptor_->FindFieldByNumber(oneof_case1);
535     //oneof_descriptor->field(oneof_case1);
536     switch (field1->cpp_type()) {
537 #define GET_TEMP_VALUE(CPPTYPE, TYPE)                                   \
538       case FieldDescriptor::CPPTYPE_##CPPTYPE:                          \
539         temp_##TYPE = GetField<TYPE>(*message1, field1);                \
540         break;
541 
542       GET_TEMP_VALUE(INT32 , int32 );
543       GET_TEMP_VALUE(INT64 , int64 );
544       GET_TEMP_VALUE(UINT32, uint32);
545       GET_TEMP_VALUE(UINT64, uint64);
546       GET_TEMP_VALUE(FLOAT , float );
547       GET_TEMP_VALUE(DOUBLE, double);
548       GET_TEMP_VALUE(BOOL  , bool  );
549       GET_TEMP_VALUE(ENUM  , int   );
550 #undef GET_TEMP_VALUE
551       case FieldDescriptor::CPPTYPE_MESSAGE:
552         temp_message = ReleaseMessage(message1, field1);
553         break;
554 
555       case FieldDescriptor::CPPTYPE_STRING:
556         temp_string = GetString(*message1, field1);
557         break;
558 
559       default:
560         GOOGLE_LOG(FATAL) << "Unimplemented type: " << field1->cpp_type();
561     }
562   }
563 
564   // Sets message1's oneof field from the message2's oneof field.
565   if (oneof_case2 > 0) {
566     const FieldDescriptor* field2 =
567         descriptor_->FindFieldByNumber(oneof_case2);
568     switch (field2->cpp_type()) {
569 #define SET_ONEOF_VALUE1(CPPTYPE, TYPE)                                 \
570       case FieldDescriptor::CPPTYPE_##CPPTYPE:                          \
571         SetField<TYPE>(message1, field2, GetField<TYPE>(*message2, field2)); \
572         break;
573 
574       SET_ONEOF_VALUE1(INT32 , int32 );
575       SET_ONEOF_VALUE1(INT64 , int64 );
576       SET_ONEOF_VALUE1(UINT32, uint32);
577       SET_ONEOF_VALUE1(UINT64, uint64);
578       SET_ONEOF_VALUE1(FLOAT , float );
579       SET_ONEOF_VALUE1(DOUBLE, double);
580       SET_ONEOF_VALUE1(BOOL  , bool  );
581       SET_ONEOF_VALUE1(ENUM  , int   );
582 #undef SET_ONEOF_VALUE1
583       case FieldDescriptor::CPPTYPE_MESSAGE:
584         SetAllocatedMessage(message1,
585                             ReleaseMessage(message2, field2),
586                             field2);
587         break;
588 
589       case FieldDescriptor::CPPTYPE_STRING:
590         SetString(message1, field2, GetString(*message2, field2));
591         break;
592 
593       default:
594         GOOGLE_LOG(FATAL) << "Unimplemented type: " << field2->cpp_type();
595     }
596   } else {
597     ClearOneof(message1, oneof_descriptor);
598   }
599 
600   // Sets message2's oneof field from the temp variable.
601   if (oneof_case1 > 0) {
602     switch (field1->cpp_type()) {
603 #define SET_ONEOF_VALUE2(CPPTYPE, TYPE)                                 \
604       case FieldDescriptor::CPPTYPE_##CPPTYPE:                          \
605         SetField<TYPE>(message2, field1, temp_##TYPE);                  \
606         break;
607 
608       SET_ONEOF_VALUE2(INT32 , int32 );
609       SET_ONEOF_VALUE2(INT64 , int64 );
610       SET_ONEOF_VALUE2(UINT32, uint32);
611       SET_ONEOF_VALUE2(UINT64, uint64);
612       SET_ONEOF_VALUE2(FLOAT , float );
613       SET_ONEOF_VALUE2(DOUBLE, double);
614       SET_ONEOF_VALUE2(BOOL  , bool  );
615       SET_ONEOF_VALUE2(ENUM  , int   );
616 #undef SET_ONEOF_VALUE2
617       case FieldDescriptor::CPPTYPE_MESSAGE:
618         SetAllocatedMessage(message2, temp_message, field1);
619         break;
620 
621       case FieldDescriptor::CPPTYPE_STRING:
622         SetString(message2, field1, temp_string);
623         break;
624 
625       default:
626         GOOGLE_LOG(FATAL) << "Unimplemented type: " << field1->cpp_type();
627     }
628   } else {
629     ClearOneof(message2, oneof_descriptor);
630   }
631 }
632 
Swap(Message * message1,Message * message2) const633 void GeneratedMessageReflection::Swap(
634     Message* message1,
635     Message* message2) const {
636   if (message1 == message2) return;
637 
638   // TODO(kenton):  Other Reflection methods should probably check this too.
639   GOOGLE_CHECK_EQ(message1->GetReflection(), this)
640     << "First argument to Swap() (of type \""
641     << message1->GetDescriptor()->full_name()
642     << "\") is not compatible with this reflection object (which is for type \""
643     << descriptor_->full_name()
644     << "\").  Note that the exact same class is required; not just the same "
645        "descriptor.";
646   GOOGLE_CHECK_EQ(message2->GetReflection(), this)
647     << "Second argument to Swap() (of type \""
648     << message2->GetDescriptor()->full_name()
649     << "\") is not compatible with this reflection object (which is for type \""
650     << descriptor_->full_name()
651     << "\").  Note that the exact same class is required; not just the same "
652        "descriptor.";
653 
654   // Check that both messages are in the same arena (or both on the heap). We
655   // need to copy all data if not, due to ownership semantics.
656   if (GetArena(message1) != GetArena(message2)) {
657     // Slow copy path.
658     // Use our arena as temp space, if available.
659     Message* temp = message1->New(GetArena(message1));
660     temp->MergeFrom(*message1);
661     message1->CopyFrom(*message2);
662     message2->CopyFrom(*temp);
663     if (GetArena(message1) == NULL) {
664       delete temp;
665     }
666     return;
667   }
668 
669   if (has_bits_offset_ != -1) {
670     uint32* has_bits1 = MutableHasBits(message1);
671     uint32* has_bits2 = MutableHasBits(message2);
672     int has_bits_size = (descriptor_->field_count() + 31) / 32;
673 
674     for (int i = 0; i < has_bits_size; i++) {
675       std::swap(has_bits1[i], has_bits2[i]);
676     }
677   }
678 
679   for (int i = 0; i < descriptor_->field_count(); i++) {
680     const FieldDescriptor* field = descriptor_->field(i);
681     if (!field->containing_oneof()) {
682       SwapField(message1, message2, field);
683     }
684   }
685 
686   for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
687     SwapOneofField(message1, message2, descriptor_->oneof_decl(i));
688   }
689 
690   if (extensions_offset_ != -1) {
691     MutableExtensionSet(message1)->Swap(MutableExtensionSet(message2));
692   }
693 
694   MutableUnknownFields(message1)->Swap(MutableUnknownFields(message2));
695 }
696 
SwapFields(Message * message1,Message * message2,const vector<const FieldDescriptor * > & fields) const697 void GeneratedMessageReflection::SwapFields(
698     Message* message1,
699     Message* message2,
700     const vector<const FieldDescriptor*>& fields) const {
701   if (message1 == message2) return;
702 
703   // TODO(kenton):  Other Reflection methods should probably check this too.
704   GOOGLE_CHECK_EQ(message1->GetReflection(), this)
705     << "First argument to SwapFields() (of type \""
706     << message1->GetDescriptor()->full_name()
707     << "\") is not compatible with this reflection object (which is for type \""
708     << descriptor_->full_name()
709     << "\").  Note that the exact same class is required; not just the same "
710        "descriptor.";
711   GOOGLE_CHECK_EQ(message2->GetReflection(), this)
712     << "Second argument to SwapFields() (of type \""
713     << message2->GetDescriptor()->full_name()
714     << "\") is not compatible with this reflection object (which is for type \""
715     << descriptor_->full_name()
716     << "\").  Note that the exact same class is required; not just the same "
717        "descriptor.";
718 
719   std::set<int> swapped_oneof;
720 
721   for (int i = 0; i < fields.size(); i++) {
722     const FieldDescriptor* field = fields[i];
723     if (field->is_extension()) {
724       MutableExtensionSet(message1)->SwapExtension(
725           MutableExtensionSet(message2),
726           field->number());
727     } else {
728       if (field->containing_oneof()) {
729         int oneof_index = field->containing_oneof()->index();
730         // Only swap the oneof field once.
731         if (swapped_oneof.find(oneof_index) != swapped_oneof.end()) {
732           continue;
733         }
734         swapped_oneof.insert(oneof_index);
735         SwapOneofField(message1, message2, field->containing_oneof());
736       } else {
737         // Swap has bit.
738         SwapBit(message1, message2, field);
739         // Swap field.
740         SwapField(message1, message2, field);
741       }
742     }
743   }
744 }
745 
746 // -------------------------------------------------------------------
747 
HasField(const Message & message,const FieldDescriptor * field) const748 bool GeneratedMessageReflection::HasField(const Message& message,
749                                           const FieldDescriptor* field) const {
750   USAGE_CHECK_MESSAGE_TYPE(HasField);
751   USAGE_CHECK_SINGULAR(HasField);
752 
753   if (field->is_extension()) {
754     return GetExtensionSet(message).Has(field->number());
755   } else {
756     if (field->containing_oneof()) {
757       return HasOneofField(message, field);
758     } else {
759       return HasBit(message, field);
760     }
761   }
762 }
763 
FieldSize(const Message & message,const FieldDescriptor * field) const764 int GeneratedMessageReflection::FieldSize(const Message& message,
765                                           const FieldDescriptor* field) const {
766   USAGE_CHECK_MESSAGE_TYPE(FieldSize);
767   USAGE_CHECK_REPEATED(FieldSize);
768 
769   if (field->is_extension()) {
770     return GetExtensionSet(message).ExtensionSize(field->number());
771   } else {
772     switch (field->cpp_type()) {
773 #define HANDLE_TYPE(UPPERCASE, LOWERCASE)                                     \
774       case FieldDescriptor::CPPTYPE_##UPPERCASE :                             \
775         return GetRaw<RepeatedField<LOWERCASE> >(message, field).size()
776 
777       HANDLE_TYPE( INT32,  int32);
778       HANDLE_TYPE( INT64,  int64);
779       HANDLE_TYPE(UINT32, uint32);
780       HANDLE_TYPE(UINT64, uint64);
781       HANDLE_TYPE(DOUBLE, double);
782       HANDLE_TYPE( FLOAT,  float);
783       HANDLE_TYPE(  BOOL,   bool);
784       HANDLE_TYPE(  ENUM,    int);
785 #undef HANDLE_TYPE
786 
787       case FieldDescriptor::CPPTYPE_STRING:
788       case FieldDescriptor::CPPTYPE_MESSAGE:
789         if (IsMapFieldInApi(field)) {
790           return GetRaw<MapFieldBase>(message, field).GetRepeatedField().size();
791         } else {
792           return GetRaw<RepeatedPtrFieldBase>(message, field).size();
793         }
794     }
795 
796     GOOGLE_LOG(FATAL) << "Can't get here.";
797     return 0;
798   }
799 }
800 
ClearField(Message * message,const FieldDescriptor * field) const801 void GeneratedMessageReflection::ClearField(
802     Message* message, const FieldDescriptor* field) const {
803   USAGE_CHECK_MESSAGE_TYPE(ClearField);
804 
805   if (field->is_extension()) {
806     MutableExtensionSet(message)->ClearExtension(field->number());
807   } else if (!field->is_repeated()) {
808     if (field->containing_oneof()) {
809       ClearOneofField(message, field);
810       return;
811     }
812 
813     if (HasBit(*message, field)) {
814       ClearBit(message, field);
815 
816       // We need to set the field back to its default value.
817       switch (field->cpp_type()) {
818 #define CLEAR_TYPE(CPPTYPE, TYPE)                                            \
819         case FieldDescriptor::CPPTYPE_##CPPTYPE:                             \
820           *MutableRaw<TYPE>(message, field) =                                \
821             field->default_value_##TYPE();                                   \
822           break;
823 
824         CLEAR_TYPE(INT32 , int32 );
825         CLEAR_TYPE(INT64 , int64 );
826         CLEAR_TYPE(UINT32, uint32);
827         CLEAR_TYPE(UINT64, uint64);
828         CLEAR_TYPE(FLOAT , float );
829         CLEAR_TYPE(DOUBLE, double);
830         CLEAR_TYPE(BOOL  , bool  );
831 #undef CLEAR_TYPE
832 
833         case FieldDescriptor::CPPTYPE_ENUM:
834           *MutableRaw<int>(message, field) =
835             field->default_value_enum()->number();
836           break;
837 
838         case FieldDescriptor::CPPTYPE_STRING: {
839           switch (field->options().ctype()) {
840             default:  // TODO(kenton):  Support other string reps.
841             case FieldOptions::STRING: {
842               const string* default_ptr =
843                   &DefaultRaw<ArenaStringPtr>(field).Get(NULL);
844               MutableRaw<ArenaStringPtr>(message, field)->Destroy(default_ptr,
845                   GetArena(message));
846               break;
847             }
848           }
849           break;
850         }
851 
852         case FieldDescriptor::CPPTYPE_MESSAGE:
853           if (has_bits_offset_ == -1) {
854             // Proto3 does not have has-bits and we need to set a message field
855             // to NULL in order to indicate its un-presence.
856             if (GetArena(message) == NULL) {
857               delete *MutableRaw<Message*>(message, field);
858             }
859             *MutableRaw<Message*>(message, field) = NULL;
860           } else {
861             (*MutableRaw<Message*>(message, field))->Clear();
862           }
863           break;
864       }
865     }
866   } else {
867     switch (field->cpp_type()) {
868 #define HANDLE_TYPE(UPPERCASE, LOWERCASE)                                     \
869       case FieldDescriptor::CPPTYPE_##UPPERCASE :                             \
870         MutableRaw<RepeatedField<LOWERCASE> >(message, field)->Clear();       \
871         break
872 
873       HANDLE_TYPE( INT32,  int32);
874       HANDLE_TYPE( INT64,  int64);
875       HANDLE_TYPE(UINT32, uint32);
876       HANDLE_TYPE(UINT64, uint64);
877       HANDLE_TYPE(DOUBLE, double);
878       HANDLE_TYPE( FLOAT,  float);
879       HANDLE_TYPE(  BOOL,   bool);
880       HANDLE_TYPE(  ENUM,    int);
881 #undef HANDLE_TYPE
882 
883       case FieldDescriptor::CPPTYPE_STRING: {
884         switch (field->options().ctype()) {
885           default:  // TODO(kenton):  Support other string reps.
886           case FieldOptions::STRING:
887             MutableRaw<RepeatedPtrField<string> >(message, field)->Clear();
888             break;
889         }
890         break;
891       }
892 
893       case FieldDescriptor::CPPTYPE_MESSAGE: {
894         if (IsMapFieldInApi(field)) {
895           MutableRaw<MapFieldBase>(message, field)
896               ->MutableRepeatedField()
897               ->Clear<GenericTypeHandler<Message> >();
898         } else {
899           // We don't know which subclass of RepeatedPtrFieldBase the type is,
900           // so we use RepeatedPtrFieldBase directly.
901           MutableRaw<RepeatedPtrFieldBase>(message, field)
902               ->Clear<GenericTypeHandler<Message> >();
903         }
904         break;
905       }
906     }
907   }
908 }
909 
RemoveLast(Message * message,const FieldDescriptor * field) const910 void GeneratedMessageReflection::RemoveLast(
911     Message* message,
912     const FieldDescriptor* field) const {
913   USAGE_CHECK_MESSAGE_TYPE(RemoveLast);
914   USAGE_CHECK_REPEATED(RemoveLast);
915 
916   if (field->is_extension()) {
917     MutableExtensionSet(message)->RemoveLast(field->number());
918   } else {
919     switch (field->cpp_type()) {
920 #define HANDLE_TYPE(UPPERCASE, LOWERCASE)                                     \
921       case FieldDescriptor::CPPTYPE_##UPPERCASE :                             \
922         MutableRaw<RepeatedField<LOWERCASE> >(message, field)->RemoveLast();  \
923         break
924 
925       HANDLE_TYPE( INT32,  int32);
926       HANDLE_TYPE( INT64,  int64);
927       HANDLE_TYPE(UINT32, uint32);
928       HANDLE_TYPE(UINT64, uint64);
929       HANDLE_TYPE(DOUBLE, double);
930       HANDLE_TYPE( FLOAT,  float);
931       HANDLE_TYPE(  BOOL,   bool);
932       HANDLE_TYPE(  ENUM,    int);
933 #undef HANDLE_TYPE
934 
935       case FieldDescriptor::CPPTYPE_STRING:
936         switch (field->options().ctype()) {
937           default:  // TODO(kenton):  Support other string reps.
938           case FieldOptions::STRING:
939             MutableRaw<RepeatedPtrField<string> >(message, field)->RemoveLast();
940             break;
941         }
942         break;
943 
944       case FieldDescriptor::CPPTYPE_MESSAGE:
945         if (IsMapFieldInApi(field)) {
946           MutableRaw<MapFieldBase>(message, field)
947               ->MutableRepeatedField()
948               ->RemoveLast<GenericTypeHandler<Message> >();
949         } else {
950           MutableRaw<RepeatedPtrFieldBase>(message, field)
951             ->RemoveLast<GenericTypeHandler<Message> >();
952         }
953         break;
954     }
955   }
956 }
957 
ReleaseLast(Message * message,const FieldDescriptor * field) const958 Message* GeneratedMessageReflection::ReleaseLast(
959     Message* message,
960     const FieldDescriptor* field) const {
961   USAGE_CHECK_ALL(ReleaseLast, REPEATED, MESSAGE);
962 
963   if (field->is_extension()) {
964     return static_cast<Message*>(
965         MutableExtensionSet(message)->ReleaseLast(field->number()));
966   } else {
967     if (IsMapFieldInApi(field)) {
968       return MutableRaw<MapFieldBase>(message, field)
969           ->MutableRepeatedField()
970           ->ReleaseLast<GenericTypeHandler<Message> >();
971     } else {
972       return MutableRaw<RepeatedPtrFieldBase>(message, field)
973         ->ReleaseLast<GenericTypeHandler<Message> >();
974     }
975   }
976 }
977 
SwapElements(Message * message,const FieldDescriptor * field,int index1,int index2) const978 void GeneratedMessageReflection::SwapElements(
979     Message* message,
980     const FieldDescriptor* field,
981     int index1,
982     int index2) const {
983   USAGE_CHECK_MESSAGE_TYPE(Swap);
984   USAGE_CHECK_REPEATED(Swap);
985 
986   if (field->is_extension()) {
987     MutableExtensionSet(message)->SwapElements(field->number(), index1, index2);
988   } else {
989     switch (field->cpp_type()) {
990 #define HANDLE_TYPE(UPPERCASE, LOWERCASE)                                     \
991       case FieldDescriptor::CPPTYPE_##UPPERCASE :                             \
992         MutableRaw<RepeatedField<LOWERCASE> >(message, field)                 \
993             ->SwapElements(index1, index2);                                   \
994         break
995 
996       HANDLE_TYPE( INT32,  int32);
997       HANDLE_TYPE( INT64,  int64);
998       HANDLE_TYPE(UINT32, uint32);
999       HANDLE_TYPE(UINT64, uint64);
1000       HANDLE_TYPE(DOUBLE, double);
1001       HANDLE_TYPE( FLOAT,  float);
1002       HANDLE_TYPE(  BOOL,   bool);
1003       HANDLE_TYPE(  ENUM,    int);
1004 #undef HANDLE_TYPE
1005 
1006       case FieldDescriptor::CPPTYPE_STRING:
1007       case FieldDescriptor::CPPTYPE_MESSAGE:
1008         if (IsMapFieldInApi(field)) {
1009           MutableRaw<MapFieldBase>(message, field)
1010               ->MutableRepeatedField()
1011               ->SwapElements(index1, index2);
1012         } else {
1013           MutableRaw<RepeatedPtrFieldBase>(message, field)
1014             ->SwapElements(index1, index2);
1015         }
1016         break;
1017     }
1018   }
1019 }
1020 
1021 namespace {
1022 // Comparison functor for sorting FieldDescriptors by field number.
1023 struct FieldNumberSorter {
operator ()google::protobuf::internal::__anon9873bf450511::FieldNumberSorter1024   bool operator()(const FieldDescriptor* left,
1025                   const FieldDescriptor* right) const {
1026     return left->number() < right->number();
1027   }
1028 };
1029 }  // namespace
1030 
ListFields(const Message & message,vector<const FieldDescriptor * > * output) const1031 void GeneratedMessageReflection::ListFields(
1032     const Message& message,
1033     vector<const FieldDescriptor*>* output) const {
1034   output->clear();
1035 
1036   // Optimization:  The default instance never has any fields set.
1037   if (&message == default_instance_) return;
1038 
1039   output->reserve(descriptor_->field_count());
1040   for (int i = 0; i < descriptor_->field_count(); i++) {
1041     const FieldDescriptor* field = descriptor_->field(i);
1042     if (field->is_repeated()) {
1043       if (FieldSize(message, field) > 0) {
1044         output->push_back(field);
1045       }
1046     } else {
1047       if (field->containing_oneof()) {
1048         if (HasOneofField(message, field)) {
1049           output->push_back(field);
1050         }
1051       } else if (HasBit(message, field)) {
1052         output->push_back(field);
1053       }
1054     }
1055   }
1056 
1057   if (extensions_offset_ != -1) {
1058     GetExtensionSet(message).AppendToList(descriptor_, descriptor_pool_,
1059                                           output);
1060   }
1061 
1062   // ListFields() must sort output by field number.
1063   std::sort(output->begin(), output->end(), FieldNumberSorter());
1064 }
1065 
1066 // -------------------------------------------------------------------
1067 
1068 #undef DEFINE_PRIMITIVE_ACCESSORS
1069 #define DEFINE_PRIMITIVE_ACCESSORS(TYPENAME, TYPE, PASSTYPE, CPPTYPE)        \
1070   PASSTYPE GeneratedMessageReflection::Get##TYPENAME(                        \
1071       const Message& message, const FieldDescriptor* field) const {          \
1072     USAGE_CHECK_ALL(Get##TYPENAME, SINGULAR, CPPTYPE);                       \
1073     if (field->is_extension()) {                                             \
1074       return GetExtensionSet(message).Get##TYPENAME(                         \
1075         field->number(), field->default_value_##PASSTYPE());                 \
1076     } else {                                                                 \
1077       return GetField<TYPE>(message, field);                                 \
1078     }                                                                        \
1079   }                                                                          \
1080                                                                              \
1081   void GeneratedMessageReflection::Set##TYPENAME(                            \
1082       Message* message, const FieldDescriptor* field,                        \
1083       PASSTYPE value) const {                                                \
1084     USAGE_CHECK_ALL(Set##TYPENAME, SINGULAR, CPPTYPE);                       \
1085     if (field->is_extension()) {                                             \
1086       return MutableExtensionSet(message)->Set##TYPENAME(                    \
1087         field->number(), field->type(), value, field);                       \
1088     } else {                                                                 \
1089       SetField<TYPE>(message, field, value);                                 \
1090     }                                                                        \
1091   }                                                                          \
1092                                                                              \
1093   PASSTYPE GeneratedMessageReflection::GetRepeated##TYPENAME(                \
1094       const Message& message,                                                \
1095       const FieldDescriptor* field, int index) const {                       \
1096     USAGE_CHECK_ALL(GetRepeated##TYPENAME, REPEATED, CPPTYPE);               \
1097     if (field->is_extension()) {                                             \
1098       return GetExtensionSet(message).GetRepeated##TYPENAME(                 \
1099         field->number(), index);                                             \
1100     } else {                                                                 \
1101       return GetRepeatedField<TYPE>(message, field, index);                  \
1102     }                                                                        \
1103   }                                                                          \
1104                                                                              \
1105   void GeneratedMessageReflection::SetRepeated##TYPENAME(                    \
1106       Message* message, const FieldDescriptor* field,                        \
1107       int index, PASSTYPE value) const {                                     \
1108     USAGE_CHECK_ALL(SetRepeated##TYPENAME, REPEATED, CPPTYPE);               \
1109     if (field->is_extension()) {                                             \
1110       MutableExtensionSet(message)->SetRepeated##TYPENAME(                   \
1111         field->number(), index, value);                                      \
1112     } else {                                                                 \
1113       SetRepeatedField<TYPE>(message, field, index, value);                  \
1114     }                                                                        \
1115   }                                                                          \
1116                                                                              \
1117   void GeneratedMessageReflection::Add##TYPENAME(                            \
1118       Message* message, const FieldDescriptor* field,                        \
1119       PASSTYPE value) const {                                                \
1120     USAGE_CHECK_ALL(Add##TYPENAME, REPEATED, CPPTYPE);                       \
1121     if (field->is_extension()) {                                             \
1122       MutableExtensionSet(message)->Add##TYPENAME(                           \
1123         field->number(), field->type(), field->options().packed(), value,    \
1124         field);                                                              \
1125     } else {                                                                 \
1126       AddField<TYPE>(message, field, value);                                 \
1127     }                                                                        \
1128   }
1129 
DEFINE_PRIMITIVE_ACCESSORS(Int32,int32,int32,INT32)1130 DEFINE_PRIMITIVE_ACCESSORS(Int32 , int32 , int32 , INT32 )
1131 DEFINE_PRIMITIVE_ACCESSORS(Int64 , int64 , int64 , INT64 )
1132 DEFINE_PRIMITIVE_ACCESSORS(UInt32, uint32, uint32, UINT32)
1133 DEFINE_PRIMITIVE_ACCESSORS(UInt64, uint64, uint64, UINT64)
1134 DEFINE_PRIMITIVE_ACCESSORS(Float , float , float , FLOAT )
1135 DEFINE_PRIMITIVE_ACCESSORS(Double, double, double, DOUBLE)
1136 DEFINE_PRIMITIVE_ACCESSORS(Bool  , bool  , bool  , BOOL  )
1137 #undef DEFINE_PRIMITIVE_ACCESSORS
1138 
1139 // -------------------------------------------------------------------
1140 
1141 string GeneratedMessageReflection::GetString(
1142     const Message& message, const FieldDescriptor* field) const {
1143   USAGE_CHECK_ALL(GetString, SINGULAR, STRING);
1144   if (field->is_extension()) {
1145     return GetExtensionSet(message).GetString(field->number(),
1146                                               field->default_value_string());
1147   } else {
1148     switch (field->options().ctype()) {
1149       default:  // TODO(kenton):  Support other string reps.
1150       case FieldOptions::STRING: {
1151         const string* default_ptr =
1152             &DefaultRaw<ArenaStringPtr>(field).Get(NULL);
1153         return GetField<ArenaStringPtr>(message, field).Get(default_ptr);
1154       }
1155     }
1156 
1157     GOOGLE_LOG(FATAL) << "Can't get here.";
1158     return GetEmptyString();  // Make compiler happy.
1159   }
1160 }
1161 
GetStringReference(const Message & message,const FieldDescriptor * field,string * scratch) const1162 const string& GeneratedMessageReflection::GetStringReference(
1163     const Message& message,
1164     const FieldDescriptor* field, string* scratch) const {
1165   USAGE_CHECK_ALL(GetStringReference, SINGULAR, STRING);
1166   if (field->is_extension()) {
1167     return GetExtensionSet(message).GetString(field->number(),
1168                                               field->default_value_string());
1169   } else {
1170     switch (field->options().ctype()) {
1171       default:  // TODO(kenton):  Support other string reps.
1172       case FieldOptions::STRING: {
1173         const string* default_ptr =
1174             &DefaultRaw<ArenaStringPtr>(field).Get(NULL);
1175         return GetField<ArenaStringPtr>(message, field).Get(default_ptr);
1176       }
1177     }
1178 
1179     GOOGLE_LOG(FATAL) << "Can't get here.";
1180     return GetEmptyString();  // Make compiler happy.
1181   }
1182 }
1183 
1184 
SetString(Message * message,const FieldDescriptor * field,const string & value) const1185 void GeneratedMessageReflection::SetString(
1186     Message* message, const FieldDescriptor* field,
1187     const string& value) const {
1188   USAGE_CHECK_ALL(SetString, SINGULAR, STRING);
1189   if (field->is_extension()) {
1190     return MutableExtensionSet(message)->SetString(field->number(),
1191                                                    field->type(), value, field);
1192   } else {
1193     switch (field->options().ctype()) {
1194       default:  // TODO(kenton):  Support other string reps.
1195       case FieldOptions::STRING: {
1196         const string* default_ptr =
1197             &DefaultRaw<ArenaStringPtr>(field).Get(NULL);
1198         if (field->containing_oneof() && !HasOneofField(*message, field)) {
1199           ClearOneof(message, field->containing_oneof());
1200           MutableField<ArenaStringPtr>(message, field)->UnsafeSetDefault(
1201               default_ptr);
1202         }
1203         MutableField<ArenaStringPtr>(message, field)->Set(default_ptr,
1204             value, GetArena(message));
1205         break;
1206       }
1207     }
1208   }
1209 }
1210 
1211 
GetRepeatedString(const Message & message,const FieldDescriptor * field,int index) const1212 string GeneratedMessageReflection::GetRepeatedString(
1213     const Message& message, const FieldDescriptor* field, int index) const {
1214   USAGE_CHECK_ALL(GetRepeatedString, REPEATED, STRING);
1215   if (field->is_extension()) {
1216     return GetExtensionSet(message).GetRepeatedString(field->number(), index);
1217   } else {
1218     switch (field->options().ctype()) {
1219       default:  // TODO(kenton):  Support other string reps.
1220       case FieldOptions::STRING:
1221         return GetRepeatedPtrField<string>(message, field, index);
1222     }
1223 
1224     GOOGLE_LOG(FATAL) << "Can't get here.";
1225     return GetEmptyString();  // Make compiler happy.
1226   }
1227 }
1228 
GetRepeatedStringReference(const Message & message,const FieldDescriptor * field,int index,string * scratch) const1229 const string& GeneratedMessageReflection::GetRepeatedStringReference(
1230     const Message& message, const FieldDescriptor* field,
1231     int index, string* scratch) const {
1232   USAGE_CHECK_ALL(GetRepeatedStringReference, REPEATED, STRING);
1233   if (field->is_extension()) {
1234     return GetExtensionSet(message).GetRepeatedString(field->number(), index);
1235   } else {
1236     switch (field->options().ctype()) {
1237       default:  // TODO(kenton):  Support other string reps.
1238       case FieldOptions::STRING:
1239         return GetRepeatedPtrField<string>(message, field, index);
1240     }
1241 
1242     GOOGLE_LOG(FATAL) << "Can't get here.";
1243     return GetEmptyString();  // Make compiler happy.
1244   }
1245 }
1246 
1247 
SetRepeatedString(Message * message,const FieldDescriptor * field,int index,const string & value) const1248 void GeneratedMessageReflection::SetRepeatedString(
1249     Message* message, const FieldDescriptor* field,
1250     int index, const string& value) const {
1251   USAGE_CHECK_ALL(SetRepeatedString, REPEATED, STRING);
1252   if (field->is_extension()) {
1253     MutableExtensionSet(message)->SetRepeatedString(
1254       field->number(), index, value);
1255   } else {
1256     switch (field->options().ctype()) {
1257       default:  // TODO(kenton):  Support other string reps.
1258       case FieldOptions::STRING:
1259         *MutableRepeatedField<string>(message, field, index) = value;
1260         break;
1261     }
1262   }
1263 }
1264 
1265 
AddString(Message * message,const FieldDescriptor * field,const string & value) const1266 void GeneratedMessageReflection::AddString(
1267     Message* message, const FieldDescriptor* field,
1268     const string& value) const {
1269   USAGE_CHECK_ALL(AddString, REPEATED, STRING);
1270   if (field->is_extension()) {
1271     MutableExtensionSet(message)->AddString(field->number(),
1272                                             field->type(), value, field);
1273   } else {
1274     switch (field->options().ctype()) {
1275       default:  // TODO(kenton):  Support other string reps.
1276       case FieldOptions::STRING:
1277         *AddField<string>(message, field) = value;
1278         break;
1279     }
1280   }
1281 }
1282 
1283 
1284 // -------------------------------------------------------------------
1285 
CreateUnknownEnumValues(const FileDescriptor * file)1286 inline bool CreateUnknownEnumValues(const FileDescriptor* file) {
1287   return file->syntax() == FileDescriptor::SYNTAX_PROTO3;
1288 }
1289 
GetEnum(const Message & message,const FieldDescriptor * field) const1290 const EnumValueDescriptor* GeneratedMessageReflection::GetEnum(
1291     const Message& message, const FieldDescriptor* field) const {
1292   // Usage checked by GetEnumValue.
1293   int value = GetEnumValue(message, field);
1294   return field->enum_type()->FindValueByNumberCreatingIfUnknown(value);
1295 }
1296 
GetEnumValue(const Message & message,const FieldDescriptor * field) const1297 int GeneratedMessageReflection::GetEnumValue(
1298     const Message& message, const FieldDescriptor* field) const {
1299   USAGE_CHECK_ALL(GetEnumValue, SINGULAR, ENUM);
1300 
1301   int32 value;
1302   if (field->is_extension()) {
1303     value = GetExtensionSet(message).GetEnum(
1304       field->number(), field->default_value_enum()->number());
1305   } else {
1306     value = GetField<int>(message, field);
1307   }
1308   return value;
1309 }
1310 
SetEnum(Message * message,const FieldDescriptor * field,const EnumValueDescriptor * value) const1311 void GeneratedMessageReflection::SetEnum(
1312     Message* message, const FieldDescriptor* field,
1313     const EnumValueDescriptor* value) const {
1314   // Usage checked by SetEnumValue.
1315   USAGE_CHECK_ENUM_VALUE(SetEnum);
1316   SetEnumValueInternal(message, field, value->number());
1317 }
1318 
SetEnumValue(Message * message,const FieldDescriptor * field,int value) const1319 void GeneratedMessageReflection::SetEnumValue(
1320     Message* message, const FieldDescriptor* field,
1321     int value) const {
1322   USAGE_CHECK_ALL(SetEnumValue, SINGULAR, ENUM);
1323   if (!CreateUnknownEnumValues(descriptor_->file())) {
1324     // Check that the value is valid if we don't support direct storage of
1325     // unknown enum values.
1326     const EnumValueDescriptor* value_desc =
1327         field->enum_type()->FindValueByNumber(value);
1328     if (value_desc == NULL) {
1329       GOOGLE_LOG(DFATAL) << "SetEnumValue accepts only valid integer values: value "
1330                   << value << " unexpected for field " << field->full_name();
1331       // In production builds, DFATAL will not terminate the program, so we have
1332       // to do something reasonable: just set the default value.
1333       value = field->default_value_enum()->number();
1334     }
1335   }
1336   SetEnumValueInternal(message, field, value);
1337 }
1338 
SetEnumValueInternal(Message * message,const FieldDescriptor * field,int value) const1339 void GeneratedMessageReflection::SetEnumValueInternal(
1340     Message* message, const FieldDescriptor* field,
1341     int value) const {
1342   if (field->is_extension()) {
1343     MutableExtensionSet(message)->SetEnum(field->number(), field->type(),
1344                                           value, field);
1345   } else {
1346     SetField<int>(message, field, value);
1347   }
1348 }
1349 
GetRepeatedEnum(const Message & message,const FieldDescriptor * field,int index) const1350 const EnumValueDescriptor* GeneratedMessageReflection::GetRepeatedEnum(
1351     const Message& message, const FieldDescriptor* field, int index) const {
1352   // Usage checked by GetRepeatedEnumValue.
1353   int value = GetRepeatedEnumValue(message, field, index);
1354   return field->enum_type()->FindValueByNumberCreatingIfUnknown(value);
1355 }
1356 
GetRepeatedEnumValue(const Message & message,const FieldDescriptor * field,int index) const1357 int GeneratedMessageReflection::GetRepeatedEnumValue(
1358     const Message& message, const FieldDescriptor* field, int index) const {
1359   USAGE_CHECK_ALL(GetRepeatedEnumValue, REPEATED, ENUM);
1360 
1361   int value;
1362   if (field->is_extension()) {
1363     value = GetExtensionSet(message).GetRepeatedEnum(field->number(), index);
1364   } else {
1365     value = GetRepeatedField<int>(message, field, index);
1366   }
1367   return value;
1368 }
1369 
SetRepeatedEnum(Message * message,const FieldDescriptor * field,int index,const EnumValueDescriptor * value) const1370 void GeneratedMessageReflection::SetRepeatedEnum(
1371     Message* message,
1372     const FieldDescriptor* field, int index,
1373     const EnumValueDescriptor* value) const {
1374   // Usage checked by SetRepeatedEnumValue.
1375   USAGE_CHECK_ENUM_VALUE(SetRepeatedEnum);
1376   SetRepeatedEnumValueInternal(message, field, index, value->number());
1377 }
1378 
SetRepeatedEnumValue(Message * message,const FieldDescriptor * field,int index,int value) const1379 void GeneratedMessageReflection::SetRepeatedEnumValue(
1380     Message* message,
1381     const FieldDescriptor* field, int index,
1382     int value) const {
1383   USAGE_CHECK_ALL(SetRepeatedEnum, REPEATED, ENUM);
1384   if (!CreateUnknownEnumValues(descriptor_->file())) {
1385     // Check that the value is valid if we don't support direct storage of
1386     // unknown enum values.
1387     const EnumValueDescriptor* value_desc =
1388         field->enum_type()->FindValueByNumber(value);
1389     if (value_desc == NULL) {
1390       GOOGLE_LOG(DFATAL) << "SetRepeatedEnumValue accepts only valid integer values: "
1391                   << "value " << value << " unexpected for field "
1392                   << field->full_name();
1393       // In production builds, DFATAL will not terminate the program, so we have
1394       // to do something reasonable: just set the default value.
1395       value = field->default_value_enum()->number();
1396     }
1397   }
1398   SetRepeatedEnumValueInternal(message, field, index, value);
1399 }
1400 
SetRepeatedEnumValueInternal(Message * message,const FieldDescriptor * field,int index,int value) const1401 void GeneratedMessageReflection::SetRepeatedEnumValueInternal(
1402     Message* message,
1403     const FieldDescriptor* field, int index,
1404     int value) const {
1405   if (field->is_extension()) {
1406     MutableExtensionSet(message)->SetRepeatedEnum(
1407       field->number(), index, value);
1408   } else {
1409     SetRepeatedField<int>(message, field, index, value);
1410   }
1411 }
1412 
AddEnum(Message * message,const FieldDescriptor * field,const EnumValueDescriptor * value) const1413 void GeneratedMessageReflection::AddEnum(
1414     Message* message, const FieldDescriptor* field,
1415     const EnumValueDescriptor* value) const {
1416   // Usage checked by AddEnumValue.
1417   USAGE_CHECK_ENUM_VALUE(AddEnum);
1418   AddEnumValueInternal(message, field, value->number());
1419 }
1420 
AddEnumValue(Message * message,const FieldDescriptor * field,int value) const1421 void GeneratedMessageReflection::AddEnumValue(
1422     Message* message, const FieldDescriptor* field,
1423     int value) const {
1424   USAGE_CHECK_ALL(AddEnum, REPEATED, ENUM);
1425   if (!CreateUnknownEnumValues(descriptor_->file())) {
1426     // Check that the value is valid if we don't support direct storage of
1427     // unknown enum values.
1428     const EnumValueDescriptor* value_desc =
1429         field->enum_type()->FindValueByNumber(value);
1430     if (value_desc == NULL) {
1431       GOOGLE_LOG(DFATAL) << "AddEnumValue accepts only valid integer values: value "
1432                   << value << " unexpected for field " << field->full_name();
1433       // In production builds, DFATAL will not terminate the program, so we have
1434       // to do something reasonable: just set the default value.
1435       value = field->default_value_enum()->number();
1436     }
1437   }
1438   AddEnumValueInternal(message, field, value);
1439 }
1440 
AddEnumValueInternal(Message * message,const FieldDescriptor * field,int value) const1441 void GeneratedMessageReflection::AddEnumValueInternal(
1442     Message* message, const FieldDescriptor* field,
1443     int value) const {
1444   if (field->is_extension()) {
1445     MutableExtensionSet(message)->AddEnum(field->number(), field->type(),
1446                                           field->options().packed(),
1447                                           value, field);
1448   } else {
1449     AddField<int>(message, field, value);
1450   }
1451 }
1452 
1453 // -------------------------------------------------------------------
1454 
GetMessage(const Message & message,const FieldDescriptor * field,MessageFactory * factory) const1455 const Message& GeneratedMessageReflection::GetMessage(
1456     const Message& message, const FieldDescriptor* field,
1457     MessageFactory* factory) const {
1458   USAGE_CHECK_ALL(GetMessage, SINGULAR, MESSAGE);
1459 
1460   if (factory == NULL) factory = message_factory_;
1461 
1462   if (field->is_extension()) {
1463     return static_cast<const Message&>(
1464         GetExtensionSet(message).GetMessage(
1465           field->number(), field->message_type(), factory));
1466   } else {
1467     const Message* result;
1468     result = GetRaw<const Message*>(message, field);
1469     if (result == NULL) {
1470       result = DefaultRaw<const Message*>(field);
1471     }
1472     return *result;
1473   }
1474 }
1475 
MutableMessage(Message * message,const FieldDescriptor * field,MessageFactory * factory) const1476 Message* GeneratedMessageReflection::MutableMessage(
1477     Message* message, const FieldDescriptor* field,
1478     MessageFactory* factory) const {
1479   USAGE_CHECK_ALL(MutableMessage, SINGULAR, MESSAGE);
1480 
1481   if (factory == NULL) factory = message_factory_;
1482 
1483   if (field->is_extension()) {
1484     return static_cast<Message*>(
1485         MutableExtensionSet(message)->MutableMessage(field, factory));
1486   } else {
1487     Message* result;
1488     Message** result_holder = MutableRaw<Message*>(message, field);
1489 
1490     if (field->containing_oneof()) {
1491       if (!HasOneofField(*message, field)) {
1492         ClearOneof(message, field->containing_oneof());
1493         result_holder = MutableField<Message*>(message, field);
1494         const Message* default_message = DefaultRaw<const Message*>(field);
1495         *result_holder = default_message->New(message->GetArena());
1496       }
1497     } else {
1498       SetBit(message, field);
1499     }
1500 
1501     if (*result_holder == NULL) {
1502       const Message* default_message = DefaultRaw<const Message*>(field);
1503       *result_holder = default_message->New(message->GetArena());
1504     }
1505     result = *result_holder;
1506     return result;
1507   }
1508 }
1509 
UnsafeArenaSetAllocatedMessage(Message * message,Message * sub_message,const FieldDescriptor * field) const1510 void GeneratedMessageReflection::UnsafeArenaSetAllocatedMessage(
1511     Message* message,
1512     Message* sub_message,
1513     const FieldDescriptor* field) const {
1514   USAGE_CHECK_ALL(SetAllocatedMessage, SINGULAR, MESSAGE);
1515 
1516   if (field->is_extension()) {
1517     MutableExtensionSet(message)->SetAllocatedMessage(
1518         field->number(), field->type(), field, sub_message);
1519   } else {
1520     if (field->containing_oneof()) {
1521       if (sub_message == NULL) {
1522         ClearOneof(message, field->containing_oneof());
1523         return;
1524       }
1525         ClearOneof(message, field->containing_oneof());
1526         *MutableRaw<Message*>(message, field) = sub_message;
1527       SetOneofCase(message, field);
1528       return;
1529     }
1530 
1531     if (sub_message == NULL) {
1532       ClearBit(message, field);
1533     } else {
1534       SetBit(message, field);
1535     }
1536     Message** sub_message_holder = MutableRaw<Message*>(message, field);
1537     if (GetArena(message) == NULL) {
1538       delete *sub_message_holder;
1539     }
1540     *sub_message_holder = sub_message;
1541   }
1542 }
1543 
SetAllocatedMessage(Message * message,Message * sub_message,const FieldDescriptor * field) const1544 void GeneratedMessageReflection::SetAllocatedMessage(
1545     Message* message,
1546     Message* sub_message,
1547     const FieldDescriptor* field) const {
1548   // If message and sub-message are in different memory ownership domains
1549   // (different arenas, or one is on heap and one is not), then we may need to
1550   // do a copy.
1551   if (sub_message != NULL &&
1552       sub_message->GetArena() != message->GetArena()) {
1553     if (sub_message->GetArena() == NULL && message->GetArena() != NULL) {
1554       // Case 1: parent is on an arena and child is heap-allocated. We can add
1555       // the child to the arena's Own() list to free on arena destruction, then
1556       // set our pointer.
1557       message->GetArena()->Own(sub_message);
1558       UnsafeArenaSetAllocatedMessage(message, sub_message, field);
1559     } else {
1560       // Case 2: all other cases. We need to make a copy. MutableMessage() will
1561       // either get the existing message object, or instantiate a new one as
1562       // appropriate w.r.t. our arena.
1563       Message* sub_message_copy = MutableMessage(message, field);
1564       sub_message_copy->CopyFrom(*sub_message);
1565     }
1566   } else {
1567     // Same memory ownership domains.
1568     UnsafeArenaSetAllocatedMessage(message, sub_message, field);
1569   }
1570 }
1571 
UnsafeArenaReleaseMessage(Message * message,const FieldDescriptor * field,MessageFactory * factory) const1572 Message* GeneratedMessageReflection::UnsafeArenaReleaseMessage(
1573     Message* message,
1574     const FieldDescriptor* field,
1575     MessageFactory* factory) const {
1576   USAGE_CHECK_ALL(ReleaseMessage, SINGULAR, MESSAGE);
1577 
1578   if (factory == NULL) factory = message_factory_;
1579 
1580   if (field->is_extension()) {
1581     return static_cast<Message*>(
1582         MutableExtensionSet(message)->ReleaseMessage(field, factory));
1583   } else {
1584     ClearBit(message, field);
1585     if (field->containing_oneof()) {
1586       if (HasOneofField(*message, field)) {
1587         *MutableOneofCase(message, field->containing_oneof()) = 0;
1588       } else {
1589         return NULL;
1590       }
1591     }
1592     Message** result = MutableRaw<Message*>(message, field);
1593     Message* ret = *result;
1594     *result = NULL;
1595     return ret;
1596   }
1597 }
1598 
ReleaseMessage(Message * message,const FieldDescriptor * field,MessageFactory * factory) const1599 Message* GeneratedMessageReflection::ReleaseMessage(
1600     Message* message,
1601     const FieldDescriptor* field,
1602     MessageFactory* factory) const {
1603   Message* released = UnsafeArenaReleaseMessage(message, field, factory);
1604   if (GetArena(message) != NULL && released != NULL) {
1605     Message* copy_from_arena = released->New();
1606     copy_from_arena->CopyFrom(*released);
1607     released = copy_from_arena;
1608   }
1609   return released;
1610 }
1611 
GetRepeatedMessage(const Message & message,const FieldDescriptor * field,int index) const1612 const Message& GeneratedMessageReflection::GetRepeatedMessage(
1613     const Message& message, const FieldDescriptor* field, int index) const {
1614   USAGE_CHECK_ALL(GetRepeatedMessage, REPEATED, MESSAGE);
1615 
1616   if (field->is_extension()) {
1617     return static_cast<const Message&>(
1618         GetExtensionSet(message).GetRepeatedMessage(field->number(), index));
1619   } else {
1620     if (IsMapFieldInApi(field)) {
1621       return GetRaw<MapFieldBase>(message, field)
1622           .GetRepeatedField()
1623           .Get<GenericTypeHandler<Message> >(index);
1624     } else {
1625       return GetRaw<RepeatedPtrFieldBase>(message, field)
1626           .Get<GenericTypeHandler<Message> >(index);
1627     }
1628   }
1629 }
1630 
MutableRepeatedMessage(Message * message,const FieldDescriptor * field,int index) const1631 Message* GeneratedMessageReflection::MutableRepeatedMessage(
1632     Message* message, const FieldDescriptor* field, int index) const {
1633   USAGE_CHECK_ALL(MutableRepeatedMessage, REPEATED, MESSAGE);
1634 
1635   if (field->is_extension()) {
1636     return static_cast<Message*>(
1637         MutableExtensionSet(message)->MutableRepeatedMessage(
1638           field->number(), index));
1639   } else {
1640     if (IsMapFieldInApi(field)) {
1641       return MutableRaw<MapFieldBase>(message, field)
1642           ->MutableRepeatedField()
1643           ->Mutable<GenericTypeHandler<Message> >(index);
1644     } else {
1645       return MutableRaw<RepeatedPtrFieldBase>(message, field)
1646         ->Mutable<GenericTypeHandler<Message> >(index);
1647     }
1648   }
1649 }
1650 
AddMessage(Message * message,const FieldDescriptor * field,MessageFactory * factory) const1651 Message* GeneratedMessageReflection::AddMessage(
1652     Message* message, const FieldDescriptor* field,
1653     MessageFactory* factory) const {
1654   USAGE_CHECK_ALL(AddMessage, REPEATED, MESSAGE);
1655 
1656   if (factory == NULL) factory = message_factory_;
1657 
1658   if (field->is_extension()) {
1659     return static_cast<Message*>(
1660         MutableExtensionSet(message)->AddMessage(field, factory));
1661   } else {
1662     Message* result = NULL;
1663 
1664     // We can't use AddField<Message>() because RepeatedPtrFieldBase doesn't
1665     // know how to allocate one.
1666     RepeatedPtrFieldBase* repeated = NULL;
1667     if (IsMapFieldInApi(field)) {
1668       repeated =
1669           MutableRaw<MapFieldBase>(message, field)->MutableRepeatedField();
1670     } else {
1671       repeated = MutableRaw<RepeatedPtrFieldBase>(message, field);
1672     }
1673     result = repeated->AddFromCleared<GenericTypeHandler<Message> >();
1674     if (result == NULL) {
1675       // We must allocate a new object.
1676       const Message* prototype;
1677       if (repeated->size() == 0) {
1678         prototype = factory->GetPrototype(field->message_type());
1679       } else {
1680         prototype = &repeated->Get<GenericTypeHandler<Message> >(0);
1681       }
1682       result = prototype->New(message->GetArena());
1683       // We can guarantee here that repeated and result are either both heap
1684       // allocated or arena owned. So it is safe to call the unsafe version
1685       // of AddAllocated.
1686       repeated->UnsafeArenaAddAllocated<GenericTypeHandler<Message> >(result);
1687     }
1688 
1689     return result;
1690   }
1691 }
1692 
AddAllocatedMessage(Message * message,const FieldDescriptor * field,Message * new_entry) const1693 void GeneratedMessageReflection::AddAllocatedMessage(
1694     Message* message, const FieldDescriptor* field,
1695     Message* new_entry) const {
1696   USAGE_CHECK_ALL(AddAllocatedMessage, REPEATED, MESSAGE);
1697 
1698   if (field->is_extension()) {
1699     MutableExtensionSet(message)->AddAllocatedMessage(field, new_entry);
1700   } else {
1701     RepeatedPtrFieldBase* repeated = NULL;
1702     if (IsMapFieldInApi(field)) {
1703       repeated =
1704           MutableRaw<MapFieldBase>(message, field)->MutableRepeatedField();
1705     } else {
1706       repeated = MutableRaw<RepeatedPtrFieldBase>(message, field);
1707     }
1708     repeated->AddAllocated<GenericTypeHandler<Message> >(new_entry);
1709   }
1710 }
1711 
MutableRawRepeatedField(Message * message,const FieldDescriptor * field,FieldDescriptor::CppType cpptype,int ctype,const Descriptor * desc) const1712 void* GeneratedMessageReflection::MutableRawRepeatedField(
1713     Message* message, const FieldDescriptor* field,
1714     FieldDescriptor::CppType cpptype,
1715     int ctype, const Descriptor* desc) const {
1716   USAGE_CHECK_REPEATED("MutableRawRepeatedField");
1717   if (field->cpp_type() != cpptype)
1718     ReportReflectionUsageTypeError(descriptor_,
1719         field, "MutableRawRepeatedField", cpptype);
1720   if (ctype >= 0)
1721     GOOGLE_CHECK_EQ(field->options().ctype(), ctype) << "subtype mismatch";
1722   if (desc != NULL)
1723     GOOGLE_CHECK_EQ(field->message_type(), desc) << "wrong submessage type";
1724   if (field->is_extension()) {
1725     return MutableExtensionSet(message)->MutableRawRepeatedField(
1726         field->number(), field->type(), field->is_packed(), field);
1727   } else {
1728     // Trigger transform for MapField
1729     if (IsMapFieldInApi(field)) {
1730       return reinterpret_cast<MapFieldBase*>(reinterpret_cast<uint8*>(message) +
1731                                              offsets_[field->index()])
1732           ->MutableRepeatedField();
1733     }
1734     return reinterpret_cast<uint8*>(message) + offsets_[field->index()];
1735   }
1736 }
1737 
GetRawRepeatedField(const Message & message,const FieldDescriptor * field,FieldDescriptor::CppType cpptype,int ctype,const Descriptor * desc) const1738 const void* GeneratedMessageReflection::GetRawRepeatedField(
1739     const Message& message, const FieldDescriptor* field,
1740     FieldDescriptor::CppType cpptype,
1741     int ctype, const Descriptor* desc) const {
1742   USAGE_CHECK_REPEATED("GetRawRepeatedField");
1743   if (field->cpp_type() != cpptype)
1744     ReportReflectionUsageTypeError(descriptor_,
1745         field, "GetRawRepeatedField", cpptype);
1746   if (ctype >= 0)
1747     GOOGLE_CHECK_EQ(field->options().ctype(), ctype) << "subtype mismatch";
1748   if (desc != NULL)
1749     GOOGLE_CHECK_EQ(field->message_type(), desc) << "wrong submessage type";
1750   if (field->is_extension()) {
1751     // Should use extension_set::GetRawRepeatedField. However, the required
1752     // parameter "default repeated value" is not very easy to get here.
1753     // Map is not supported in extensions, it is acceptable to use
1754     // extension_set::MutableRawRepeatedField which does not change the message.
1755     return MutableExtensionSet(const_cast<Message*>(&message))
1756         ->MutableRawRepeatedField(
1757         field->number(), field->type(), field->is_packed(), field);
1758   } else {
1759     // Trigger transform for MapField
1760     if (IsMapFieldInApi(field)) {
1761       return &(reinterpret_cast<const MapFieldBase*>(
1762           reinterpret_cast<const uint8*>(&message) +
1763           offsets_[field->index()])->GetRepeatedField());
1764     }
1765     return reinterpret_cast<const uint8*>(&message) + offsets_[field->index()];
1766   }
1767 }
1768 
GetOneofFieldDescriptor(const Message & message,const OneofDescriptor * oneof_descriptor) const1769 const FieldDescriptor* GeneratedMessageReflection::GetOneofFieldDescriptor(
1770     const Message& message,
1771     const OneofDescriptor* oneof_descriptor) const {
1772   uint32 field_number = GetOneofCase(message, oneof_descriptor);
1773   if (field_number == 0) {
1774     return NULL;
1775   }
1776   return descriptor_->FindFieldByNumber(field_number);
1777 }
1778 
ContainsMapKey(const Message & message,const FieldDescriptor * field,const MapKey & key) const1779 bool GeneratedMessageReflection::ContainsMapKey(
1780     const Message& message,
1781     const FieldDescriptor* field,
1782     const MapKey& key) const {
1783   USAGE_CHECK(IsMapFieldInApi(field),
1784               "LookupMapValue",
1785               "Field is not a map field.");
1786   return GetRaw<MapFieldBase>(message, field).ContainsMapKey(key);
1787 }
1788 
InsertOrLookupMapValue(Message * message,const FieldDescriptor * field,const MapKey & key,MapValueRef * val) const1789 bool GeneratedMessageReflection::InsertOrLookupMapValue(
1790     Message* message,
1791     const FieldDescriptor* field,
1792     const MapKey& key,
1793     MapValueRef* val) const {
1794   USAGE_CHECK(IsMapFieldInApi(field),
1795               "InsertOrLookupMapValue",
1796               "Field is not a map field.");
1797   val->SetType(field->message_type()->FindFieldByName("value")->cpp_type());
1798   return MutableRaw<MapFieldBase>(message, field)->InsertOrLookupMapValue(
1799       key, val);
1800 }
1801 
DeleteMapValue(Message * message,const FieldDescriptor * field,const MapKey & key) const1802 bool GeneratedMessageReflection::DeleteMapValue(
1803     Message* message,
1804     const FieldDescriptor* field,
1805     const MapKey& key) const {
1806   USAGE_CHECK(IsMapFieldInApi(field),
1807               "DeleteMapValue",
1808               "Field is not a map field.");
1809   return MutableRaw<MapFieldBase>(message, field)->DeleteMapValue(key);
1810 }
1811 
MapBegin(Message * message,const FieldDescriptor * field) const1812 MapIterator GeneratedMessageReflection::MapBegin(
1813     Message* message,
1814     const FieldDescriptor* field) const {
1815   USAGE_CHECK(IsMapFieldInApi(field),
1816               "MapBegin",
1817               "Field is not a map field.");
1818   MapIterator iter(message, field);
1819   GetRaw<MapFieldBase>(*message, field).MapBegin(&iter);
1820   return iter;
1821 }
1822 
MapEnd(Message * message,const FieldDescriptor * field) const1823 MapIterator GeneratedMessageReflection::MapEnd(
1824     Message* message,
1825     const FieldDescriptor* field) const {
1826   USAGE_CHECK(IsMapFieldInApi(field),
1827               "MapEnd",
1828               "Field is not a map field.");
1829   MapIterator iter(message, field);
1830   GetRaw<MapFieldBase>(*message, field).MapEnd(&iter);
1831   return iter;
1832 }
1833 
MapSize(const Message & message,const FieldDescriptor * field) const1834 int GeneratedMessageReflection::MapSize(
1835     const Message& message,
1836     const FieldDescriptor* field) const {
1837   USAGE_CHECK(IsMapFieldInApi(field),
1838               "MapSize",
1839               "Field is not a map field.");
1840   return GetRaw<MapFieldBase>(message, field).size();
1841 }
1842 
1843 // -----------------------------------------------------------------------------
1844 
FindKnownExtensionByName(const string & name) const1845 const FieldDescriptor* GeneratedMessageReflection::FindKnownExtensionByName(
1846     const string& name) const {
1847   if (extensions_offset_ == -1) return NULL;
1848 
1849   const FieldDescriptor* result = descriptor_pool_->FindExtensionByName(name);
1850   if (result != NULL && result->containing_type() == descriptor_) {
1851     return result;
1852   }
1853 
1854   if (descriptor_->options().message_set_wire_format()) {
1855     // MessageSet extensions may be identified by type name.
1856     const Descriptor* type = descriptor_pool_->FindMessageTypeByName(name);
1857     if (type != NULL) {
1858       // Look for a matching extension in the foreign type's scope.
1859       for (int i = 0; i < type->extension_count(); i++) {
1860         const FieldDescriptor* extension = type->extension(i);
1861         if (extension->containing_type() == descriptor_ &&
1862             extension->type() == FieldDescriptor::TYPE_MESSAGE &&
1863             extension->is_optional() &&
1864             extension->message_type() == type) {
1865           // Found it.
1866           return extension;
1867         }
1868       }
1869     }
1870   }
1871 
1872   return NULL;
1873 }
1874 
FindKnownExtensionByNumber(int number) const1875 const FieldDescriptor* GeneratedMessageReflection::FindKnownExtensionByNumber(
1876     int number) const {
1877   if (extensions_offset_ == -1) return NULL;
1878   return descriptor_pool_->FindExtensionByNumber(descriptor_, number);
1879 }
1880 
SupportsUnknownEnumValues() const1881 bool GeneratedMessageReflection::SupportsUnknownEnumValues() const {
1882   return CreateUnknownEnumValues(descriptor_->file());
1883 }
1884 
1885 // ===================================================================
1886 // Some private helpers.
1887 
1888 // These simple template accessors obtain pointers (or references) to
1889 // the given field.
1890 template <typename Type>
GetRaw(const Message & message,const FieldDescriptor * field) const1891 inline const Type& GeneratedMessageReflection::GetRaw(
1892     const Message& message, const FieldDescriptor* field) const {
1893   if (field->containing_oneof() && !HasOneofField(message, field)) {
1894     return DefaultRaw<Type>(field);
1895   }
1896   int index = field->containing_oneof() ?
1897       descriptor_->field_count() + field->containing_oneof()->index() :
1898       field->index();
1899   const void* ptr = reinterpret_cast<const uint8*>(&message) +
1900       offsets_[index];
1901   return *reinterpret_cast<const Type*>(ptr);
1902 }
1903 
1904 template <typename Type>
MutableRaw(Message * message,const FieldDescriptor * field) const1905 inline Type* GeneratedMessageReflection::MutableRaw(
1906     Message* message, const FieldDescriptor* field) const {
1907   int index = field->containing_oneof() ?
1908       descriptor_->field_count() + field->containing_oneof()->index() :
1909       field->index();
1910   void* ptr = reinterpret_cast<uint8*>(message) + offsets_[index];
1911   return reinterpret_cast<Type*>(ptr);
1912 }
1913 
1914 template <typename Type>
DefaultRaw(const FieldDescriptor * field) const1915 inline const Type& GeneratedMessageReflection::DefaultRaw(
1916     const FieldDescriptor* field) const {
1917   const void* ptr = field->containing_oneof() ?
1918       reinterpret_cast<const uint8*>(default_oneof_instance_) +
1919       offsets_[field->index()] :
1920       reinterpret_cast<const uint8*>(default_instance_) +
1921       offsets_[field->index()];
1922   return *reinterpret_cast<const Type*>(ptr);
1923 }
1924 
GetHasBits(const Message & message) const1925 inline const uint32* GeneratedMessageReflection::GetHasBits(
1926     const Message& message) const {
1927   if (has_bits_offset_ == -1) {  // proto3 with no has-bits.
1928     return NULL;
1929   }
1930   const void* ptr = reinterpret_cast<const uint8*>(&message) + has_bits_offset_;
1931   return reinterpret_cast<const uint32*>(ptr);
1932 }
MutableHasBits(Message * message) const1933 inline uint32* GeneratedMessageReflection::MutableHasBits(
1934     Message* message) const {
1935   if (has_bits_offset_ == -1) {
1936     return NULL;
1937   }
1938   void* ptr = reinterpret_cast<uint8*>(message) + has_bits_offset_;
1939   return reinterpret_cast<uint32*>(ptr);
1940 }
1941 
GetOneofCase(const Message & message,const OneofDescriptor * oneof_descriptor) const1942 inline uint32 GeneratedMessageReflection::GetOneofCase(
1943     const Message& message,
1944     const OneofDescriptor* oneof_descriptor) const {
1945   const void* ptr = reinterpret_cast<const uint8*>(&message)
1946       + oneof_case_offset_;
1947   return reinterpret_cast<const uint32*>(ptr)[oneof_descriptor->index()];
1948 }
1949 
MutableOneofCase(Message * message,const OneofDescriptor * oneof_descriptor) const1950 inline uint32* GeneratedMessageReflection::MutableOneofCase(
1951     Message* message,
1952     const OneofDescriptor* oneof_descriptor) const {
1953   void* ptr = reinterpret_cast<uint8*>(message) + oneof_case_offset_;
1954   return &(reinterpret_cast<uint32*>(ptr)[oneof_descriptor->index()]);
1955 }
1956 
GetExtensionSet(const Message & message) const1957 inline const ExtensionSet& GeneratedMessageReflection::GetExtensionSet(
1958     const Message& message) const {
1959   GOOGLE_DCHECK_NE(extensions_offset_, -1);
1960   const void* ptr = reinterpret_cast<const uint8*>(&message) +
1961                     extensions_offset_;
1962   return *reinterpret_cast<const ExtensionSet*>(ptr);
1963 }
MutableExtensionSet(Message * message) const1964 inline ExtensionSet* GeneratedMessageReflection::MutableExtensionSet(
1965     Message* message) const {
1966   GOOGLE_DCHECK_NE(extensions_offset_, -1);
1967   void* ptr = reinterpret_cast<uint8*>(message) + extensions_offset_;
1968   return reinterpret_cast<ExtensionSet*>(ptr);
1969 }
1970 
GetArena(Message * message) const1971 inline Arena* GeneratedMessageReflection::GetArena(Message* message) const {
1972   if (arena_offset_ == kNoArenaPointer) {
1973     return NULL;
1974   }
1975 
1976   if (unknown_fields_offset_ == kUnknownFieldSetInMetadata) {
1977     // zero-overhead arena pointer overloading UnknownFields
1978     return GetInternalMetadataWithArena(*message).arena();
1979   }
1980 
1981   // Baseline case: message class has a dedicated arena pointer.
1982   void* ptr = reinterpret_cast<uint8*>(message) + arena_offset_;
1983   return *reinterpret_cast<Arena**>(ptr);
1984 }
1985 
1986 inline const InternalMetadataWithArena&
GetInternalMetadataWithArena(const Message & message) const1987 GeneratedMessageReflection::GetInternalMetadataWithArena(
1988     const Message& message) const {
1989   const void* ptr = reinterpret_cast<const uint8*>(&message) + arena_offset_;
1990   return *reinterpret_cast<const InternalMetadataWithArena*>(ptr);
1991 }
1992 
1993 inline InternalMetadataWithArena*
MutableInternalMetadataWithArena(Message * message) const1994 GeneratedMessageReflection::MutableInternalMetadataWithArena(
1995     Message* message) const {
1996   void* ptr = reinterpret_cast<uint8*>(message) + arena_offset_;
1997   return reinterpret_cast<InternalMetadataWithArena*>(ptr);
1998 }
1999 
2000 inline bool
GetIsDefaultInstance(const Message & message) const2001 GeneratedMessageReflection::GetIsDefaultInstance(
2002     const Message& message) const {
2003   if (is_default_instance_offset_ == kHasNoDefaultInstanceField) {
2004     return false;
2005   }
2006   const void* ptr = reinterpret_cast<const uint8*>(&message) +
2007       is_default_instance_offset_;
2008   return *reinterpret_cast<const bool*>(ptr);
2009 }
2010 
2011 // Simple accessors for manipulating has_bits_.
HasBit(const Message & message,const FieldDescriptor * field) const2012 inline bool GeneratedMessageReflection::HasBit(
2013     const Message& message, const FieldDescriptor* field) const {
2014   if (has_bits_offset_ == -1) {
2015     // proto3: no has-bits. All fields present except messages, which are
2016     // present only if their message-field pointer is non-NULL.
2017     if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
2018       return !GetIsDefaultInstance(message) &&
2019           GetRaw<const Message*>(message, field) != NULL;
2020     } else {
2021       // Non-message field (and non-oneof, since that was handled in HasField()
2022       // before calling us), and singular (again, checked in HasField). So, this
2023       // field must be a scalar.
2024 
2025       // Scalar primitive (numeric or string/bytes) fields are present if
2026       // their value is non-zero (numeric) or non-empty (string/bytes).  N.B.:
2027       // we must use this definition here, rather than the "scalar fields
2028       // always present" in the proto3 docs, because MergeFrom() semantics
2029       // require presence as "present on wire", and reflection-based merge
2030       // (which uses HasField()) needs to be consistent with this.
2031       switch (field->cpp_type()) {
2032         case FieldDescriptor::CPPTYPE_STRING:
2033           switch (field->options().ctype()) {
2034             default: {
2035               const string* default_ptr =
2036                   &DefaultRaw<ArenaStringPtr>(field).Get(NULL);
2037               return GetField<ArenaStringPtr>(message, field).Get(
2038                   default_ptr).size() > 0;
2039             }
2040           }
2041           return false;
2042         case FieldDescriptor::CPPTYPE_BOOL:
2043           return GetRaw<bool>(message, field) != false;
2044         case FieldDescriptor::CPPTYPE_INT32:
2045           return GetRaw<int32>(message, field) != 0;
2046         case FieldDescriptor::CPPTYPE_INT64:
2047           return GetRaw<int64>(message, field) != 0;
2048         case FieldDescriptor::CPPTYPE_UINT32:
2049           return GetRaw<uint32>(message, field) != 0;
2050         case FieldDescriptor::CPPTYPE_UINT64:
2051           return GetRaw<uint64>(message, field) != 0;
2052         case FieldDescriptor::CPPTYPE_FLOAT:
2053           return GetRaw<float>(message, field) != 0.0;
2054         case FieldDescriptor::CPPTYPE_DOUBLE:
2055           return GetRaw<double>(message, field) != 0.0;
2056         case FieldDescriptor::CPPTYPE_ENUM:
2057           return GetRaw<int>(message, field) != 0;
2058         case FieldDescriptor::CPPTYPE_MESSAGE:
2059           // handled above; avoid warning
2060           GOOGLE_LOG(FATAL) << "Reached impossible case in HasBit().";
2061           break;
2062       }
2063     }
2064   }
2065   return GetHasBits(message)[field->index() / 32] &
2066     (1 << (field->index() % 32));
2067 }
2068 
SetBit(Message * message,const FieldDescriptor * field) const2069 inline void GeneratedMessageReflection::SetBit(
2070     Message* message, const FieldDescriptor* field) const {
2071   if (has_bits_offset_ == -1) {
2072     return;
2073   }
2074   MutableHasBits(message)[field->index() / 32] |= (1 << (field->index() % 32));
2075 }
2076 
ClearBit(Message * message,const FieldDescriptor * field) const2077 inline void GeneratedMessageReflection::ClearBit(
2078     Message* message, const FieldDescriptor* field) const {
2079   if (has_bits_offset_ == -1) {
2080     return;
2081   }
2082   MutableHasBits(message)[field->index() / 32] &= ~(1 << (field->index() % 32));
2083 }
2084 
SwapBit(Message * message1,Message * message2,const FieldDescriptor * field) const2085 inline void GeneratedMessageReflection::SwapBit(
2086     Message* message1, Message* message2, const FieldDescriptor* field) const {
2087   if (has_bits_offset_ == -1) {
2088     return;
2089   }
2090   bool temp_has_bit = HasBit(*message1, field);
2091   if (HasBit(*message2, field)) {
2092     SetBit(message1, field);
2093   } else {
2094     ClearBit(message1, field);
2095   }
2096   if (temp_has_bit) {
2097     SetBit(message2, field);
2098   } else {
2099     ClearBit(message2, field);
2100   }
2101 }
2102 
HasOneof(const Message & message,const OneofDescriptor * oneof_descriptor) const2103 inline bool GeneratedMessageReflection::HasOneof(
2104     const Message& message, const OneofDescriptor* oneof_descriptor) const {
2105   return (GetOneofCase(message, oneof_descriptor) > 0);
2106 }
2107 
HasOneofField(const Message & message,const FieldDescriptor * field) const2108 inline bool GeneratedMessageReflection::HasOneofField(
2109     const Message& message, const FieldDescriptor* field) const {
2110   return (GetOneofCase(message, field->containing_oneof()) == field->number());
2111 }
2112 
SetOneofCase(Message * message,const FieldDescriptor * field) const2113 inline void GeneratedMessageReflection::SetOneofCase(
2114     Message* message, const FieldDescriptor* field) const {
2115   *MutableOneofCase(message, field->containing_oneof()) = field->number();
2116 }
2117 
ClearOneofField(Message * message,const FieldDescriptor * field) const2118 inline void GeneratedMessageReflection::ClearOneofField(
2119     Message* message, const FieldDescriptor* field) const {
2120   if (HasOneofField(*message, field)) {
2121     ClearOneof(message, field->containing_oneof());
2122   }
2123 }
2124 
ClearOneof(Message * message,const OneofDescriptor * oneof_descriptor) const2125 inline void GeneratedMessageReflection::ClearOneof(
2126     Message* message, const OneofDescriptor* oneof_descriptor) const {
2127   // TODO(jieluo): Consider to cache the unused object instead of deleting
2128   // it. It will be much faster if an aplication switches a lot from
2129   // a few oneof fields.  Time/space tradeoff
2130   uint32 oneof_case = GetOneofCase(*message, oneof_descriptor);
2131   if (oneof_case > 0) {
2132     const FieldDescriptor* field = descriptor_->FindFieldByNumber(oneof_case);
2133     if (GetArena(message) == NULL) {
2134       switch (field->cpp_type()) {
2135         case FieldDescriptor::CPPTYPE_STRING: {
2136           switch (field->options().ctype()) {
2137             default:  // TODO(kenton):  Support other string reps.
2138             case FieldOptions::STRING: {
2139               const string* default_ptr =
2140                   &DefaultRaw<ArenaStringPtr>(field).Get(NULL);
2141               MutableField<ArenaStringPtr>(message, field)->
2142                   Destroy(default_ptr, GetArena(message));
2143               break;
2144             }
2145           }
2146           break;
2147         }
2148 
2149         case FieldDescriptor::CPPTYPE_MESSAGE:
2150           delete *MutableRaw<Message*>(message, field);
2151           break;
2152         default:
2153           break;
2154       }
2155     }
2156 
2157     *MutableOneofCase(message, oneof_descriptor) = 0;
2158   }
2159 }
2160 
2161 // Template implementations of basic accessors.  Inline because each
2162 // template instance is only called from one location.  These are
2163 // used for all types except messages.
2164 template <typename Type>
GetField(const Message & message,const FieldDescriptor * field) const2165 inline const Type& GeneratedMessageReflection::GetField(
2166     const Message& message, const FieldDescriptor* field) const {
2167   return GetRaw<Type>(message, field);
2168 }
2169 
2170 template <typename Type>
SetField(Message * message,const FieldDescriptor * field,const Type & value) const2171 inline void GeneratedMessageReflection::SetField(
2172     Message* message, const FieldDescriptor* field, const Type& value) const {
2173   if (field->containing_oneof() && !HasOneofField(*message, field)) {
2174     ClearOneof(message, field->containing_oneof());
2175   }
2176   *MutableRaw<Type>(message, field) = value;
2177   field->containing_oneof() ?
2178       SetOneofCase(message, field) : SetBit(message, field);
2179 }
2180 
2181 template <typename Type>
MutableField(Message * message,const FieldDescriptor * field) const2182 inline Type* GeneratedMessageReflection::MutableField(
2183     Message* message, const FieldDescriptor* field) const {
2184   field->containing_oneof() ?
2185       SetOneofCase(message, field) : SetBit(message, field);
2186   return MutableRaw<Type>(message, field);
2187 }
2188 
2189 template <typename Type>
GetRepeatedField(const Message & message,const FieldDescriptor * field,int index) const2190 inline const Type& GeneratedMessageReflection::GetRepeatedField(
2191     const Message& message, const FieldDescriptor* field, int index) const {
2192   return GetRaw<RepeatedField<Type> >(message, field).Get(index);
2193 }
2194 
2195 template <typename Type>
GetRepeatedPtrField(const Message & message,const FieldDescriptor * field,int index) const2196 inline const Type& GeneratedMessageReflection::GetRepeatedPtrField(
2197     const Message& message, const FieldDescriptor* field, int index) const {
2198   return GetRaw<RepeatedPtrField<Type> >(message, field).Get(index);
2199 }
2200 
2201 template <typename Type>
SetRepeatedField(Message * message,const FieldDescriptor * field,int index,Type value) const2202 inline void GeneratedMessageReflection::SetRepeatedField(
2203     Message* message, const FieldDescriptor* field,
2204     int index, Type value) const {
2205   MutableRaw<RepeatedField<Type> >(message, field)->Set(index, value);
2206 }
2207 
2208 template <typename Type>
MutableRepeatedField(Message * message,const FieldDescriptor * field,int index) const2209 inline Type* GeneratedMessageReflection::MutableRepeatedField(
2210     Message* message, const FieldDescriptor* field, int index) const {
2211   RepeatedPtrField<Type>* repeated =
2212     MutableRaw<RepeatedPtrField<Type> >(message, field);
2213   return repeated->Mutable(index);
2214 }
2215 
2216 template <typename Type>
AddField(Message * message,const FieldDescriptor * field,const Type & value) const2217 inline void GeneratedMessageReflection::AddField(
2218     Message* message, const FieldDescriptor* field, const Type& value) const {
2219   MutableRaw<RepeatedField<Type> >(message, field)->Add(value);
2220 }
2221 
2222 template <typename Type>
AddField(Message * message,const FieldDescriptor * field) const2223 inline Type* GeneratedMessageReflection::AddField(
2224     Message* message, const FieldDescriptor* field) const {
2225   RepeatedPtrField<Type>* repeated =
2226     MutableRaw<RepeatedPtrField<Type> >(message, field);
2227   return repeated->Add();
2228 }
2229 
GetMessageFactory() const2230 MessageFactory* GeneratedMessageReflection::GetMessageFactory() const {
2231   return message_factory_;
2232 }
2233 
RepeatedFieldData(Message * message,const FieldDescriptor * field,FieldDescriptor::CppType cpp_type,const Descriptor * message_type) const2234 void* GeneratedMessageReflection::RepeatedFieldData(
2235     Message* message, const FieldDescriptor* field,
2236     FieldDescriptor::CppType cpp_type,
2237     const Descriptor* message_type) const {
2238   GOOGLE_CHECK(field->is_repeated());
2239   GOOGLE_CHECK(field->cpp_type() == cpp_type ||
2240         (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM &&
2241          cpp_type == FieldDescriptor::CPPTYPE_INT32))
2242       << "The type parameter T in RepeatedFieldRef<T> API doesn't match "
2243       << "the actual field type (for enums T should be the generated enum "
2244       << "type or int32).";
2245   if (message_type != NULL) {
2246     GOOGLE_CHECK_EQ(message_type, field->message_type());
2247   }
2248   if (field->is_extension()) {
2249     return MutableExtensionSet(message)->MutableRawRepeatedField(
2250         field->number(), field->type(), field->is_packed(), field);
2251   } else {
2252     return reinterpret_cast<uint8*>(message) + offsets_[field->index()];
2253   }
2254 }
2255 
MapData(Message * message,const FieldDescriptor * field) const2256 MapFieldBase* GeneratedMessageReflection::MapData(
2257     Message* message, const FieldDescriptor* field) const {
2258   USAGE_CHECK(IsMapFieldInApi(field),
2259               "GetMapData",
2260               "Field is not a map field.");
2261   return MutableRaw<MapFieldBase>(message, field);
2262 }
2263 
2264 GeneratedMessageReflection*
NewGeneratedMessageReflection(const Descriptor * descriptor,const Message * default_instance,const int offsets[],int has_bits_offset,int unknown_fields_offset,int extensions_offset,const void * default_oneof_instance,int oneof_case_offset,int object_size,int arena_offset,int is_default_instance_offset)2265 GeneratedMessageReflection::NewGeneratedMessageReflection(
2266     const Descriptor* descriptor,
2267     const Message* default_instance,
2268     const int offsets[],
2269     int has_bits_offset,
2270     int unknown_fields_offset,
2271     int extensions_offset,
2272     const void* default_oneof_instance,
2273     int oneof_case_offset,
2274     int object_size,
2275     int arena_offset,
2276     int is_default_instance_offset) {
2277   return new GeneratedMessageReflection(descriptor,
2278                                         default_instance,
2279                                         offsets,
2280                                         has_bits_offset,
2281                                         unknown_fields_offset,
2282                                         extensions_offset,
2283                                         default_oneof_instance,
2284                                         oneof_case_offset,
2285                                         DescriptorPool::generated_pool(),
2286                                         MessageFactory::generated_factory(),
2287                                         object_size,
2288                                         arena_offset,
2289                                         is_default_instance_offset);
2290 }
2291 
2292 GeneratedMessageReflection*
NewGeneratedMessageReflection(const Descriptor * descriptor,const Message * default_instance,const int offsets[],int has_bits_offset,int unknown_fields_offset,int extensions_offset,int object_size,int arena_offset,int is_default_instance_offset)2293 GeneratedMessageReflection::NewGeneratedMessageReflection(
2294     const Descriptor* descriptor,
2295     const Message* default_instance,
2296     const int offsets[],
2297     int has_bits_offset,
2298     int unknown_fields_offset,
2299     int extensions_offset,
2300     int object_size,
2301     int arena_offset,
2302     int is_default_instance_offset) {
2303   return new GeneratedMessageReflection(descriptor,
2304                                         default_instance,
2305                                         offsets,
2306                                         has_bits_offset,
2307                                         unknown_fields_offset,
2308                                         extensions_offset,
2309                                         DescriptorPool::generated_pool(),
2310                                         MessageFactory::generated_factory(),
2311                                         object_size,
2312                                         arena_offset,
2313                                         is_default_instance_offset);
2314 }
2315 
2316 }  // namespace internal
2317 }  // namespace protobuf
2318 }  // namespace google
2319