test_cereal.cpp 1.28 KB
Newer Older
Christoph Gerum's avatar
Christoph Gerum committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#include <cereal/types/unordered_map.hpp>
#include <cereal/types/memory.hpp>
#include <cereal/archives/binary.hpp>
#include <cereal/archives/xml.hpp>
#include <cereal/archives/json.hpp>
#include <fstream>
#include <memory>

struct MyRecord
{
private:
  uint8_t x, y;
  float z;

public:
  template <class Archive>
  void serialize( Archive & ar )
  {
    ar( x, y, z );
  }
};

struct SomeData
{
  int32_t id;
  std::shared_ptr<std::unordered_map<uint32_t, MyRecord>> data;

  template <class Archive>
  void save( Archive & ar ) const
  {
    ar( data );
  }

  template <class Archive>
  void load( Archive & ar )
  {
    static int32_t idGen = 0;
    id = idGen++;
    ar( data );
  }
};

int main()
{
  SomeData myData;
  myData.data = std::make_shared<std::unordered_map<uint32_t, MyRecord> >();

  MyRecord r1, r2, r3;
  (*myData.data)[0] =  r1;
  (*myData.data)[1] =  r2;
  (*myData.data)[2] =  r3;
  
  {
    std::ofstream os("out.cereal", std::ios::binary);
    cereal::BinaryOutputArchive archive( os );
    archive( myData );
  }

  {
    std::ofstream os("out.xml", std::ios::binary);
    cereal::XMLOutputArchive archive( os );
    archive( myData );
  }

  {
    std::ofstream os("out.json", std::ios::binary);
    cereal::JSONOutputArchive archive( os );
    archive( myData );
  }
  
  return 0;
}