Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the proper way to handle optional messages in protobuf?
    text
    copied!<p>Consider the following implementation:</p> <p>person.proto:</p> <pre><code> enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { required float number = 1; required PhoneType type = 2; } message Person { required string name = 1; optional PhoneNumber number = 2; } </code></pre> <p>main.cpp:</p> <pre><code>#include &lt;stdint.h&gt; #include &lt;stdio.h&gt; #include "person.pb.h" #include &lt;iostream&gt; int main(int argc, char *argv[]) { static const uint32_t outputbuflen = 1024; uint8_t outputbuffer[outputbuflen]; uint32_t writtenlenght = 0; // Encode a person and send it over any datalink. // SENDER Person p_sender; p_sender.set_name("FooBar"); // Set the phonenumber. // Does not work because returns const ref. // p.number().set_number(0123123); // Is this correct? PhoneNumber * number = p_sender.mutable_number(); number-&gt;set_number(0800123123.0); number-&gt;set_type(MOBILE); p_sender.SerializeToArray(outputbuffer, outputbuflen); writtenlenght = p_sender.ByteSize(); std::cout &lt;&lt; writtenlenght &lt;&lt; "B written to output."&lt;&lt; std::endl; // Great, now send the stream somwhere // sendStream(...); // RECEIVER // Does not know how many bytes to expect, so we'll let protobuf handle that. // Simulate a reception loop. Person p_receiver; uint32_t bytesparsed; for(bytesparsed = 0; bytesparsed &lt; writtenlenght; bytesparsed++){ // Look at the data as if receiving it byte by byte. std::cout &lt;&lt; "Trying to parse message " &lt;&lt; bytesparsed &lt;&lt; std::endl; if(p_receiver.ParseFromArray(outputbuffer, bytesparsed)){ std::cout &lt;&lt; "Found message" &lt;&lt; std::endl;; break; } } std::cout &lt;&lt; "Needed " &lt;&lt; bytesparsed &lt;&lt; "B to read message, but has still " \ &lt;&lt; writtenlenght - bytesparsed &lt;&lt; "B left in buffer" &lt;&lt; std::endl; return 0; } </code></pre> <p>Using: <a href="https://developers.google.com/protocol-buffers/" rel="nofollow">https://developers.google.com/protocol-buffers/</a> In a real world situation the receiver will not know the amount of bytes that should be received, but protobuf should (to my understanding) be able to check for a complete message from the buffer. This seems to work fine if there are no optional messages. At this moment it does not happen and I end up with a broken person with no phone number. :) What am I doing wrong and how should this situation be handled?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload