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 | |
33 | explicit memory_resource_logger() |
34 | : m_info() |
35 | , m_mismatches() |
36 | {} |
37 | |
38 | virtual ~memory_resource_logger() BOOST_OVERRIDE |
39 | { this->reset(); } |
40 | |
41 | virtual void* do_allocate(std::size_t bytes, std::size_t alignment) BOOST_OVERRIDE |
42 | { |
43 | char *addr =(char*)std::malloc(size: 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(x: info); |
52 | return addr; |
53 | } |
54 | |
55 | virtual void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) BOOST_OVERRIDE |
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(ptr: p); |
68 | m_info.erase(position: m_info.nth(n: i)); |
69 | } |
70 | } |
71 | |
72 | virtual bool do_is_equal(const boost::container::pmr::memory_resource& other) const BOOST_NOEXCEPT BOOST_OVERRIDE |
73 | { |
74 | return static_cast<const memory_resource *>(this) == &other; |
75 | } |
76 | |
77 | void reset() |
78 | { |
79 | while(!m_info.empty()){ |
80 | std::free(ptr: 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 |