PhpDeveloper
PhpDeveloper

Reputation: 35

How to read Protocol Buffers delimited I/O functions

I'm trying to read files that contain length-delimited Protocol buffer messages, each record is a varint specifying the length of the message, followed by the protobuf message itself. But there's no way to do that by default (that I could see). I use google/protobuf 3.6.1 library

However, the Java API in version 2.1.0 received a set of "Delimited" I/O functions which apparently do that job: parseDelimitedFrom mergeDelimitedFrom

Are there PHP equivalents? so I can parse those messages in PHP? No i receive this error when use the mergeFromString method
"Error occurred during parsing: Unexpected wire type."

Upvotes: 2

Views: 369

Answers (1)

jpa
jpa

Reputation: 12176

I haven't tested, but based on source this might work:

 $data = /* Length-prefixed protobuf data in string */;
 $input = new CodedInputStream($data);

 /* Read length prefix */
 $length = 0;
 $input->readVarint32($length);

 /* Limit the stream so that only $length bytes get parsed */
 $input->pushLimit($length);

 /* Parse the message */
 $msg = new MyMessage();
 $msg->parseFromStream($input);

Upvotes: 1

Related Questions