mock-allocator.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. #ifndef FMT_MOCK_ALLOCATOR_H_
  8. #define FMT_MOCK_ALLOCATOR_H_
  9. #include <assert.h> // assert
  10. #include <stddef.h> // size_t
  11. #include <memory> // std::allocator_traits
  12. #include "gmock/gmock.h"
  13. template <typename T> class mock_allocator {
  14. public:
  15. mock_allocator() {}
  16. mock_allocator(const mock_allocator&) {}
  17. using value_type = T;
  18. MOCK_METHOD1_T(allocate, T*(size_t n));
  19. MOCK_METHOD2_T(deallocate, void(T* p, size_t n));
  20. };
  21. template <typename Allocator> class allocator_ref {
  22. private:
  23. Allocator* alloc_;
  24. void move(allocator_ref& other) {
  25. alloc_ = other.alloc_;
  26. other.alloc_ = nullptr;
  27. }
  28. public:
  29. using value_type = typename Allocator::value_type;
  30. explicit allocator_ref(Allocator* alloc = nullptr) : alloc_(alloc) {}
  31. allocator_ref(const allocator_ref& other) : alloc_(other.alloc_) {}
  32. allocator_ref(allocator_ref&& other) { move(other); }
  33. allocator_ref& operator=(allocator_ref&& other) {
  34. assert(this != &other);
  35. move(other);
  36. return *this;
  37. }
  38. allocator_ref& operator=(const allocator_ref& other) {
  39. alloc_ = other.alloc_;
  40. return *this;
  41. }
  42. public:
  43. Allocator* get() const { return alloc_; }
  44. value_type* allocate(size_t n) {
  45. return std::allocator_traits<Allocator>::allocate(*alloc_, n);
  46. }
  47. void deallocate(value_type* p, size_t n) { alloc_->deallocate(p, n); }
  48. };
  49. #endif // FMT_MOCK_ALLOCATOR_H_