mock-allocator.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. using value_type = T;
  16. using size_type = size_t;
  17. using pointer = T*;
  18. using const_pointer = const T*;
  19. using reference = T&;
  20. using const_reference = const T&;
  21. using difference_type = ptrdiff_t;
  22. template <typename U> struct rebind {
  23. using other = mock_allocator<U>;
  24. };
  25. mock_allocator() {}
  26. mock_allocator(const mock_allocator&) {}
  27. MOCK_METHOD(T*, allocate, (size_t));
  28. MOCK_METHOD(void, deallocate, (T*, size_t));
  29. };
  30. template <typename Allocator> class allocator_ref {
  31. private:
  32. Allocator* alloc_;
  33. void move(allocator_ref& other) {
  34. alloc_ = other.alloc_;
  35. other.alloc_ = nullptr;
  36. }
  37. public:
  38. using value_type = typename Allocator::value_type;
  39. explicit allocator_ref(Allocator* alloc = nullptr) : alloc_(alloc) {}
  40. allocator_ref(const allocator_ref& other) : alloc_(other.alloc_) {}
  41. allocator_ref(allocator_ref&& other) { move(other); }
  42. allocator_ref& operator=(allocator_ref&& other) {
  43. assert(this != &other);
  44. move(other);
  45. return *this;
  46. }
  47. allocator_ref& operator=(const allocator_ref& other) {
  48. alloc_ = other.alloc_;
  49. return *this;
  50. }
  51. public:
  52. Allocator* get() const { return alloc_; }
  53. value_type* allocate(size_t n) {
  54. return std::allocator_traits<Allocator>::allocate(*alloc_, n);
  55. }
  56. void deallocate(value_type* p, size_t n) { alloc_->deallocate(p, n); }
  57. };
  58. #endif // FMT_MOCK_ALLOCATOR_H_