• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
11 #ifndef BOOST_CONTAINER_TEST_MEMORY_RESOURCE_TESTER_HPP
12 #define BOOST_CONTAINER_TEST_MEMORY_RESOURCE_TESTER_HPP
13 
14 #include <boost/container/pmr/memory_resource.hpp>
15 #include <boost/container/vector.hpp>
16 #include <cstdlib>
17 
18 class memory_resource_logger
19    : public boost::container::pmr::memory_resource
20 {
21    public:
22    struct allocation_info
23    {
24       char *address;
25       std::size_t bytes;
26       std::size_t alignment;
27    };
28 
29    boost::container::vector<allocation_info> m_info;
30    unsigned m_mismatches;
31 
memory_resource_logger()32    explicit memory_resource_logger()
33       : m_info()
34       , m_mismatches()
35    {}
36 
~memory_resource_logger()37    virtual ~memory_resource_logger()
38    {  this->reset();  }
39 
do_allocate(std::size_t bytes,std::size_t alignment)40    virtual void* do_allocate(std::size_t bytes, std::size_t alignment)
41    {
42       char *addr =(char*)std::malloc(bytes);
43       if(!addr){
44          throw std::bad_alloc();
45       }
46       allocation_info info;
47       info.address   = addr;
48       info.bytes     = bytes;
49       info.alignment = alignment;
50       m_info.push_back(info);
51       return addr;
52    }
53 
do_deallocate(void * p,std::size_t bytes,std::size_t alignment)54    virtual void do_deallocate(void* p, std::size_t bytes, std::size_t alignment)
55    {
56       std::size_t i = 0, max = m_info.size();
57       while(i != max && m_info[i].address != p){
58          ++i;
59       }
60       if(i == max){
61          ++m_mismatches;
62       }
63       else{
64          const allocation_info &info = m_info[i];
65          m_mismatches += info.bytes != bytes || info.alignment != alignment;
66          std::free(p);
67          m_info.erase(m_info.nth(i));
68       }
69    }
70 
do_is_equal(const boost::container::pmr::memory_resource & other) const71    virtual bool do_is_equal(const boost::container::pmr::memory_resource& other) const BOOST_NOEXCEPT
72    {
73       return static_cast<const memory_resource *>(this) == &other;
74    }
75 
reset()76    void reset()
77    {
78       while(!m_info.empty()){
79          std::free(m_info.back().address);
80          m_info.pop_back();
81       }
82       m_mismatches = 0u;
83    }
84 };
85 
86 #endif   //#ifndef BOOST_CONTAINER_TEST_MEMORY_RESOURCE_TESTER_HPP
87