serialize_stl.hh 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #ifndef SERIALIZE_STL_HH
  2. #define SERIALIZE_STL_HH
  3. #include "serialize_core.hh"
  4. #include "circular_buffer.hh"
  5. #include <vector>
  6. #include <iterator>
  7. namespace openmsx {
  8. template<typename T> struct serialize_as_stl_collection : std::true_type
  9. {
  10. static const int size = -1; // variable size
  11. using value_type = typename T::value_type;
  12. // save
  13. using const_iterator = typename T::const_iterator;
  14. static const_iterator begin(const T& t) { return t.begin(); }
  15. static const_iterator end (const T& t) { return t.end(); }
  16. // load
  17. static const bool loadInPlace = false;
  18. using output_iterator = typename std::insert_iterator<T>;
  19. static void prepare(T& t, int /*n*/) {
  20. t.clear();
  21. }
  22. static output_iterator output(T& t) {
  23. return std::inserter(t, begin(t));
  24. }
  25. };
  26. //template<typename T> struct serialize_as_collection<std::list<T>>
  27. // : serialize_as_stl_collection<std::list<T>> {};
  28. //template<typename T> struct serialize_as_collection<std::set<T>>
  29. // : serialize_as_stl_collection<std::set<T>> {};
  30. //template<typename T> struct serialize_as_collection<std::deque<T>>
  31. // : serialize_as_stl_collection<std::deque<T>> {};
  32. //template<typename T1, typename T2> struct serialize_as_collection<std::map<T1, T2>>
  33. // : serialize_as_stl_collection<std::map<T1, T2>> {};
  34. template<typename T> struct serialize_as_collection<std::vector<T>>
  35. : serialize_as_stl_collection<std::vector<T>>
  36. {
  37. // Override load-part from base class.
  38. // Don't load vectors in-place, even though it's technically possible
  39. // and slightly more efficient. This is done to keep the correct vector
  40. // size at all intermediate steps. This may be important in case an
  41. // exception occurs during loading.
  42. static const bool loadInPlace = false;
  43. using output_iterator =
  44. typename std::back_insert_iterator<std::vector<T>>;
  45. static void prepare(std::vector<T>& v, int n) {
  46. v.clear(); v.reserve(n);
  47. }
  48. static output_iterator output(std::vector<T>& v) {
  49. return std::back_inserter(v);
  50. }
  51. };
  52. template<typename T> struct serialize_as_collection<cb_queue<T>>
  53. : serialize_as_stl_collection<cb_queue<T>>
  54. {
  55. using output_iterator =
  56. typename std::back_insert_iterator<circular_buffer<T>>;
  57. static void prepare(cb_queue<T>& q, int n) {
  58. q.clear(); q.getBuffer().set_capacity(n);
  59. }
  60. static output_iterator output(cb_queue<T>& q) {
  61. return std::back_inserter(q.getBuffer());
  62. }
  63. };
  64. } // namespace openmsx
  65. #endif