any_iterator_buffer.hpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. // Boost.Range library
  2. //
  3. // Copyright Neil Groves 2010. Use, modification and
  4. // distribution is subject to the Boost Software License, Version
  5. // 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt)
  7. //
  8. // For more information, see http://www.boost.org/libs/range/
  9. //
  10. #ifndef BOOST_RANGE_DETAIL_ANY_ITERATOR_BUFFER_HPP_INCLUDED
  11. #define BOOST_RANGE_DETAIL_ANY_ITERATOR_BUFFER_HPP_INCLUDED
  12. #include <boost/array.hpp>
  13. #include <boost/assert.hpp>
  14. #include <boost/static_assert.hpp>
  15. #include <boost/noncopyable.hpp>
  16. namespace boost
  17. {
  18. template<std::size_t StackBufferSize>
  19. class any_iterator_buffer
  20. : noncopyable
  21. {
  22. BOOST_STATIC_ASSERT(( StackBufferSize > 0 ));
  23. public:
  24. any_iterator_buffer()
  25. : m_ptr()
  26. {
  27. }
  28. ~any_iterator_buffer()
  29. {
  30. delete [] m_ptr;
  31. }
  32. void* allocate(std::size_t bytes)
  33. {
  34. BOOST_ASSERT( !m_ptr );
  35. if (bytes <= StackBufferSize)
  36. return m_buffer.data();
  37. m_ptr = new char[bytes];
  38. return m_ptr;
  39. }
  40. void deallocate()
  41. {
  42. delete [] m_ptr;
  43. m_ptr = 0;
  44. }
  45. private:
  46. // Rationale:
  47. // Do not use inheritance from noncopyable because this causes
  48. // the concepts to erroneous detect the derived any_iterator
  49. // as noncopyable.
  50. any_iterator_buffer(const any_iterator_buffer&);
  51. void operator=(const any_iterator_buffer&);
  52. char* m_ptr;
  53. boost::array<char, StackBufferSize> m_buffer;
  54. };
  55. class any_iterator_heap_only_buffer
  56. : noncopyable
  57. {
  58. public:
  59. any_iterator_heap_only_buffer()
  60. : m_ptr()
  61. {
  62. }
  63. ~any_iterator_heap_only_buffer()
  64. {
  65. delete [] m_ptr;
  66. }
  67. void* allocate(std::size_t bytes)
  68. {
  69. BOOST_ASSERT( !m_ptr );
  70. m_ptr = new char[bytes];
  71. return m_ptr;
  72. }
  73. void deallocate()
  74. {
  75. delete [] m_ptr;
  76. m_ptr = 0;
  77. }
  78. private:
  79. char* m_ptr;
  80. };
  81. template<std::size_t StackBufferSize>
  82. class any_iterator_stack_only_buffer
  83. {
  84. BOOST_STATIC_ASSERT(( StackBufferSize > 0 ));
  85. public:
  86. void* allocate(std::size_t bytes)
  87. {
  88. BOOST_ASSERT( bytes <= m_buffer.size() );
  89. return m_buffer.data();
  90. }
  91. void deallocate()
  92. {
  93. }
  94. private:
  95. boost::array<char, StackBufferSize> m_buffer;
  96. };
  97. typedef any_iterator_buffer<64> any_iterator_default_buffer;
  98. } // namespace boost
  99. #endif // include guard