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