Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when ParseFromArray return true in protocol buffer

I ParseFromArray the protocol buffer's protocol, the protocol is not lack any filed. But the ParseFromArray function returns false. Why?

like image 995
user2231794 Avatar asked Dec 26 '22 18:12

user2231794


1 Answers

I'm assuming you are using C++. ParseFromArray() fails if:

  • The input data is not in valid protobuf format.
  • The input data is lacking a required field.

If you are sure that all required fields are set, then it must be the case that your input data is corrupted. You should verify that the bytes and size you are passing into ParseFromArray() are exactly the bytes and size that you got from SerializeToArray() and ByteSize() on the sending side. You will probably find that you are losing some bytes somewhere, or that some bytes got corrupted.

Common reasons for corruption include:

  • Passing the encoded bytes over a text-only channel. E.g. if you write the data to (or read it from) a file that is not opened in "binary" mode, or if you at some point store the bytes in a Java String, the data will become corrupted, as these channels expect text, and encoded protobufs are not text.
  • Passing the bytes as a char*, i.e. assuming NUL-termination. Encoded protobufs can contain '\0' bytes, meaning that you cannot represent one as a char* alone -- you must include the size separately.
  • Serializing to an array that is larger than needed, and then forgetting to pay attention to how much data was actually written. When you call SerializeToArray(), you must also call ByteSize() to see how large the message is, and you must make sure the receiving end receives that size and passes it to ParseFromArray(). Otherwise, the parser will think that the extra bytes at the end of the buffer are part of the message, and will fail to parse them.
like image 92
Kenton Varda Avatar answered Jan 04 '23 04:01

Kenton Varda