serialization_helper.hpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 <vector>
  19. namespace boost{
  20. namespace flyweights{
  21. namespace detail{
  22. /* The serialization helpers for flyweight<T> map numerical IDs to
  23. * flyweight exemplars --an exemplar is the flyweight object
  24. * associated to a given value that appears first on the serialization
  25. * stream, so that subsequent equivalent flyweight objects will be made
  26. * to refer to it during the serialization process.
  27. */
  28. template<typename Flyweight>
  29. struct flyweight_value_address
  30. {
  31. typedef const typename Flyweight::value_type* result_type;
  32. result_type operator()(const Flyweight& x)const{return &x.get();}
  33. };
  34. template<typename Flyweight>
  35. class save_helper:private noncopyable
  36. {
  37. typedef multi_index::multi_index_container<
  38. Flyweight,
  39. multi_index::indexed_by<
  40. multi_index::random_access<>,
  41. multi_index::hashed_unique<flyweight_value_address<Flyweight> >
  42. >
  43. > table;
  44. public:
  45. typedef typename table::size_type size_type;
  46. size_type size()const{return t.size();}
  47. size_type find(const Flyweight& x)const
  48. {
  49. return multi_index::project<0>(t,multi_index::get<1>(t).find(&x.get()))
  50. -t.begin();
  51. }
  52. void push_back(const Flyweight& x){t.push_back(x);}
  53. private:
  54. table t;
  55. };
  56. template<typename Flyweight>
  57. class load_helper:private noncopyable
  58. {
  59. typedef std::vector<Flyweight> table;
  60. public:
  61. typedef typename table::size_type size_type;
  62. size_type size()const{return t.size();}
  63. Flyweight operator[](size_type n)const{return t[n];}
  64. void push_back(const Flyweight& x){t.push_back(x);}
  65. private:
  66. table t;
  67. };
  68. } /* namespace flyweights::detail */
  69. } /* namespace flyweights */
  70. } /* namespace boost */
  71. #endif