memory_resource_logger.hpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2015-2015. Distributed under the Boost
  4. // Software License, Version 1.0. (See accompanying file
  5. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // See http://www.boost.org/libs/container for documentation.
  8. //
  9. //////////////////////////////////////////////////////////////////////////////
  10. #ifndef BOOST_CONTAINER_TEST_MEMORY_RESOURCE_TESTER_HPP
  11. #define BOOST_CONTAINER_TEST_MEMORY_RESOURCE_TESTER_HPP
  12. #include <boost/container/pmr/memory_resource.hpp>
  13. #include <boost/container/vector.hpp>
  14. #include <cstdlib>
  15. class memory_resource_logger
  16. : public boost::container::pmr::memory_resource
  17. {
  18. public:
  19. struct allocation_info
  20. {
  21. char *address;
  22. std::size_t bytes;
  23. std::size_t alignment;
  24. };
  25. boost::container::vector<allocation_info> m_info;
  26. unsigned m_mismatches;
  27. explicit memory_resource_logger()
  28. : m_info()
  29. , m_mismatches()
  30. {}
  31. virtual ~memory_resource_logger()
  32. { this->reset(); }
  33. virtual void* do_allocate(std::size_t bytes, std::size_t alignment)
  34. {
  35. char *addr =(char*)std::malloc(bytes);
  36. if(!addr){
  37. throw std::bad_alloc();
  38. }
  39. allocation_info info;
  40. info.address = addr;
  41. info.bytes = bytes;
  42. info.alignment = alignment;
  43. m_info.push_back(info);
  44. return addr;
  45. }
  46. virtual void do_deallocate(void* p, std::size_t bytes, std::size_t alignment)
  47. {
  48. std::size_t i = 0, max = m_info.size();
  49. while(i != max && m_info[i].address != p){
  50. ++i;
  51. }
  52. if(i == max){
  53. ++m_mismatches;
  54. }
  55. else{
  56. const allocation_info &info = m_info[i];
  57. m_mismatches += info.bytes != bytes || info.alignment != alignment;
  58. std::free(p);
  59. m_info.erase(m_info.nth(i));
  60. }
  61. }
  62. virtual bool do_is_equal(const boost::container::pmr::memory_resource& other) const BOOST_NOEXCEPT
  63. {
  64. return static_cast<const memory_resource *>(this) == &other;
  65. }
  66. void reset()
  67. {
  68. while(!m_info.empty()){
  69. std::free(m_info.back().address);
  70. m_info.pop_back();
  71. }
  72. m_mismatches = 0u;
  73. }
  74. };
  75. #endif //#ifndef BOOST_CONTAINER_TEST_MEMORY_RESOURCE_TESTER_HPP