wire_format.cc 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  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 <stack>
  34. #include <string>
  35. #include <vector>
  36. #include <google/protobuf/wire_format.h>
  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/descriptor.pb.h>
  41. #include <google/protobuf/io/coded_stream.h>
  42. #include <google/protobuf/io/zero_copy_stream.h>
  43. #include <google/protobuf/io/zero_copy_stream_impl.h>
  44. #include <google/protobuf/descriptor.h>
  45. #include <google/protobuf/dynamic_message.h>
  46. #include <google/protobuf/map_field.h>
  47. #include <google/protobuf/unknown_field_set.h>
  48. #include <google/protobuf/wire_format_lite_inl.h>
  49. namespace google {
  50. const size_t kMapEntryTagByteSize = 2;
  51. namespace protobuf {
  52. namespace internal {
  53. // Forward declare static functions
  54. static size_t MapKeyDataOnlyByteSize(const FieldDescriptor* field,
  55. const MapKey& value);
  56. static size_t MapValueRefDataOnlyByteSize(const FieldDescriptor* field,
  57. const MapValueRef& value);
  58. // ===================================================================
  59. bool UnknownFieldSetFieldSkipper::SkipField(
  60. io::CodedInputStream* input, uint32 tag) {
  61. return WireFormat::SkipField(input, tag, unknown_fields_);
  62. }
  63. bool UnknownFieldSetFieldSkipper::SkipMessage(io::CodedInputStream* input) {
  64. return WireFormat::SkipMessage(input, unknown_fields_);
  65. }
  66. void UnknownFieldSetFieldSkipper::SkipUnknownEnum(
  67. int field_number, int value) {
  68. unknown_fields_->AddVarint(field_number, value);
  69. }
  70. bool WireFormat::SkipField(io::CodedInputStream* input, uint32 tag,
  71. UnknownFieldSet* unknown_fields) {
  72. int number = WireFormatLite::GetTagFieldNumber(tag);
  73. // Field number 0 is illegal.
  74. if (number == 0) return false;
  75. switch (WireFormatLite::GetTagWireType(tag)) {
  76. case WireFormatLite::WIRETYPE_VARINT: {
  77. uint64 value;
  78. if (!input->ReadVarint64(&value)) return false;
  79. if (unknown_fields != NULL) unknown_fields->AddVarint(number, value);
  80. return true;
  81. }
  82. case WireFormatLite::WIRETYPE_FIXED64: {
  83. uint64 value;
  84. if (!input->ReadLittleEndian64(&value)) return false;
  85. if (unknown_fields != NULL) unknown_fields->AddFixed64(number, value);
  86. return true;
  87. }
  88. case WireFormatLite::WIRETYPE_LENGTH_DELIMITED: {
  89. uint32 length;
  90. if (!input->ReadVarint32(&length)) return false;
  91. if (unknown_fields == NULL) {
  92. if (!input->Skip(length)) return false;
  93. } else {
  94. if (!input->ReadString(unknown_fields->AddLengthDelimited(number),
  95. length)) {
  96. return false;
  97. }
  98. }
  99. return true;
  100. }
  101. case WireFormatLite::WIRETYPE_START_GROUP: {
  102. if (!input->IncrementRecursionDepth()) return false;
  103. if (!SkipMessage(input, (unknown_fields == NULL) ?
  104. NULL : unknown_fields->AddGroup(number))) {
  105. return false;
  106. }
  107. input->DecrementRecursionDepth();
  108. // Check that the ending tag matched the starting tag.
  109. if (!input->LastTagWas(WireFormatLite::MakeTag(
  110. WireFormatLite::GetTagFieldNumber(tag),
  111. WireFormatLite::WIRETYPE_END_GROUP))) {
  112. return false;
  113. }
  114. return true;
  115. }
  116. case WireFormatLite::WIRETYPE_END_GROUP: {
  117. return false;
  118. }
  119. case WireFormatLite::WIRETYPE_FIXED32: {
  120. uint32 value;
  121. if (!input->ReadLittleEndian32(&value)) return false;
  122. if (unknown_fields != NULL) unknown_fields->AddFixed32(number, value);
  123. return true;
  124. }
  125. default: {
  126. return false;
  127. }
  128. }
  129. }
  130. bool WireFormat::SkipMessage(io::CodedInputStream* input,
  131. UnknownFieldSet* unknown_fields) {
  132. while (true) {
  133. uint32 tag = input->ReadTag();
  134. if (tag == 0) {
  135. // End of input. This is a valid place to end, so return true.
  136. return true;
  137. }
  138. WireFormatLite::WireType wire_type = WireFormatLite::GetTagWireType(tag);
  139. if (wire_type == WireFormatLite::WIRETYPE_END_GROUP) {
  140. // Must be the end of the message.
  141. return true;
  142. }
  143. if (!SkipField(input, tag, unknown_fields)) return false;
  144. }
  145. }
  146. bool WireFormat::ReadPackedEnumPreserveUnknowns(io::CodedInputStream* input,
  147. uint32 field_number,
  148. bool (*is_valid)(int),
  149. UnknownFieldSet* unknown_fields,
  150. RepeatedField<int>* values) {
  151. uint32 length;
  152. if (!input->ReadVarint32(&length)) return false;
  153. io::CodedInputStream::Limit limit = input->PushLimit(length);
  154. while (input->BytesUntilLimit() > 0) {
  155. int value;
  156. if (!google::protobuf::internal::WireFormatLite::ReadPrimitive<
  157. int, WireFormatLite::TYPE_ENUM>(input, &value)) {
  158. return false;
  159. }
  160. if (is_valid == NULL || is_valid(value)) {
  161. values->Add(value);
  162. } else {
  163. unknown_fields->AddVarint(field_number, value);
  164. }
  165. }
  166. input->PopLimit(limit);
  167. return true;
  168. }
  169. void WireFormat::SerializeUnknownFields(const UnknownFieldSet& unknown_fields,
  170. io::CodedOutputStream* output) {
  171. for (int i = 0; i < unknown_fields.field_count(); i++) {
  172. const UnknownField& field = unknown_fields.field(i);
  173. switch (field.type()) {
  174. case UnknownField::TYPE_VARINT:
  175. output->WriteVarint32(WireFormatLite::MakeTag(field.number(),
  176. WireFormatLite::WIRETYPE_VARINT));
  177. output->WriteVarint64(field.varint());
  178. break;
  179. case UnknownField::TYPE_FIXED32:
  180. output->WriteVarint32(WireFormatLite::MakeTag(field.number(),
  181. WireFormatLite::WIRETYPE_FIXED32));
  182. output->WriteLittleEndian32(field.fixed32());
  183. break;
  184. case UnknownField::TYPE_FIXED64:
  185. output->WriteVarint32(WireFormatLite::MakeTag(field.number(),
  186. WireFormatLite::WIRETYPE_FIXED64));
  187. output->WriteLittleEndian64(field.fixed64());
  188. break;
  189. case UnknownField::TYPE_LENGTH_DELIMITED:
  190. output->WriteVarint32(WireFormatLite::MakeTag(field.number(),
  191. WireFormatLite::WIRETYPE_LENGTH_DELIMITED));
  192. output->WriteVarint32(field.length_delimited().size());
  193. output->WriteRawMaybeAliased(field.length_delimited().data(),
  194. field.length_delimited().size());
  195. break;
  196. case UnknownField::TYPE_GROUP:
  197. output->WriteVarint32(WireFormatLite::MakeTag(field.number(),
  198. WireFormatLite::WIRETYPE_START_GROUP));
  199. SerializeUnknownFields(field.group(), output);
  200. output->WriteVarint32(WireFormatLite::MakeTag(field.number(),
  201. WireFormatLite::WIRETYPE_END_GROUP));
  202. break;
  203. }
  204. }
  205. }
  206. uint8* WireFormat::SerializeUnknownFieldsToArray(
  207. const UnknownFieldSet& unknown_fields,
  208. uint8* target) {
  209. for (int i = 0; i < unknown_fields.field_count(); i++) {
  210. const UnknownField& field = unknown_fields.field(i);
  211. switch (field.type()) {
  212. case UnknownField::TYPE_VARINT:
  213. target = WireFormatLite::WriteInt64ToArray(
  214. field.number(), field.varint(), target);
  215. break;
  216. case UnknownField::TYPE_FIXED32:
  217. target = WireFormatLite::WriteFixed32ToArray(
  218. field.number(), field.fixed32(), target);
  219. break;
  220. case UnknownField::TYPE_FIXED64:
  221. target = WireFormatLite::WriteFixed64ToArray(
  222. field.number(), field.fixed64(), target);
  223. break;
  224. case UnknownField::TYPE_LENGTH_DELIMITED:
  225. target = WireFormatLite::WriteBytesToArray(
  226. field.number(), field.length_delimited(), target);
  227. break;
  228. case UnknownField::TYPE_GROUP:
  229. target = WireFormatLite::WriteTagToArray(
  230. field.number(), WireFormatLite::WIRETYPE_START_GROUP, target);
  231. target = SerializeUnknownFieldsToArray(field.group(), target);
  232. target = WireFormatLite::WriteTagToArray(
  233. field.number(), WireFormatLite::WIRETYPE_END_GROUP, target);
  234. break;
  235. }
  236. }
  237. return target;
  238. }
  239. void WireFormat::SerializeUnknownMessageSetItems(
  240. const UnknownFieldSet& unknown_fields,
  241. io::CodedOutputStream* output) {
  242. for (int i = 0; i < unknown_fields.field_count(); i++) {
  243. const UnknownField& field = unknown_fields.field(i);
  244. // The only unknown fields that are allowed to exist in a MessageSet are
  245. // messages, which are length-delimited.
  246. if (field.type() == UnknownField::TYPE_LENGTH_DELIMITED) {
  247. // Start group.
  248. output->WriteVarint32(WireFormatLite::kMessageSetItemStartTag);
  249. // Write type ID.
  250. output->WriteVarint32(WireFormatLite::kMessageSetTypeIdTag);
  251. output->WriteVarint32(field.number());
  252. // Write message.
  253. output->WriteVarint32(WireFormatLite::kMessageSetMessageTag);
  254. field.SerializeLengthDelimitedNoTag(output);
  255. // End group.
  256. output->WriteVarint32(WireFormatLite::kMessageSetItemEndTag);
  257. }
  258. }
  259. }
  260. uint8* WireFormat::SerializeUnknownMessageSetItemsToArray(
  261. const UnknownFieldSet& unknown_fields,
  262. uint8* target) {
  263. for (int i = 0; i < unknown_fields.field_count(); i++) {
  264. const UnknownField& field = unknown_fields.field(i);
  265. // The only unknown fields that are allowed to exist in a MessageSet are
  266. // messages, which are length-delimited.
  267. if (field.type() == UnknownField::TYPE_LENGTH_DELIMITED) {
  268. // Start group.
  269. target = io::CodedOutputStream::WriteTagToArray(
  270. WireFormatLite::kMessageSetItemStartTag, target);
  271. // Write type ID.
  272. target = io::CodedOutputStream::WriteTagToArray(
  273. WireFormatLite::kMessageSetTypeIdTag, target);
  274. target = io::CodedOutputStream::WriteVarint32ToArray(
  275. field.number(), target);
  276. // Write message.
  277. target = io::CodedOutputStream::WriteTagToArray(
  278. WireFormatLite::kMessageSetMessageTag, target);
  279. target = field.SerializeLengthDelimitedNoTagToArray(target);
  280. // End group.
  281. target = io::CodedOutputStream::WriteTagToArray(
  282. WireFormatLite::kMessageSetItemEndTag, target);
  283. }
  284. }
  285. return target;
  286. }
  287. size_t WireFormat::ComputeUnknownFieldsSize(
  288. const UnknownFieldSet& unknown_fields) {
  289. size_t size = 0;
  290. for (int i = 0; i < unknown_fields.field_count(); i++) {
  291. const UnknownField& field = unknown_fields.field(i);
  292. switch (field.type()) {
  293. case UnknownField::TYPE_VARINT:
  294. size += io::CodedOutputStream::VarintSize32(
  295. WireFormatLite::MakeTag(field.number(),
  296. WireFormatLite::WIRETYPE_VARINT));
  297. size += io::CodedOutputStream::VarintSize64(field.varint());
  298. break;
  299. case UnknownField::TYPE_FIXED32:
  300. size += io::CodedOutputStream::VarintSize32(
  301. WireFormatLite::MakeTag(field.number(),
  302. WireFormatLite::WIRETYPE_FIXED32));
  303. size += sizeof(int32);
  304. break;
  305. case UnknownField::TYPE_FIXED64:
  306. size += io::CodedOutputStream::VarintSize32(
  307. WireFormatLite::MakeTag(field.number(),
  308. WireFormatLite::WIRETYPE_FIXED64));
  309. size += sizeof(int64);
  310. break;
  311. case UnknownField::TYPE_LENGTH_DELIMITED:
  312. size += io::CodedOutputStream::VarintSize32(
  313. WireFormatLite::MakeTag(field.number(),
  314. WireFormatLite::WIRETYPE_LENGTH_DELIMITED));
  315. size += io::CodedOutputStream::VarintSize32(
  316. field.length_delimited().size());
  317. size += field.length_delimited().size();
  318. break;
  319. case UnknownField::TYPE_GROUP:
  320. size += io::CodedOutputStream::VarintSize32(
  321. WireFormatLite::MakeTag(field.number(),
  322. WireFormatLite::WIRETYPE_START_GROUP));
  323. size += ComputeUnknownFieldsSize(field.group());
  324. size += io::CodedOutputStream::VarintSize32(
  325. WireFormatLite::MakeTag(field.number(),
  326. WireFormatLite::WIRETYPE_END_GROUP));
  327. break;
  328. }
  329. }
  330. return size;
  331. }
  332. size_t WireFormat::ComputeUnknownMessageSetItemsSize(
  333. const UnknownFieldSet& unknown_fields) {
  334. size_t size = 0;
  335. for (int i = 0; i < unknown_fields.field_count(); i++) {
  336. const UnknownField& field = unknown_fields.field(i);
  337. // The only unknown fields that are allowed to exist in a MessageSet are
  338. // messages, which are length-delimited.
  339. if (field.type() == UnknownField::TYPE_LENGTH_DELIMITED) {
  340. size += WireFormatLite::kMessageSetItemTagsSize;
  341. size += io::CodedOutputStream::VarintSize32(field.number());
  342. int field_size = field.GetLengthDelimitedSize();
  343. size += io::CodedOutputStream::VarintSize32(field_size);
  344. size += field_size;
  345. }
  346. }
  347. return size;
  348. }
  349. // ===================================================================
  350. bool WireFormat::ParseAndMergePartial(io::CodedInputStream* input,
  351. Message* message) {
  352. const Descriptor* descriptor = message->GetDescriptor();
  353. const Reflection* message_reflection = message->GetReflection();
  354. while(true) {
  355. uint32 tag = input->ReadTag();
  356. if (tag == 0) {
  357. // End of input. This is a valid place to end, so return true.
  358. return true;
  359. }
  360. if (WireFormatLite::GetTagWireType(tag) ==
  361. WireFormatLite::WIRETYPE_END_GROUP) {
  362. // Must be the end of the message.
  363. return true;
  364. }
  365. const FieldDescriptor* field = NULL;
  366. if (descriptor != NULL) {
  367. int field_number = WireFormatLite::GetTagFieldNumber(tag);
  368. field = descriptor->FindFieldByNumber(field_number);
  369. // If that failed, check if the field is an extension.
  370. if (field == NULL && descriptor->IsExtensionNumber(field_number)) {
  371. if (input->GetExtensionPool() == NULL) {
  372. field = message_reflection->FindKnownExtensionByNumber(field_number);
  373. } else {
  374. field = input->GetExtensionPool()
  375. ->FindExtensionByNumber(descriptor, field_number);
  376. }
  377. }
  378. // If that failed, but we're a MessageSet, and this is the tag for a
  379. // MessageSet item, then parse that.
  380. if (field == NULL &&
  381. descriptor->options().message_set_wire_format() &&
  382. tag == WireFormatLite::kMessageSetItemStartTag) {
  383. if (!ParseAndMergeMessageSetItem(input, message)) {
  384. return false;
  385. }
  386. continue; // Skip ParseAndMergeField(); already taken care of.
  387. }
  388. }
  389. if (!ParseAndMergeField(tag, field, message, input)) {
  390. return false;
  391. }
  392. }
  393. }
  394. bool WireFormat::SkipMessageSetField(io::CodedInputStream* input,
  395. uint32 field_number,
  396. UnknownFieldSet* unknown_fields) {
  397. uint32 length;
  398. if (!input->ReadVarint32(&length)) return false;
  399. return input->ReadString(
  400. unknown_fields->AddLengthDelimited(field_number), length);
  401. }
  402. bool WireFormat::ParseAndMergeMessageSetField(uint32 field_number,
  403. const FieldDescriptor* field,
  404. Message* message,
  405. io::CodedInputStream* input) {
  406. const Reflection* message_reflection = message->GetReflection();
  407. if (field == NULL) {
  408. // We store unknown MessageSet extensions as groups.
  409. return SkipMessageSetField(
  410. input, field_number, message_reflection->MutableUnknownFields(message));
  411. } else if (field->is_repeated() ||
  412. field->type() != FieldDescriptor::TYPE_MESSAGE) {
  413. // This shouldn't happen as we only allow optional message extensions to
  414. // MessageSet.
  415. GOOGLE_LOG(ERROR) << "Extensions of MessageSets must be optional messages.";
  416. return false;
  417. } else {
  418. Message* sub_message = message_reflection->MutableMessage(
  419. message, field, input->GetExtensionFactory());
  420. return WireFormatLite::ReadMessage(input, sub_message);
  421. }
  422. }
  423. static bool StrictUtf8Check(const FieldDescriptor* field) {
  424. return field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3;
  425. }
  426. bool WireFormat::ParseAndMergeField(
  427. uint32 tag,
  428. const FieldDescriptor* field, // May be NULL for unknown
  429. Message* message,
  430. io::CodedInputStream* input) {
  431. const Reflection* message_reflection = message->GetReflection();
  432. enum { UNKNOWN, NORMAL_FORMAT, PACKED_FORMAT } value_format;
  433. if (field == NULL) {
  434. value_format = UNKNOWN;
  435. } else if (WireFormatLite::GetTagWireType(tag) ==
  436. WireTypeForFieldType(field->type())) {
  437. value_format = NORMAL_FORMAT;
  438. } else if (field->is_packable() &&
  439. WireFormatLite::GetTagWireType(tag) ==
  440. WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
  441. value_format = PACKED_FORMAT;
  442. } else {
  443. // We don't recognize this field. Either the field number is unknown
  444. // or the wire type doesn't match. Put it in our unknown field set.
  445. value_format = UNKNOWN;
  446. }
  447. if (value_format == UNKNOWN) {
  448. return SkipField(input, tag,
  449. message_reflection->MutableUnknownFields(message));
  450. } else if (value_format == PACKED_FORMAT) {
  451. uint32 length;
  452. if (!input->ReadVarint32(&length)) return false;
  453. io::CodedInputStream::Limit limit = input->PushLimit(length);
  454. switch (field->type()) {
  455. #define HANDLE_PACKED_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD) \
  456. case FieldDescriptor::TYPE_##TYPE: { \
  457. while (input->BytesUntilLimit() > 0) { \
  458. CPPTYPE value; \
  459. if (!WireFormatLite::ReadPrimitive< \
  460. CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)) \
  461. return false; \
  462. message_reflection->Add##CPPTYPE_METHOD(message, field, value); \
  463. } \
  464. break; \
  465. }
  466. HANDLE_PACKED_TYPE( INT32, int32, Int32)
  467. HANDLE_PACKED_TYPE( INT64, int64, Int64)
  468. HANDLE_PACKED_TYPE(SINT32, int32, Int32)
  469. HANDLE_PACKED_TYPE(SINT64, int64, Int64)
  470. HANDLE_PACKED_TYPE(UINT32, uint32, UInt32)
  471. HANDLE_PACKED_TYPE(UINT64, uint64, UInt64)
  472. HANDLE_PACKED_TYPE( FIXED32, uint32, UInt32)
  473. HANDLE_PACKED_TYPE( FIXED64, uint64, UInt64)
  474. HANDLE_PACKED_TYPE(SFIXED32, int32, Int32)
  475. HANDLE_PACKED_TYPE(SFIXED64, int64, Int64)
  476. HANDLE_PACKED_TYPE(FLOAT , float , Float )
  477. HANDLE_PACKED_TYPE(DOUBLE, double, Double)
  478. HANDLE_PACKED_TYPE(BOOL, bool, Bool)
  479. #undef HANDLE_PACKED_TYPE
  480. case FieldDescriptor::TYPE_ENUM: {
  481. while (input->BytesUntilLimit() > 0) {
  482. int value;
  483. if (!WireFormatLite::ReadPrimitive<int, WireFormatLite::TYPE_ENUM>(
  484. input, &value)) return false;
  485. if (message->GetDescriptor()->file()->syntax() ==
  486. FileDescriptor::SYNTAX_PROTO3) {
  487. message_reflection->AddEnumValue(message, field, value);
  488. } else {
  489. const EnumValueDescriptor* enum_value =
  490. field->enum_type()->FindValueByNumber(value);
  491. if (enum_value != NULL) {
  492. message_reflection->AddEnum(message, field, enum_value);
  493. } else {
  494. // The enum value is not one of the known values. Add it to the
  495. // UnknownFieldSet.
  496. int64 sign_extended_value = static_cast<int64>(value);
  497. message_reflection->MutableUnknownFields(message)
  498. ->AddVarint(
  499. WireFormatLite::GetTagFieldNumber(tag),
  500. sign_extended_value);
  501. }
  502. }
  503. }
  504. break;
  505. }
  506. case FieldDescriptor::TYPE_STRING:
  507. case FieldDescriptor::TYPE_GROUP:
  508. case FieldDescriptor::TYPE_MESSAGE:
  509. case FieldDescriptor::TYPE_BYTES:
  510. // Can't have packed fields of these types: these should be caught by
  511. // the protocol compiler.
  512. return false;
  513. break;
  514. }
  515. input->PopLimit(limit);
  516. } else {
  517. // Non-packed value (value_format == NORMAL_FORMAT)
  518. switch (field->type()) {
  519. #define HANDLE_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD) \
  520. case FieldDescriptor::TYPE_##TYPE: { \
  521. CPPTYPE value; \
  522. if (!WireFormatLite::ReadPrimitive< \
  523. CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)) \
  524. return false; \
  525. if (field->is_repeated()) { \
  526. message_reflection->Add##CPPTYPE_METHOD(message, field, value); \
  527. } else { \
  528. message_reflection->Set##CPPTYPE_METHOD(message, field, value); \
  529. } \
  530. break; \
  531. }
  532. HANDLE_TYPE( INT32, int32, Int32)
  533. HANDLE_TYPE( INT64, int64, Int64)
  534. HANDLE_TYPE(SINT32, int32, Int32)
  535. HANDLE_TYPE(SINT64, int64, Int64)
  536. HANDLE_TYPE(UINT32, uint32, UInt32)
  537. HANDLE_TYPE(UINT64, uint64, UInt64)
  538. HANDLE_TYPE( FIXED32, uint32, UInt32)
  539. HANDLE_TYPE( FIXED64, uint64, UInt64)
  540. HANDLE_TYPE(SFIXED32, int32, Int32)
  541. HANDLE_TYPE(SFIXED64, int64, Int64)
  542. HANDLE_TYPE(FLOAT , float , Float )
  543. HANDLE_TYPE(DOUBLE, double, Double)
  544. HANDLE_TYPE(BOOL, bool, Bool)
  545. #undef HANDLE_TYPE
  546. case FieldDescriptor::TYPE_ENUM: {
  547. int value;
  548. if (!WireFormatLite::ReadPrimitive<int, WireFormatLite::TYPE_ENUM>(
  549. input, &value)) return false;
  550. if (message->GetDescriptor()->file()->syntax() ==
  551. FileDescriptor::SYNTAX_PROTO3) {
  552. if (field->is_repeated()) {
  553. message_reflection->AddEnumValue(message, field, value);
  554. } else {
  555. message_reflection->SetEnumValue(message, field, value);
  556. }
  557. } else {
  558. const EnumValueDescriptor* enum_value =
  559. field->enum_type()->FindValueByNumber(value);
  560. if (enum_value != NULL) {
  561. if (field->is_repeated()) {
  562. message_reflection->AddEnum(message, field, enum_value);
  563. } else {
  564. message_reflection->SetEnum(message, field, enum_value);
  565. }
  566. } else {
  567. // The enum value is not one of the known values. Add it to the
  568. // UnknownFieldSet.
  569. int64 sign_extended_value = static_cast<int64>(value);
  570. message_reflection->MutableUnknownFields(message)
  571. ->AddVarint(
  572. WireFormatLite::GetTagFieldNumber(tag),
  573. sign_extended_value);
  574. }
  575. }
  576. break;
  577. }
  578. // Handle strings separately so that we can optimize the ctype=CORD case.
  579. case FieldDescriptor::TYPE_STRING: {
  580. bool strict_utf8_check = StrictUtf8Check(field);
  581. string value;
  582. if (!WireFormatLite::ReadString(input, &value)) return false;
  583. if (strict_utf8_check) {
  584. if (!WireFormatLite::VerifyUtf8String(
  585. value.data(), value.length(), WireFormatLite::PARSE,
  586. field->full_name().c_str())) {
  587. return false;
  588. }
  589. } else {
  590. VerifyUTF8StringNamedField(value.data(), value.length(), PARSE,
  591. field->full_name().c_str());
  592. }
  593. if (field->is_repeated()) {
  594. message_reflection->AddString(message, field, value);
  595. } else {
  596. message_reflection->SetString(message, field, value);
  597. }
  598. break;
  599. }
  600. case FieldDescriptor::TYPE_BYTES: {
  601. string value;
  602. if (!WireFormatLite::ReadBytes(input, &value)) return false;
  603. if (field->is_repeated()) {
  604. message_reflection->AddString(message, field, value);
  605. } else {
  606. message_reflection->SetString(message, field, value);
  607. }
  608. break;
  609. }
  610. case FieldDescriptor::TYPE_GROUP: {
  611. Message* sub_message;
  612. if (field->is_repeated()) {
  613. sub_message = message_reflection->AddMessage(
  614. message, field, input->GetExtensionFactory());
  615. } else {
  616. sub_message = message_reflection->MutableMessage(
  617. message, field, input->GetExtensionFactory());
  618. }
  619. if (!WireFormatLite::ReadGroup(WireFormatLite::GetTagFieldNumber(tag),
  620. input, sub_message))
  621. return false;
  622. break;
  623. }
  624. case FieldDescriptor::TYPE_MESSAGE: {
  625. Message* sub_message;
  626. if (field->is_repeated()) {
  627. sub_message = message_reflection->AddMessage(
  628. message, field, input->GetExtensionFactory());
  629. } else {
  630. sub_message = message_reflection->MutableMessage(
  631. message, field, input->GetExtensionFactory());
  632. }
  633. if (!WireFormatLite::ReadMessage(input, sub_message)) return false;
  634. break;
  635. }
  636. }
  637. }
  638. return true;
  639. }
  640. bool WireFormat::ParseAndMergeMessageSetItem(
  641. io::CodedInputStream* input,
  642. Message* message) {
  643. const Reflection* message_reflection = message->GetReflection();
  644. // This method parses a group which should contain two fields:
  645. // required int32 type_id = 2;
  646. // required data message = 3;
  647. uint32 last_type_id = 0;
  648. // Once we see a type_id, we'll look up the FieldDescriptor for the
  649. // extension.
  650. const FieldDescriptor* field = NULL;
  651. // If we see message data before the type_id, we'll append it to this so
  652. // we can parse it later.
  653. string message_data;
  654. while (true) {
  655. uint32 tag = input->ReadTag();
  656. if (tag == 0) return false;
  657. switch (tag) {
  658. case WireFormatLite::kMessageSetTypeIdTag: {
  659. uint32 type_id;
  660. if (!input->ReadVarint32(&type_id)) return false;
  661. last_type_id = type_id;
  662. field = message_reflection->FindKnownExtensionByNumber(type_id);
  663. if (!message_data.empty()) {
  664. // We saw some message data before the type_id. Have to parse it
  665. // now.
  666. io::ArrayInputStream raw_input(message_data.data(),
  667. message_data.size());
  668. io::CodedInputStream sub_input(&raw_input);
  669. if (!ParseAndMergeMessageSetField(last_type_id, field, message,
  670. &sub_input)) {
  671. return false;
  672. }
  673. message_data.clear();
  674. }
  675. break;
  676. }
  677. case WireFormatLite::kMessageSetMessageTag: {
  678. if (last_type_id == 0) {
  679. // We haven't seen a type_id yet. Append this data to message_data.
  680. string temp;
  681. uint32 length;
  682. if (!input->ReadVarint32(&length)) return false;
  683. if (!input->ReadString(&temp, length)) return false;
  684. io::StringOutputStream output_stream(&message_data);
  685. io::CodedOutputStream coded_output(&output_stream);
  686. coded_output.WriteVarint32(length);
  687. coded_output.WriteString(temp);
  688. } else {
  689. // Already saw type_id, so we can parse this directly.
  690. if (!ParseAndMergeMessageSetField(last_type_id, field, message,
  691. input)) {
  692. return false;
  693. }
  694. }
  695. break;
  696. }
  697. case WireFormatLite::kMessageSetItemEndTag: {
  698. return true;
  699. }
  700. default: {
  701. if (!SkipField(input, tag, NULL)) return false;
  702. }
  703. }
  704. }
  705. }
  706. // ===================================================================
  707. void WireFormat::SerializeWithCachedSizes(
  708. const Message& message,
  709. int size, io::CodedOutputStream* output) {
  710. const Descriptor* descriptor = message.GetDescriptor();
  711. const Reflection* message_reflection = message.GetReflection();
  712. int expected_endpoint = output->ByteCount() + size;
  713. std::vector<const FieldDescriptor*> fields;
  714. // Fields of map entry should always be serialized.
  715. if (descriptor->options().map_entry()) {
  716. for (int i = 0; i < descriptor->field_count(); i++) {
  717. fields.push_back(descriptor->field(i));
  718. }
  719. } else {
  720. message_reflection->ListFields(message, &fields);
  721. }
  722. for (int i = 0; i < fields.size(); i++) {
  723. SerializeFieldWithCachedSizes(fields[i], message, output);
  724. }
  725. if (descriptor->options().message_set_wire_format()) {
  726. SerializeUnknownMessageSetItems(
  727. message_reflection->GetUnknownFields(message), output);
  728. } else {
  729. SerializeUnknownFields(
  730. message_reflection->GetUnknownFields(message), output);
  731. }
  732. GOOGLE_CHECK_EQ(output->ByteCount(), expected_endpoint)
  733. << ": Protocol message serialized to a size different from what was "
  734. "originally expected. Perhaps it was modified by another thread "
  735. "during serialization?";
  736. }
  737. static void SerializeMapKeyWithCachedSizes(const FieldDescriptor* field,
  738. const MapKey& value,
  739. io::CodedOutputStream* output) {
  740. switch (field->type()) {
  741. case FieldDescriptor::TYPE_DOUBLE:
  742. case FieldDescriptor::TYPE_FLOAT:
  743. case FieldDescriptor::TYPE_GROUP:
  744. case FieldDescriptor::TYPE_MESSAGE:
  745. case FieldDescriptor::TYPE_BYTES:
  746. case FieldDescriptor::TYPE_ENUM:
  747. GOOGLE_LOG(FATAL) << "Unsupported";
  748. break;
  749. #define CASE_TYPE(FieldType, CamelFieldType, CamelCppType) \
  750. case FieldDescriptor::TYPE_##FieldType: \
  751. WireFormatLite::Write##CamelFieldType(1, value.Get##CamelCppType##Value(), \
  752. output); \
  753. break;
  754. CASE_TYPE(INT64, Int64, Int64)
  755. CASE_TYPE(UINT64, UInt64, UInt64)
  756. CASE_TYPE(INT32, Int32, Int32)
  757. CASE_TYPE(FIXED64, Fixed64, UInt64)
  758. CASE_TYPE(FIXED32, Fixed32, UInt32)
  759. CASE_TYPE(BOOL, Bool, Bool)
  760. CASE_TYPE(UINT32, UInt32, UInt32)
  761. CASE_TYPE(SFIXED32, SFixed32, Int32)
  762. CASE_TYPE(SFIXED64, SFixed64, Int64)
  763. CASE_TYPE(SINT32, SInt32, Int32)
  764. CASE_TYPE(SINT64, SInt64, Int64)
  765. CASE_TYPE(STRING, String, String)
  766. #undef CASE_TYPE
  767. }
  768. }
  769. static void SerializeMapValueRefWithCachedSizes(const FieldDescriptor* field,
  770. const MapValueRef& value,
  771. io::CodedOutputStream* output) {
  772. switch (field->type()) {
  773. #define CASE_TYPE(FieldType, CamelFieldType, CamelCppType) \
  774. case FieldDescriptor::TYPE_##FieldType: \
  775. WireFormatLite::Write##CamelFieldType(2, value.Get##CamelCppType##Value(), \
  776. output); \
  777. break;
  778. CASE_TYPE(INT64, Int64, Int64)
  779. CASE_TYPE(UINT64, UInt64, UInt64)
  780. CASE_TYPE(INT32, Int32, Int32)
  781. CASE_TYPE(FIXED64, Fixed64, UInt64)
  782. CASE_TYPE(FIXED32, Fixed32, UInt32)
  783. CASE_TYPE(BOOL, Bool, Bool)
  784. CASE_TYPE(UINT32, UInt32, UInt32)
  785. CASE_TYPE(SFIXED32, SFixed32, Int32)
  786. CASE_TYPE(SFIXED64, SFixed64, Int64)
  787. CASE_TYPE(SINT32, SInt32, Int32)
  788. CASE_TYPE(SINT64, SInt64, Int64)
  789. CASE_TYPE(ENUM, Enum, Enum)
  790. CASE_TYPE(DOUBLE, Double, Double)
  791. CASE_TYPE(FLOAT, Float, Float)
  792. CASE_TYPE(STRING, String, String)
  793. CASE_TYPE(BYTES, Bytes, String)
  794. CASE_TYPE(MESSAGE, Message, Message)
  795. CASE_TYPE(GROUP, Group, Message)
  796. #undef CASE_TYPE
  797. }
  798. }
  799. class MapKeySorter {
  800. public:
  801. static std::vector<MapKey> SortKey(const Message& message,
  802. const Reflection* reflection,
  803. const FieldDescriptor* field) {
  804. std::vector<MapKey> sorted_key_list;
  805. for (MapIterator it =
  806. reflection->MapBegin(const_cast<Message*>(&message), field);
  807. it != reflection->MapEnd(const_cast<Message*>(&message), field);
  808. ++it) {
  809. sorted_key_list.push_back(it.GetKey());
  810. }
  811. MapKeyComparator comparator;
  812. std::sort(sorted_key_list.begin(), sorted_key_list.end(), comparator);
  813. return sorted_key_list;
  814. }
  815. private:
  816. class MapKeyComparator {
  817. public:
  818. bool operator()(const MapKey& a, const MapKey& b) const {
  819. GOOGLE_DCHECK(a.type() == b.type());
  820. switch (a.type()) {
  821. #define CASE_TYPE(CppType, CamelCppType) \
  822. case FieldDescriptor::CPPTYPE_##CppType: { \
  823. return a.Get##CamelCppType##Value() < b.Get##CamelCppType##Value(); \
  824. }
  825. CASE_TYPE(STRING, String)
  826. CASE_TYPE(INT64, Int64)
  827. CASE_TYPE(INT32, Int32)
  828. CASE_TYPE(UINT64, UInt64)
  829. CASE_TYPE(UINT32, UInt32)
  830. CASE_TYPE(BOOL, Bool)
  831. #undef CASE_TYPE
  832. default:
  833. GOOGLE_LOG(DFATAL) << "Invalid key for map field.";
  834. return true;
  835. }
  836. }
  837. };
  838. };
  839. static void SerializeMapEntry(const FieldDescriptor* field, const MapKey& key,
  840. const MapValueRef& value,
  841. io::CodedOutputStream* output) {
  842. const FieldDescriptor* key_field = field->message_type()->field(0);
  843. const FieldDescriptor* value_field = field->message_type()->field(1);
  844. WireFormatLite::WriteTag(field->number(),
  845. WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
  846. size_t size = kMapEntryTagByteSize;
  847. size += MapKeyDataOnlyByteSize(key_field, key);
  848. size += MapValueRefDataOnlyByteSize(value_field, value);
  849. output->WriteVarint32(size);
  850. SerializeMapKeyWithCachedSizes(key_field, key, output);
  851. SerializeMapValueRefWithCachedSizes(value_field, value, output);
  852. }
  853. void WireFormat::SerializeFieldWithCachedSizes(
  854. const FieldDescriptor* field,
  855. const Message& message,
  856. io::CodedOutputStream* output) {
  857. const Reflection* message_reflection = message.GetReflection();
  858. if (field->is_extension() &&
  859. field->containing_type()->options().message_set_wire_format() &&
  860. field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
  861. !field->is_repeated()) {
  862. SerializeMessageSetItemWithCachedSizes(field, message, output);
  863. return;
  864. }
  865. // For map fields, we can use either repeated field reflection or map
  866. // reflection. Our choice has some subtle effects. If we use repeated field
  867. // reflection here, then the repeated field representation becomes
  868. // authoritative for this field: any existing references that came from map
  869. // reflection remain valid for reading, but mutations to them are lost and
  870. // will be overwritten next time we call map reflection!
  871. //
  872. // So far this mainly affects Python, which keeps long-term references to map
  873. // values around, and always uses map reflection. See: b/35918691
  874. //
  875. // Here we choose to use map reflection API as long as the internal
  876. // map is valid. In this way, the serialization doesn't change map field's
  877. // internal state and existing references that came from map reflection remain
  878. // valid for both reading and writing.
  879. if (field->is_map()) {
  880. MapFieldBase* map_field =
  881. message_reflection->MapData(const_cast<Message*>(&message), field);
  882. if (map_field->IsMapValid()) {
  883. if (output->IsSerializationDeterministic()) {
  884. std::vector<MapKey> sorted_key_list =
  885. MapKeySorter::SortKey(message, message_reflection, field);
  886. for (std::vector<MapKey>::iterator it = sorted_key_list.begin();
  887. it != sorted_key_list.end(); ++it) {
  888. MapValueRef map_value;
  889. message_reflection->InsertOrLookupMapValue(
  890. const_cast<Message*>(&message), field, *it, &map_value);
  891. SerializeMapEntry(field, *it, map_value, output);
  892. }
  893. } else {
  894. for (MapIterator it = message_reflection->MapBegin(
  895. const_cast<Message*>(&message), field);
  896. it !=
  897. message_reflection->MapEnd(const_cast<Message*>(&message), field);
  898. ++it) {
  899. SerializeMapEntry(field, it.GetKey(), it.GetValueRef(), output);
  900. }
  901. }
  902. return;
  903. }
  904. }
  905. int count = 0;
  906. if (field->is_repeated()) {
  907. count = message_reflection->FieldSize(message, field);
  908. } else if (field->containing_type()->options().map_entry()) {
  909. // Map entry fields always need to be serialized.
  910. count = 1;
  911. } else if (message_reflection->HasField(message, field)) {
  912. count = 1;
  913. }
  914. // map_entries is for maps that'll be deterministically serialized.
  915. std::vector<const Message*> map_entries;
  916. if (count > 1 && field->is_map() && output->IsSerializationDeterministic()) {
  917. map_entries =
  918. DynamicMapSorter::Sort(message, count, message_reflection, field);
  919. }
  920. const bool is_packed = field->is_packed();
  921. if (is_packed && count > 0) {
  922. WireFormatLite::WriteTag(field->number(),
  923. WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
  924. const size_t data_size = FieldDataOnlyByteSize(field, message);
  925. output->WriteVarint32(data_size);
  926. }
  927. for (int j = 0; j < count; j++) {
  928. switch (field->type()) {
  929. #define HANDLE_PRIMITIVE_TYPE(TYPE, CPPTYPE, TYPE_METHOD, CPPTYPE_METHOD) \
  930. case FieldDescriptor::TYPE_##TYPE: { \
  931. const CPPTYPE value = field->is_repeated() ? \
  932. message_reflection->GetRepeated##CPPTYPE_METHOD( \
  933. message, field, j) : \
  934. message_reflection->Get##CPPTYPE_METHOD( \
  935. message, field); \
  936. if (is_packed) { \
  937. WireFormatLite::Write##TYPE_METHOD##NoTag(value, output); \
  938. } else { \
  939. WireFormatLite::Write##TYPE_METHOD(field->number(), value, output); \
  940. } \
  941. break; \
  942. }
  943. HANDLE_PRIMITIVE_TYPE( INT32, int32, Int32, Int32)
  944. HANDLE_PRIMITIVE_TYPE( INT64, int64, Int64, Int64)
  945. HANDLE_PRIMITIVE_TYPE(SINT32, int32, SInt32, Int32)
  946. HANDLE_PRIMITIVE_TYPE(SINT64, int64, SInt64, Int64)
  947. HANDLE_PRIMITIVE_TYPE(UINT32, uint32, UInt32, UInt32)
  948. HANDLE_PRIMITIVE_TYPE(UINT64, uint64, UInt64, UInt64)
  949. HANDLE_PRIMITIVE_TYPE( FIXED32, uint32, Fixed32, UInt32)
  950. HANDLE_PRIMITIVE_TYPE( FIXED64, uint64, Fixed64, UInt64)
  951. HANDLE_PRIMITIVE_TYPE(SFIXED32, int32, SFixed32, Int32)
  952. HANDLE_PRIMITIVE_TYPE(SFIXED64, int64, SFixed64, Int64)
  953. HANDLE_PRIMITIVE_TYPE(FLOAT , float , Float , Float )
  954. HANDLE_PRIMITIVE_TYPE(DOUBLE, double, Double, Double)
  955. HANDLE_PRIMITIVE_TYPE(BOOL, bool, Bool, Bool)
  956. #undef HANDLE_PRIMITIVE_TYPE
  957. #define HANDLE_TYPE(TYPE, TYPE_METHOD, CPPTYPE_METHOD) \
  958. case FieldDescriptor::TYPE_##TYPE: \
  959. WireFormatLite::Write##TYPE_METHOD( \
  960. field->number(), \
  961. field->is_repeated() ? \
  962. (map_entries.empty() ? \
  963. message_reflection->GetRepeated##CPPTYPE_METHOD( \
  964. message, field, j) : \
  965. *map_entries[j]) : \
  966. message_reflection->Get##CPPTYPE_METHOD(message, field), \
  967. output); \
  968. break;
  969. HANDLE_TYPE(GROUP , Group , Message)
  970. HANDLE_TYPE(MESSAGE, Message, Message)
  971. #undef HANDLE_TYPE
  972. case FieldDescriptor::TYPE_ENUM: {
  973. const EnumValueDescriptor* value = field->is_repeated() ?
  974. message_reflection->GetRepeatedEnum(message, field, j) :
  975. message_reflection->GetEnum(message, field);
  976. if (is_packed) {
  977. WireFormatLite::WriteEnumNoTag(value->number(), output);
  978. } else {
  979. WireFormatLite::WriteEnum(field->number(), value->number(), output);
  980. }
  981. break;
  982. }
  983. // Handle strings separately so that we can get string references
  984. // instead of copying.
  985. case FieldDescriptor::TYPE_STRING: {
  986. bool strict_utf8_check = StrictUtf8Check(field);
  987. string scratch;
  988. const string& value = field->is_repeated() ?
  989. message_reflection->GetRepeatedStringReference(
  990. message, field, j, &scratch) :
  991. message_reflection->GetStringReference(message, field, &scratch);
  992. if (strict_utf8_check) {
  993. WireFormatLite::VerifyUtf8String(value.data(), value.length(),
  994. WireFormatLite::SERIALIZE,
  995. field->full_name().c_str());
  996. } else {
  997. VerifyUTF8StringNamedField(value.data(), value.length(), SERIALIZE,
  998. field->full_name().c_str());
  999. }
  1000. WireFormatLite::WriteString(field->number(), value, output);
  1001. break;
  1002. }
  1003. case FieldDescriptor::TYPE_BYTES: {
  1004. string scratch;
  1005. const string& value = field->is_repeated() ?
  1006. message_reflection->GetRepeatedStringReference(
  1007. message, field, j, &scratch) :
  1008. message_reflection->GetStringReference(message, field, &scratch);
  1009. WireFormatLite::WriteBytes(field->number(), value, output);
  1010. break;
  1011. }
  1012. }
  1013. }
  1014. }
  1015. void WireFormat::SerializeMessageSetItemWithCachedSizes(
  1016. const FieldDescriptor* field,
  1017. const Message& message,
  1018. io::CodedOutputStream* output) {
  1019. const Reflection* message_reflection = message.GetReflection();
  1020. // Start group.
  1021. output->WriteVarint32(WireFormatLite::kMessageSetItemStartTag);
  1022. // Write type ID.
  1023. output->WriteVarint32(WireFormatLite::kMessageSetTypeIdTag);
  1024. output->WriteVarint32(field->number());
  1025. // Write message.
  1026. output->WriteVarint32(WireFormatLite::kMessageSetMessageTag);
  1027. const Message& sub_message = message_reflection->GetMessage(message, field);
  1028. output->WriteVarint32(sub_message.GetCachedSize());
  1029. sub_message.SerializeWithCachedSizes(output);
  1030. // End group.
  1031. output->WriteVarint32(WireFormatLite::kMessageSetItemEndTag);
  1032. }
  1033. // ===================================================================
  1034. size_t WireFormat::ByteSize(const Message& message) {
  1035. const Descriptor* descriptor = message.GetDescriptor();
  1036. const Reflection* message_reflection = message.GetReflection();
  1037. size_t our_size = 0;
  1038. std::vector<const FieldDescriptor*> fields;
  1039. // Fields of map entry should always be serialized.
  1040. if (descriptor->options().map_entry()) {
  1041. for (int i = 0; i < descriptor->field_count(); i++) {
  1042. fields.push_back(descriptor->field(i));
  1043. }
  1044. } else {
  1045. message_reflection->ListFields(message, &fields);
  1046. }
  1047. for (int i = 0; i < fields.size(); i++) {
  1048. our_size += FieldByteSize(fields[i], message);
  1049. }
  1050. if (descriptor->options().message_set_wire_format()) {
  1051. our_size += ComputeUnknownMessageSetItemsSize(
  1052. message_reflection->GetUnknownFields(message));
  1053. } else {
  1054. our_size += ComputeUnknownFieldsSize(
  1055. message_reflection->GetUnknownFields(message));
  1056. }
  1057. return our_size;
  1058. }
  1059. size_t WireFormat::FieldByteSize(
  1060. const FieldDescriptor* field,
  1061. const Message& message) {
  1062. const Reflection* message_reflection = message.GetReflection();
  1063. if (field->is_extension() &&
  1064. field->containing_type()->options().message_set_wire_format() &&
  1065. field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
  1066. !field->is_repeated()) {
  1067. return MessageSetItemByteSize(field, message);
  1068. }
  1069. size_t count = 0;
  1070. if (field->is_repeated()) {
  1071. count = FromIntSize(message_reflection->FieldSize(message, field));
  1072. } else if (field->containing_type()->options().map_entry()) {
  1073. // Map entry fields always need to be serialized.
  1074. count = 1;
  1075. } else if (message_reflection->HasField(message, field)) {
  1076. count = 1;
  1077. }
  1078. const size_t data_size = FieldDataOnlyByteSize(field, message);
  1079. size_t our_size = data_size;
  1080. if (field->is_packed()) {
  1081. if (data_size > 0) {
  1082. // Packed fields get serialized like a string, not their native type.
  1083. // Technically this doesn't really matter; the size only changes if it's
  1084. // a GROUP
  1085. our_size += TagSize(field->number(), FieldDescriptor::TYPE_STRING);
  1086. our_size += io::CodedOutputStream::VarintSize32(data_size);
  1087. }
  1088. } else {
  1089. our_size += count * TagSize(field->number(), field->type());
  1090. }
  1091. return our_size;
  1092. }
  1093. static size_t MapKeyDataOnlyByteSize(const FieldDescriptor* field,
  1094. const MapKey& value) {
  1095. GOOGLE_DCHECK_EQ(FieldDescriptor::TypeToCppType(field->type()), value.type());
  1096. switch (field->type()) {
  1097. case FieldDescriptor::TYPE_DOUBLE:
  1098. case FieldDescriptor::TYPE_FLOAT:
  1099. case FieldDescriptor::TYPE_GROUP:
  1100. case FieldDescriptor::TYPE_MESSAGE:
  1101. case FieldDescriptor::TYPE_BYTES:
  1102. case FieldDescriptor::TYPE_ENUM:
  1103. GOOGLE_LOG(FATAL) << "Unsupported";
  1104. return 0;
  1105. #define CASE_TYPE(FieldType, CamelFieldType, CamelCppType) \
  1106. case FieldDescriptor::TYPE_##FieldType: \
  1107. return WireFormatLite::CamelFieldType##Size( \
  1108. value.Get##CamelCppType##Value());
  1109. #define FIXED_CASE_TYPE(FieldType, CamelFieldType) \
  1110. case FieldDescriptor::TYPE_##FieldType: \
  1111. return WireFormatLite::k##CamelFieldType##Size;
  1112. CASE_TYPE(INT32, Int32, Int32);
  1113. CASE_TYPE(INT64, Int64, Int64);
  1114. CASE_TYPE(UINT32, UInt32, UInt32);
  1115. CASE_TYPE(UINT64, UInt64, UInt64);
  1116. CASE_TYPE(SINT32, SInt32, Int32);
  1117. CASE_TYPE(SINT64, SInt64, Int64);
  1118. CASE_TYPE(STRING, String, String);
  1119. FIXED_CASE_TYPE(FIXED32, Fixed32);
  1120. FIXED_CASE_TYPE(FIXED64, Fixed64);
  1121. FIXED_CASE_TYPE(SFIXED32, SFixed32);
  1122. FIXED_CASE_TYPE(SFIXED64, SFixed64);
  1123. FIXED_CASE_TYPE(BOOL, Bool);
  1124. #undef CASE_TYPE
  1125. #undef FIXED_CASE_TYPE
  1126. }
  1127. GOOGLE_LOG(FATAL) << "Cannot get here";
  1128. return 0;
  1129. }
  1130. static size_t MapValueRefDataOnlyByteSize(const FieldDescriptor* field,
  1131. const MapValueRef& value) {
  1132. switch (field->type()) {
  1133. case FieldDescriptor::TYPE_GROUP:
  1134. GOOGLE_LOG(FATAL) << "Unsupported";
  1135. return 0;
  1136. #define CASE_TYPE(FieldType, CamelFieldType, CamelCppType) \
  1137. case FieldDescriptor::TYPE_##FieldType: \
  1138. return WireFormatLite::CamelFieldType##Size( \
  1139. value.Get##CamelCppType##Value());
  1140. #define FIXED_CASE_TYPE(FieldType, CamelFieldType) \
  1141. case FieldDescriptor::TYPE_##FieldType: \
  1142. return WireFormatLite::k##CamelFieldType##Size;
  1143. CASE_TYPE(INT32, Int32, Int32);
  1144. CASE_TYPE(INT64, Int64, Int64);
  1145. CASE_TYPE(UINT32, UInt32, UInt32);
  1146. CASE_TYPE(UINT64, UInt64, UInt64);
  1147. CASE_TYPE(SINT32, SInt32, Int32);
  1148. CASE_TYPE(SINT64, SInt64, Int64);
  1149. CASE_TYPE(STRING, String, String);
  1150. CASE_TYPE(BYTES, Bytes, String);
  1151. CASE_TYPE(ENUM, Enum, Enum);
  1152. CASE_TYPE(MESSAGE, Message, Message);
  1153. FIXED_CASE_TYPE(FIXED32, Fixed32);
  1154. FIXED_CASE_TYPE(FIXED64, Fixed64);
  1155. FIXED_CASE_TYPE(SFIXED32, SFixed32);
  1156. FIXED_CASE_TYPE(SFIXED64, SFixed64);
  1157. FIXED_CASE_TYPE(DOUBLE, Double);
  1158. FIXED_CASE_TYPE(FLOAT, Float);
  1159. FIXED_CASE_TYPE(BOOL, Bool);
  1160. #undef CASE_TYPE
  1161. #undef FIXED_CASE_TYPE
  1162. }
  1163. GOOGLE_LOG(FATAL) << "Cannot get here";
  1164. return 0;
  1165. }
  1166. size_t WireFormat::FieldDataOnlyByteSize(
  1167. const FieldDescriptor* field,
  1168. const Message& message) {
  1169. const Reflection* message_reflection = message.GetReflection();
  1170. size_t data_size = 0;
  1171. if (field->is_map()) {
  1172. MapFieldBase* map_field =
  1173. message_reflection->MapData(const_cast<Message*>(&message), field);
  1174. if (map_field->IsMapValid()) {
  1175. MapIterator iter(const_cast<Message*>(&message), field);
  1176. MapIterator end(const_cast<Message*>(&message), field);
  1177. const FieldDescriptor* key_field = field->message_type()->field(0);
  1178. const FieldDescriptor* value_field = field->message_type()->field(1);
  1179. for (map_field->MapBegin(&iter), map_field->MapEnd(&end); iter != end;
  1180. ++iter) {
  1181. size_t size = kMapEntryTagByteSize;
  1182. size += MapKeyDataOnlyByteSize(key_field, iter.GetKey());
  1183. size += MapValueRefDataOnlyByteSize(value_field, iter.GetValueRef());
  1184. data_size += WireFormatLite::LengthDelimitedSize(size);
  1185. }
  1186. return data_size;
  1187. }
  1188. }
  1189. size_t count = 0;
  1190. if (field->is_repeated()) {
  1191. count =
  1192. internal::FromIntSize(message_reflection->FieldSize(message, field));
  1193. } else if (field->containing_type()->options().map_entry()) {
  1194. // Map entry fields always need to be serialized.
  1195. count = 1;
  1196. } else if (message_reflection->HasField(message, field)) {
  1197. count = 1;
  1198. }
  1199. switch (field->type()) {
  1200. #define HANDLE_TYPE(TYPE, TYPE_METHOD, CPPTYPE_METHOD) \
  1201. case FieldDescriptor::TYPE_##TYPE: \
  1202. if (field->is_repeated()) { \
  1203. for (int j = 0; j < count; j++) { \
  1204. data_size += WireFormatLite::TYPE_METHOD##Size( \
  1205. message_reflection->GetRepeated##CPPTYPE_METHOD( \
  1206. message, field, j)); \
  1207. } \
  1208. } else { \
  1209. data_size += WireFormatLite::TYPE_METHOD##Size( \
  1210. message_reflection->Get##CPPTYPE_METHOD(message, field)); \
  1211. } \
  1212. break;
  1213. #define HANDLE_FIXED_TYPE(TYPE, TYPE_METHOD) \
  1214. case FieldDescriptor::TYPE_##TYPE: \
  1215. data_size += count * WireFormatLite::k##TYPE_METHOD##Size; \
  1216. break;
  1217. HANDLE_TYPE( INT32, Int32, Int32)
  1218. HANDLE_TYPE( INT64, Int64, Int64)
  1219. HANDLE_TYPE(SINT32, SInt32, Int32)
  1220. HANDLE_TYPE(SINT64, SInt64, Int64)
  1221. HANDLE_TYPE(UINT32, UInt32, UInt32)
  1222. HANDLE_TYPE(UINT64, UInt64, UInt64)
  1223. HANDLE_FIXED_TYPE( FIXED32, Fixed32)
  1224. HANDLE_FIXED_TYPE( FIXED64, Fixed64)
  1225. HANDLE_FIXED_TYPE(SFIXED32, SFixed32)
  1226. HANDLE_FIXED_TYPE(SFIXED64, SFixed64)
  1227. HANDLE_FIXED_TYPE(FLOAT , Float )
  1228. HANDLE_FIXED_TYPE(DOUBLE, Double)
  1229. HANDLE_FIXED_TYPE(BOOL, Bool)
  1230. HANDLE_TYPE(GROUP , Group , Message)
  1231. HANDLE_TYPE(MESSAGE, Message, Message)
  1232. #undef HANDLE_TYPE
  1233. #undef HANDLE_FIXED_TYPE
  1234. case FieldDescriptor::TYPE_ENUM: {
  1235. if (field->is_repeated()) {
  1236. for (int j = 0; j < count; j++) {
  1237. data_size += WireFormatLite::EnumSize(
  1238. message_reflection->GetRepeatedEnum(message, field, j)->number());
  1239. }
  1240. } else {
  1241. data_size += WireFormatLite::EnumSize(
  1242. message_reflection->GetEnum(message, field)->number());
  1243. }
  1244. break;
  1245. }
  1246. // Handle strings separately so that we can get string references
  1247. // instead of copying.
  1248. case FieldDescriptor::TYPE_STRING:
  1249. case FieldDescriptor::TYPE_BYTES: {
  1250. for (int j = 0; j < count; j++) {
  1251. string scratch;
  1252. const string& value = field->is_repeated() ?
  1253. message_reflection->GetRepeatedStringReference(
  1254. message, field, j, &scratch) :
  1255. message_reflection->GetStringReference(message, field, &scratch);
  1256. data_size += WireFormatLite::StringSize(value);
  1257. }
  1258. break;
  1259. }
  1260. }
  1261. return data_size;
  1262. }
  1263. size_t WireFormat::MessageSetItemByteSize(
  1264. const FieldDescriptor* field,
  1265. const Message& message) {
  1266. const Reflection* message_reflection = message.GetReflection();
  1267. size_t our_size = WireFormatLite::kMessageSetItemTagsSize;
  1268. // type_id
  1269. our_size += io::CodedOutputStream::VarintSize32(field->number());
  1270. // message
  1271. const Message& sub_message = message_reflection->GetMessage(message, field);
  1272. size_t message_size = sub_message.ByteSizeLong();
  1273. our_size += io::CodedOutputStream::VarintSize32(message_size);
  1274. our_size += message_size;
  1275. return our_size;
  1276. }
  1277. } // namespace internal
  1278. } // namespace protobuf
  1279. } // namespace google