Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Serialization Using Boost and uint8_t

When working with binary data I tend to use uint8_t. I guess that just seems like the type of a byte to me. However, I can't figure out how to get the binary serialization in boost to work with that type. Am I asking the impossible or just missing something simple?

This example program doesn't compile on VS2013 with some complaint about not being about to convert the streams into std::ostream or std::istream.

The program works fine with char instead of uint8_t, but that bugs me. :)

#include <cstdlib> // EXIT_SUCCESS
#include <vector>

#include "boost/archive/binary_iarchive.hpp"
#include "boost/archive/binary_oarchive.hpp"
#include "boost/iostreams/device/array.hpp"
#include "boost/iostreams/device/back_inserter.hpp"
#include "boost/iostreams/stream_buffer.hpp"

int main(int argc, char** argv)
{
   typedef std::vector< uint8_t > Buffer;
   Buffer buffer;

   // Serialization
   {
      int foo = 1;

      typedef boost::iostreams::back_insert_device< Buffer > Device;
      Device device(buffer);

      typedef boost::iostreams::stream_buffer< Device > Stream;
      Stream stream(device);

      {
         boost::archive::binary_oarchive archive(stream);
         archive << foo;
      }
   }

   // Deserialization
   {
      int foo;

      typedef boost::iostreams::basic_array_source< uint8_t > Device;
      Device device(buffer.data(), buffer.size());

      typedef boost::iostreams::stream_buffer< Device > Stream;
      Stream stream(device);

      {
         boost::archive::binary_iarchive archive(stream);
         archive >> foo;
      }
   }

   return EXIT_SUCCESS;
}
like image 538
Aaron Wright Avatar asked May 06 '26 17:05

Aaron Wright


1 Answers

The binary archives take a std::istream / std::ostream argument, so you're stuck using std::basic_istream<char> / std::basic_ostream<char>.

Incidentally there's no guarantee that implementations offer unsigned char / uint8_t versions of streams (or rather std::char_traits<unsigned char>).

like image 66
user657267 Avatar answered May 08 '26 08:05

user657267



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!