4

How to binary serialize in a buffer?

I didn't find answer on official documentation and on stackoverflow it absent too.

The most part of examples show how to binary serialize in some file. Other part show how to binary serialize in the string. (I think this is wrong way because binary could have a lot of null-s, but sting - don't)

But how to binary serialize in some buffer - there are no information. Could someone show how to do it?

1 Answer 1

2

(I think this is wrong way because binary could have a lot of null-s, but sting - don't)

C++ strings contain NUL characters just fine

But how to binary serialize in some buffer - there are no information. Could someone show how to do it?

Strings are also "some buffer". So using std::stringstream (which you likely saw) is already an answer to your question.

However, if you think a buffer is only when you have a naked array of char or something, you can "mount" a stream onto that. Now this is supposedly not too much work with std::streambuf, but the little I know about it is that it gets tricky around char_traits.

So, let's do the easy thing and use the Boost Iostreams types that already do this:

Live On Coliru

#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/string.hpp>
#include <iostream>
#include <iomanip>

namespace bio = boost::iostreams;
using Map = std::map<int, std::string>;

int main()
{
    char buf[1024*10];

    {
        bio::stream<bio::array_sink>    os(buf);
        boost::archive::binary_oarchive oa(os);
        oa << Map{
            {1, "one"},  {2, "two"},  {3, "three"},
            {4, "four"}, {5, "five"}, {6, "six"},
        };
    }

    {
        bio::stream<bio::array_source>  is(buf);
        boost::archive::binary_iarchive ia(is);
        Map m;
        ia >> m;

        for (auto& [k,v] : m)
            std::cout << " - " << k << " -> " << std::quoted(v) << "\n";
    }
}

Printing

 - 1 -> "one"
 - 2 -> "two"
 - 3 -> "three"
 - 4 -> "four"
 - 5 -> "five"
 - 6 -> "six"
Sign up to request clarification or add additional context in comments.

2 Comments

do you know how to get the numer of bytes that was writed/read to/from buffer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.