generated_message_reflection.cc 89 KB

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