Howard Hinnant | 3e51952 | 2010-05-11 19:42:16 +0000 | [diff] [blame] | 1 | #ifndef TEST_ALLOCATOR_H |
| 2 | #define TEST_ALLOCATOR_H |
| 3 | |
| 4 | #include <cstddef> |
| 5 | #include <type_traits> |
| 6 | #include <cstdlib> |
| 7 | #include <new> |
| 8 | #include <climits> |
| 9 | |
| 10 | class test_alloc_base |
| 11 | { |
| 12 | protected: |
| 13 | static int count; |
| 14 | public: |
| 15 | static int throw_after; |
| 16 | }; |
| 17 | |
| 18 | int test_alloc_base::count = 0; |
| 19 | int test_alloc_base::throw_after = INT_MAX; |
| 20 | |
| 21 | template <class T> |
| 22 | class test_allocator |
| 23 | : public test_alloc_base |
| 24 | { |
| 25 | int data_; |
| 26 | |
| 27 | template <class U> friend class test_allocator; |
| 28 | public: |
| 29 | |
| 30 | typedef unsigned size_type; |
| 31 | typedef int difference_type; |
| 32 | typedef T value_type; |
| 33 | typedef value_type* pointer; |
| 34 | typedef const value_type* const_pointer; |
| 35 | typedef typename std::add_lvalue_reference<value_type>::type reference; |
| 36 | typedef typename std::add_lvalue_reference<const value_type>::type const_reference; |
| 37 | |
| 38 | template <class U> struct rebind {typedef test_allocator<U> other;}; |
| 39 | |
| 40 | test_allocator() throw() : data_(-1) {} |
| 41 | explicit test_allocator(int i) throw() : data_(i) {} |
| 42 | test_allocator(const test_allocator& a) throw() |
| 43 | : data_(a.data_) {} |
| 44 | template <class U> test_allocator(const test_allocator<U>& a) throw() |
| 45 | : data_(a.data_) {} |
| 46 | ~test_allocator() throw() {data_ = 0;} |
| 47 | pointer address(reference x) const {return &x;} |
| 48 | const_pointer address(const_reference x) const {return &x;} |
| 49 | pointer allocate(size_type n, const void* = 0) |
| 50 | { |
| 51 | if (count >= throw_after) |
| 52 | throw std::bad_alloc(); |
| 53 | ++count; |
| 54 | return (pointer)std::malloc(n * sizeof(T)); |
| 55 | } |
| 56 | void deallocate(pointer p, size_type n) |
| 57 | {std::free(p);} |
| 58 | size_type max_size() const throw() |
| 59 | {return UINT_MAX / sizeof(T);} |
| 60 | void construct(pointer p, const T& val) |
| 61 | {::new(p) T(val);} |
| 62 | void destroy(pointer p) {p->~T();} |
| 63 | |
| 64 | friend bool operator==(const test_allocator& x, const test_allocator& y) |
| 65 | {return x.data_ == y.data_;} |
| 66 | friend bool operator!=(const test_allocator& x, const test_allocator& y) |
| 67 | {return !(x == y);} |
| 68 | }; |
| 69 | |
Howard Hinnant | bf2897c | 2010-08-22 00:47:54 +0000 | [diff] [blame] | 70 | #endif // TEST_ALLOCATOR_H |