诸暨麻将添加redis
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

2440 rindas
94 KiB

  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. // Author: kenton@google.com (Kenton Varda)
  31. // Based on original Protocol Buffers design by
  32. // Sanjay Ghemawat, Jeff Dean, and others.
  33. #include <algorithm>
  34. #include <set>
  35. #include <google/protobuf/stubs/logging.h>
  36. #include <google/protobuf/stubs/common.h>
  37. #include <google/protobuf/descriptor.pb.h>
  38. #include <google/protobuf/descriptor.h>
  39. #include <google/protobuf/extension_set.h>
  40. #include <google/protobuf/generated_message_reflection.h>
  41. #include <google/protobuf/generated_message_util.h>
  42. #include <google/protobuf/inlined_string_field.h>
  43. #include <google/protobuf/map_field.h>
  44. #include <google/protobuf/map_field_inl.h>
  45. #include <google/protobuf/stubs/mutex.h>
  46. #include <google/protobuf/repeated_field.h>
  47. #include <google/protobuf/wire_format.h>
  48. #include <google/protobuf/port_def.inc>
  49. #define GOOGLE_PROTOBUF_HAS_ONEOF
  50. using google::protobuf::internal::ArenaStringPtr;
  51. using google::protobuf::internal::DescriptorTable;
  52. using google::protobuf::internal::ExtensionSet;
  53. using google::protobuf::internal::GenericTypeHandler;
  54. using google::protobuf::internal::GetEmptyString;
  55. using google::protobuf::internal::InlinedStringField;
  56. using google::protobuf::internal::InternalMetadataWithArena;
  57. using google::protobuf::internal::LazyField;
  58. using google::protobuf::internal::MapFieldBase;
  59. using google::protobuf::internal::MigrationSchema;
  60. using google::protobuf::internal::OnShutdownDelete;
  61. using google::protobuf::internal::ReflectionSchema;
  62. using google::protobuf::internal::RepeatedPtrFieldBase;
  63. using google::protobuf::internal::StringSpaceUsedExcludingSelfLong;
  64. using google::protobuf::internal::WrappedMutex;
  65. namespace google {
  66. namespace protobuf {
  67. namespace {
  68. bool IsMapFieldInApi(const FieldDescriptor* field) { return field->is_map(); }
  69. } // anonymous namespace
  70. namespace internal {
  71. bool ParseNamedEnum(const EnumDescriptor* descriptor, const std::string& name,
  72. int* value) {
  73. const EnumValueDescriptor* d = descriptor->FindValueByName(name);
  74. if (d == nullptr) return false;
  75. *value = d->number();
  76. return true;
  77. }
  78. const std::string& NameOfEnum(const EnumDescriptor* descriptor, int value) {
  79. const EnumValueDescriptor* d = descriptor->FindValueByNumber(value);
  80. return (d == nullptr ? GetEmptyString() : d->name());
  81. }
  82. } // namespace internal
  83. // ===================================================================
  84. // Helpers for reporting usage errors (e.g. trying to use GetInt32() on
  85. // a string field).
  86. namespace {
  87. template <class To>
  88. To* GetPointerAtOffset(Message* message, uint32 offset) {
  89. return reinterpret_cast<To*>(reinterpret_cast<char*>(message) + offset);
  90. }
  91. template <class To>
  92. const To* GetConstPointerAtOffset(const Message* message, uint32 offset) {
  93. return reinterpret_cast<const To*>(reinterpret_cast<const char*>(message) +
  94. offset);
  95. }
  96. template <class To>
  97. const To& GetConstRefAtOffset(const Message& message, uint32 offset) {
  98. return *GetConstPointerAtOffset<To>(&message, offset);
  99. }
  100. void ReportReflectionUsageError(const Descriptor* descriptor,
  101. const FieldDescriptor* field,
  102. const char* method, const char* description) {
  103. GOOGLE_LOG(FATAL) << "Protocol Buffer reflection usage error:\n"
  104. " Method : google::protobuf::Reflection::"
  105. << method
  106. << "\n"
  107. " Message type: "
  108. << descriptor->full_name()
  109. << "\n"
  110. " Field : "
  111. << field->full_name()
  112. << "\n"
  113. " Problem : "
  114. << description;
  115. }
  116. const char* cpptype_names_[FieldDescriptor::MAX_CPPTYPE + 1] = {
  117. "INVALID_CPPTYPE", "CPPTYPE_INT32", "CPPTYPE_INT64", "CPPTYPE_UINT32",
  118. "CPPTYPE_UINT64", "CPPTYPE_DOUBLE", "CPPTYPE_FLOAT", "CPPTYPE_BOOL",
  119. "CPPTYPE_ENUM", "CPPTYPE_STRING", "CPPTYPE_MESSAGE"};
  120. static void ReportReflectionUsageTypeError(
  121. const Descriptor* descriptor, const FieldDescriptor* field,
  122. const char* method, FieldDescriptor::CppType expected_type) {
  123. GOOGLE_LOG(FATAL)
  124. << "Protocol Buffer reflection usage error:\n"
  125. " Method : google::protobuf::Reflection::"
  126. << method
  127. << "\n"
  128. " Message type: "
  129. << descriptor->full_name()
  130. << "\n"
  131. " Field : "
  132. << field->full_name()
  133. << "\n"
  134. " Problem : Field is not the right type for this message:\n"
  135. " Expected : "
  136. << cpptype_names_[expected_type]
  137. << "\n"
  138. " Field type: "
  139. << cpptype_names_[field->cpp_type()];
  140. }
  141. static void ReportReflectionUsageEnumTypeError(
  142. const Descriptor* descriptor, const FieldDescriptor* field,
  143. const char* method, const EnumValueDescriptor* value) {
  144. GOOGLE_LOG(FATAL) << "Protocol Buffer reflection usage error:\n"
  145. " Method : google::protobuf::Reflection::"
  146. << method
  147. << "\n"
  148. " Message type: "
  149. << descriptor->full_name()
  150. << "\n"
  151. " Field : "
  152. << field->full_name()
  153. << "\n"
  154. " Problem : Enum value did not match field type:\n"
  155. " Expected : "
  156. << field->enum_type()->full_name()
  157. << "\n"
  158. " Actual : "
  159. << value->full_name();
  160. }
  161. #define USAGE_CHECK(CONDITION, METHOD, ERROR_DESCRIPTION) \
  162. if (!(CONDITION)) \
  163. ReportReflectionUsageError(descriptor_, field, #METHOD, ERROR_DESCRIPTION)
  164. #define USAGE_CHECK_EQ(A, B, METHOD, ERROR_DESCRIPTION) \
  165. USAGE_CHECK((A) == (B), METHOD, ERROR_DESCRIPTION)
  166. #define USAGE_CHECK_NE(A, B, METHOD, ERROR_DESCRIPTION) \
  167. USAGE_CHECK((A) != (B), METHOD, ERROR_DESCRIPTION)
  168. #define USAGE_CHECK_TYPE(METHOD, CPPTYPE) \
  169. if (field->cpp_type() != FieldDescriptor::CPPTYPE_##CPPTYPE) \
  170. ReportReflectionUsageTypeError(descriptor_, field, #METHOD, \
  171. FieldDescriptor::CPPTYPE_##CPPTYPE)
  172. #define USAGE_CHECK_ENUM_VALUE(METHOD) \
  173. if (value->type() != field->enum_type()) \
  174. ReportReflectionUsageEnumTypeError(descriptor_, field, #METHOD, value)
  175. #define USAGE_CHECK_MESSAGE_TYPE(METHOD) \
  176. USAGE_CHECK_EQ(field->containing_type(), descriptor_, METHOD, \
  177. "Field does not match message type.");
  178. #define USAGE_CHECK_SINGULAR(METHOD) \
  179. USAGE_CHECK_NE(field->label(), FieldDescriptor::LABEL_REPEATED, METHOD, \
  180. "Field is repeated; the method requires a singular field.")
  181. #define USAGE_CHECK_REPEATED(METHOD) \
  182. USAGE_CHECK_EQ(field->label(), FieldDescriptor::LABEL_REPEATED, METHOD, \
  183. "Field is singular; the method requires a repeated field.")
  184. #define USAGE_CHECK_ALL(METHOD, LABEL, CPPTYPE) \
  185. USAGE_CHECK_MESSAGE_TYPE(METHOD); \
  186. USAGE_CHECK_##LABEL(METHOD); \
  187. USAGE_CHECK_TYPE(METHOD, CPPTYPE)
  188. } // namespace
  189. // ===================================================================
  190. Reflection::Reflection(const Descriptor* descriptor,
  191. const internal::ReflectionSchema& schema,
  192. const DescriptorPool* pool, MessageFactory* factory)
  193. : descriptor_(descriptor),
  194. schema_(schema),
  195. descriptor_pool_(
  196. (pool == nullptr) ? DescriptorPool::internal_generated_pool() : pool),
  197. message_factory_(factory),
  198. last_non_weak_field_index_(-1) {
  199. last_non_weak_field_index_ = descriptor_->field_count() - 1;
  200. }
  201. const UnknownFieldSet& Reflection::GetUnknownFields(
  202. const Message& message) const {
  203. return GetInternalMetadataWithArena(message).unknown_fields();
  204. }
  205. UnknownFieldSet* Reflection::MutableUnknownFields(Message* message) const {
  206. return MutableInternalMetadataWithArena(message)->mutable_unknown_fields();
  207. }
  208. size_t Reflection::SpaceUsedLong(const Message& message) const {
  209. // object_size_ already includes the in-memory representation of each field
  210. // in the message, so we only need to account for additional memory used by
  211. // the fields.
  212. size_t total_size = schema_.GetObjectSize();
  213. total_size += GetUnknownFields(message).SpaceUsedExcludingSelfLong();
  214. if (schema_.HasExtensionSet()) {
  215. total_size += GetExtensionSet(message).SpaceUsedExcludingSelfLong();
  216. }
  217. for (int i = 0; i <= last_non_weak_field_index_; i++) {
  218. const FieldDescriptor* field = descriptor_->field(i);
  219. if (field->is_repeated()) {
  220. switch (field->cpp_type()) {
  221. #define HANDLE_TYPE(UPPERCASE, LOWERCASE) \
  222. case FieldDescriptor::CPPTYPE_##UPPERCASE: \
  223. total_size += GetRaw<RepeatedField<LOWERCASE> >(message, field) \
  224. .SpaceUsedExcludingSelfLong(); \
  225. break
  226. HANDLE_TYPE(INT32, int32);
  227. HANDLE_TYPE(INT64, int64);
  228. HANDLE_TYPE(UINT32, uint32);
  229. HANDLE_TYPE(UINT64, uint64);
  230. HANDLE_TYPE(DOUBLE, double);
  231. HANDLE_TYPE(FLOAT, float);
  232. HANDLE_TYPE(BOOL, bool);
  233. HANDLE_TYPE(ENUM, int);
  234. #undef HANDLE_TYPE
  235. case FieldDescriptor::CPPTYPE_STRING:
  236. switch (field->options().ctype()) {
  237. default: // TODO(kenton): Support other string reps.
  238. case FieldOptions::STRING:
  239. total_size +=
  240. GetRaw<RepeatedPtrField<std::string> >(message, field)
  241. .SpaceUsedExcludingSelfLong();
  242. break;
  243. }
  244. break;
  245. case FieldDescriptor::CPPTYPE_MESSAGE:
  246. if (IsMapFieldInApi(field)) {
  247. total_size += GetRaw<internal::MapFieldBase>(message, field)
  248. .SpaceUsedExcludingSelfLong();
  249. } else {
  250. // We don't know which subclass of RepeatedPtrFieldBase the type is,
  251. // so we use RepeatedPtrFieldBase directly.
  252. total_size +=
  253. GetRaw<RepeatedPtrFieldBase>(message, field)
  254. .SpaceUsedExcludingSelfLong<GenericTypeHandler<Message> >();
  255. }
  256. break;
  257. }
  258. } else {
  259. if (field->containing_oneof() && !HasOneofField(message, field)) {
  260. continue;
  261. }
  262. switch (field->cpp_type()) {
  263. case FieldDescriptor::CPPTYPE_INT32:
  264. case FieldDescriptor::CPPTYPE_INT64:
  265. case FieldDescriptor::CPPTYPE_UINT32:
  266. case FieldDescriptor::CPPTYPE_UINT64:
  267. case FieldDescriptor::CPPTYPE_DOUBLE:
  268. case FieldDescriptor::CPPTYPE_FLOAT:
  269. case FieldDescriptor::CPPTYPE_BOOL:
  270. case FieldDescriptor::CPPTYPE_ENUM:
  271. // Field is inline, so we've already counted it.
  272. break;
  273. case FieldDescriptor::CPPTYPE_STRING: {
  274. switch (field->options().ctype()) {
  275. default: // TODO(kenton): Support other string reps.
  276. case FieldOptions::STRING: {
  277. if (IsInlined(field)) {
  278. const std::string* ptr =
  279. &GetField<InlinedStringField>(message, field).GetNoArena();
  280. total_size += StringSpaceUsedExcludingSelfLong(*ptr);
  281. break;
  282. }
  283. // Initially, the string points to the default value stored
  284. // in the prototype. Only count the string if it has been
  285. // changed from the default value.
  286. const std::string* default_ptr =
  287. &DefaultRaw<ArenaStringPtr>(field).Get();
  288. const std::string* ptr =
  289. &GetField<ArenaStringPtr>(message, field).Get();
  290. if (ptr != default_ptr) {
  291. // string fields are represented by just a pointer, so also
  292. // include sizeof(string) as well.
  293. total_size +=
  294. sizeof(*ptr) + StringSpaceUsedExcludingSelfLong(*ptr);
  295. }
  296. break;
  297. }
  298. }
  299. break;
  300. }
  301. case FieldDescriptor::CPPTYPE_MESSAGE:
  302. if (schema_.IsDefaultInstance(message)) {
  303. // For singular fields, the prototype just stores a pointer to the
  304. // external type's prototype, so there is no extra memory usage.
  305. } else {
  306. const Message* sub_message = GetRaw<const Message*>(message, field);
  307. if (sub_message != nullptr) {
  308. total_size += sub_message->SpaceUsedLong();
  309. }
  310. }
  311. break;
  312. }
  313. }
  314. }
  315. return total_size;
  316. }
  317. void Reflection::SwapField(Message* message1, Message* message2,
  318. const FieldDescriptor* field) const {
  319. if (field->is_repeated()) {
  320. switch (field->cpp_type()) {
  321. #define SWAP_ARRAYS(CPPTYPE, TYPE) \
  322. case FieldDescriptor::CPPTYPE_##CPPTYPE: \
  323. MutableRaw<RepeatedField<TYPE> >(message1, field) \
  324. ->Swap(MutableRaw<RepeatedField<TYPE> >(message2, field)); \
  325. break;
  326. SWAP_ARRAYS(INT32, int32);
  327. SWAP_ARRAYS(INT64, int64);
  328. SWAP_ARRAYS(UINT32, uint32);
  329. SWAP_ARRAYS(UINT64, uint64);
  330. SWAP_ARRAYS(FLOAT, float);
  331. SWAP_ARRAYS(DOUBLE, double);
  332. SWAP_ARRAYS(BOOL, bool);
  333. SWAP_ARRAYS(ENUM, int);
  334. #undef SWAP_ARRAYS
  335. case FieldDescriptor::CPPTYPE_STRING:
  336. switch (field->options().ctype()) {
  337. default: // TODO(kenton): Support other string reps.
  338. case FieldOptions::STRING:
  339. MutableRaw<RepeatedPtrFieldBase>(message1, field)
  340. ->Swap<GenericTypeHandler<std::string> >(
  341. MutableRaw<RepeatedPtrFieldBase>(message2, field));
  342. break;
  343. }
  344. break;
  345. case FieldDescriptor::CPPTYPE_MESSAGE:
  346. if (IsMapFieldInApi(field)) {
  347. MutableRaw<MapFieldBase>(message1, field)
  348. ->Swap(MutableRaw<MapFieldBase>(message2, field));
  349. } else {
  350. MutableRaw<RepeatedPtrFieldBase>(message1, field)
  351. ->Swap<GenericTypeHandler<Message> >(
  352. MutableRaw<RepeatedPtrFieldBase>(message2, field));
  353. }
  354. break;
  355. default:
  356. GOOGLE_LOG(FATAL) << "Unimplemented type: " << field->cpp_type();
  357. }
  358. } else {
  359. switch (field->cpp_type()) {
  360. #define SWAP_VALUES(CPPTYPE, TYPE) \
  361. case FieldDescriptor::CPPTYPE_##CPPTYPE: \
  362. std::swap(*MutableRaw<TYPE>(message1, field), \
  363. *MutableRaw<TYPE>(message2, field)); \
  364. break;
  365. SWAP_VALUES(INT32, int32);
  366. SWAP_VALUES(INT64, int64);
  367. SWAP_VALUES(UINT32, uint32);
  368. SWAP_VALUES(UINT64, uint64);
  369. SWAP_VALUES(FLOAT, float);
  370. SWAP_VALUES(DOUBLE, double);
  371. SWAP_VALUES(BOOL, bool);
  372. SWAP_VALUES(ENUM, int);
  373. #undef SWAP_VALUES
  374. case FieldDescriptor::CPPTYPE_MESSAGE:
  375. if (GetArena(message1) == GetArena(message2)) {
  376. std::swap(*MutableRaw<Message*>(message1, field),
  377. *MutableRaw<Message*>(message2, field));
  378. } else {
  379. Message** sub_msg1 = MutableRaw<Message*>(message1, field);
  380. Message** sub_msg2 = MutableRaw<Message*>(message2, field);
  381. if (*sub_msg1 == nullptr && *sub_msg2 == nullptr) break;
  382. if (*sub_msg1 && *sub_msg2) {
  383. (*sub_msg1)->GetReflection()->Swap(*sub_msg1, *sub_msg2);
  384. break;
  385. }
  386. if (*sub_msg1 == nullptr) {
  387. *sub_msg1 = (*sub_msg2)->New(message1->GetArena());
  388. (*sub_msg1)->CopyFrom(**sub_msg2);
  389. ClearField(message2, field);
  390. } else {
  391. *sub_msg2 = (*sub_msg1)->New(message2->GetArena());
  392. (*sub_msg2)->CopyFrom(**sub_msg1);
  393. ClearField(message1, field);
  394. }
  395. }
  396. break;
  397. case FieldDescriptor::CPPTYPE_STRING:
  398. switch (field->options().ctype()) {
  399. default: // TODO(kenton): Support other string reps.
  400. case FieldOptions::STRING: {
  401. Arena* arena1 = GetArena(message1);
  402. Arena* arena2 = GetArena(message2);
  403. if (IsInlined(field)) {
  404. InlinedStringField* string1 =
  405. MutableRaw<InlinedStringField>(message1, field);
  406. InlinedStringField* string2 =
  407. MutableRaw<InlinedStringField>(message2, field);
  408. string1->Swap(string2);
  409. break;
  410. }
  411. ArenaStringPtr* string1 =
  412. MutableRaw<ArenaStringPtr>(message1, field);
  413. ArenaStringPtr* string2 =
  414. MutableRaw<ArenaStringPtr>(message2, field);
  415. const std::string* default_ptr =
  416. &DefaultRaw<ArenaStringPtr>(field).Get();
  417. if (arena1 == arena2) {
  418. string1->Swap(string2, default_ptr, arena1);
  419. } else {
  420. const std::string temp = string1->Get();
  421. string1->Set(default_ptr, string2->Get(), arena1);
  422. string2->Set(default_ptr, temp, arena2);
  423. }
  424. } break;
  425. }
  426. break;
  427. default:
  428. GOOGLE_LOG(FATAL) << "Unimplemented type: " << field->cpp_type();
  429. }
  430. }
  431. }
  432. void Reflection::SwapOneofField(Message* message1, Message* message2,
  433. const OneofDescriptor* oneof_descriptor) const {
  434. uint32 oneof_case1 = GetOneofCase(*message1, oneof_descriptor);
  435. uint32 oneof_case2 = GetOneofCase(*message2, oneof_descriptor);
  436. int32 temp_int32;
  437. int64 temp_int64;
  438. uint32 temp_uint32;
  439. uint64 temp_uint64;
  440. float temp_float;
  441. double temp_double;
  442. bool temp_bool;
  443. int temp_int;
  444. Message* temp_message = nullptr;
  445. std::string temp_string;
  446. // Stores message1's oneof field to a temp variable.
  447. const FieldDescriptor* field1 = nullptr;
  448. if (oneof_case1 > 0) {
  449. field1 = descriptor_->FindFieldByNumber(oneof_case1);
  450. // oneof_descriptor->field(oneof_case1);
  451. switch (field1->cpp_type()) {
  452. #define GET_TEMP_VALUE(CPPTYPE, TYPE) \
  453. case FieldDescriptor::CPPTYPE_##CPPTYPE: \
  454. temp_##TYPE = GetField<TYPE>(*message1, field1); \
  455. break;
  456. GET_TEMP_VALUE(INT32, int32);
  457. GET_TEMP_VALUE(INT64, int64);
  458. GET_TEMP_VALUE(UINT32, uint32);
  459. GET_TEMP_VALUE(UINT64, uint64);
  460. GET_TEMP_VALUE(FLOAT, float);
  461. GET_TEMP_VALUE(DOUBLE, double);
  462. GET_TEMP_VALUE(BOOL, bool);
  463. GET_TEMP_VALUE(ENUM, int);
  464. #undef GET_TEMP_VALUE
  465. case FieldDescriptor::CPPTYPE_MESSAGE:
  466. temp_message = ReleaseMessage(message1, field1);
  467. break;
  468. case FieldDescriptor::CPPTYPE_STRING:
  469. temp_string = GetString(*message1, field1);
  470. break;
  471. default:
  472. GOOGLE_LOG(FATAL) << "Unimplemented type: " << field1->cpp_type();
  473. }
  474. }
  475. // Sets message1's oneof field from the message2's oneof field.
  476. if (oneof_case2 > 0) {
  477. const FieldDescriptor* field2 = descriptor_->FindFieldByNumber(oneof_case2);
  478. switch (field2->cpp_type()) {
  479. #define SET_ONEOF_VALUE1(CPPTYPE, TYPE) \
  480. case FieldDescriptor::CPPTYPE_##CPPTYPE: \
  481. SetField<TYPE>(message1, field2, GetField<TYPE>(*message2, field2)); \
  482. break;
  483. SET_ONEOF_VALUE1(INT32, int32);
  484. SET_ONEOF_VALUE1(INT64, int64);
  485. SET_ONEOF_VALUE1(UINT32, uint32);
  486. SET_ONEOF_VALUE1(UINT64, uint64);
  487. SET_ONEOF_VALUE1(FLOAT, float);
  488. SET_ONEOF_VALUE1(DOUBLE, double);
  489. SET_ONEOF_VALUE1(BOOL, bool);
  490. SET_ONEOF_VALUE1(ENUM, int);
  491. #undef SET_ONEOF_VALUE1
  492. case FieldDescriptor::CPPTYPE_MESSAGE:
  493. SetAllocatedMessage(message1, ReleaseMessage(message2, field2), field2);
  494. break;
  495. case FieldDescriptor::CPPTYPE_STRING:
  496. SetString(message1, field2, GetString(*message2, field2));
  497. break;
  498. default:
  499. GOOGLE_LOG(FATAL) << "Unimplemented type: " << field2->cpp_type();
  500. }
  501. } else {
  502. ClearOneof(message1, oneof_descriptor);
  503. }
  504. // Sets message2's oneof field from the temp variable.
  505. if (oneof_case1 > 0) {
  506. switch (field1->cpp_type()) {
  507. #define SET_ONEOF_VALUE2(CPPTYPE, TYPE) \
  508. case FieldDescriptor::CPPTYPE_##CPPTYPE: \
  509. SetField<TYPE>(message2, field1, temp_##TYPE); \
  510. break;
  511. SET_ONEOF_VALUE2(INT32, int32);
  512. SET_ONEOF_VALUE2(INT64, int64);
  513. SET_ONEOF_VALUE2(UINT32, uint32);
  514. SET_ONEOF_VALUE2(UINT64, uint64);
  515. SET_ONEOF_VALUE2(FLOAT, float);
  516. SET_ONEOF_VALUE2(DOUBLE, double);
  517. SET_ONEOF_VALUE2(BOOL, bool);
  518. SET_ONEOF_VALUE2(ENUM, int);
  519. #undef SET_ONEOF_VALUE2
  520. case FieldDescriptor::CPPTYPE_MESSAGE:
  521. SetAllocatedMessage(message2, temp_message, field1);
  522. break;
  523. case FieldDescriptor::CPPTYPE_STRING:
  524. SetString(message2, field1, temp_string);
  525. break;
  526. default:
  527. GOOGLE_LOG(FATAL) << "Unimplemented type: " << field1->cpp_type();
  528. }
  529. } else {
  530. ClearOneof(message2, oneof_descriptor);
  531. }
  532. }
  533. void Reflection::Swap(Message* message1, Message* message2) const {
  534. if (message1 == message2) return;
  535. // TODO(kenton): Other Reflection methods should probably check this too.
  536. GOOGLE_CHECK_EQ(message1->GetReflection(), this)
  537. << "First argument to Swap() (of type \""
  538. << message1->GetDescriptor()->full_name()
  539. << "\") is not compatible with this reflection object (which is for type "
  540. "\""
  541. << descriptor_->full_name()
  542. << "\"). Note that the exact same class is required; not just the same "
  543. "descriptor.";
  544. GOOGLE_CHECK_EQ(message2->GetReflection(), this)
  545. << "Second argument to Swap() (of type \""
  546. << message2->GetDescriptor()->full_name()
  547. << "\") is not compatible with this reflection object (which is for type "
  548. "\""
  549. << descriptor_->full_name()
  550. << "\"). Note that the exact same class is required; not just the same "
  551. "descriptor.";
  552. // Check that both messages are in the same arena (or both on the heap). We
  553. // need to copy all data if not, due to ownership semantics.
  554. if (GetArena(message1) != GetArena(message2)) {
  555. // Slow copy path.
  556. // Use our arena as temp space, if available.
  557. Message* temp = message1->New(GetArena(message1));
  558. temp->MergeFrom(*message2);
  559. message2->CopyFrom(*message1);
  560. Swap(message1, temp);
  561. if (GetArena(message1) == nullptr) {
  562. delete temp;
  563. }
  564. return;
  565. }
  566. if (schema_.HasHasbits()) {
  567. uint32* has_bits1 = MutableHasBits(message1);
  568. uint32* has_bits2 = MutableHasBits(message2);
  569. int fields_with_has_bits = 0;
  570. for (int i = 0; i < descriptor_->field_count(); i++) {
  571. const FieldDescriptor* field = descriptor_->field(i);
  572. if (field->is_repeated() || field->containing_oneof()) {
  573. continue;
  574. }
  575. fields_with_has_bits++;
  576. }
  577. int has_bits_size = (fields_with_has_bits + 31) / 32;
  578. for (int i = 0; i < has_bits_size; i++) {
  579. std::swap(has_bits1[i], has_bits2[i]);
  580. }
  581. }
  582. for (int i = 0; i <= last_non_weak_field_index_; i++) {
  583. const FieldDescriptor* field = descriptor_->field(i);
  584. if (field->containing_oneof()) continue;
  585. SwapField(message1, message2, field);
  586. }
  587. const int oneof_decl_count = descriptor_->oneof_decl_count();
  588. for (int i = 0; i < oneof_decl_count; i++) {
  589. SwapOneofField(message1, message2, descriptor_->oneof_decl(i));
  590. }
  591. if (schema_.HasExtensionSet()) {
  592. MutableExtensionSet(message1)->Swap(MutableExtensionSet(message2));
  593. }
  594. MutableUnknownFields(message1)->Swap(MutableUnknownFields(message2));
  595. }
  596. void Reflection::SwapFields(
  597. Message* message1, Message* message2,
  598. const std::vector<const FieldDescriptor*>& fields) const {
  599. if (message1 == message2) return;
  600. // TODO(kenton): Other Reflection methods should probably check this too.
  601. GOOGLE_CHECK_EQ(message1->GetReflection(), this)
  602. << "First argument to SwapFields() (of type \""
  603. << message1->GetDescriptor()->full_name()
  604. << "\") is not compatible with this reflection object (which is for type "
  605. "\""
  606. << descriptor_->full_name()
  607. << "\"). Note that the exact same class is required; not just the same "
  608. "descriptor.";
  609. GOOGLE_CHECK_EQ(message2->GetReflection(), this)
  610. << "Second argument to SwapFields() (of type \""
  611. << message2->GetDescriptor()->full_name()
  612. << "\") is not compatible with this reflection object (which is for type "
  613. "\""
  614. << descriptor_->full_name()
  615. << "\"). Note that the exact same class is required; not just the same "
  616. "descriptor.";
  617. std::set<int> swapped_oneof;
  618. const int fields_size = static_cast<int>(fields.size());
  619. for (int i = 0; i < fields_size; i++) {
  620. const FieldDescriptor* field = fields[i];
  621. if (field->is_extension()) {
  622. MutableExtensionSet(message1)->SwapExtension(
  623. MutableExtensionSet(message2), field->number());
  624. } else {
  625. if (field->containing_oneof()) {
  626. int oneof_index = field->containing_oneof()->index();
  627. // Only swap the oneof field once.
  628. if (swapped_oneof.find(oneof_index) != swapped_oneof.end()) {
  629. continue;
  630. }
  631. swapped_oneof.insert(oneof_index);
  632. SwapOneofField(message1, message2, field->containing_oneof());
  633. } else {
  634. // Swap has bit for non-repeated fields. We have already checked for
  635. // oneof already.
  636. if (!field->is_repeated()) {
  637. SwapBit(message1, message2, field);
  638. }
  639. // Swap field.
  640. SwapField(message1, message2, field);
  641. }
  642. }
  643. }
  644. }
  645. // -------------------------------------------------------------------
  646. bool Reflection::HasField(const Message& message,
  647. const FieldDescriptor* field) const {
  648. USAGE_CHECK_MESSAGE_TYPE(HasField);
  649. USAGE_CHECK_SINGULAR(HasField);
  650. if (field->is_extension()) {
  651. return GetExtensionSet(message).Has(field->number());
  652. } else {
  653. if (field->containing_oneof()) {
  654. return HasOneofField(message, field);
  655. } else {
  656. return HasBit(message, field);
  657. }
  658. }
  659. }
  660. int Reflection::FieldSize(const Message& message,
  661. const FieldDescriptor* field) const {
  662. USAGE_CHECK_MESSAGE_TYPE(FieldSize);
  663. USAGE_CHECK_REPEATED(FieldSize);
  664. if (field->is_extension()) {
  665. return GetExtensionSet(message).ExtensionSize(field->number());
  666. } else {
  667. switch (field->cpp_type()) {
  668. #define HANDLE_TYPE(UPPERCASE, LOWERCASE) \
  669. case FieldDescriptor::CPPTYPE_##UPPERCASE: \
  670. return GetRaw<RepeatedField<LOWERCASE> >(message, field).size()
  671. HANDLE_TYPE(INT32, int32);
  672. HANDLE_TYPE(INT64, int64);
  673. HANDLE_TYPE(UINT32, uint32);
  674. HANDLE_TYPE(UINT64, uint64);
  675. HANDLE_TYPE(DOUBLE, double);
  676. HANDLE_TYPE(FLOAT, float);
  677. HANDLE_TYPE(BOOL, bool);
  678. HANDLE_TYPE(ENUM, int);
  679. #undef HANDLE_TYPE
  680. case FieldDescriptor::CPPTYPE_STRING:
  681. case FieldDescriptor::CPPTYPE_MESSAGE:
  682. if (IsMapFieldInApi(field)) {
  683. const internal::MapFieldBase& map =
  684. GetRaw<MapFieldBase>(message, field);
  685. if (map.IsRepeatedFieldValid()) {
  686. return map.GetRepeatedField().size();
  687. } else {
  688. // No need to materialize the repeated field if it is out of sync:
  689. // its size will be the same as the map's size.
  690. return map.size();
  691. }
  692. } else {
  693. return GetRaw<RepeatedPtrFieldBase>(message, field).size();
  694. }
  695. }
  696. GOOGLE_LOG(FATAL) << "Can't get here.";
  697. return 0;
  698. }
  699. }
  700. void Reflection::ClearField(Message* message,
  701. const FieldDescriptor* field) const {
  702. USAGE_CHECK_MESSAGE_TYPE(ClearField);
  703. if (field->is_extension()) {
  704. MutableExtensionSet(message)->ClearExtension(field->number());
  705. } else if (!field->is_repeated()) {
  706. if (field->containing_oneof()) {
  707. ClearOneofField(message, field);
  708. return;
  709. }
  710. if (HasBit(*message, field)) {
  711. ClearBit(message, field);
  712. // We need to set the field back to its default value.
  713. switch (field->cpp_type()) {
  714. #define CLEAR_TYPE(CPPTYPE, TYPE) \
  715. case FieldDescriptor::CPPTYPE_##CPPTYPE: \
  716. *MutableRaw<TYPE>(message, field) = field->default_value_##TYPE(); \
  717. break;
  718. CLEAR_TYPE(INT32, int32);
  719. CLEAR_TYPE(INT64, int64);
  720. CLEAR_TYPE(UINT32, uint32);
  721. CLEAR_TYPE(UINT64, uint64);
  722. CLEAR_TYPE(FLOAT, float);
  723. CLEAR_TYPE(DOUBLE, double);
  724. CLEAR_TYPE(BOOL, bool);
  725. #undef CLEAR_TYPE
  726. case FieldDescriptor::CPPTYPE_ENUM:
  727. *MutableRaw<int>(message, field) =
  728. field->default_value_enum()->number();
  729. break;
  730. case FieldDescriptor::CPPTYPE_STRING: {
  731. switch (field->options().ctype()) {
  732. default: // TODO(kenton): Support other string reps.
  733. case FieldOptions::STRING: {
  734. if (IsInlined(field)) {
  735. const std::string* default_ptr =
  736. &DefaultRaw<InlinedStringField>(field).GetNoArena();
  737. MutableRaw<InlinedStringField>(message, field)
  738. ->SetNoArena(default_ptr, *default_ptr);
  739. break;
  740. }
  741. const std::string* default_ptr =
  742. &DefaultRaw<ArenaStringPtr>(field).Get();
  743. MutableRaw<ArenaStringPtr>(message, field)
  744. ->SetAllocated(default_ptr, nullptr, GetArena(message));
  745. break;
  746. }
  747. }
  748. break;
  749. }
  750. case FieldDescriptor::CPPTYPE_MESSAGE:
  751. if (!schema_.HasHasbits()) {
  752. // Proto3 does not have has-bits and we need to set a message field
  753. // to nullptr in order to indicate its un-presence.
  754. if (GetArena(message) == nullptr) {
  755. delete *MutableRaw<Message*>(message, field);
  756. }
  757. *MutableRaw<Message*>(message, field) = nullptr;
  758. } else {
  759. (*MutableRaw<Message*>(message, field))->Clear();
  760. }
  761. break;
  762. }
  763. }
  764. } else {
  765. switch (field->cpp_type()) {
  766. #define HANDLE_TYPE(UPPERCASE, LOWERCASE) \
  767. case FieldDescriptor::CPPTYPE_##UPPERCASE: \
  768. MutableRaw<RepeatedField<LOWERCASE> >(message, field)->Clear(); \
  769. break
  770. HANDLE_TYPE(INT32, int32);
  771. HANDLE_TYPE(INT64, int64);
  772. HANDLE_TYPE(UINT32, uint32);
  773. HANDLE_TYPE(UINT64, uint64);
  774. HANDLE_TYPE(DOUBLE, double);
  775. HANDLE_TYPE(FLOAT, float);
  776. HANDLE_TYPE(BOOL, bool);
  777. HANDLE_TYPE(ENUM, int);
  778. #undef HANDLE_TYPE
  779. case FieldDescriptor::CPPTYPE_STRING: {
  780. switch (field->options().ctype()) {
  781. default: // TODO(kenton): Support other string reps.
  782. case FieldOptions::STRING:
  783. MutableRaw<RepeatedPtrField<std::string> >(message, field)->Clear();
  784. break;
  785. }
  786. break;
  787. }
  788. case FieldDescriptor::CPPTYPE_MESSAGE: {
  789. if (IsMapFieldInApi(field)) {
  790. MutableRaw<MapFieldBase>(message, field)->Clear();
  791. } else {
  792. // We don't know which subclass of RepeatedPtrFieldBase the type is,
  793. // so we use RepeatedPtrFieldBase directly.
  794. MutableRaw<RepeatedPtrFieldBase>(message, field)
  795. ->Clear<GenericTypeHandler<Message> >();
  796. }
  797. break;
  798. }
  799. }
  800. }
  801. }
  802. void Reflection::RemoveLast(Message* message,
  803. const FieldDescriptor* field) const {
  804. USAGE_CHECK_MESSAGE_TYPE(RemoveLast);
  805. USAGE_CHECK_REPEATED(RemoveLast);
  806. if (field->is_extension()) {
  807. MutableExtensionSet(message)->RemoveLast(field->number());
  808. } else {
  809. switch (field->cpp_type()) {
  810. #define HANDLE_TYPE(UPPERCASE, LOWERCASE) \
  811. case FieldDescriptor::CPPTYPE_##UPPERCASE: \
  812. MutableRaw<RepeatedField<LOWERCASE> >(message, field)->RemoveLast(); \
  813. break
  814. HANDLE_TYPE(INT32, int32);
  815. HANDLE_TYPE(INT64, int64);
  816. HANDLE_TYPE(UINT32, uint32);
  817. HANDLE_TYPE(UINT64, uint64);
  818. HANDLE_TYPE(DOUBLE, double);
  819. HANDLE_TYPE(FLOAT, float);
  820. HANDLE_TYPE(BOOL, bool);
  821. HANDLE_TYPE(ENUM, int);
  822. #undef HANDLE_TYPE
  823. case FieldDescriptor::CPPTYPE_STRING:
  824. switch (field->options().ctype()) {
  825. default: // TODO(kenton): Support other string reps.
  826. case FieldOptions::STRING:
  827. MutableRaw<RepeatedPtrField<std::string> >(message, field)
  828. ->RemoveLast();
  829. break;
  830. }
  831. break;
  832. case FieldDescriptor::CPPTYPE_MESSAGE:
  833. if (IsMapFieldInApi(field)) {
  834. MutableRaw<MapFieldBase>(message, field)
  835. ->MutableRepeatedField()
  836. ->RemoveLast<GenericTypeHandler<Message> >();
  837. } else {
  838. MutableRaw<RepeatedPtrFieldBase>(message, field)
  839. ->RemoveLast<GenericTypeHandler<Message> >();
  840. }
  841. break;
  842. }
  843. }
  844. }
  845. Message* Reflection::ReleaseLast(Message* message,
  846. const FieldDescriptor* field) const {
  847. USAGE_CHECK_ALL(ReleaseLast, REPEATED, MESSAGE);
  848. if (field->is_extension()) {
  849. return static_cast<Message*>(
  850. MutableExtensionSet(message)->ReleaseLast(field->number()));
  851. } else {
  852. if (IsMapFieldInApi(field)) {
  853. return MutableRaw<MapFieldBase>(message, field)
  854. ->MutableRepeatedField()
  855. ->ReleaseLast<GenericTypeHandler<Message> >();
  856. } else {
  857. return MutableRaw<RepeatedPtrFieldBase>(message, field)
  858. ->ReleaseLast<GenericTypeHandler<Message> >();
  859. }
  860. }
  861. }
  862. void Reflection::SwapElements(Message* message, const FieldDescriptor* field,
  863. int index1, int index2) const {
  864. USAGE_CHECK_MESSAGE_TYPE(Swap);
  865. USAGE_CHECK_REPEATED(Swap);
  866. if (field->is_extension()) {
  867. MutableExtensionSet(message)->SwapElements(field->number(), index1, index2);
  868. } else {
  869. switch (field->cpp_type()) {
  870. #define HANDLE_TYPE(UPPERCASE, LOWERCASE) \
  871. case FieldDescriptor::CPPTYPE_##UPPERCASE: \
  872. MutableRaw<RepeatedField<LOWERCASE> >(message, field) \
  873. ->SwapElements(index1, index2); \
  874. break
  875. HANDLE_TYPE(INT32, int32);
  876. HANDLE_TYPE(INT64, int64);
  877. HANDLE_TYPE(UINT32, uint32);
  878. HANDLE_TYPE(UINT64, uint64);
  879. HANDLE_TYPE(DOUBLE, double);
  880. HANDLE_TYPE(FLOAT, float);
  881. HANDLE_TYPE(BOOL, bool);
  882. HANDLE_TYPE(ENUM, int);
  883. #undef HANDLE_TYPE
  884. case FieldDescriptor::CPPTYPE_STRING:
  885. case FieldDescriptor::CPPTYPE_MESSAGE:
  886. if (IsMapFieldInApi(field)) {
  887. MutableRaw<MapFieldBase>(message, field)
  888. ->MutableRepeatedField()
  889. ->SwapElements(index1, index2);
  890. } else {
  891. MutableRaw<RepeatedPtrFieldBase>(message, field)
  892. ->SwapElements(index1, index2);
  893. }
  894. break;
  895. }
  896. }
  897. }
  898. namespace {
  899. // Comparison functor for sorting FieldDescriptors by field number.
  900. struct FieldNumberSorter {
  901. bool operator()(const FieldDescriptor* left,
  902. const FieldDescriptor* right) const {
  903. return left->number() < right->number();
  904. }
  905. };
  906. bool IsIndexInHasBitSet(const uint32* has_bit_set, uint32 has_bit_index) {
  907. GOOGLE_DCHECK_NE(has_bit_index, ~0u);
  908. return ((has_bit_set[has_bit_index / 32] >> (has_bit_index % 32)) &
  909. static_cast<uint32>(1)) != 0;
  910. }
  911. bool CreateUnknownEnumValues(const FileDescriptor* file) {
  912. return file->syntax() == FileDescriptor::SYNTAX_PROTO3;
  913. }
  914. } // namespace
  915. void Reflection::ListFields(const Message& message,
  916. std::vector<const FieldDescriptor*>* output) const {
  917. output->clear();
  918. // Optimization: The default instance never has any fields set.
  919. if (schema_.IsDefaultInstance(message)) return;
  920. // Optimization: Avoid calling GetHasBits() and HasOneofField() many times
  921. // within the field loop. We allow this violation of ReflectionSchema
  922. // encapsulation because this function takes a noticable about of CPU
  923. // fleetwide and properly allowing this optimization through public interfaces
  924. // seems more trouble than it is worth.
  925. const uint32* const has_bits =
  926. schema_.HasHasbits() ? GetHasBits(message) : nullptr;
  927. const uint32* const has_bits_indices = schema_.has_bit_indices_;
  928. output->reserve(descriptor_->field_count());
  929. for (int i = 0; i <= last_non_weak_field_index_; i++) {
  930. const FieldDescriptor* field = descriptor_->field(i);
  931. if (field->is_repeated()) {
  932. if (FieldSize(message, field) > 0) {
  933. output->push_back(field);
  934. }
  935. } else {
  936. const OneofDescriptor* containing_oneof = field->containing_oneof();
  937. if (containing_oneof) {
  938. const uint32* const oneof_case_array = GetConstPointerAtOffset<uint32>(
  939. &message, schema_.oneof_case_offset_);
  940. // Equivalent to: HasOneofField(message, field)
  941. if (oneof_case_array[containing_oneof->index()] == field->number()) {
  942. output->push_back(field);
  943. }
  944. } else if (has_bits) {
  945. // Equivalent to: HasBit(message, field)
  946. if (IsIndexInHasBitSet(has_bits, has_bits_indices[i])) {
  947. output->push_back(field);
  948. }
  949. } else if (HasBit(message, field)) { // Fall back on proto3-style HasBit.
  950. output->push_back(field);
  951. }
  952. }
  953. }
  954. if (schema_.HasExtensionSet()) {
  955. GetExtensionSet(message).AppendToList(descriptor_, descriptor_pool_,
  956. output);
  957. }
  958. // ListFields() must sort output by field number.
  959. std::sort(output->begin(), output->end(), FieldNumberSorter());
  960. }
  961. // -------------------------------------------------------------------
  962. #undef DEFINE_PRIMITIVE_ACCESSORS
  963. #define DEFINE_PRIMITIVE_ACCESSORS(TYPENAME, TYPE, PASSTYPE, CPPTYPE) \
  964. PASSTYPE Reflection::Get##TYPENAME(const Message& message, \
  965. const FieldDescriptor* field) const { \
  966. USAGE_CHECK_ALL(Get##TYPENAME, SINGULAR, CPPTYPE); \
  967. if (field->is_extension()) { \
  968. return GetExtensionSet(message).Get##TYPENAME( \
  969. field->number(), field->default_value_##PASSTYPE()); \
  970. } else { \
  971. return GetField<TYPE>(message, field); \
  972. } \
  973. } \
  974. \
  975. void Reflection::Set##TYPENAME( \
  976. Message* message, const FieldDescriptor* field, PASSTYPE value) const { \
  977. USAGE_CHECK_ALL(Set##TYPENAME, SINGULAR, CPPTYPE); \
  978. if (field->is_extension()) { \
  979. return MutableExtensionSet(message)->Set##TYPENAME( \
  980. field->number(), field->type(), value, field); \
  981. } else { \
  982. SetField<TYPE>(message, field, value); \
  983. } \
  984. } \
  985. \
  986. PASSTYPE Reflection::GetRepeated##TYPENAME( \
  987. const Message& message, const FieldDescriptor* field, int index) const { \
  988. USAGE_CHECK_ALL(GetRepeated##TYPENAME, REPEATED, CPPTYPE); \
  989. if (field->is_extension()) { \
  990. return GetExtensionSet(message).GetRepeated##TYPENAME(field->number(), \
  991. index); \
  992. } else { \
  993. return GetRepeatedField<TYPE>(message, field, index); \
  994. } \
  995. } \
  996. \
  997. void Reflection::SetRepeated##TYPENAME(Message* message, \
  998. const FieldDescriptor* field, \
  999. int index, PASSTYPE value) const { \
  1000. USAGE_CHECK_ALL(SetRepeated##TYPENAME, REPEATED, CPPTYPE); \
  1001. if (field->is_extension()) { \
  1002. MutableExtensionSet(message)->SetRepeated##TYPENAME(field->number(), \
  1003. index, value); \
  1004. } else { \
  1005. SetRepeatedField<TYPE>(message, field, index, value); \
  1006. } \
  1007. } \
  1008. \
  1009. void Reflection::Add##TYPENAME( \
  1010. Message* message, const FieldDescriptor* field, PASSTYPE value) const { \
  1011. USAGE_CHECK_ALL(Add##TYPENAME, REPEATED, CPPTYPE); \
  1012. if (field->is_extension()) { \
  1013. MutableExtensionSet(message)->Add##TYPENAME( \
  1014. field->number(), field->type(), field->options().packed(), value, \
  1015. field); \
  1016. } else { \
  1017. AddField<TYPE>(message, field, value); \
  1018. } \
  1019. }
  1020. DEFINE_PRIMITIVE_ACCESSORS(Int32, int32, int32, INT32)
  1021. DEFINE_PRIMITIVE_ACCESSORS(Int64, int64, int64, INT64)
  1022. DEFINE_PRIMITIVE_ACCESSORS(UInt32, uint32, uint32, UINT32)
  1023. DEFINE_PRIMITIVE_ACCESSORS(UInt64, uint64, uint64, UINT64)
  1024. DEFINE_PRIMITIVE_ACCESSORS(Float, float, float, FLOAT)
  1025. DEFINE_PRIMITIVE_ACCESSORS(Double, double, double, DOUBLE)
  1026. DEFINE_PRIMITIVE_ACCESSORS(Bool, bool, bool, BOOL)
  1027. #undef DEFINE_PRIMITIVE_ACCESSORS
  1028. // -------------------------------------------------------------------
  1029. std::string Reflection::GetString(const Message& message,
  1030. const FieldDescriptor* field) const {
  1031. USAGE_CHECK_ALL(GetString, SINGULAR, STRING);
  1032. if (field->is_extension()) {
  1033. return GetExtensionSet(message).GetString(field->number(),
  1034. field->default_value_string());
  1035. } else {
  1036. switch (field->options().ctype()) {
  1037. default: // TODO(kenton): Support other string reps.
  1038. case FieldOptions::STRING: {
  1039. if (IsInlined(field)) {
  1040. return GetField<InlinedStringField>(message, field).GetNoArena();
  1041. }
  1042. return GetField<ArenaStringPtr>(message, field).Get();
  1043. }
  1044. }
  1045. }
  1046. }
  1047. const std::string& Reflection::GetStringReference(const Message& message,
  1048. const FieldDescriptor* field,
  1049. std::string* scratch) const {
  1050. USAGE_CHECK_ALL(GetStringReference, SINGULAR, STRING);
  1051. if (field->is_extension()) {
  1052. return GetExtensionSet(message).GetString(field->number(),
  1053. field->default_value_string());
  1054. } else {
  1055. switch (field->options().ctype()) {
  1056. default: // TODO(kenton): Support other string reps.
  1057. case FieldOptions::STRING: {
  1058. if (IsInlined(field)) {
  1059. return GetField<InlinedStringField>(message, field).GetNoArena();
  1060. }
  1061. return GetField<ArenaStringPtr>(message, field).Get();
  1062. }
  1063. }
  1064. }
  1065. }
  1066. void Reflection::SetString(Message* message, const FieldDescriptor* field,
  1067. std::string value) const {
  1068. USAGE_CHECK_ALL(SetString, SINGULAR, STRING);
  1069. if (field->is_extension()) {
  1070. return MutableExtensionSet(message)->SetString(
  1071. field->number(), field->type(), std::move(value), field);
  1072. } else {
  1073. switch (field->options().ctype()) {
  1074. default: // TODO(kenton): Support other string reps.
  1075. case FieldOptions::STRING: {
  1076. if (IsInlined(field)) {
  1077. MutableField<InlinedStringField>(message, field)
  1078. ->SetNoArena(nullptr, std::move(value));
  1079. break;
  1080. }
  1081. const std::string* default_ptr =
  1082. &DefaultRaw<ArenaStringPtr>(field).Get();
  1083. if (field->containing_oneof() && !HasOneofField(*message, field)) {
  1084. ClearOneof(message, field->containing_oneof());
  1085. MutableField<ArenaStringPtr>(message, field)
  1086. ->UnsafeSetDefault(default_ptr);
  1087. }
  1088. MutableField<ArenaStringPtr>(message, field)
  1089. ->Mutable(default_ptr, GetArena(message))
  1090. ->assign(std::move(value));
  1091. break;
  1092. }
  1093. }
  1094. }
  1095. }
  1096. std::string Reflection::GetRepeatedString(const Message& message,
  1097. const FieldDescriptor* field,
  1098. int index) const {
  1099. USAGE_CHECK_ALL(GetRepeatedString, REPEATED, STRING);
  1100. if (field->is_extension()) {
  1101. return GetExtensionSet(message).GetRepeatedString(field->number(), index);
  1102. } else {
  1103. switch (field->options().ctype()) {
  1104. default: // TODO(kenton): Support other string reps.
  1105. case FieldOptions::STRING:
  1106. return GetRepeatedPtrField<std::string>(message, field, index);
  1107. }
  1108. }
  1109. }
  1110. const std::string& Reflection::GetRepeatedStringReference(
  1111. const Message& message, const FieldDescriptor* field, int index,
  1112. std::string* scratch) const {
  1113. USAGE_CHECK_ALL(GetRepeatedStringReference, REPEATED, STRING);
  1114. if (field->is_extension()) {
  1115. return GetExtensionSet(message).GetRepeatedString(field->number(), index);
  1116. } else {
  1117. switch (field->options().ctype()) {
  1118. default: // TODO(kenton): Support other string reps.
  1119. case FieldOptions::STRING:
  1120. return GetRepeatedPtrField<std::string>(message, field, index);
  1121. }
  1122. }
  1123. }
  1124. void Reflection::SetRepeatedString(Message* message,
  1125. const FieldDescriptor* field, int index,
  1126. std::string value) const {
  1127. USAGE_CHECK_ALL(SetRepeatedString, REPEATED, STRING);
  1128. if (field->is_extension()) {
  1129. MutableExtensionSet(message)->SetRepeatedString(field->number(), index,
  1130. std::move(value));
  1131. } else {
  1132. switch (field->options().ctype()) {
  1133. default: // TODO(kenton): Support other string reps.
  1134. case FieldOptions::STRING:
  1135. MutableRepeatedField<std::string>(message, field, index)
  1136. ->assign(std::move(value));
  1137. break;
  1138. }
  1139. }
  1140. }
  1141. void Reflection::AddString(Message* message, const FieldDescriptor* field,
  1142. std::string value) const {
  1143. USAGE_CHECK_ALL(AddString, REPEATED, STRING);
  1144. if (field->is_extension()) {
  1145. MutableExtensionSet(message)->AddString(field->number(), field->type(),
  1146. std::move(value), field);
  1147. } else {
  1148. switch (field->options().ctype()) {
  1149. default: // TODO(kenton): Support other string reps.
  1150. case FieldOptions::STRING:
  1151. AddField<std::string>(message, field)->assign(std::move(value));
  1152. break;
  1153. }
  1154. }
  1155. }
  1156. // -------------------------------------------------------------------
  1157. const EnumValueDescriptor* Reflection::GetEnum(
  1158. const Message& message, const FieldDescriptor* field) const {
  1159. // Usage checked by GetEnumValue.
  1160. int value = GetEnumValue(message, field);
  1161. return field->enum_type()->FindValueByNumberCreatingIfUnknown(value);
  1162. }
  1163. int Reflection::GetEnumValue(const Message& message,
  1164. const FieldDescriptor* field) const {
  1165. USAGE_CHECK_ALL(GetEnumValue, SINGULAR, ENUM);
  1166. int32 value;
  1167. if (field->is_extension()) {
  1168. value = GetExtensionSet(message).GetEnum(
  1169. field->number(), field->default_value_enum()->number());
  1170. } else {
  1171. value = GetField<int>(message, field);
  1172. }
  1173. return value;
  1174. }
  1175. void Reflection::SetEnum(Message* message, const FieldDescriptor* field,
  1176. const EnumValueDescriptor* value) const {
  1177. // Usage checked by SetEnumValue.
  1178. USAGE_CHECK_ENUM_VALUE(SetEnum);
  1179. SetEnumValueInternal(message, field, value->number());
  1180. }
  1181. void Reflection::SetEnumValue(Message* message, const FieldDescriptor* field,
  1182. int value) const {
  1183. USAGE_CHECK_ALL(SetEnumValue, SINGULAR, ENUM);
  1184. if (!CreateUnknownEnumValues(descriptor_->file())) {
  1185. // Check that the value is valid if we don't support direct storage of
  1186. // unknown enum values.
  1187. const EnumValueDescriptor* value_desc =
  1188. field->enum_type()->FindValueByNumber(value);
  1189. if (value_desc == nullptr) {
  1190. MutableUnknownFields(message)->AddVarint(field->number(), value);
  1191. return;
  1192. }
  1193. }
  1194. SetEnumValueInternal(message, field, value);
  1195. }
  1196. void Reflection::SetEnumValueInternal(Message* message,
  1197. const FieldDescriptor* field,
  1198. int value) const {
  1199. if (field->is_extension()) {
  1200. MutableExtensionSet(message)->SetEnum(field->number(), field->type(), value,
  1201. field);
  1202. } else {
  1203. SetField<int>(message, field, value);
  1204. }
  1205. }
  1206. const EnumValueDescriptor* Reflection::GetRepeatedEnum(
  1207. const Message& message, const FieldDescriptor* field, int index) const {
  1208. // Usage checked by GetRepeatedEnumValue.
  1209. int value = GetRepeatedEnumValue(message, field, index);
  1210. return field->enum_type()->FindValueByNumberCreatingIfUnknown(value);
  1211. }
  1212. int Reflection::GetRepeatedEnumValue(const Message& message,
  1213. const FieldDescriptor* field,
  1214. int index) const {
  1215. USAGE_CHECK_ALL(GetRepeatedEnumValue, REPEATED, ENUM);
  1216. int value;
  1217. if (field->is_extension()) {
  1218. value = GetExtensionSet(message).GetRepeatedEnum(field->number(), index);
  1219. } else {
  1220. value = GetRepeatedField<int>(message, field, index);
  1221. }
  1222. return value;
  1223. }
  1224. void Reflection::SetRepeatedEnum(Message* message, const FieldDescriptor* field,
  1225. int index,
  1226. const EnumValueDescriptor* value) const {
  1227. // Usage checked by SetRepeatedEnumValue.
  1228. USAGE_CHECK_ENUM_VALUE(SetRepeatedEnum);
  1229. SetRepeatedEnumValueInternal(message, field, index, value->number());
  1230. }
  1231. void Reflection::SetRepeatedEnumValue(Message* message,
  1232. const FieldDescriptor* field, int index,
  1233. int value) const {
  1234. USAGE_CHECK_ALL(SetRepeatedEnum, REPEATED, ENUM);
  1235. if (!CreateUnknownEnumValues(descriptor_->file())) {
  1236. // Check that the value is valid if we don't support direct storage of
  1237. // unknown enum values.
  1238. const EnumValueDescriptor* value_desc =
  1239. field->enum_type()->FindValueByNumber(value);
  1240. if (value_desc == nullptr) {
  1241. MutableUnknownFields(message)->AddVarint(field->number(), value);
  1242. return;
  1243. }
  1244. }
  1245. SetRepeatedEnumValueInternal(message, field, index, value);
  1246. }
  1247. void Reflection::SetRepeatedEnumValueInternal(Message* message,
  1248. const FieldDescriptor* field,
  1249. int index, int value) const {
  1250. if (field->is_extension()) {
  1251. MutableExtensionSet(message)->SetRepeatedEnum(field->number(), index,
  1252. value);
  1253. } else {
  1254. SetRepeatedField<int>(message, field, index, value);
  1255. }
  1256. }
  1257. void Reflection::AddEnum(Message* message, const FieldDescriptor* field,
  1258. const EnumValueDescriptor* value) const {
  1259. // Usage checked by AddEnumValue.
  1260. USAGE_CHECK_ENUM_VALUE(AddEnum);
  1261. AddEnumValueInternal(message, field, value->number());
  1262. }
  1263. void Reflection::AddEnumValue(Message* message, const FieldDescriptor* field,
  1264. int value) const {
  1265. USAGE_CHECK_ALL(AddEnum, REPEATED, ENUM);
  1266. if (!CreateUnknownEnumValues(descriptor_->file())) {
  1267. // Check that the value is valid if we don't support direct storage of
  1268. // unknown enum values.
  1269. const EnumValueDescriptor* value_desc =
  1270. field->enum_type()->FindValueByNumber(value);
  1271. if (value_desc == nullptr) {
  1272. MutableUnknownFields(message)->AddVarint(field->number(), value);
  1273. return;
  1274. }
  1275. }
  1276. AddEnumValueInternal(message, field, value);
  1277. }
  1278. void Reflection::AddEnumValueInternal(Message* message,
  1279. const FieldDescriptor* field,
  1280. int value) const {
  1281. if (field->is_extension()) {
  1282. MutableExtensionSet(message)->AddEnum(field->number(), field->type(),
  1283. field->options().packed(), value,
  1284. field);
  1285. } else {
  1286. AddField<int>(message, field, value);
  1287. }
  1288. }
  1289. // -------------------------------------------------------------------
  1290. const Message& Reflection::GetMessage(const Message& message,
  1291. const FieldDescriptor* field,
  1292. MessageFactory* factory) const {
  1293. USAGE_CHECK_ALL(GetMessage, SINGULAR, MESSAGE);
  1294. if (factory == nullptr) factory = message_factory_;
  1295. if (field->is_extension()) {
  1296. return static_cast<const Message&>(GetExtensionSet(message).GetMessage(
  1297. field->number(), field->message_type(), factory));
  1298. } else {
  1299. const Message* result = GetRaw<const Message*>(message, field);
  1300. if (result == nullptr) {
  1301. result = DefaultRaw<const Message*>(field);
  1302. }
  1303. return *result;
  1304. }
  1305. }
  1306. Message* Reflection::MutableMessage(Message* message,
  1307. const FieldDescriptor* field,
  1308. MessageFactory* factory) const {
  1309. USAGE_CHECK_ALL(MutableMessage, SINGULAR, MESSAGE);
  1310. if (factory == nullptr) factory = message_factory_;
  1311. if (field->is_extension()) {
  1312. return static_cast<Message*>(
  1313. MutableExtensionSet(message)->MutableMessage(field, factory));
  1314. } else {
  1315. Message* result;
  1316. Message** result_holder = MutableRaw<Message*>(message, field);
  1317. if (field->containing_oneof()) {
  1318. if (!HasOneofField(*message, field)) {
  1319. ClearOneof(message, field->containing_oneof());
  1320. result_holder = MutableField<Message*>(message, field);
  1321. const Message* default_message = DefaultRaw<const Message*>(field);
  1322. *result_holder = default_message->New(message->GetArena());
  1323. }
  1324. } else {
  1325. SetBit(message, field);
  1326. }
  1327. if (*result_holder == nullptr) {
  1328. const Message* default_message = DefaultRaw<const Message*>(field);
  1329. *result_holder = default_message->New(message->GetArena());
  1330. }
  1331. result = *result_holder;
  1332. return result;
  1333. }
  1334. }
  1335. void Reflection::UnsafeArenaSetAllocatedMessage(
  1336. Message* message, Message* sub_message,
  1337. const FieldDescriptor* field) const {
  1338. USAGE_CHECK_ALL(SetAllocatedMessage, SINGULAR, MESSAGE);
  1339. if (field->is_extension()) {
  1340. MutableExtensionSet(message)->UnsafeArenaSetAllocatedMessage(
  1341. field->number(), field->type(), field, sub_message);
  1342. } else {
  1343. if (field->containing_oneof()) {
  1344. if (sub_message == nullptr) {
  1345. ClearOneof(message, field->containing_oneof());
  1346. return;
  1347. }
  1348. ClearOneof(message, field->containing_oneof());
  1349. *MutableRaw<Message*>(message, field) = sub_message;
  1350. SetOneofCase(message, field);
  1351. return;
  1352. }
  1353. if (sub_message == nullptr) {
  1354. ClearBit(message, field);
  1355. } else {
  1356. SetBit(message, field);
  1357. }
  1358. Message** sub_message_holder = MutableRaw<Message*>(message, field);
  1359. if (GetArena(message) == nullptr) {
  1360. delete *sub_message_holder;
  1361. }
  1362. *sub_message_holder = sub_message;
  1363. }
  1364. }
  1365. void Reflection::SetAllocatedMessage(Message* message, Message* sub_message,
  1366. const FieldDescriptor* field) const {
  1367. // If message and sub-message are in different memory ownership domains
  1368. // (different arenas, or one is on heap and one is not), then we may need to
  1369. // do a copy.
  1370. if (sub_message != nullptr &&
  1371. sub_message->GetArena() != message->GetArena()) {
  1372. if (sub_message->GetArena() == nullptr && message->GetArena() != nullptr) {
  1373. // Case 1: parent is on an arena and child is heap-allocated. We can add
  1374. // the child to the arena's Own() list to free on arena destruction, then
  1375. // set our pointer.
  1376. message->GetArena()->Own(sub_message);
  1377. UnsafeArenaSetAllocatedMessage(message, sub_message, field);
  1378. } else {
  1379. // Case 2: all other cases. We need to make a copy. MutableMessage() will
  1380. // either get the existing message object, or instantiate a new one as
  1381. // appropriate w.r.t. our arena.
  1382. Message* sub_message_copy = MutableMessage(message, field);
  1383. sub_message_copy->CopyFrom(*sub_message);
  1384. }
  1385. } else {
  1386. // Same memory ownership domains.
  1387. UnsafeArenaSetAllocatedMessage(message, sub_message, field);
  1388. }
  1389. }
  1390. Message* Reflection::UnsafeArenaReleaseMessage(Message* message,
  1391. const FieldDescriptor* field,
  1392. MessageFactory* factory) const {
  1393. USAGE_CHECK_ALL(ReleaseMessage, SINGULAR, MESSAGE);
  1394. if (factory == nullptr) factory = message_factory_;
  1395. if (field->is_extension()) {
  1396. return static_cast<Message*>(
  1397. MutableExtensionSet(message)->UnsafeArenaReleaseMessage(field,
  1398. factory));
  1399. } else {
  1400. if (!(field->is_repeated() || field->containing_oneof())) {
  1401. ClearBit(message, field);
  1402. }
  1403. if (field->containing_oneof()) {
  1404. if (HasOneofField(*message, field)) {
  1405. *MutableOneofCase(message, field->containing_oneof()) = 0;
  1406. } else {
  1407. return nullptr;
  1408. }
  1409. }
  1410. Message** result = MutableRaw<Message*>(message, field);
  1411. Message* ret = *result;
  1412. *result = nullptr;
  1413. return ret;
  1414. }
  1415. }
  1416. Message* Reflection::ReleaseMessage(Message* message,
  1417. const FieldDescriptor* field,
  1418. MessageFactory* factory) const {
  1419. Message* released = UnsafeArenaReleaseMessage(message, field, factory);
  1420. if (GetArena(message) != nullptr && released != nullptr) {
  1421. Message* copy_from_arena = released->New();
  1422. copy_from_arena->CopyFrom(*released);
  1423. released = copy_from_arena;
  1424. }
  1425. return released;
  1426. }
  1427. const Message& Reflection::GetRepeatedMessage(const Message& message,
  1428. const FieldDescriptor* field,
  1429. int index) const {
  1430. USAGE_CHECK_ALL(GetRepeatedMessage, REPEATED, MESSAGE);
  1431. if (field->is_extension()) {
  1432. return static_cast<const Message&>(
  1433. GetExtensionSet(message).GetRepeatedMessage(field->number(), index));
  1434. } else {
  1435. if (IsMapFieldInApi(field)) {
  1436. return GetRaw<MapFieldBase>(message, field)
  1437. .GetRepeatedField()
  1438. .Get<GenericTypeHandler<Message> >(index);
  1439. } else {
  1440. return GetRaw<RepeatedPtrFieldBase>(message, field)
  1441. .Get<GenericTypeHandler<Message> >(index);
  1442. }
  1443. }
  1444. }
  1445. Message* Reflection::MutableRepeatedMessage(Message* message,
  1446. const FieldDescriptor* field,
  1447. int index) const {
  1448. USAGE_CHECK_ALL(MutableRepeatedMessage, REPEATED, MESSAGE);
  1449. if (field->is_extension()) {
  1450. return static_cast<Message*>(
  1451. MutableExtensionSet(message)->MutableRepeatedMessage(field->number(),
  1452. index));
  1453. } else {
  1454. if (IsMapFieldInApi(field)) {
  1455. return MutableRaw<MapFieldBase>(message, field)
  1456. ->MutableRepeatedField()
  1457. ->Mutable<GenericTypeHandler<Message> >(index);
  1458. } else {
  1459. return MutableRaw<RepeatedPtrFieldBase>(message, field)
  1460. ->Mutable<GenericTypeHandler<Message> >(index);
  1461. }
  1462. }
  1463. }
  1464. Message* Reflection::AddMessage(Message* message, const FieldDescriptor* field,
  1465. MessageFactory* factory) const {
  1466. USAGE_CHECK_ALL(AddMessage, REPEATED, MESSAGE);
  1467. if (factory == nullptr) factory = message_factory_;
  1468. if (field->is_extension()) {
  1469. return static_cast<Message*>(
  1470. MutableExtensionSet(message)->AddMessage(field, factory));
  1471. } else {
  1472. Message* result = nullptr;
  1473. // We can't use AddField<Message>() because RepeatedPtrFieldBase doesn't
  1474. // know how to allocate one.
  1475. RepeatedPtrFieldBase* repeated = nullptr;
  1476. if (IsMapFieldInApi(field)) {
  1477. repeated =
  1478. MutableRaw<MapFieldBase>(message, field)->MutableRepeatedField();
  1479. } else {
  1480. repeated = MutableRaw<RepeatedPtrFieldBase>(message, field);
  1481. }
  1482. result = repeated->AddFromCleared<GenericTypeHandler<Message> >();
  1483. if (result == nullptr) {
  1484. // We must allocate a new object.
  1485. const Message* prototype;
  1486. if (repeated->size() == 0) {
  1487. prototype = factory->GetPrototype(field->message_type());
  1488. } else {
  1489. prototype = &repeated->Get<GenericTypeHandler<Message> >(0);
  1490. }
  1491. result = prototype->New(message->GetArena());
  1492. // We can guarantee here that repeated and result are either both heap
  1493. // allocated or arena owned. So it is safe to call the unsafe version
  1494. // of AddAllocated.
  1495. repeated->UnsafeArenaAddAllocated<GenericTypeHandler<Message> >(result);
  1496. }
  1497. return result;
  1498. }
  1499. }
  1500. void Reflection::AddAllocatedMessage(Message* message,
  1501. const FieldDescriptor* field,
  1502. Message* new_entry) const {
  1503. USAGE_CHECK_ALL(AddAllocatedMessage, REPEATED, MESSAGE);
  1504. if (field->is_extension()) {
  1505. MutableExtensionSet(message)->AddAllocatedMessage(field, new_entry);
  1506. } else {
  1507. RepeatedPtrFieldBase* repeated = nullptr;
  1508. if (IsMapFieldInApi(field)) {
  1509. repeated =
  1510. MutableRaw<MapFieldBase>(message, field)->MutableRepeatedField();
  1511. } else {
  1512. repeated = MutableRaw<RepeatedPtrFieldBase>(message, field);
  1513. }
  1514. repeated->AddAllocated<GenericTypeHandler<Message> >(new_entry);
  1515. }
  1516. }
  1517. void* Reflection::MutableRawRepeatedField(Message* message,
  1518. const FieldDescriptor* field,
  1519. FieldDescriptor::CppType cpptype,
  1520. int ctype,
  1521. const Descriptor* desc) const {
  1522. USAGE_CHECK_REPEATED("MutableRawRepeatedField");
  1523. if (field->cpp_type() != cpptype &&
  1524. (field->cpp_type() != FieldDescriptor::CPPTYPE_ENUM ||
  1525. cpptype != FieldDescriptor::CPPTYPE_INT32))
  1526. ReportReflectionUsageTypeError(descriptor_, field,
  1527. "MutableRawRepeatedField", cpptype);
  1528. if (desc != nullptr)
  1529. GOOGLE_CHECK_EQ(field->message_type(), desc) << "wrong submessage type";
  1530. if (field->is_extension()) {
  1531. return MutableExtensionSet(message)->MutableRawRepeatedField(
  1532. field->number(), field->type(), field->is_packed(), field);
  1533. } else {
  1534. // Trigger transform for MapField
  1535. if (IsMapFieldInApi(field)) {
  1536. return MutableRawNonOneof<MapFieldBase>(message, field)
  1537. ->MutableRepeatedField();
  1538. }
  1539. return MutableRawNonOneof<void>(message, field);
  1540. }
  1541. }
  1542. const void* Reflection::GetRawRepeatedField(const Message& message,
  1543. const FieldDescriptor* field,
  1544. FieldDescriptor::CppType cpptype,
  1545. int ctype,
  1546. const Descriptor* desc) const {
  1547. USAGE_CHECK_REPEATED("GetRawRepeatedField");
  1548. if (field->cpp_type() != cpptype)
  1549. ReportReflectionUsageTypeError(descriptor_, field, "GetRawRepeatedField",
  1550. cpptype);
  1551. if (ctype >= 0)
  1552. GOOGLE_CHECK_EQ(field->options().ctype(), ctype) << "subtype mismatch";
  1553. if (desc != nullptr)
  1554. GOOGLE_CHECK_EQ(field->message_type(), desc) << "wrong submessage type";
  1555. if (field->is_extension()) {
  1556. // Should use extension_set::GetRawRepeatedField. However, the required
  1557. // parameter "default repeated value" is not very easy to get here.
  1558. // Map is not supported in extensions, it is acceptable to use
  1559. // extension_set::MutableRawRepeatedField which does not change the message.
  1560. return MutableExtensionSet(const_cast<Message*>(&message))
  1561. ->MutableRawRepeatedField(field->number(), field->type(),
  1562. field->is_packed(), field);
  1563. } else {
  1564. // Trigger transform for MapField
  1565. if (IsMapFieldInApi(field)) {
  1566. return &(GetRawNonOneof<MapFieldBase>(message, field).GetRepeatedField());
  1567. }
  1568. return &GetRawNonOneof<char>(message, field);
  1569. }
  1570. }
  1571. const FieldDescriptor* Reflection::GetOneofFieldDescriptor(
  1572. const Message& message, const OneofDescriptor* oneof_descriptor) const {
  1573. uint32 field_number = GetOneofCase(message, oneof_descriptor);
  1574. if (field_number == 0) {
  1575. return nullptr;
  1576. }
  1577. return descriptor_->FindFieldByNumber(field_number);
  1578. }
  1579. bool Reflection::ContainsMapKey(const Message& message,
  1580. const FieldDescriptor* field,
  1581. const MapKey& key) const {
  1582. USAGE_CHECK(IsMapFieldInApi(field), "LookupMapValue",
  1583. "Field is not a map field.");
  1584. return GetRaw<MapFieldBase>(message, field).ContainsMapKey(key);
  1585. }
  1586. bool Reflection::InsertOrLookupMapValue(Message* message,
  1587. const FieldDescriptor* field,
  1588. const MapKey& key,
  1589. MapValueRef* val) const {
  1590. USAGE_CHECK(IsMapFieldInApi(field), "InsertOrLookupMapValue",
  1591. "Field is not a map field.");
  1592. val->SetType(field->message_type()->FindFieldByName("value")->cpp_type());
  1593. return MutableRaw<MapFieldBase>(message, field)
  1594. ->InsertOrLookupMapValue(key, val);
  1595. }
  1596. bool Reflection::DeleteMapValue(Message* message, const FieldDescriptor* field,
  1597. const MapKey& key) const {
  1598. USAGE_CHECK(IsMapFieldInApi(field), "DeleteMapValue",
  1599. "Field is not a map field.");
  1600. return MutableRaw<MapFieldBase>(message, field)->DeleteMapValue(key);
  1601. }
  1602. MapIterator Reflection::MapBegin(Message* message,
  1603. const FieldDescriptor* field) const {
  1604. USAGE_CHECK(IsMapFieldInApi(field), "MapBegin", "Field is not a map field.");
  1605. MapIterator iter(message, field);
  1606. GetRaw<MapFieldBase>(*message, field).MapBegin(&iter);
  1607. return iter;
  1608. }
  1609. MapIterator Reflection::MapEnd(Message* message,
  1610. const FieldDescriptor* field) const {
  1611. USAGE_CHECK(IsMapFieldInApi(field), "MapEnd", "Field is not a map field.");
  1612. MapIterator iter(message, field);
  1613. GetRaw<MapFieldBase>(*message, field).MapEnd(&iter);
  1614. return iter;
  1615. }
  1616. int Reflection::MapSize(const Message& message,
  1617. const FieldDescriptor* field) const {
  1618. USAGE_CHECK(IsMapFieldInApi(field), "MapSize", "Field is not a map field.");
  1619. return GetRaw<MapFieldBase>(message, field).size();
  1620. }
  1621. // -----------------------------------------------------------------------------
  1622. const FieldDescriptor* Reflection::FindKnownExtensionByName(
  1623. const std::string& name) const {
  1624. if (!schema_.HasExtensionSet()) return nullptr;
  1625. return descriptor_pool_->FindExtensionByPrintableName(descriptor_, name);
  1626. }
  1627. const FieldDescriptor* Reflection::FindKnownExtensionByNumber(
  1628. int number) const {
  1629. if (!schema_.HasExtensionSet()) return nullptr;
  1630. return descriptor_pool_->FindExtensionByNumber(descriptor_, number);
  1631. }
  1632. bool Reflection::SupportsUnknownEnumValues() const {
  1633. return CreateUnknownEnumValues(descriptor_->file());
  1634. }
  1635. // ===================================================================
  1636. // Some private helpers.
  1637. // These simple template accessors obtain pointers (or references) to
  1638. // the given field.
  1639. template <class Type>
  1640. const Type& Reflection::GetRawNonOneof(const Message& message,
  1641. const FieldDescriptor* field) const {
  1642. return GetConstRefAtOffset<Type>(message,
  1643. schema_.GetFieldOffsetNonOneof(field));
  1644. }
  1645. template <class Type>
  1646. Type* Reflection::MutableRawNonOneof(Message* message,
  1647. const FieldDescriptor* field) const {
  1648. return GetPointerAtOffset<Type>(message,
  1649. schema_.GetFieldOffsetNonOneof(field));
  1650. }
  1651. template <typename Type>
  1652. const Type& Reflection::GetRaw(const Message& message,
  1653. const FieldDescriptor* field) const {
  1654. if (field->containing_oneof() && !HasOneofField(message, field)) {
  1655. return DefaultRaw<Type>(field);
  1656. }
  1657. return GetConstRefAtOffset<Type>(message, schema_.GetFieldOffset(field));
  1658. }
  1659. bool Reflection::IsInlined(const FieldDescriptor* field) const {
  1660. return schema_.IsFieldInlined(field);
  1661. }
  1662. template <typename Type>
  1663. Type* Reflection::MutableRaw(Message* message,
  1664. const FieldDescriptor* field) const {
  1665. return GetPointerAtOffset<Type>(message, schema_.GetFieldOffset(field));
  1666. }
  1667. const uint32* Reflection::GetHasBits(const Message& message) const {
  1668. GOOGLE_DCHECK(schema_.HasHasbits());
  1669. return &GetConstRefAtOffset<uint32>(message, schema_.HasBitsOffset());
  1670. }
  1671. uint32* Reflection::MutableHasBits(Message* message) const {
  1672. GOOGLE_DCHECK(schema_.HasHasbits());
  1673. return GetPointerAtOffset<uint32>(message, schema_.HasBitsOffset());
  1674. }
  1675. uint32 Reflection::GetOneofCase(const Message& message,
  1676. const OneofDescriptor* oneof_descriptor) const {
  1677. return GetConstRefAtOffset<uint32>(
  1678. message, schema_.GetOneofCaseOffset(oneof_descriptor));
  1679. }
  1680. uint32* Reflection::MutableOneofCase(
  1681. Message* message, const OneofDescriptor* oneof_descriptor) const {
  1682. return GetPointerAtOffset<uint32>(
  1683. message, schema_.GetOneofCaseOffset(oneof_descriptor));
  1684. }
  1685. const ExtensionSet& Reflection::GetExtensionSet(const Message& message) const {
  1686. return GetConstRefAtOffset<ExtensionSet>(message,
  1687. schema_.GetExtensionSetOffset());
  1688. }
  1689. ExtensionSet* Reflection::MutableExtensionSet(Message* message) const {
  1690. return GetPointerAtOffset<ExtensionSet>(message,
  1691. schema_.GetExtensionSetOffset());
  1692. }
  1693. Arena* Reflection::GetArena(Message* message) const {
  1694. return GetInternalMetadataWithArena(*message).arena();
  1695. }
  1696. const InternalMetadataWithArena& Reflection::GetInternalMetadataWithArena(
  1697. const Message& message) const {
  1698. return GetConstRefAtOffset<InternalMetadataWithArena>(
  1699. message, schema_.GetMetadataOffset());
  1700. }
  1701. InternalMetadataWithArena* Reflection::MutableInternalMetadataWithArena(
  1702. Message* message) const {
  1703. return GetPointerAtOffset<InternalMetadataWithArena>(
  1704. message, schema_.GetMetadataOffset());
  1705. }
  1706. template <typename Type>
  1707. const Type& Reflection::DefaultRaw(const FieldDescriptor* field) const {
  1708. return *reinterpret_cast<const Type*>(schema_.GetFieldDefault(field));
  1709. }
  1710. // Simple accessors for manipulating has_bits_.
  1711. bool Reflection::HasBit(const Message& message,
  1712. const FieldDescriptor* field) const {
  1713. GOOGLE_DCHECK(!field->options().weak());
  1714. if (schema_.HasHasbits()) {
  1715. return IsIndexInHasBitSet(GetHasBits(message), schema_.HasBitIndex(field));
  1716. }
  1717. // proto3: no has-bits. All fields present except messages, which are
  1718. // present only if their message-field pointer is non-null.
  1719. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  1720. return !schema_.IsDefaultInstance(message) &&
  1721. GetRaw<const Message*>(message, field) != nullptr;
  1722. } else {
  1723. // Non-message field (and non-oneof, since that was handled in HasField()
  1724. // before calling us), and singular (again, checked in HasField). So, this
  1725. // field must be a scalar.
  1726. // Scalar primitive (numeric or string/bytes) fields are present if
  1727. // their value is non-zero (numeric) or non-empty (string/bytes). N.B.:
  1728. // we must use this definition here, rather than the "scalar fields
  1729. // always present" in the proto3 docs, because MergeFrom() semantics
  1730. // require presence as "present on wire", and reflection-based merge
  1731. // (which uses HasField()) needs to be consistent with this.
  1732. switch (field->cpp_type()) {
  1733. case FieldDescriptor::CPPTYPE_STRING:
  1734. switch (field->options().ctype()) {
  1735. default: {
  1736. if (IsInlined(field)) {
  1737. return !GetField<InlinedStringField>(message, field)
  1738. .GetNoArena()
  1739. .empty();
  1740. }
  1741. return GetField<ArenaStringPtr>(message, field).Get().size() > 0;
  1742. }
  1743. }
  1744. return false;
  1745. case FieldDescriptor::CPPTYPE_BOOL:
  1746. return GetRaw<bool>(message, field) != false;
  1747. case FieldDescriptor::CPPTYPE_INT32:
  1748. return GetRaw<int32>(message, field) != 0;
  1749. case FieldDescriptor::CPPTYPE_INT64:
  1750. return GetRaw<int64>(message, field) != 0;
  1751. case FieldDescriptor::CPPTYPE_UINT32:
  1752. return GetRaw<uint32>(message, field) != 0;
  1753. case FieldDescriptor::CPPTYPE_UINT64:
  1754. return GetRaw<uint64>(message, field) != 0;
  1755. case FieldDescriptor::CPPTYPE_FLOAT:
  1756. return GetRaw<float>(message, field) != 0.0;
  1757. case FieldDescriptor::CPPTYPE_DOUBLE:
  1758. return GetRaw<double>(message, field) != 0.0;
  1759. case FieldDescriptor::CPPTYPE_ENUM:
  1760. return GetRaw<int>(message, field) != 0;
  1761. case FieldDescriptor::CPPTYPE_MESSAGE:
  1762. // handled above; avoid warning
  1763. break;
  1764. }
  1765. GOOGLE_LOG(FATAL) << "Reached impossible case in HasBit().";
  1766. return false;
  1767. }
  1768. }
  1769. void Reflection::SetBit(Message* message, const FieldDescriptor* field) const {
  1770. GOOGLE_DCHECK(!field->options().weak());
  1771. if (!schema_.HasHasbits()) {
  1772. return;
  1773. }
  1774. const uint32 index = schema_.HasBitIndex(field);
  1775. MutableHasBits(message)[index / 32] |=
  1776. (static_cast<uint32>(1) << (index % 32));
  1777. }
  1778. void Reflection::ClearBit(Message* message,
  1779. const FieldDescriptor* field) const {
  1780. GOOGLE_DCHECK(!field->options().weak());
  1781. if (!schema_.HasHasbits()) {
  1782. return;
  1783. }
  1784. const uint32 index = schema_.HasBitIndex(field);
  1785. MutableHasBits(message)[index / 32] &=
  1786. ~(static_cast<uint32>(1) << (index % 32));
  1787. }
  1788. void Reflection::SwapBit(Message* message1, Message* message2,
  1789. const FieldDescriptor* field) const {
  1790. GOOGLE_DCHECK(!field->options().weak());
  1791. if (!schema_.HasHasbits()) {
  1792. return;
  1793. }
  1794. bool temp_has_bit = HasBit(*message1, field);
  1795. if (HasBit(*message2, field)) {
  1796. SetBit(message1, field);
  1797. } else {
  1798. ClearBit(message1, field);
  1799. }
  1800. if (temp_has_bit) {
  1801. SetBit(message2, field);
  1802. } else {
  1803. ClearBit(message2, field);
  1804. }
  1805. }
  1806. bool Reflection::HasOneof(const Message& message,
  1807. const OneofDescriptor* oneof_descriptor) const {
  1808. return (GetOneofCase(message, oneof_descriptor) > 0);
  1809. }
  1810. bool Reflection::HasOneofField(const Message& message,
  1811. const FieldDescriptor* field) const {
  1812. return (GetOneofCase(message, field->containing_oneof()) == field->number());
  1813. }
  1814. void Reflection::SetOneofCase(Message* message,
  1815. const FieldDescriptor* field) const {
  1816. *MutableOneofCase(message, field->containing_oneof()) = field->number();
  1817. }
  1818. void Reflection::ClearOneofField(Message* message,
  1819. const FieldDescriptor* field) const {
  1820. if (HasOneofField(*message, field)) {
  1821. ClearOneof(message, field->containing_oneof());
  1822. }
  1823. }
  1824. void Reflection::ClearOneof(Message* message,
  1825. const OneofDescriptor* oneof_descriptor) const {
  1826. // TODO(jieluo): Consider to cache the unused object instead of deleting
  1827. // it. It will be much faster if an application switches a lot from
  1828. // a few oneof fields. Time/space tradeoff
  1829. uint32 oneof_case = GetOneofCase(*message, oneof_descriptor);
  1830. if (oneof_case > 0) {
  1831. const FieldDescriptor* field = descriptor_->FindFieldByNumber(oneof_case);
  1832. if (GetArena(message) == nullptr) {
  1833. switch (field->cpp_type()) {
  1834. case FieldDescriptor::CPPTYPE_STRING: {
  1835. switch (field->options().ctype()) {
  1836. default: // TODO(kenton): Support other string reps.
  1837. case FieldOptions::STRING: {
  1838. const std::string* default_ptr =
  1839. &DefaultRaw<ArenaStringPtr>(field).Get();
  1840. MutableField<ArenaStringPtr>(message, field)
  1841. ->Destroy(default_ptr, GetArena(message));
  1842. break;
  1843. }
  1844. }
  1845. break;
  1846. }
  1847. case FieldDescriptor::CPPTYPE_MESSAGE:
  1848. delete *MutableRaw<Message*>(message, field);
  1849. break;
  1850. default:
  1851. break;
  1852. }
  1853. }
  1854. *MutableOneofCase(message, oneof_descriptor) = 0;
  1855. }
  1856. }
  1857. #define HANDLE_TYPE(TYPE, CPPTYPE, CTYPE) \
  1858. template <> \
  1859. const RepeatedField<TYPE>& Reflection::GetRepeatedField<TYPE>( \
  1860. const Message& message, const FieldDescriptor* field) const { \
  1861. return *static_cast<RepeatedField<TYPE>*>(MutableRawRepeatedField( \
  1862. const_cast<Message*>(&message), field, CPPTYPE, CTYPE, NULL)); \
  1863. } \
  1864. \
  1865. template <> \
  1866. RepeatedField<TYPE>* Reflection::MutableRepeatedField<TYPE>( \
  1867. Message * message, const FieldDescriptor* field) const { \
  1868. return static_cast<RepeatedField<TYPE>*>( \
  1869. MutableRawRepeatedField(message, field, CPPTYPE, CTYPE, NULL)); \
  1870. }
  1871. HANDLE_TYPE(int32, FieldDescriptor::CPPTYPE_INT32, -1);
  1872. HANDLE_TYPE(int64, FieldDescriptor::CPPTYPE_INT64, -1);
  1873. HANDLE_TYPE(uint32, FieldDescriptor::CPPTYPE_UINT32, -1);
  1874. HANDLE_TYPE(uint64, FieldDescriptor::CPPTYPE_UINT64, -1);
  1875. HANDLE_TYPE(float, FieldDescriptor::CPPTYPE_FLOAT, -1);
  1876. HANDLE_TYPE(double, FieldDescriptor::CPPTYPE_DOUBLE, -1);
  1877. HANDLE_TYPE(bool, FieldDescriptor::CPPTYPE_BOOL, -1);
  1878. #undef HANDLE_TYPE
  1879. void* Reflection::MutableRawRepeatedString(Message* message,
  1880. const FieldDescriptor* field,
  1881. bool is_string) const {
  1882. return MutableRawRepeatedField(message, field,
  1883. FieldDescriptor::CPPTYPE_STRING,
  1884. FieldOptions::STRING, NULL);
  1885. }
  1886. // Template implementations of basic accessors. Inline because each
  1887. // template instance is only called from one location. These are
  1888. // used for all types except messages.
  1889. template <typename Type>
  1890. const Type& Reflection::GetField(const Message& message,
  1891. const FieldDescriptor* field) const {
  1892. return GetRaw<Type>(message, field);
  1893. }
  1894. template <typename Type>
  1895. void Reflection::SetField(Message* message, const FieldDescriptor* field,
  1896. const Type& value) const {
  1897. if (field->containing_oneof() && !HasOneofField(*message, field)) {
  1898. ClearOneof(message, field->containing_oneof());
  1899. }
  1900. *MutableRaw<Type>(message, field) = value;
  1901. field->containing_oneof() ? SetOneofCase(message, field)
  1902. : SetBit(message, field);
  1903. }
  1904. template <typename Type>
  1905. Type* Reflection::MutableField(Message* message,
  1906. const FieldDescriptor* field) const {
  1907. field->containing_oneof() ? SetOneofCase(message, field)
  1908. : SetBit(message, field);
  1909. return MutableRaw<Type>(message, field);
  1910. }
  1911. template <typename Type>
  1912. const Type& Reflection::GetRepeatedField(const Message& message,
  1913. const FieldDescriptor* field,
  1914. int index) const {
  1915. return GetRaw<RepeatedField<Type> >(message, field).Get(index);
  1916. }
  1917. template <typename Type>
  1918. const Type& Reflection::GetRepeatedPtrField(const Message& message,
  1919. const FieldDescriptor* field,
  1920. int index) const {
  1921. return GetRaw<RepeatedPtrField<Type> >(message, field).Get(index);
  1922. }
  1923. template <typename Type>
  1924. void Reflection::SetRepeatedField(Message* message,
  1925. const FieldDescriptor* field, int index,
  1926. Type value) const {
  1927. MutableRaw<RepeatedField<Type> >(message, field)->Set(index, value);
  1928. }
  1929. template <typename Type>
  1930. Type* Reflection::MutableRepeatedField(Message* message,
  1931. const FieldDescriptor* field,
  1932. int index) const {
  1933. RepeatedPtrField<Type>* repeated =
  1934. MutableRaw<RepeatedPtrField<Type> >(message, field);
  1935. return repeated->Mutable(index);
  1936. }
  1937. template <typename Type>
  1938. void Reflection::AddField(Message* message, const FieldDescriptor* field,
  1939. const Type& value) const {
  1940. MutableRaw<RepeatedField<Type> >(message, field)->Add(value);
  1941. }
  1942. template <typename Type>
  1943. Type* Reflection::AddField(Message* message,
  1944. const FieldDescriptor* field) const {
  1945. RepeatedPtrField<Type>* repeated =
  1946. MutableRaw<RepeatedPtrField<Type> >(message, field);
  1947. return repeated->Add();
  1948. }
  1949. MessageFactory* Reflection::GetMessageFactory() const {
  1950. return message_factory_;
  1951. }
  1952. void* Reflection::RepeatedFieldData(Message* message,
  1953. const FieldDescriptor* field,
  1954. FieldDescriptor::CppType cpp_type,
  1955. const Descriptor* message_type) const {
  1956. GOOGLE_CHECK(field->is_repeated());
  1957. GOOGLE_CHECK(field->cpp_type() == cpp_type ||
  1958. (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM &&
  1959. cpp_type == FieldDescriptor::CPPTYPE_INT32))
  1960. << "The type parameter T in RepeatedFieldRef<T> API doesn't match "
  1961. << "the actual field type (for enums T should be the generated enum "
  1962. << "type or int32).";
  1963. if (message_type != nullptr) {
  1964. GOOGLE_CHECK_EQ(message_type, field->message_type());
  1965. }
  1966. if (field->is_extension()) {
  1967. return MutableExtensionSet(message)->MutableRawRepeatedField(
  1968. field->number(), field->type(), field->is_packed(), field);
  1969. } else {
  1970. return MutableRawNonOneof<char>(message, field);
  1971. }
  1972. }
  1973. MapFieldBase* Reflection::MutableMapData(Message* message,
  1974. const FieldDescriptor* field) const {
  1975. USAGE_CHECK(IsMapFieldInApi(field), "GetMapData",
  1976. "Field is not a map field.");
  1977. return MutableRaw<MapFieldBase>(message, field);
  1978. }
  1979. const MapFieldBase* Reflection::GetMapData(const Message& message,
  1980. const FieldDescriptor* field) const {
  1981. USAGE_CHECK(IsMapFieldInApi(field), "GetMapData",
  1982. "Field is not a map field.");
  1983. return &(GetRaw<MapFieldBase>(message, field));
  1984. }
  1985. namespace {
  1986. // Helper function to transform migration schema into reflection schema.
  1987. ReflectionSchema MigrationToReflectionSchema(
  1988. const Message* const* default_instance, const uint32* offsets,
  1989. MigrationSchema migration_schema) {
  1990. ReflectionSchema result;
  1991. result.default_instance_ = *default_instance;
  1992. // First 6 offsets are offsets to the special fields. The following offsets
  1993. // are the proto fields.
  1994. result.offsets_ = offsets + migration_schema.offsets_index + 5;
  1995. result.has_bit_indices_ = offsets + migration_schema.has_bit_indices_index;
  1996. result.has_bits_offset_ = offsets[migration_schema.offsets_index + 0];
  1997. result.metadata_offset_ = offsets[migration_schema.offsets_index + 1];
  1998. result.extensions_offset_ = offsets[migration_schema.offsets_index + 2];
  1999. result.oneof_case_offset_ = offsets[migration_schema.offsets_index + 3];
  2000. result.object_size_ = migration_schema.object_size;
  2001. result.weak_field_map_offset_ = offsets[migration_schema.offsets_index + 4];
  2002. return result;
  2003. }
  2004. } // namespace
  2005. class AssignDescriptorsHelper {
  2006. public:
  2007. AssignDescriptorsHelper(MessageFactory* factory,
  2008. Metadata* file_level_metadata,
  2009. const EnumDescriptor** file_level_enum_descriptors,
  2010. const MigrationSchema* schemas,
  2011. const Message* const* default_instance_data,
  2012. const uint32* offsets)
  2013. : factory_(factory),
  2014. file_level_metadata_(file_level_metadata),
  2015. file_level_enum_descriptors_(file_level_enum_descriptors),
  2016. schemas_(schemas),
  2017. default_instance_data_(default_instance_data),
  2018. offsets_(offsets) {}
  2019. void AssignMessageDescriptor(const Descriptor* descriptor) {
  2020. for (int i = 0; i < descriptor->nested_type_count(); i++) {
  2021. AssignMessageDescriptor(descriptor->nested_type(i));
  2022. }
  2023. file_level_metadata_->descriptor = descriptor;
  2024. file_level_metadata_->reflection =
  2025. new Reflection(descriptor,
  2026. MigrationToReflectionSchema(default_instance_data_,
  2027. offsets_, *schemas_),
  2028. DescriptorPool::internal_generated_pool(), factory_);
  2029. for (int i = 0; i < descriptor->enum_type_count(); i++) {
  2030. AssignEnumDescriptor(descriptor->enum_type(i));
  2031. }
  2032. schemas_++;
  2033. default_instance_data_++;
  2034. file_level_metadata_++;
  2035. }
  2036. void AssignEnumDescriptor(const EnumDescriptor* descriptor) {
  2037. *file_level_enum_descriptors_ = descriptor;
  2038. file_level_enum_descriptors_++;
  2039. }
  2040. const Metadata* GetCurrentMetadataPtr() const { return file_level_metadata_; }
  2041. private:
  2042. MessageFactory* factory_;
  2043. Metadata* file_level_metadata_;
  2044. const EnumDescriptor** file_level_enum_descriptors_;
  2045. const MigrationSchema* schemas_;
  2046. const Message* const* default_instance_data_;
  2047. const uint32* offsets_;
  2048. };
  2049. namespace {
  2050. // We have the routines that assign descriptors and build reflection
  2051. // automatically delete the allocated reflection. MetadataOwner owns
  2052. // all the allocated reflection instances.
  2053. struct MetadataOwner {
  2054. ~MetadataOwner() {
  2055. for (auto range : metadata_arrays_) {
  2056. for (const Metadata* m = range.first; m < range.second; m++) {
  2057. delete m->reflection;
  2058. }
  2059. }
  2060. }
  2061. void AddArray(const Metadata* begin, const Metadata* end) {
  2062. mu_.Lock();
  2063. metadata_arrays_.push_back(std::make_pair(begin, end));
  2064. mu_.Unlock();
  2065. }
  2066. static MetadataOwner* Instance() {
  2067. static MetadataOwner* res = OnShutdownDelete(new MetadataOwner);
  2068. return res;
  2069. }
  2070. private:
  2071. MetadataOwner() = default; // private because singleton
  2072. WrappedMutex mu_;
  2073. std::vector<std::pair<const Metadata*, const Metadata*> > metadata_arrays_;
  2074. };
  2075. void AssignDescriptorsImpl(const DescriptorTable* table) {
  2076. // Ensure the file descriptor is added to the pool.
  2077. {
  2078. // This only happens once per proto file. So a global mutex to serialize
  2079. // calls to AddDescriptors.
  2080. static WrappedMutex mu{GOOGLE_PROTOBUF_LINKER_INITIALIZED};
  2081. mu.Lock();
  2082. AddDescriptors(table);
  2083. mu.Unlock();
  2084. }
  2085. // Fill the arrays with pointers to descriptors and reflection classes.
  2086. const FileDescriptor* file =
  2087. DescriptorPool::internal_generated_pool()->FindFileByName(
  2088. table->filename);
  2089. GOOGLE_CHECK(file != nullptr);
  2090. MessageFactory* factory = MessageFactory::generated_factory();
  2091. AssignDescriptorsHelper helper(
  2092. factory, table->file_level_metadata, table->file_level_enum_descriptors,
  2093. table->schemas, table->default_instances, table->offsets);
  2094. for (int i = 0; i < file->message_type_count(); i++) {
  2095. helper.AssignMessageDescriptor(file->message_type(i));
  2096. }
  2097. for (int i = 0; i < file->enum_type_count(); i++) {
  2098. helper.AssignEnumDescriptor(file->enum_type(i));
  2099. }
  2100. if (file->options().cc_generic_services()) {
  2101. for (int i = 0; i < file->service_count(); i++) {
  2102. table->file_level_service_descriptors[i] = file->service(i);
  2103. }
  2104. }
  2105. MetadataOwner::Instance()->AddArray(table->file_level_metadata,
  2106. helper.GetCurrentMetadataPtr());
  2107. }
  2108. void AddDescriptorsImpl(const DescriptorTable* table) {
  2109. // Reflection refers to the default instances so make sure they are
  2110. // initialized.
  2111. for (int i = 0; i < table->num_sccs; i++) {
  2112. internal::InitSCC(table->init_default_instances[i]);
  2113. }
  2114. // Ensure all dependent descriptors are registered to the generated descriptor
  2115. // pool and message factory.
  2116. for (int i = 0; i < table->num_deps; i++) {
  2117. // In case of weak fields deps[i] could be null.
  2118. if (table->deps[i]) AddDescriptors(table->deps[i]);
  2119. }
  2120. // Register the descriptor of this file.
  2121. DescriptorPool::InternalAddGeneratedFile(table->descriptor, table->size);
  2122. MessageFactory::InternalRegisterGeneratedFile(table);
  2123. }
  2124. } // namespace
  2125. // Separate function because it needs to be a friend of
  2126. // Reflection
  2127. void RegisterAllTypesInternal(const Metadata* file_level_metadata, int size) {
  2128. for (int i = 0; i < size; i++) {
  2129. const Reflection* reflection = file_level_metadata[i].reflection;
  2130. MessageFactory::InternalRegisterGeneratedMessage(
  2131. file_level_metadata[i].descriptor,
  2132. reflection->schema_.default_instance_);
  2133. }
  2134. }
  2135. namespace internal {
  2136. void AssignDescriptors(const DescriptorTable* table) {
  2137. call_once(*table->once, AssignDescriptorsImpl, table);
  2138. }
  2139. void AddDescriptors(const DescriptorTable* table) {
  2140. // AddDescriptors is not thread safe. Callers need to ensure calls are
  2141. // properly serialized. This function is only called pre-main by global
  2142. // descriptors and we can assume single threaded access or it's called
  2143. // by AssignDescriptorImpl which uses a mutex to sequence calls.
  2144. if (*table->is_initialized) return;
  2145. *table->is_initialized = true;
  2146. AddDescriptorsImpl(table);
  2147. }
  2148. void RegisterFileLevelMetadata(const DescriptorTable* table) {
  2149. AssignDescriptors(table);
  2150. RegisterAllTypesInternal(table->file_level_metadata, table->num_messages);
  2151. }
  2152. void UnknownFieldSetSerializer(const uint8* base, uint32 offset, uint32 tag,
  2153. uint32 has_offset,
  2154. io::CodedOutputStream* output) {
  2155. const void* ptr = base + offset;
  2156. const InternalMetadataWithArena* metadata =
  2157. static_cast<const InternalMetadataWithArena*>(ptr);
  2158. if (metadata->have_unknown_fields()) {
  2159. internal::WireFormat::SerializeUnknownFields(metadata->unknown_fields(),
  2160. output);
  2161. }
  2162. }
  2163. } // namespace internal
  2164. } // namespace protobuf
  2165. } // namespace google