utility_serialization.hpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright 2019 Hans Dembinski
  2. //
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt
  5. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. #ifndef BOOST_HISTOGRAM_TEST_UTILITY_SERIALIZATION_HPP
  7. #define BOOST_HISTOGRAM_TEST_UTILITY_SERIALIZATION_HPP
  8. #include <boost/archive/xml_iarchive.hpp>
  9. #include <boost/archive/xml_oarchive.hpp>
  10. #include <boost/assert.hpp>
  11. #include <boost/config.hpp>
  12. #include <boost/core/nvp.hpp>
  13. #include <fstream>
  14. #include <iostream>
  15. #include <string>
  16. std::string join(const char* a, const char* b) {
  17. std::string filename = a;
  18. filename +=
  19. #ifdef BOOST_WINDOWS
  20. "\\";
  21. #else
  22. "/";
  23. #endif
  24. filename += b;
  25. return filename;
  26. }
  27. template <class T>
  28. void load_xml(const std::string& filename, T& t) {
  29. std::ifstream ifs(filename);
  30. BOOST_ASSERT(ifs.is_open());
  31. // manually skip XML comments at the beginning of the stream, because of
  32. // https://github.com/boostorg/serialization/issues/169
  33. char line[128];
  34. do {
  35. ifs.getline(line, 128);
  36. BOOST_ASSERT(std::strlen(line) < 127);
  37. } while (!ifs.fail() && !ifs.eof() && std::strstr(line, "-->") == nullptr);
  38. boost::archive::xml_iarchive ia(ifs);
  39. ia >> boost::make_nvp("item", t);
  40. }
  41. template <class T>
  42. void print_xml(const std::string& filename, const T& t) {
  43. std::cout << filename << "\n";
  44. boost::archive::xml_oarchive oa(std::cout);
  45. oa << boost::make_nvp("item", t);
  46. std::cout << std::flush;
  47. }
  48. #endif