1

I have this code:

std::vector<uint8_t> getWriteBuffer()
{
    boost::property_tree::ptree jsonTree=getJson();  //This function returns a json  in a ptree

    // I have this code, but is there any faster way to do this?
    std::ostringstream jsonStream;
    boost::property_tree::write_json(jsonStream, jsonTree);
    std::string jsonString = jsonStream.str();
    std::vector<uint8_t> output(jsonString.begin(), jsonString.end());
    return output;
}

As the code, I can do this by writing Ptree to a string stream, then convert it to a string and then copy it to a buffer.

Is there any faster way to do this?

mans
  • 17,104
  • 45
  • 172
  • 321
  • @ildjarn Yes, assume that I want to get the serialized data as a buffer that I send over a method to somewhere else. I need to have a vector which holds the json string (vector is just a way to represent a simple buffer) – mans May 17 '18 at 15:02
  • Perhaps you can improve the interface to take a `span` or `string_view` (or even `boost::asio::const_buffer`) instead of something specific (like the `vector`). That way you solve the problem for any future usage (providing that the caller has the buffer in some kind of contiguous POD container) – sehe May 17 '18 at 15:19

1 Answers1

0

I'd probably just write to a stream that sits on a streambuffer around a back_inserter_device: https://www.boost.org/doc/libs/1_67_0/libs/iostreams/doc/classes/back_inserter.html

You can also combine this with Boost Serialization, see:

In that case using binary_oarchive and using no_header archive flags would reduce the data volume.

sehe
  • 374,641
  • 47
  • 450
  • 633