generated_message_util.cc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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 <google/protobuf/generated_message_util.h>
  34. #include <limits>
  35. // We're only using this as a standard way for getting the thread id.
  36. // We're not using any thread functionality.
  37. #include <thread> // NOLINT
  38. #include <vector>
  39. #include <google/protobuf/io/coded_stream_inl.h>
  40. #include <google/protobuf/io/coded_stream.h>
  41. #include <google/protobuf/arenastring.h>
  42. #include <google/protobuf/extension_set.h>
  43. #include <google/protobuf/message_lite.h>
  44. #include <google/protobuf/metadata_lite.h>
  45. #include <google/protobuf/stubs/mutex.h>
  46. #include <google/protobuf/stubs/port.h>
  47. #include <google/protobuf/repeated_field.h>
  48. #include <google/protobuf/wire_format_lite.h>
  49. #include <google/protobuf/wire_format_lite_inl.h>
  50. namespace google {
  51. namespace protobuf {
  52. namespace internal {
  53. void DestroyMessage(const void* message) {
  54. static_cast<const MessageLite*>(message)->~MessageLite();
  55. }
  56. void DestroyString(const void* s) { static_cast<const string*>(s)->~string(); }
  57. ExplicitlyConstructed<std::string> fixed_address_empty_string;
  58. double Infinity() {
  59. return std::numeric_limits<double>::infinity();
  60. }
  61. double NaN() {
  62. return std::numeric_limits<double>::quiet_NaN();
  63. }
  64. static bool InitProtobufDefaultsImpl() {
  65. fixed_address_empty_string.DefaultConstruct();
  66. OnShutdownDestroyString(fixed_address_empty_string.get_mutable());
  67. return true;
  68. }
  69. void InitProtobufDefaults() {
  70. static bool is_inited = InitProtobufDefaultsImpl();
  71. (void)is_inited;
  72. }
  73. size_t StringSpaceUsedExcludingSelfLong(const string& str) {
  74. const void* start = &str;
  75. const void* end = &str + 1;
  76. if (start <= str.data() && str.data() < end) {
  77. // The string's data is stored inside the string object itself.
  78. return 0;
  79. } else {
  80. return str.capacity();
  81. }
  82. }
  83. template <typename T>
  84. const T& Get(const void* ptr) {
  85. return *static_cast<const T*>(ptr);
  86. }
  87. // PrimitiveTypeHelper is a wrapper around the interface of WireFormatLite.
  88. // WireFormatLite has a very inconvenient interface with respect to template
  89. // meta-programming. This class wraps the different named functions into
  90. // a single Serialize / SerializeToArray interface.
  91. template <int type>
  92. struct PrimitiveTypeHelper;
  93. template <>
  94. struct PrimitiveTypeHelper<WireFormatLite::TYPE_BOOL> {
  95. typedef bool Type;
  96. static void Serialize(const void* ptr,
  97. ::google::protobuf::io::CodedOutputStream* output) {
  98. WireFormatLite::WriteBoolNoTag(Get<bool>(ptr), output);
  99. }
  100. static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
  101. return WireFormatLite::WriteBoolNoTagToArray(Get<Type>(ptr), buffer);
  102. }
  103. };
  104. template <>
  105. struct PrimitiveTypeHelper<WireFormatLite::TYPE_INT32> {
  106. typedef int32 Type;
  107. static void Serialize(const void* ptr,
  108. ::google::protobuf::io::CodedOutputStream* output) {
  109. WireFormatLite::WriteInt32NoTag(Get<int32>(ptr), output);
  110. }
  111. static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
  112. return WireFormatLite::WriteInt32NoTagToArray(Get<Type>(ptr), buffer);
  113. }
  114. };
  115. template <>
  116. struct PrimitiveTypeHelper<WireFormatLite::TYPE_SINT32> {
  117. typedef int32 Type;
  118. static void Serialize(const void* ptr,
  119. ::google::protobuf::io::CodedOutputStream* output) {
  120. WireFormatLite::WriteSInt32NoTag(Get<int32>(ptr), output);
  121. }
  122. static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
  123. return WireFormatLite::WriteSInt32NoTagToArray(Get<Type>(ptr), buffer);
  124. }
  125. };
  126. template <>
  127. struct PrimitiveTypeHelper<WireFormatLite::TYPE_UINT32> {
  128. typedef uint32 Type;
  129. static void Serialize(const void* ptr,
  130. ::google::protobuf::io::CodedOutputStream* output) {
  131. WireFormatLite::WriteUInt32NoTag(Get<uint32>(ptr), output);
  132. }
  133. static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
  134. return WireFormatLite::WriteUInt32NoTagToArray(Get<Type>(ptr), buffer);
  135. }
  136. };
  137. template <>
  138. struct PrimitiveTypeHelper<WireFormatLite::TYPE_INT64> {
  139. typedef int64 Type;
  140. static void Serialize(const void* ptr,
  141. ::google::protobuf::io::CodedOutputStream* output) {
  142. WireFormatLite::WriteInt64NoTag(Get<int64>(ptr), output);
  143. }
  144. static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
  145. return WireFormatLite::WriteInt64NoTagToArray(Get<Type>(ptr), buffer);
  146. }
  147. };
  148. template <>
  149. struct PrimitiveTypeHelper<WireFormatLite::TYPE_SINT64> {
  150. typedef int64 Type;
  151. static void Serialize(const void* ptr,
  152. ::google::protobuf::io::CodedOutputStream* output) {
  153. WireFormatLite::WriteSInt64NoTag(Get<int64>(ptr), output);
  154. }
  155. static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
  156. return WireFormatLite::WriteSInt64NoTagToArray(Get<Type>(ptr), buffer);
  157. }
  158. };
  159. template <>
  160. struct PrimitiveTypeHelper<WireFormatLite::TYPE_UINT64> {
  161. typedef uint64 Type;
  162. static void Serialize(const void* ptr,
  163. ::google::protobuf::io::CodedOutputStream* output) {
  164. WireFormatLite::WriteUInt64NoTag(Get<uint64>(ptr), output);
  165. }
  166. static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
  167. return WireFormatLite::WriteUInt64NoTagToArray(Get<Type>(ptr), buffer);
  168. }
  169. };
  170. template <>
  171. struct PrimitiveTypeHelper<WireFormatLite::TYPE_FIXED32> {
  172. typedef uint32 Type;
  173. static void Serialize(const void* ptr,
  174. ::google::protobuf::io::CodedOutputStream* output) {
  175. WireFormatLite::WriteFixed32NoTag(Get<uint32>(ptr), output);
  176. }
  177. static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
  178. return WireFormatLite::WriteFixed32NoTagToArray(Get<Type>(ptr), buffer);
  179. }
  180. };
  181. template <>
  182. struct PrimitiveTypeHelper<WireFormatLite::TYPE_FIXED64> {
  183. typedef uint64 Type;
  184. static void Serialize(const void* ptr,
  185. ::google::protobuf::io::CodedOutputStream* output) {
  186. WireFormatLite::WriteFixed64NoTag(Get<uint64>(ptr), output);
  187. }
  188. static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
  189. return WireFormatLite::WriteFixed64NoTagToArray(Get<Type>(ptr), buffer);
  190. }
  191. };
  192. template <>
  193. struct PrimitiveTypeHelper<WireFormatLite::TYPE_ENUM>
  194. : PrimitiveTypeHelper<WireFormatLite::TYPE_INT32> {};
  195. template <>
  196. struct PrimitiveTypeHelper<WireFormatLite::TYPE_SFIXED32>
  197. : PrimitiveTypeHelper<WireFormatLite::TYPE_FIXED32> {
  198. typedef int32 Type;
  199. };
  200. template <>
  201. struct PrimitiveTypeHelper<WireFormatLite::TYPE_SFIXED64>
  202. : PrimitiveTypeHelper<WireFormatLite::TYPE_FIXED64> {
  203. typedef int64 Type;
  204. };
  205. template <>
  206. struct PrimitiveTypeHelper<WireFormatLite::TYPE_FLOAT>
  207. : PrimitiveTypeHelper<WireFormatLite::TYPE_FIXED32> {
  208. typedef float Type;
  209. };
  210. template <>
  211. struct PrimitiveTypeHelper<WireFormatLite::TYPE_DOUBLE>
  212. : PrimitiveTypeHelper<WireFormatLite::TYPE_FIXED64> {
  213. typedef double Type;
  214. };
  215. template <>
  216. struct PrimitiveTypeHelper<WireFormatLite::TYPE_STRING> {
  217. typedef string Type;
  218. static void Serialize(const void* ptr,
  219. ::google::protobuf::io::CodedOutputStream* output) {
  220. const Type& value = *static_cast<const Type*>(ptr);
  221. output->WriteVarint32(value.size());
  222. output->WriteRawMaybeAliased(value.data(), value.size());
  223. }
  224. static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
  225. const Type& value = *static_cast<const Type*>(ptr);
  226. return io::CodedOutputStream::WriteStringWithSizeToArray(value, buffer);
  227. }
  228. };
  229. template <>
  230. struct PrimitiveTypeHelper<WireFormatLite::TYPE_BYTES>
  231. : PrimitiveTypeHelper<WireFormatLite::TYPE_STRING> {};
  232. template <>
  233. struct PrimitiveTypeHelper<FieldMetadata::kInlinedType>
  234. : PrimitiveTypeHelper<WireFormatLite::TYPE_STRING> {};
  235. // We want to serialize to both CodedOutputStream and directly into byte arrays
  236. // without duplicating the code. In fact we might want extra output channels in
  237. // the future.
  238. template <typename O, int type>
  239. struct OutputHelper;
  240. template <int type, typename O>
  241. void SerializeTo(const void* ptr, O* output) {
  242. OutputHelper<O, type>::Serialize(ptr, output);
  243. }
  244. template <typename O>
  245. void WriteTagTo(uint32 tag, O* output) {
  246. SerializeTo<WireFormatLite::TYPE_UINT32>(&tag, output);
  247. }
  248. template <typename O>
  249. void WriteLengthTo(uint32 length, O* output) {
  250. SerializeTo<WireFormatLite::TYPE_UINT32>(&length, output);
  251. }
  252. // Specialization for coded output stream
  253. template <int type>
  254. struct OutputHelper<::google::protobuf::io::CodedOutputStream, type> {
  255. static void Serialize(const void* ptr,
  256. ::google::protobuf::io::CodedOutputStream* output) {
  257. PrimitiveTypeHelper<type>::Serialize(ptr, output);
  258. }
  259. };
  260. // Specialization for writing into a plain array
  261. struct ArrayOutput {
  262. uint8* ptr;
  263. bool is_deterministic;
  264. };
  265. template <int type>
  266. struct OutputHelper<ArrayOutput, type> {
  267. static void Serialize(const void* ptr, ArrayOutput* output) {
  268. output->ptr = PrimitiveTypeHelper<type>::SerializeToArray(ptr, output->ptr);
  269. }
  270. };
  271. void SerializeMessageNoTable(const MessageLite* msg,
  272. ::google::protobuf::io::CodedOutputStream* output) {
  273. msg->SerializeWithCachedSizes(output);
  274. }
  275. void SerializeMessageNoTable(const MessageLite* msg, ArrayOutput* output) {
  276. output->ptr = msg->InternalSerializeWithCachedSizesToArray(
  277. output->is_deterministic, output->ptr);
  278. }
  279. // Helper to branch to fast path if possible
  280. void SerializeMessageDispatch(const ::google::protobuf::MessageLite& msg,
  281. const FieldMetadata* field_table, int num_fields,
  282. int32 cached_size,
  283. ::google::protobuf::io::CodedOutputStream* output) {
  284. const uint8* base = reinterpret_cast<const uint8*>(&msg);
  285. // Try the fast path
  286. uint8* ptr = output->GetDirectBufferForNBytesAndAdvance(cached_size);
  287. if (ptr) {
  288. // We use virtual dispatch to enable dedicated generated code for the
  289. // fast path.
  290. msg.InternalSerializeWithCachedSizesToArray(
  291. output->IsSerializationDeterministic(), ptr);
  292. return;
  293. }
  294. SerializeInternal(base, field_table, num_fields, output);
  295. }
  296. // Helper to branch to fast path if possible
  297. void SerializeMessageDispatch(const ::google::protobuf::MessageLite& msg,
  298. const FieldMetadata* field_table, int num_fields,
  299. int32 cached_size, ArrayOutput* output) {
  300. const uint8* base = reinterpret_cast<const uint8*>(&msg);
  301. output->ptr = SerializeInternalToArray(base, field_table, num_fields,
  302. output->is_deterministic, output->ptr);
  303. }
  304. // Serializing messages is special as it's not a primitive type and needs an
  305. // explicit overload for each output type.
  306. template <typename O>
  307. void SerializeMessageTo(const MessageLite* msg, const void* table_ptr,
  308. O* output) {
  309. const SerializationTable* table =
  310. static_cast<const SerializationTable*>(table_ptr);
  311. if (!table) {
  312. // Proto1
  313. WriteLengthTo(msg->GetCachedSize(), output);
  314. SerializeMessageNoTable(msg, output);
  315. return;
  316. }
  317. const FieldMetadata* field_table = table->field_table;
  318. const uint8* base = reinterpret_cast<const uint8*>(msg);
  319. int cached_size = *reinterpret_cast<const int32*>(base + field_table->offset);
  320. WriteLengthTo(cached_size, output);
  321. int num_fields = table->num_fields - 1;
  322. SerializeMessageDispatch(*msg, field_table + 1, num_fields, cached_size,
  323. output);
  324. }
  325. // Almost the same as above only it doesn't output the length field.
  326. template <typename O>
  327. void SerializeGroupTo(const MessageLite* msg, const void* table_ptr,
  328. O* output) {
  329. const SerializationTable* table =
  330. static_cast<const SerializationTable*>(table_ptr);
  331. if (!table) {
  332. // Proto1
  333. SerializeMessageNoTable(msg, output);
  334. return;
  335. }
  336. const FieldMetadata* field_table = table->field_table;
  337. const uint8* base = reinterpret_cast<const uint8*>(msg);
  338. int cached_size = *reinterpret_cast<const int32*>(base + field_table->offset);
  339. int num_fields = table->num_fields - 1;
  340. SerializeMessageDispatch(*msg, field_table + 1, num_fields, cached_size,
  341. output);
  342. }
  343. template <int type>
  344. struct SingularFieldHelper {
  345. template <typename O>
  346. static void Serialize(const void* field, const FieldMetadata& md, O* output) {
  347. WriteTagTo(md.tag, output);
  348. SerializeTo<type>(field, output);
  349. }
  350. };
  351. template <>
  352. struct SingularFieldHelper<WireFormatLite::TYPE_STRING> {
  353. template <typename O>
  354. static void Serialize(const void* field, const FieldMetadata& md, O* output) {
  355. WriteTagTo(md.tag, output);
  356. SerializeTo<WireFormatLite::TYPE_STRING>(&Get<ArenaStringPtr>(field).Get(),
  357. output);
  358. }
  359. };
  360. template <>
  361. struct SingularFieldHelper<WireFormatLite::TYPE_BYTES>
  362. : SingularFieldHelper<WireFormatLite::TYPE_STRING> {};
  363. template <>
  364. struct SingularFieldHelper<WireFormatLite::TYPE_GROUP> {
  365. template <typename O>
  366. static void Serialize(const void* field, const FieldMetadata& md, O* output) {
  367. WriteTagTo(md.tag, output);
  368. SerializeGroupTo(Get<const MessageLite*>(field),
  369. static_cast<const SerializationTable*>(md.ptr), output);
  370. WriteTagTo(md.tag + 1, output);
  371. }
  372. };
  373. template <>
  374. struct SingularFieldHelper<WireFormatLite::TYPE_MESSAGE> {
  375. template <typename O>
  376. static void Serialize(const void* field, const FieldMetadata& md, O* output) {
  377. WriteTagTo(md.tag, output);
  378. SerializeMessageTo(Get<const MessageLite*>(field),
  379. static_cast<const SerializationTable*>(md.ptr), output);
  380. }
  381. };
  382. template <>
  383. struct SingularFieldHelper<FieldMetadata::kInlinedType> {
  384. template <typename O>
  385. static void Serialize(const void* field, const FieldMetadata& md, O* output) {
  386. WriteTagTo(md.tag, output);
  387. SerializeTo<FieldMetadata::kInlinedType>(&Get<::std::string>(field), output);
  388. }
  389. };
  390. template <int type>
  391. struct RepeatedFieldHelper {
  392. template <typename O>
  393. static void Serialize(const void* field, const FieldMetadata& md, O* output) {
  394. typedef typename PrimitiveTypeHelper<type>::Type T;
  395. const RepeatedField<T>& array = Get<RepeatedField<T> >(field);
  396. for (int i = 0; i < array.size(); i++) {
  397. WriteTagTo(md.tag, output);
  398. SerializeTo<type>(&array[i], output);
  399. }
  400. }
  401. };
  402. // We need to use a helper class to get access to the private members
  403. class AccessorHelper {
  404. public:
  405. static int Size(const RepeatedPtrFieldBase& x) { return x.size(); }
  406. static void const* Get(const RepeatedPtrFieldBase& x, int idx) {
  407. return x.raw_data()[idx];
  408. }
  409. };
  410. template <>
  411. struct RepeatedFieldHelper<WireFormatLite::TYPE_STRING> {
  412. template <typename O>
  413. static void Serialize(const void* field, const FieldMetadata& md, O* output) {
  414. const internal::RepeatedPtrFieldBase& array =
  415. Get<internal::RepeatedPtrFieldBase>(field);
  416. for (int i = 0; i < AccessorHelper::Size(array); i++) {
  417. WriteTagTo(md.tag, output);
  418. SerializeTo<WireFormatLite::TYPE_STRING>(AccessorHelper::Get(array, i),
  419. output);
  420. }
  421. }
  422. };
  423. template <>
  424. struct RepeatedFieldHelper<WireFormatLite::TYPE_BYTES>
  425. : RepeatedFieldHelper<WireFormatLite::TYPE_STRING> {};
  426. template <>
  427. struct RepeatedFieldHelper<WireFormatLite::TYPE_GROUP> {
  428. template <typename O>
  429. static void Serialize(const void* field, const FieldMetadata& md, O* output) {
  430. const internal::RepeatedPtrFieldBase& array =
  431. Get<internal::RepeatedPtrFieldBase>(field);
  432. for (int i = 0; i < AccessorHelper::Size(array); i++) {
  433. WriteTagTo(md.tag, output);
  434. SerializeGroupTo(
  435. static_cast<const MessageLite*>(AccessorHelper::Get(array, i)),
  436. static_cast<const SerializationTable*>(md.ptr), output);
  437. WriteTagTo(md.tag + 1, output);
  438. }
  439. }
  440. };
  441. template <>
  442. struct RepeatedFieldHelper<WireFormatLite::TYPE_MESSAGE> {
  443. template <typename O>
  444. static void Serialize(const void* field, const FieldMetadata& md, O* output) {
  445. const internal::RepeatedPtrFieldBase& array =
  446. Get<internal::RepeatedPtrFieldBase>(field);
  447. for (int i = 0; i < AccessorHelper::Size(array); i++) {
  448. WriteTagTo(md.tag, output);
  449. SerializeMessageTo(
  450. static_cast<const MessageLite*>(AccessorHelper::Get(array, i)), md.ptr,
  451. output);
  452. }
  453. }
  454. };
  455. template <>
  456. struct RepeatedFieldHelper<FieldMetadata::kInlinedType>
  457. : RepeatedFieldHelper<WireFormatLite::TYPE_STRING> {};
  458. template <int type>
  459. struct PackedFieldHelper {
  460. template <typename O>
  461. static void Serialize(const void* field, const FieldMetadata& md, O* output) {
  462. typedef typename PrimitiveTypeHelper<type>::Type T;
  463. const RepeatedField<T>& array = Get<RepeatedField<T> >(field);
  464. if (array.empty()) return;
  465. WriteTagTo(md.tag, output);
  466. int cached_size =
  467. Get<int>(static_cast<const uint8*>(field) + sizeof(RepeatedField<T>));
  468. WriteLengthTo(cached_size, output);
  469. for (int i = 0; i < array.size(); i++) {
  470. SerializeTo<type>(&array[i], output);
  471. }
  472. }
  473. };
  474. template <>
  475. struct PackedFieldHelper<WireFormatLite::TYPE_STRING> {
  476. template <typename O>
  477. static void Serialize(const void* field, const FieldMetadata& md, O* output) {
  478. GOOGLE_LOG(FATAL) << "Not implemented field number " << md.tag << " with type "
  479. << md.type;
  480. }
  481. };
  482. template <>
  483. struct PackedFieldHelper<WireFormatLite::TYPE_BYTES>
  484. : PackedFieldHelper<WireFormatLite::TYPE_STRING> {};
  485. template <>
  486. struct PackedFieldHelper<WireFormatLite::TYPE_GROUP>
  487. : PackedFieldHelper<WireFormatLite::TYPE_STRING> {};
  488. template <>
  489. struct PackedFieldHelper<WireFormatLite::TYPE_MESSAGE>
  490. : PackedFieldHelper<WireFormatLite::TYPE_STRING> {};
  491. template <>
  492. struct PackedFieldHelper<FieldMetadata::kInlinedType>
  493. : PackedFieldHelper<WireFormatLite::TYPE_STRING> {};
  494. template <int type>
  495. struct OneOfFieldHelper {
  496. template <typename O>
  497. static void Serialize(const void* field, const FieldMetadata& md, O* output) {
  498. SingularFieldHelper<type>::Serialize(field, md, output);
  499. }
  500. };
  501. template <>
  502. struct OneOfFieldHelper<FieldMetadata::kInlinedType> {
  503. template <typename O>
  504. static void Serialize(const void* field, const FieldMetadata& md, O* output) {
  505. SingularFieldHelper<FieldMetadata::kInlinedType>::Serialize(
  506. Get<const ::std::string*>(field), md, output);
  507. }
  508. };
  509. void SerializeNotImplemented(int field) {
  510. GOOGLE_LOG(FATAL) << "Not implemented field number " << field;
  511. }
  512. // When switching to c++11 we should make these constexpr functions
  513. #define SERIALIZE_TABLE_OP(type, type_class) \
  514. ((type - 1) + static_cast<int>(type_class) * FieldMetadata::kNumTypes)
  515. int FieldMetadata::CalculateType(int type,
  516. FieldMetadata::FieldTypeClass type_class) {
  517. return SERIALIZE_TABLE_OP(type, type_class);
  518. }
  519. template <int type>
  520. bool IsNull(const void* ptr) {
  521. return *static_cast<const typename PrimitiveTypeHelper<type>::Type*>(ptr) ==
  522. 0;
  523. }
  524. template <>
  525. bool IsNull<WireFormatLite::TYPE_STRING>(const void* ptr) {
  526. return static_cast<const ArenaStringPtr*>(ptr)->Get().size() == 0;
  527. }
  528. template <>
  529. bool IsNull<WireFormatLite::TYPE_BYTES>(const void* ptr) {
  530. return static_cast<const ArenaStringPtr*>(ptr)->Get().size() == 0;
  531. }
  532. template <>
  533. bool IsNull<WireFormatLite::TYPE_GROUP>(const void* ptr) {
  534. return Get<const MessageLite*>(ptr) == NULL;
  535. }
  536. template <>
  537. bool IsNull<WireFormatLite::TYPE_MESSAGE>(const void* ptr) {
  538. return Get<const MessageLite*>(ptr) == NULL;
  539. }
  540. template <>
  541. bool IsNull<FieldMetadata::kInlinedType>(const void* ptr) {
  542. return static_cast<const ::std::string*>(ptr)->empty();
  543. }
  544. #define SERIALIZERS_FOR_TYPE(type) \
  545. case SERIALIZE_TABLE_OP(type, FieldMetadata::kPresence): \
  546. if (!IsPresent(base, field_metadata.has_offset)) continue; \
  547. SingularFieldHelper<type>::Serialize(ptr, field_metadata, output); \
  548. break; \
  549. case SERIALIZE_TABLE_OP(type, FieldMetadata::kNoPresence): \
  550. if (IsNull<type>(ptr)) continue; \
  551. SingularFieldHelper<type>::Serialize(ptr, field_metadata, output); \
  552. break; \
  553. case SERIALIZE_TABLE_OP(type, FieldMetadata::kRepeated): \
  554. RepeatedFieldHelper<type>::Serialize(ptr, field_metadata, output); \
  555. break; \
  556. case SERIALIZE_TABLE_OP(type, FieldMetadata::kPacked): \
  557. PackedFieldHelper<type>::Serialize(ptr, field_metadata, output); \
  558. break; \
  559. case SERIALIZE_TABLE_OP(type, FieldMetadata::kOneOf): \
  560. if (!IsOneofPresent(base, field_metadata.has_offset, field_metadata.tag)) \
  561. continue; \
  562. OneOfFieldHelper<type>::Serialize(ptr, field_metadata, output); \
  563. break
  564. void SerializeInternal(const uint8* base,
  565. const FieldMetadata* field_metadata_table,
  566. int32 num_fields,
  567. ::google::protobuf::io::CodedOutputStream* output) {
  568. for (int i = 0; i < num_fields; i++) {
  569. const FieldMetadata& field_metadata = field_metadata_table[i];
  570. const uint8* ptr = base + field_metadata.offset;
  571. switch (field_metadata.type) {
  572. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_DOUBLE);
  573. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_FLOAT);
  574. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_INT64);
  575. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_UINT64);
  576. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_INT32);
  577. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_FIXED64);
  578. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_FIXED32);
  579. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_BOOL);
  580. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_STRING);
  581. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_GROUP);
  582. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_MESSAGE);
  583. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_BYTES);
  584. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_UINT32);
  585. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_ENUM);
  586. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SFIXED32);
  587. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SFIXED64);
  588. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT32);
  589. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT64);
  590. SERIALIZERS_FOR_TYPE(FieldMetadata::kInlinedType);
  591. // Special cases
  592. case FieldMetadata::kSpecial:
  593. reinterpret_cast<SpecialSerializer>(
  594. const_cast<void*>(field_metadata.ptr))(
  595. base, field_metadata.offset, field_metadata.tag,
  596. field_metadata.has_offset, output);
  597. break;
  598. default:
  599. // __builtin_unreachable()
  600. SerializeNotImplemented(field_metadata.type);
  601. }
  602. }
  603. }
  604. uint8* SerializeInternalToArray(const uint8* base,
  605. const FieldMetadata* field_metadata_table,
  606. int32 num_fields, bool is_deterministic,
  607. uint8* buffer) {
  608. ArrayOutput array_output = {buffer, is_deterministic};
  609. ArrayOutput* output = &array_output;
  610. for (int i = 0; i < num_fields; i++) {
  611. const FieldMetadata& field_metadata = field_metadata_table[i];
  612. const uint8* ptr = base + field_metadata.offset;
  613. switch (field_metadata.type) {
  614. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_DOUBLE);
  615. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_FLOAT);
  616. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_INT64);
  617. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_UINT64);
  618. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_INT32);
  619. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_FIXED64);
  620. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_FIXED32);
  621. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_BOOL);
  622. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_STRING);
  623. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_GROUP);
  624. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_MESSAGE);
  625. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_BYTES);
  626. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_UINT32);
  627. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_ENUM);
  628. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SFIXED32);
  629. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SFIXED64);
  630. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT32);
  631. SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT64);
  632. SERIALIZERS_FOR_TYPE(FieldMetadata::kInlinedType);
  633. // Special cases
  634. case FieldMetadata::kSpecial: {
  635. io::ArrayOutputStream array_stream(array_output.ptr, INT_MAX);
  636. io::CodedOutputStream output(&array_stream);
  637. output.SetSerializationDeterministic(is_deterministic);
  638. reinterpret_cast<SpecialSerializer>(
  639. const_cast<void*>(field_metadata.ptr))(
  640. base, field_metadata.offset, field_metadata.tag,
  641. field_metadata.has_offset, &output);
  642. array_output.ptr += output.ByteCount();
  643. } break;
  644. default:
  645. // __builtin_unreachable()
  646. SerializeNotImplemented(field_metadata.type);
  647. }
  648. }
  649. return array_output.ptr;
  650. }
  651. #undef SERIALIZERS_FOR_TYPE
  652. void ExtensionSerializer(const uint8* ptr, uint32 offset, uint32 tag,
  653. uint32 has_offset,
  654. ::google::protobuf::io::CodedOutputStream* output) {
  655. reinterpret_cast<const ExtensionSet*>(ptr + offset)
  656. ->SerializeWithCachedSizes(tag, has_offset, output);
  657. }
  658. void UnknownFieldSerializerLite(const uint8* ptr, uint32 offset, uint32 tag,
  659. uint32 has_offset,
  660. ::google::protobuf::io::CodedOutputStream* output) {
  661. output->WriteString(
  662. reinterpret_cast<const InternalMetadataWithArenaLite*>(ptr + offset)
  663. ->unknown_fields());
  664. }
  665. MessageLite* DuplicateIfNonNullInternal(MessageLite* message) {
  666. if (message) {
  667. MessageLite* ret = message->New();
  668. ret->CheckTypeAndMergeFrom(*message);
  669. return ret;
  670. } else {
  671. return NULL;
  672. }
  673. }
  674. // Returns a message owned by this Arena. This may require Own()ing or
  675. // duplicating the message.
  676. MessageLite* GetOwnedMessageInternal(Arena* message_arena,
  677. MessageLite* submessage,
  678. Arena* submessage_arena) {
  679. GOOGLE_DCHECK(submessage->GetArena() == submessage_arena);
  680. GOOGLE_DCHECK(message_arena != submessage_arena);
  681. if (message_arena != NULL && submessage_arena == NULL) {
  682. message_arena->Own(submessage);
  683. return submessage;
  684. } else {
  685. MessageLite* ret = submessage->New(message_arena);
  686. ret->CheckTypeAndMergeFrom(*submessage);
  687. return ret;
  688. }
  689. }
  690. namespace {
  691. void InitSCC_DFS(SCCInfoBase* scc) {
  692. if (scc->visit_status.load(std::memory_order_relaxed) !=
  693. SCCInfoBase::kUninitialized) return;
  694. scc->visit_status.store(SCCInfoBase::kRunning, std::memory_order_relaxed);
  695. // Each base is followed by an array of pointers to deps
  696. auto deps = reinterpret_cast<SCCInfoBase* const*>(scc + 1);
  697. for (int i = 0; i < scc->num_deps; i++) {
  698. if (deps[i]) InitSCC_DFS(deps[i]);
  699. }
  700. scc->init_func();
  701. // Mark done (note we use memory order release here), other threads could
  702. // now see this as initialized and thus the initialization must have happened
  703. // before.
  704. scc->visit_status.store(SCCInfoBase::kInitialized, std::memory_order_release);
  705. }
  706. } // namespace
  707. void InitSCCImpl(SCCInfoBase* scc) {
  708. static WrappedMutex mu{GOOGLE_PROTOBUF_LINKER_INITIALIZED};
  709. // Either the default in case no initialization is running or the id of the
  710. // thread that is currently initializing.
  711. static std::atomic<std::thread::id> runner;
  712. auto me = std::this_thread::get_id();
  713. // This will only happen because the constructor will call InitSCC while
  714. // constructing the default instance.
  715. if (runner.load(std::memory_order_relaxed) == me) {
  716. // Because we're in the process of constructing the default instance.
  717. // We can be assured that we're already exploring this SCC.
  718. GOOGLE_CHECK_EQ(scc->visit_status.load(std::memory_order_relaxed),
  719. SCCInfoBase::kRunning);
  720. return;
  721. }
  722. InitProtobufDefaults();
  723. mu.Lock();
  724. runner.store(me, std::memory_order_relaxed);
  725. InitSCC_DFS(scc);
  726. runner.store(std::thread::id{}, std::memory_order_relaxed);
  727. mu.Unlock();
  728. }
  729. } // namespace internal
  730. } // namespace protobuf
  731. } // namespace google