Storing a set of serialized protobuf objects

I use SerializeToStringProtobuf for my objects and then save the row to the database.

However, sometimes I have an array of such objects. I would like to save the entire serialized array, and for this I need a separator string between serialized strings.

According to the documentation I saw, the string is just a byte array, and therefore I did not promise me anything regarding its contents.

What would be the best approach here?

I do not know the length of the array, because objects can be added to it when we go, and I want it to be stored in the database throughout the process.

+4
source share
2 answers

Suppose your protobuf messagelooks like this:

message Object
{
  ... = 1;
  ... = 2;
  ... = 3;
}

Then in the same file, enter another 1 message, which is a collection of these Objects.

message Objects
{
  repeated Object array = 1;
}

Therefore, when you have many elements, you can just use Objectsand use SerializeAsString()on Objects. This will save your efforts on serializing an individual Objectseparately and place your own handmade limiter. You can serialize everything Objectusing one instance Objects.
With this approach, you delegate all parsing and serialization processing to the Protobuf library as well . I use this in my project and it works like a charm.

, Objects Object. . repeated protobufs ++ 11, for.


, Objects::SerializeAsString() , string, . , . std::fstream :

struct fstreamEncoded : std::fstream
{
    // other methods
    void  // returns `void` to avoid multiple `<<` in a single line
    operator<< (const string& content)
    {  // below casting would avoid recursive calling of this method
       // adding `length() + 1` to include the protobuf last character as well
      static_cast<std::fstream&>(*this) << (content.length() + 1) << "\n" << content << std::endl;
    }

    string
    getline ()
    {
      char length_[20] = {};
      std::istream::getline(length_, sizeof(length_) - 1);
      if(*length_ == 0)
        return "";

      const size_t length = std::atol(length_);  // length of encoded input
      string content(length, 0);  // resize the `string`
      read(&content[0], length);  // member of `class istream`
      return content;
    }
}

. .

+3

, , , , .

+1

All Articles