wire_format_lite.cc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  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/wire_format_lite_inl.h>
  34. #include <stack>
  35. #include <string>
  36. #include <vector>
  37. #include <google/protobuf/stubs/logging.h>
  38. #include <google/protobuf/stubs/common.h>
  39. #include <google/protobuf/stubs/stringprintf.h>
  40. #include <google/protobuf/io/coded_stream_inl.h>
  41. #include <google/protobuf/io/zero_copy_stream.h>
  42. #include <google/protobuf/io/zero_copy_stream_impl_lite.h>
  43. namespace google {
  44. namespace protobuf {
  45. namespace internal {
  46. #if !defined(_MSC_VER) || _MSC_VER >= 1900
  47. // Old version of MSVC doesn't like definitions of inline constants, GCC
  48. // requires them.
  49. const int WireFormatLite::kMessageSetItemStartTag;
  50. const int WireFormatLite::kMessageSetItemEndTag;
  51. const int WireFormatLite::kMessageSetTypeIdTag;
  52. const int WireFormatLite::kMessageSetMessageTag;
  53. #endif
  54. // IBM xlC requires prefixing constants with WireFormatLite::
  55. const size_t WireFormatLite::kMessageSetItemTagsSize =
  56. io::CodedOutputStream::StaticVarintSize32<
  57. WireFormatLite::kMessageSetItemStartTag>::value +
  58. io::CodedOutputStream::StaticVarintSize32<
  59. WireFormatLite::kMessageSetItemEndTag>::value +
  60. io::CodedOutputStream::StaticVarintSize32<
  61. WireFormatLite::kMessageSetTypeIdTag>::value +
  62. io::CodedOutputStream::StaticVarintSize32<
  63. WireFormatLite::kMessageSetMessageTag>::value;
  64. const WireFormatLite::CppType
  65. WireFormatLite::kFieldTypeToCppTypeMap[MAX_FIELD_TYPE + 1] = {
  66. static_cast<CppType>(0), // 0 is reserved for errors
  67. CPPTYPE_DOUBLE, // TYPE_DOUBLE
  68. CPPTYPE_FLOAT, // TYPE_FLOAT
  69. CPPTYPE_INT64, // TYPE_INT64
  70. CPPTYPE_UINT64, // TYPE_UINT64
  71. CPPTYPE_INT32, // TYPE_INT32
  72. CPPTYPE_UINT64, // TYPE_FIXED64
  73. CPPTYPE_UINT32, // TYPE_FIXED32
  74. CPPTYPE_BOOL, // TYPE_BOOL
  75. CPPTYPE_STRING, // TYPE_STRING
  76. CPPTYPE_MESSAGE, // TYPE_GROUP
  77. CPPTYPE_MESSAGE, // TYPE_MESSAGE
  78. CPPTYPE_STRING, // TYPE_BYTES
  79. CPPTYPE_UINT32, // TYPE_UINT32
  80. CPPTYPE_ENUM, // TYPE_ENUM
  81. CPPTYPE_INT32, // TYPE_SFIXED32
  82. CPPTYPE_INT64, // TYPE_SFIXED64
  83. CPPTYPE_INT32, // TYPE_SINT32
  84. CPPTYPE_INT64, // TYPE_SINT64
  85. };
  86. const WireFormatLite::WireType
  87. WireFormatLite::kWireTypeForFieldType[MAX_FIELD_TYPE + 1] = {
  88. static_cast<WireFormatLite::WireType>(-1), // invalid
  89. WireFormatLite::WIRETYPE_FIXED64, // TYPE_DOUBLE
  90. WireFormatLite::WIRETYPE_FIXED32, // TYPE_FLOAT
  91. WireFormatLite::WIRETYPE_VARINT, // TYPE_INT64
  92. WireFormatLite::WIRETYPE_VARINT, // TYPE_UINT64
  93. WireFormatLite::WIRETYPE_VARINT, // TYPE_INT32
  94. WireFormatLite::WIRETYPE_FIXED64, // TYPE_FIXED64
  95. WireFormatLite::WIRETYPE_FIXED32, // TYPE_FIXED32
  96. WireFormatLite::WIRETYPE_VARINT, // TYPE_BOOL
  97. WireFormatLite::WIRETYPE_LENGTH_DELIMITED, // TYPE_STRING
  98. WireFormatLite::WIRETYPE_START_GROUP, // TYPE_GROUP
  99. WireFormatLite::WIRETYPE_LENGTH_DELIMITED, // TYPE_MESSAGE
  100. WireFormatLite::WIRETYPE_LENGTH_DELIMITED, // TYPE_BYTES
  101. WireFormatLite::WIRETYPE_VARINT, // TYPE_UINT32
  102. WireFormatLite::WIRETYPE_VARINT, // TYPE_ENUM
  103. WireFormatLite::WIRETYPE_FIXED32, // TYPE_SFIXED32
  104. WireFormatLite::WIRETYPE_FIXED64, // TYPE_SFIXED64
  105. WireFormatLite::WIRETYPE_VARINT, // TYPE_SINT32
  106. WireFormatLite::WIRETYPE_VARINT, // TYPE_SINT64
  107. };
  108. bool WireFormatLite::SkipField(
  109. io::CodedInputStream* input, uint32 tag) {
  110. // Field number 0 is illegal.
  111. if (WireFormatLite::GetTagFieldNumber(tag) == 0) return false;
  112. switch (WireFormatLite::GetTagWireType(tag)) {
  113. case WireFormatLite::WIRETYPE_VARINT: {
  114. uint64 value;
  115. if (!input->ReadVarint64(&value)) return false;
  116. return true;
  117. }
  118. case WireFormatLite::WIRETYPE_FIXED64: {
  119. uint64 value;
  120. if (!input->ReadLittleEndian64(&value)) return false;
  121. return true;
  122. }
  123. case WireFormatLite::WIRETYPE_LENGTH_DELIMITED: {
  124. uint32 length;
  125. if (!input->ReadVarint32(&length)) return false;
  126. if (!input->Skip(length)) return false;
  127. return true;
  128. }
  129. case WireFormatLite::WIRETYPE_START_GROUP: {
  130. if (!input->IncrementRecursionDepth()) return false;
  131. if (!SkipMessage(input)) return false;
  132. input->DecrementRecursionDepth();
  133. // Check that the ending tag matched the starting tag.
  134. if (!input->LastTagWas(WireFormatLite::MakeTag(
  135. WireFormatLite::GetTagFieldNumber(tag),
  136. WireFormatLite::WIRETYPE_END_GROUP))) {
  137. return false;
  138. }
  139. return true;
  140. }
  141. case WireFormatLite::WIRETYPE_END_GROUP: {
  142. return false;
  143. }
  144. case WireFormatLite::WIRETYPE_FIXED32: {
  145. uint32 value;
  146. if (!input->ReadLittleEndian32(&value)) return false;
  147. return true;
  148. }
  149. default: {
  150. return false;
  151. }
  152. }
  153. }
  154. bool WireFormatLite::SkipField(
  155. io::CodedInputStream* input, uint32 tag, io::CodedOutputStream* output) {
  156. // Field number 0 is illegal.
  157. if (WireFormatLite::GetTagFieldNumber(tag) == 0) return false;
  158. switch (WireFormatLite::GetTagWireType(tag)) {
  159. case WireFormatLite::WIRETYPE_VARINT: {
  160. uint64 value;
  161. if (!input->ReadVarint64(&value)) return false;
  162. output->WriteVarint32(tag);
  163. output->WriteVarint64(value);
  164. return true;
  165. }
  166. case WireFormatLite::WIRETYPE_FIXED64: {
  167. uint64 value;
  168. if (!input->ReadLittleEndian64(&value)) return false;
  169. output->WriteVarint32(tag);
  170. output->WriteLittleEndian64(value);
  171. return true;
  172. }
  173. case WireFormatLite::WIRETYPE_LENGTH_DELIMITED: {
  174. uint32 length;
  175. if (!input->ReadVarint32(&length)) return false;
  176. output->WriteVarint32(tag);
  177. output->WriteVarint32(length);
  178. // TODO(mkilavuz): Provide API to prevent extra string copying.
  179. string temp;
  180. if (!input->ReadString(&temp, length)) return false;
  181. output->WriteString(temp);
  182. return true;
  183. }
  184. case WireFormatLite::WIRETYPE_START_GROUP: {
  185. output->WriteVarint32(tag);
  186. if (!input->IncrementRecursionDepth()) return false;
  187. if (!SkipMessage(input, output)) return false;
  188. input->DecrementRecursionDepth();
  189. // Check that the ending tag matched the starting tag.
  190. if (!input->LastTagWas(WireFormatLite::MakeTag(
  191. WireFormatLite::GetTagFieldNumber(tag),
  192. WireFormatLite::WIRETYPE_END_GROUP))) {
  193. return false;
  194. }
  195. return true;
  196. }
  197. case WireFormatLite::WIRETYPE_END_GROUP: {
  198. return false;
  199. }
  200. case WireFormatLite::WIRETYPE_FIXED32: {
  201. uint32 value;
  202. if (!input->ReadLittleEndian32(&value)) return false;
  203. output->WriteVarint32(tag);
  204. output->WriteLittleEndian32(value);
  205. return true;
  206. }
  207. default: {
  208. return false;
  209. }
  210. }
  211. }
  212. bool WireFormatLite::SkipMessage(io::CodedInputStream* input) {
  213. while (true) {
  214. uint32 tag = input->ReadTag();
  215. if (tag == 0) {
  216. // End of input. This is a valid place to end, so return true.
  217. return true;
  218. }
  219. WireFormatLite::WireType wire_type = WireFormatLite::GetTagWireType(tag);
  220. if (wire_type == WireFormatLite::WIRETYPE_END_GROUP) {
  221. // Must be the end of the message.
  222. return true;
  223. }
  224. if (!SkipField(input, tag)) return false;
  225. }
  226. }
  227. bool WireFormatLite::SkipMessage(io::CodedInputStream* input,
  228. io::CodedOutputStream* output) {
  229. while (true) {
  230. uint32 tag = input->ReadTag();
  231. if (tag == 0) {
  232. // End of input. This is a valid place to end, so return true.
  233. return true;
  234. }
  235. WireFormatLite::WireType wire_type = WireFormatLite::GetTagWireType(tag);
  236. if (wire_type == WireFormatLite::WIRETYPE_END_GROUP) {
  237. output->WriteVarint32(tag);
  238. // Must be the end of the message.
  239. return true;
  240. }
  241. if (!SkipField(input, tag, output)) return false;
  242. }
  243. }
  244. bool FieldSkipper::SkipField(
  245. io::CodedInputStream* input, uint32 tag) {
  246. return WireFormatLite::SkipField(input, tag);
  247. }
  248. bool FieldSkipper::SkipMessage(io::CodedInputStream* input) {
  249. return WireFormatLite::SkipMessage(input);
  250. }
  251. void FieldSkipper::SkipUnknownEnum(
  252. int /* field_number */, int /* value */) {
  253. // Nothing.
  254. }
  255. bool CodedOutputStreamFieldSkipper::SkipField(
  256. io::CodedInputStream* input, uint32 tag) {
  257. return WireFormatLite::SkipField(input, tag, unknown_fields_);
  258. }
  259. bool CodedOutputStreamFieldSkipper::SkipMessage(io::CodedInputStream* input) {
  260. return WireFormatLite::SkipMessage(input, unknown_fields_);
  261. }
  262. void CodedOutputStreamFieldSkipper::SkipUnknownEnum(
  263. int field_number, int value) {
  264. unknown_fields_->WriteVarint32(field_number);
  265. unknown_fields_->WriteVarint64(value);
  266. }
  267. bool WireFormatLite::ReadPackedEnumNoInline(io::CodedInputStream* input,
  268. bool (*is_valid)(int),
  269. RepeatedField<int>* values) {
  270. uint32 length;
  271. if (!input->ReadVarint32(&length)) return false;
  272. io::CodedInputStream::Limit limit = input->PushLimit(length);
  273. while (input->BytesUntilLimit() > 0) {
  274. int value;
  275. if (!google::protobuf::internal::WireFormatLite::ReadPrimitive<
  276. int, WireFormatLite::TYPE_ENUM>(input, &value)) {
  277. return false;
  278. }
  279. if (is_valid == NULL || is_valid(value)) {
  280. values->Add(value);
  281. }
  282. }
  283. input->PopLimit(limit);
  284. return true;
  285. }
  286. bool WireFormatLite::ReadPackedEnumPreserveUnknowns(
  287. io::CodedInputStream* input,
  288. int field_number,
  289. bool (*is_valid)(int),
  290. io::CodedOutputStream* unknown_fields_stream,
  291. RepeatedField<int>* values) {
  292. uint32 length;
  293. if (!input->ReadVarint32(&length)) return false;
  294. io::CodedInputStream::Limit limit = input->PushLimit(length);
  295. while (input->BytesUntilLimit() > 0) {
  296. int value;
  297. if (!google::protobuf::internal::WireFormatLite::ReadPrimitive<
  298. int, WireFormatLite::TYPE_ENUM>(input, &value)) {
  299. return false;
  300. }
  301. if (is_valid == NULL || is_valid(value)) {
  302. values->Add(value);
  303. } else {
  304. uint32 tag = WireFormatLite::MakeTag(field_number,
  305. WireFormatLite::WIRETYPE_VARINT);
  306. unknown_fields_stream->WriteVarint32(tag);
  307. unknown_fields_stream->WriteVarint32(value);
  308. }
  309. }
  310. input->PopLimit(limit);
  311. return true;
  312. }
  313. #if !defined(PROTOBUF_LITTLE_ENDIAN)
  314. namespace {
  315. void EncodeFixedSizeValue(float v, uint8* dest) {
  316. WireFormatLite::WriteFloatNoTagToArray(v, dest);
  317. }
  318. void EncodeFixedSizeValue(double v, uint8* dest) {
  319. WireFormatLite::WriteDoubleNoTagToArray(v, dest);
  320. }
  321. void EncodeFixedSizeValue(uint32 v, uint8* dest) {
  322. WireFormatLite::WriteFixed32NoTagToArray(v, dest);
  323. }
  324. void EncodeFixedSizeValue(uint64 v, uint8* dest) {
  325. WireFormatLite::WriteFixed64NoTagToArray(v, dest);
  326. }
  327. void EncodeFixedSizeValue(int32 v, uint8* dest) {
  328. WireFormatLite::WriteSFixed32NoTagToArray(v, dest);
  329. }
  330. void EncodeFixedSizeValue(int64 v, uint8* dest) {
  331. WireFormatLite::WriteSFixed64NoTagToArray(v, dest);
  332. }
  333. void EncodeFixedSizeValue(bool v, uint8* dest) {
  334. WireFormatLite::WriteBoolNoTagToArray(v, dest);
  335. }
  336. } // anonymous namespace
  337. #endif // !defined(PROTOBUF_LITTLE_ENDIAN)
  338. template <typename CType>
  339. static void WriteArray(const CType* a, int n, io::CodedOutputStream* output) {
  340. #if defined(PROTOBUF_LITTLE_ENDIAN)
  341. output->WriteRaw(reinterpret_cast<const char*>(a), n * sizeof(a[0]));
  342. #else
  343. const int kAtATime = 128;
  344. uint8 buf[sizeof(CType) * kAtATime];
  345. for (int i = 0; i < n; i += kAtATime) {
  346. int to_do = std::min(kAtATime, n - i);
  347. uint8* ptr = buf;
  348. for (int j = 0; j < to_do; j++) {
  349. EncodeFixedSizeValue(a[i+j], ptr);
  350. ptr += sizeof(a[0]);
  351. }
  352. output->WriteRaw(buf, to_do * sizeof(a[0]));
  353. }
  354. #endif
  355. }
  356. void WireFormatLite::WriteFloatArray(const float* a, int n,
  357. io::CodedOutputStream* output) {
  358. WriteArray<float>(a, n, output);
  359. }
  360. void WireFormatLite::WriteDoubleArray(const double* a, int n,
  361. io::CodedOutputStream* output) {
  362. WriteArray<double>(a, n, output);
  363. }
  364. void WireFormatLite::WriteFixed32Array(const uint32* a, int n,
  365. io::CodedOutputStream* output) {
  366. WriteArray<uint32>(a, n, output);
  367. }
  368. void WireFormatLite::WriteFixed64Array(const uint64* a, int n,
  369. io::CodedOutputStream* output) {
  370. WriteArray<uint64>(a, n, output);
  371. }
  372. void WireFormatLite::WriteSFixed32Array(const int32* a, int n,
  373. io::CodedOutputStream* output) {
  374. WriteArray<int32>(a, n, output);
  375. }
  376. void WireFormatLite::WriteSFixed64Array(const int64* a, int n,
  377. io::CodedOutputStream* output) {
  378. WriteArray<int64>(a, n, output);
  379. }
  380. void WireFormatLite::WriteBoolArray(const bool* a, int n,
  381. io::CodedOutputStream* output) {
  382. WriteArray<bool>(a, n, output);
  383. }
  384. void WireFormatLite::WriteInt32(int field_number, int32 value,
  385. io::CodedOutputStream* output) {
  386. WriteTag(field_number, WIRETYPE_VARINT, output);
  387. WriteInt32NoTag(value, output);
  388. }
  389. void WireFormatLite::WriteInt64(int field_number, int64 value,
  390. io::CodedOutputStream* output) {
  391. WriteTag(field_number, WIRETYPE_VARINT, output);
  392. WriteInt64NoTag(value, output);
  393. }
  394. void WireFormatLite::WriteUInt32(int field_number, uint32 value,
  395. io::CodedOutputStream* output) {
  396. WriteTag(field_number, WIRETYPE_VARINT, output);
  397. WriteUInt32NoTag(value, output);
  398. }
  399. void WireFormatLite::WriteUInt64(int field_number, uint64 value,
  400. io::CodedOutputStream* output) {
  401. WriteTag(field_number, WIRETYPE_VARINT, output);
  402. WriteUInt64NoTag(value, output);
  403. }
  404. void WireFormatLite::WriteSInt32(int field_number, int32 value,
  405. io::CodedOutputStream* output) {
  406. WriteTag(field_number, WIRETYPE_VARINT, output);
  407. WriteSInt32NoTag(value, output);
  408. }
  409. void WireFormatLite::WriteSInt64(int field_number, int64 value,
  410. io::CodedOutputStream* output) {
  411. WriteTag(field_number, WIRETYPE_VARINT, output);
  412. WriteSInt64NoTag(value, output);
  413. }
  414. void WireFormatLite::WriteFixed32(int field_number, uint32 value,
  415. io::CodedOutputStream* output) {
  416. WriteTag(field_number, WIRETYPE_FIXED32, output);
  417. WriteFixed32NoTag(value, output);
  418. }
  419. void WireFormatLite::WriteFixed64(int field_number, uint64 value,
  420. io::CodedOutputStream* output) {
  421. WriteTag(field_number, WIRETYPE_FIXED64, output);
  422. WriteFixed64NoTag(value, output);
  423. }
  424. void WireFormatLite::WriteSFixed32(int field_number, int32 value,
  425. io::CodedOutputStream* output) {
  426. WriteTag(field_number, WIRETYPE_FIXED32, output);
  427. WriteSFixed32NoTag(value, output);
  428. }
  429. void WireFormatLite::WriteSFixed64(int field_number, int64 value,
  430. io::CodedOutputStream* output) {
  431. WriteTag(field_number, WIRETYPE_FIXED64, output);
  432. WriteSFixed64NoTag(value, output);
  433. }
  434. void WireFormatLite::WriteFloat(int field_number, float value,
  435. io::CodedOutputStream* output) {
  436. WriteTag(field_number, WIRETYPE_FIXED32, output);
  437. WriteFloatNoTag(value, output);
  438. }
  439. void WireFormatLite::WriteDouble(int field_number, double value,
  440. io::CodedOutputStream* output) {
  441. WriteTag(field_number, WIRETYPE_FIXED64, output);
  442. WriteDoubleNoTag(value, output);
  443. }
  444. void WireFormatLite::WriteBool(int field_number, bool value,
  445. io::CodedOutputStream* output) {
  446. WriteTag(field_number, WIRETYPE_VARINT, output);
  447. WriteBoolNoTag(value, output);
  448. }
  449. void WireFormatLite::WriteEnum(int field_number, int value,
  450. io::CodedOutputStream* output) {
  451. WriteTag(field_number, WIRETYPE_VARINT, output);
  452. WriteEnumNoTag(value, output);
  453. }
  454. void WireFormatLite::WriteString(int field_number, const string& value,
  455. io::CodedOutputStream* output) {
  456. // String is for UTF-8 text only
  457. WriteTag(field_number, WIRETYPE_LENGTH_DELIMITED, output);
  458. GOOGLE_CHECK_LE(value.size(), kint32max);
  459. output->WriteVarint32(value.size());
  460. output->WriteString(value);
  461. }
  462. void WireFormatLite::WriteStringMaybeAliased(
  463. int field_number, const string& value,
  464. io::CodedOutputStream* output) {
  465. // String is for UTF-8 text only
  466. WriteTag(field_number, WIRETYPE_LENGTH_DELIMITED, output);
  467. GOOGLE_CHECK_LE(value.size(), kint32max);
  468. output->WriteVarint32(value.size());
  469. output->WriteRawMaybeAliased(value.data(), value.size());
  470. }
  471. void WireFormatLite::WriteBytes(int field_number, const string& value,
  472. io::CodedOutputStream* output) {
  473. WriteTag(field_number, WIRETYPE_LENGTH_DELIMITED, output);
  474. GOOGLE_CHECK_LE(value.size(), kint32max);
  475. output->WriteVarint32(value.size());
  476. output->WriteString(value);
  477. }
  478. void WireFormatLite::WriteBytesMaybeAliased(
  479. int field_number, const string& value,
  480. io::CodedOutputStream* output) {
  481. WriteTag(field_number, WIRETYPE_LENGTH_DELIMITED, output);
  482. GOOGLE_CHECK_LE(value.size(), kint32max);
  483. output->WriteVarint32(value.size());
  484. output->WriteRawMaybeAliased(value.data(), value.size());
  485. }
  486. void WireFormatLite::WriteGroup(int field_number,
  487. const MessageLite& value,
  488. io::CodedOutputStream* output) {
  489. WriteTag(field_number, WIRETYPE_START_GROUP, output);
  490. value.SerializeWithCachedSizes(output);
  491. WriteTag(field_number, WIRETYPE_END_GROUP, output);
  492. }
  493. void WireFormatLite::WriteMessage(int field_number,
  494. const MessageLite& value,
  495. io::CodedOutputStream* output) {
  496. WriteTag(field_number, WIRETYPE_LENGTH_DELIMITED, output);
  497. const int size = value.GetCachedSize();
  498. output->WriteVarint32(size);
  499. value.SerializeWithCachedSizes(output);
  500. }
  501. void WireFormatLite::WriteGroupMaybeToArray(int field_number,
  502. const MessageLite& value,
  503. io::CodedOutputStream* output) {
  504. WriteTag(field_number, WIRETYPE_START_GROUP, output);
  505. const int size = value.GetCachedSize();
  506. uint8* target = output->GetDirectBufferForNBytesAndAdvance(size);
  507. if (target != NULL) {
  508. uint8* end = value.InternalSerializeWithCachedSizesToArray(
  509. output->IsSerializationDeterministic(), target);
  510. GOOGLE_DCHECK_EQ(end - target, size);
  511. } else {
  512. value.SerializeWithCachedSizes(output);
  513. }
  514. WriteTag(field_number, WIRETYPE_END_GROUP, output);
  515. }
  516. void WireFormatLite::WriteMessageMaybeToArray(int field_number,
  517. const MessageLite& value,
  518. io::CodedOutputStream* output) {
  519. WriteTag(field_number, WIRETYPE_LENGTH_DELIMITED, output);
  520. const int size = value.GetCachedSize();
  521. output->WriteVarint32(size);
  522. uint8* target = output->GetDirectBufferForNBytesAndAdvance(size);
  523. if (target != NULL) {
  524. uint8* end = value.InternalSerializeWithCachedSizesToArray(
  525. output->IsSerializationDeterministic(), target);
  526. GOOGLE_DCHECK_EQ(end - target, size);
  527. } else {
  528. value.SerializeWithCachedSizes(output);
  529. }
  530. }
  531. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static bool ReadBytesToString(
  532. io::CodedInputStream* input, string* value);
  533. inline static bool ReadBytesToString(io::CodedInputStream* input,
  534. string* value) {
  535. uint32 length;
  536. return input->ReadVarint32(&length) &&
  537. input->InternalReadStringInline(value, length);
  538. }
  539. bool WireFormatLite::ReadBytes(io::CodedInputStream* input, string* value) {
  540. return ReadBytesToString(input, value);
  541. }
  542. bool WireFormatLite::ReadBytes(io::CodedInputStream* input, string** p) {
  543. if (*p == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
  544. *p = new ::std::string();
  545. }
  546. return ReadBytesToString(input, *p);
  547. }
  548. bool WireFormatLite::VerifyUtf8String(const char* data,
  549. int size,
  550. Operation op,
  551. const char* field_name) {
  552. if (!IsStructurallyValidUTF8(data, size)) {
  553. const char* operation_str = NULL;
  554. switch (op) {
  555. case PARSE:
  556. operation_str = "parsing";
  557. break;
  558. case SERIALIZE:
  559. operation_str = "serializing";
  560. break;
  561. // no default case: have the compiler warn if a case is not covered.
  562. }
  563. string quoted_field_name = "";
  564. if (field_name != NULL) {
  565. quoted_field_name = StringPrintf(" '%s'", field_name);
  566. }
  567. // no space below to avoid double space when the field name is missing.
  568. GOOGLE_LOG(ERROR) << "String field" << quoted_field_name << " contains invalid "
  569. << "UTF-8 data when " << operation_str << " a protocol "
  570. << "buffer. Use the 'bytes' type if you intend to send raw "
  571. << "bytes. ";
  572. return false;
  573. }
  574. return true;
  575. }
  576. // this code is deliberately written such that clang makes it into really
  577. // efficient SSE code.
  578. template<bool ZigZag, bool SignExtended, typename T>
  579. static size_t VarintSize(const T* data, const int n) {
  580. #if __cplusplus >= 201103L
  581. static_assert(sizeof(T) == 4, "This routine only works for 32 bit integers");
  582. // is_unsigned<T> => !ZigZag
  583. static_assert((std::is_unsigned<T>::value ^ ZigZag) ||
  584. std::is_signed<T>::value,
  585. "Cannot ZigZag encode unsigned types");
  586. // is_unsigned<T> => !SignExtended
  587. static_assert((std::is_unsigned<T>::value ^ SignExtended) ||
  588. std::is_signed<T>::value,
  589. "Cannot SignExtended unsigned types");
  590. static_assert(!(SignExtended && ZigZag),
  591. "Cannot SignExtended and ZigZag on the same type");
  592. #endif
  593. uint32 sum = n;
  594. uint32 msb_sum = 0;
  595. for (int i = 0; i < n; i++) {
  596. uint32 x = data[i];
  597. if (ZigZag) {
  598. x = WireFormatLite::ZigZagEncode32(x);
  599. } else if (SignExtended) {
  600. msb_sum += x >> 31;
  601. }
  602. // clang is so smart that it produces optimal SSE sequence unrolling
  603. // the loop 8 ints at a time. With a sequence of 4
  604. // cmpres = cmpgt x, sizeclass ( -1 or 0)
  605. // sum = sum - cmpres
  606. if (x > 0x7F) sum++;
  607. if (x > 0x3FFF) sum++;
  608. if (x > 0x1FFFFF) sum++;
  609. if (x > 0xFFFFFFF) sum++;
  610. }
  611. if (SignExtended) sum += msb_sum * 5;
  612. return sum;
  613. }
  614. template<bool ZigZag, typename T>
  615. static size_t VarintSize64(const T* data, const int n) {
  616. #if __cplusplus >= 201103L
  617. static_assert(sizeof(T) == 8, "This routine only works for 64 bit integers");
  618. // is_unsigned<T> => !ZigZag
  619. static_assert(!ZigZag || !std::is_unsigned<T>::value,
  620. "Cannot ZigZag encode unsigned types");
  621. #endif
  622. uint64 sum = n;
  623. for (int i = 0; i < n; i++) {
  624. uint64 x = data[i];
  625. if (ZigZag) {
  626. x = WireFormatLite::ZigZagEncode64(x);
  627. }
  628. // First step is a binary search, we can't branch in sse so we use the
  629. // result of the compare to adjust sum and appropriately. This code is
  630. // written to make clang recognize the vectorization.
  631. uint64 tmp = x >= (static_cast<uint64>(1) << 35) ? -1 : 0;
  632. sum += 5 & tmp;
  633. x >>= 35 & tmp;
  634. if (x > 0x7F) sum++;
  635. if (x > 0x3FFF) sum++;
  636. if (x > 0x1FFFFF) sum++;
  637. if (x > 0xFFFFFFF) sum++;
  638. }
  639. return sum;
  640. }
  641. // GCC does not recognize the vectorization opportunity
  642. // and other platforms are untested, in those cases using the optimized
  643. // varint size routine for each element is faster.
  644. // Hence we enable it only for clang
  645. #if defined(__SSE__) && defined(__clang__)
  646. size_t WireFormatLite::Int32Size(const RepeatedField<int32>& value) {
  647. return VarintSize<false, true>(value.data(), value.size());
  648. }
  649. size_t WireFormatLite::UInt32Size(const RepeatedField<uint32>& value) {
  650. return VarintSize<false, false>(value.data(), value.size());
  651. }
  652. size_t WireFormatLite::SInt32Size(const RepeatedField<int32>& value) {
  653. return VarintSize<true, false>(value.data(), value.size());
  654. }
  655. size_t WireFormatLite::EnumSize(const RepeatedField<int>& value) {
  656. // On ILP64, sizeof(int) == 8, which would require a different template.
  657. return VarintSize<false, true>(value.data(), value.size());
  658. }
  659. #else // !(defined(__SSE4_1__) && defined(__clang__))
  660. size_t WireFormatLite::Int32Size(const RepeatedField<int32>& value) {
  661. size_t out = 0;
  662. const int n = value.size();
  663. for (int i = 0; i < n; i++) {
  664. out += Int32Size(value.Get(i));
  665. }
  666. return out;
  667. }
  668. size_t WireFormatLite::UInt32Size(const RepeatedField<uint32>& value) {
  669. size_t out = 0;
  670. const int n = value.size();
  671. for (int i = 0; i < n; i++) {
  672. out += UInt32Size(value.Get(i));
  673. }
  674. return out;
  675. }
  676. size_t WireFormatLite::SInt32Size(const RepeatedField<int32>& value) {
  677. size_t out = 0;
  678. const int n = value.size();
  679. for (int i = 0; i < n; i++) {
  680. out += SInt32Size(value.Get(i));
  681. }
  682. return out;
  683. }
  684. size_t WireFormatLite::EnumSize(const RepeatedField<int>& value) {
  685. size_t out = 0;
  686. const int n = value.size();
  687. for (int i = 0; i < n; i++) {
  688. out += EnumSize(value.Get(i));
  689. }
  690. return out;
  691. }
  692. #endif
  693. // Micro benchmarks show that the SSE improved loop only starts beating
  694. // the normal loop on Haswell platforms and then only for >32 ints. We
  695. // disable this for now. Some specialized users might find it worthwhile to
  696. // enable this.
  697. #define USE_SSE_FOR_64_BIT_INTEGER_ARRAYS 0
  698. #if USE_SSE_FOR_64_BIT_INTEGER_ARRAYS
  699. size_t WireFormatLite::Int64Size (const RepeatedField< int64>& value) {
  700. return VarintSize64<false>(value.data(), value.size());
  701. }
  702. size_t WireFormatLite::UInt64Size(const RepeatedField<uint64>& value) {
  703. return VarintSize64<false>(value.data(), value.size());
  704. }
  705. size_t WireFormatLite::SInt64Size(const RepeatedField< int64>& value) {
  706. return VarintSize64<true>(value.data(), value.size());
  707. }
  708. #else
  709. size_t WireFormatLite::Int64Size (const RepeatedField< int64>& value) {
  710. size_t out = 0;
  711. const int n = value.size();
  712. for (int i = 0; i < n; i++) {
  713. out += Int64Size(value.Get(i));
  714. }
  715. return out;
  716. }
  717. size_t WireFormatLite::UInt64Size(const RepeatedField<uint64>& value) {
  718. size_t out = 0;
  719. const int n = value.size();
  720. for (int i = 0; i < n; i++) {
  721. out += UInt64Size(value.Get(i));
  722. }
  723. return out;
  724. }
  725. size_t WireFormatLite::SInt64Size(const RepeatedField< int64>& value) {
  726. size_t out = 0;
  727. const int n = value.size();
  728. for (int i = 0; i < n; i++) {
  729. out += SInt64Size(value.Get(i));
  730. }
  731. return out;
  732. }
  733. #endif
  734. } // namespace internal
  735. } // namespace protobuf
  736. } // namespace google