serialization_helper.hpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /* Copyright 2006-2014 Joaquin M Lopez Munoz.
  2. * Distributed under the Boost Software License, Version 1.0.
  3. * (See accompanying file LICENSE_1_0.txt or copy at
  4. * http://www.boost.org/LICENSE_1_0.txt)
  5. *
  6. * See http://www.boost.org/libs/flyweight for library home page.
  7. */
  8. #ifndef BOOST_FLYWEIGHT_DETAIL_SERIALIZATION_HELPER_HPP
  9. #define BOOST_FLYWEIGHT_DETAIL_SERIALIZATION_HELPER_HPP
  10. #if defined(_MSC_VER)&&(_MSC_VER>=1200)
  11. #pragma once
  12. #endif
  13. #include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */
  14. #include <boost/multi_index_container.hpp>
  15. #include <boost/multi_index/hashed_index.hpp>
  16. #include <boost/multi_index/random_access_index.hpp>
  17. #include <boost/noncopyable.hpp>
  18. #include <boost/serialization/extended_type_info.hpp>
  19. #include <vector>
  20. namespace boost{
  21. namespace flyweights{
  22. namespace detail{
  23. /* The serialization helpers for flyweight<T> map numerical IDs to
  24. * flyweight exemplars --an exemplar is the flyweight object
  25. * associated to a given value that appears first on the serialization
  26. * stream, so that subsequent equivalent flyweight objects will be made
  27. * to refer to it during the serialization process.
  28. */
  29. template<typename Flyweight>
  30. struct flyweight_value_address
  31. {
  32. typedef const typename Flyweight::value_type* result_type;
  33. result_type operator()(const Flyweight& x)const{return &x.get();}
  34. };
  35. template<typename Flyweight>
  36. class save_helper:private noncopyable
  37. {
  38. typedef multi_index::multi_index_container<
  39. Flyweight,
  40. multi_index::indexed_by<
  41. multi_index::random_access<>,
  42. multi_index::hashed_unique<flyweight_value_address<Flyweight> >
  43. >
  44. > table;
  45. public:
  46. typedef typename table::size_type size_type;
  47. size_type size()const{return t.size();}
  48. size_type find(const Flyweight& x)const
  49. {
  50. return multi_index::project<0>(t,multi_index::get<1>(t).find(&x.get()))
  51. -t.begin();
  52. }
  53. void push_back(const Flyweight& x){t.push_back(x);}
  54. private:
  55. table t;
  56. };
  57. template<typename Flyweight>
  58. class load_helper:private noncopyable
  59. {
  60. typedef std::vector<Flyweight> table;
  61. public:
  62. typedef typename table::size_type size_type;
  63. size_type size()const{return t.size();}
  64. Flyweight operator[](size_type n)const{return t[n];}
  65. void push_back(const Flyweight& x){t.push_back(x);}
  66. private:
  67. table t;
  68. };
  69. } /* namespace flyweights::detail */
  70. } /* namespace flyweights */
  71. } /* namespace boost */
  72. #endif