1 // Formatting library for C++ - mock allocator 2 // 3 // Copyright (c) 2012 - present, Victor Zverovich 4 // All rights reserved. 5 // 6 // For the license information refer to format.h. 7 8 #ifndef FMT_MOCK_ALLOCATOR_H_ 9 #define FMT_MOCK_ALLOCATOR_H_ 10 11 #include <assert.h> // assert 12 #include <stddef.h> // size_t 13 14 #include <memory> // std::allocator_traits 15 16 #include "gmock/gmock.h" 17 18 template <typename T> class mock_allocator { 19 public: mock_allocator()20 mock_allocator() {} mock_allocator(const mock_allocator &)21 mock_allocator(const mock_allocator&) {} 22 using value_type = T; 23 MOCK_METHOD1_T(allocate, T*(size_t n)); 24 MOCK_METHOD2_T(deallocate, void(T* p, size_t n)); 25 }; 26 27 template <typename Allocator> class allocator_ref { 28 private: 29 Allocator* alloc_; 30 move(allocator_ref & other)31 void move(allocator_ref& other) { 32 alloc_ = other.alloc_; 33 other.alloc_ = nullptr; 34 } 35 36 public: 37 using value_type = typename Allocator::value_type; 38 alloc_(alloc)39 explicit allocator_ref(Allocator* alloc = nullptr) : alloc_(alloc) {} 40 allocator_ref(const allocator_ref & other)41 allocator_ref(const allocator_ref& other) : alloc_(other.alloc_) {} allocator_ref(allocator_ref && other)42 allocator_ref(allocator_ref&& other) { move(other); } 43 44 allocator_ref& operator=(allocator_ref&& other) { 45 assert(this != &other); 46 move(other); 47 return *this; 48 } 49 50 allocator_ref& operator=(const allocator_ref& other) { 51 alloc_ = other.alloc_; 52 return *this; 53 } 54 55 public: get()56 Allocator* get() const { return alloc_; } 57 allocate(size_t n)58 value_type* allocate(size_t n) { 59 return std::allocator_traits<Allocator>::allocate(*alloc_, n); 60 } deallocate(value_type * p,size_t n)61 void deallocate(value_type* p, size_t n) { alloc_->deallocate(p, n); } 62 }; 63 64 #endif // FMT_MOCK_ALLOCATOR_H_ 65